Reputation: 11
I'm building a Hangman game as my first Pygame project. Once the game ends, I want the screen to pause for a second and then display a result message for a few seconds, before exiting the game. I have the following function for that:
def display_result_msg(win):
pygame.time.delay(1500)
if win:
msg = 'You win!'
else:
msg = 'You lose.'
screen.fill(BLACK)
msg_text = MESSAGE_DISPLAY_FONT.render(msg, True, WHITE)
msg_width, msg_height = msg_text.get_size()
msg_x, msg_y = (WIDTH - msg_width)/2, (HEIGHT - msg_height)/2
screen.blit(msg_text,(msg_x, msg_y))
pygame.display.update()
pygame.time.delay(10000)
The game behaves as expected till the last correct/incorrect guess, but when it comes to displaying the result message, the game starts buffering for the entire delay duration, and the result message only flashes on the screen momentarily just before exiting the game. This happens no matter what delay time I set. Please help me understand what exactly I'm missing here. Thank you.
Upvotes: 1
Views: 424
Reputation: 14906
I suspect the problem is you are blocking the event loop. It's better not to have these hard-set delays.
If you must do a hard-delay, make a function that waits, but also tends to the event-loop:
def waitFor( milliseconds ):
""" Wait for the given time period, but handling some events """
time_now = pygame.time.get_ticks() # zero point
finish_time = time_now + milliseconds # finish time
while time_now < finish_time:
# Handle user-input
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
# re-post this to handle in the main loop
pygame.event.post( pygame.event.Event( pygame.QUIT ) )
break
elif ( event.type == pygame.KEYDOWN ):
if ( event.key == pygame.K_ESCAPE ):
break
# TODO handle any other important events here
pygame.display.update() # do we need this?
pygame.time.wait( 300 ) # save some CPU for a split-second
time_now = pygame.time.get_ticks()
Giving you something like:
def display_result_msg(win):
#pygame.time.delay(1500)
if win:
msg = 'You win!'
else:
msg = 'You lose.'
screen.fill(BLACK)
msg_text = MESSAGE_DISPLAY_FONT.render(msg, True, WHITE)
msg_width, msg_height = msg_text.get_size()
msg_x, msg_y = (WIDTH - msg_width)/2, (HEIGHT - msg_height)/2
screen.blit(msg_text,(msg_x, msg_y))
waitFor( 10*1000 )
Upvotes: 1