1

I am using pygame and I want to display "Game Over" message before the window closes. For that I wanted to use time.sleep() function like that:

message('Game Over', red)
pygame.display.update()

time.sleep(3)

However it seems like time.sleep() delays the execution of pygame.display.update() and basically, the message appears after the delay instead of before. How can I ensure that time.sleep() is called only after the previous function is fully executed? Thank you in advance.

NatP
  • 11
  • 3
  • 2
    `pygame.display.update()` only works at the end of the code. `time.sleep()` will prevent the screen from updating until it finishes running – Orbital May 20 '21 at 10:27

1 Answers1

1

In general you want to avoid using time.sleep() in pygame or inside loops. One workaround is to use the datetime module.

The code below will run doSomething(), wait 3 seconds once the variable GameOver is true, and start running doSomething() again after 3 seconds, all while updating the screen so you can draw and run doOtherStuff() while the 3 second passes.

d = datetime.now()
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    if not GameOver:
        d = datetime.now()
        # your main code will go here
        doSomething()
    
    # wait 3 seconds when GameOver is True
    if GameOver and (datetime.now() - d).total_seconds() >= 3:
        GameOver = False
        # you can put anything else you want to run at the end of the 3 seconds here
    
    # do other stuff even while waiting
    doOtherStuff()
    pygame.display.update()
Orbital
  • 565
  • 3
  • 13