I have made a python snake game using pygame
in which I wanted to show game over screen when the snake hits itself but instead it resets the snake.
So, please help me to add game over image when snake collide with itself and also add key "P" to restart the game and key "ESC" to exit the game, as same that I have done to
def check_fail(self):
if not 0 <= self.snake.body[0].x < cell_number or not 0 <= self.snake.body[0].y < cell_number:
self.play_wall_crash_sound()
self.game_over()
Game_Over()
pygame.mixer.music.unpause()
Any other suggestions are always welcome.
# Game over text
def Game_Over():
game_over = True
while game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
game_over = False
elif event.key == pygame.K_ESCAPE:
pygame.quit()
quit()
pygame.mixer.music.pause()
clock.tick(10)
screen.blit(game_over_bg, (0, 0))
pygame.display.update()
# Main game code
class MAIN:
def __init__(self):
self.play_background_music()
self.snake = SNAKE()
self.fruit = FRUIT()
# Update all
def update(self):
self.snake.move_snake()
self.check_collision()
self.check_fail()
# Draw elements
def draw_elements(self):
self.draw_grass()
self.fruit.draw_fruit()
self.snake.draw_snake()
self.draw_score()
# Check if snake collide the fruit
def check_collision(self):
if self.fruit.pos == self.snake.body[0]:
self.fruit.randomize()
self.snake.add_block()
self.snake.play_crunch_sound()
for block in self.snake.body[1:]:
if block == self.fruit.pos:
self.fruit.randomize()
# Check if snake collide wall and itself and then game over
def check_fail(self):
if not 0 <= self.snake.body[0].x < cell_number or not 0 <= self.snake.body[0].y < cell_number:
self.play_wall_crash_sound()
self.game_over()
Game_Over()
pygame.mixer.music.unpause()
for block in self.snake.body[1:]:
if block == self.snake.body[0]:
self.game_over()
# Reseting the snake after game over
def game_over(self):
self.snake.reset()