3
votes

I'm making a Snake type game using Pygame. Everything's pretty much working, but below is the end of my game. There's a sound effect, and I put in the delay so the window didn't close before the sound finished playing. It all worked fine, and I just added in the Game Over text. For some reason, the sound plays, the game pauses, and then the Game Over quickly flashes on the screen. Can anyone explain to me why this is going out of order?

I'm using Python 2.7 on Mac 10.6.8.

if w.crashed or w.x<=0 or w.x >= width - 1 or w.y<=0 or w.y >= height -1:
    gameover.play()
    font = pygame.font.Font(None, 80)
    end_game = font.render("Game Over!", True, (255, 0, 0), (0,0,0))
    endRect = end_game.get_rect(centerx = width/2, centery = height / 2)
    screen.blit(end_game, endRect)
    pygame.time.delay(3500)
    running = False
3

3 Answers

2
votes

Could it be that you are missing pygame.display.flip() or display.update(rectangle=endRect) right after the screen.blit() call ?

0
votes

I think your problem is with the running varibale. If that ends your main while loop*, it ends the program, and that would be your problem.

*main while loop:

while running:
    #everything that the program does goes here

Most games have one, and doing anything to affect it would ruin the loop, and therefore end everything in your program. Since the code you displayed in the question would be inside that loop, the text and the sound would not play.

I know it would make sense for python to pause the program when it finds the delay command, but it actually does not actually pause the program. It just pauses pygame. The program will continue running, assign running to false, and your loop just ended. The font will not render because it is in the loop, and the sound won't play because pygame was paused. It never un-paused because that would be an event called in the while loop, which is now closed.

As a side note, the reason Pygame keeps the "frozen" window open is because the variables for every other image and font on the screen stays the same, and it was not told to close.

Of course this whole answer could have been a waste of both of our time if the running variable isn't what I think it is.

A worthy question :)

0
votes
pygame.display.flip() should be done before `pygame.time.delay(3500)`. 

Change your code to this

if w.crashed or w.x<=0 or w.x >= width - 1 or w.y<=0 or w.y >= height -1:
    gameover.play()
    font = pygame.font.Font(None, 80)
    end_game = font.render("Game Over!", True, (255, 0, 0), (0,0,0))
    endRect = end_game.get_rect(centerx = width/2, centery = height / 2)
    screen.blit(end_game, endRect)

    pygame.display.update()

    pygame.time.delay(3500)

    running = False