'How to add Game Over image and play again function in Flappy Bird PyGame when sprite collides?
I am doing a flappy bird PyGame project for a computer science class. I have the main code, but when the bird collides with a pipe or the ground, it just stops. I want to add a "Game Over" image (I have the PNG) and an option to play again. I think below is the part of the code that I need to add to. What should I add to make it work?
if (pygame.sprite.groupcollide(bird_group, ground_group, False, False, pygame.sprite.collide_mask) or
pygame.sprite.groupcollide(bird_group, pipe_group, False, False, pygame.sprite.collide_mask)):
pygame.mixer.music.load(hit)
pygame.mixer.music.play()
# play again
GAMEOVER = pygame.image.load('assets/sprites/gameover.png')
GAMEOVER = pygame.transform.scale(GAMEOVER, (0,0))
break
Solution 1:[1]
You have to add a variable that indicates the state of the game. Draw the scene depending on the state of this variable:
GAMEOVER = pygame.image.load('assets/sprites/gameover.png')
game_state = "play"
run = True
while run:
event_list = pygame.event.get()
for event in event_list:
if event.type == pygame.qUIT:
run = False
if game_state == "play":
for event in event_list:
# game events
# [...]
# draw game
# [...]
if (pygame.sprite.groupcollide(bird_group, ground_group, False, False, pygame.sprite.collide_mask) or
pygame.sprite.groupcollide(bird_group, pipe_group, False, False, pygame.sprite.collide_mask)):
pygame.mixer.music.load(hit)
pygame.mixer.music.play()
game_state == "game over"
elif game_state == "game over":
for event in event_list:
# game over events
# [...]
screen.blit(GAMEOVER, (0, 0))
pygame.display.update()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rabbid76 |