# create a rectangular object for the text # surface object score_rect = score_surface.get_rect()
# displaying text game_window.blit(score_surface, score_rect)
# game over function def game_over():
# creating font object my_font my_font = pygame.font.SysFont('times new roman', 50)
# creating a text surface on which text # will be drawn game_over_surface = my_font.render( 'Your Score is : ' + str(score), True, red)
# create a rectangular object for the text # surface object game_over_rect = game_over_surface.get_rect()
# setting position of the text game_over_rect.midtop = (window_x/2, window_y/4)
# blit wil draw the text on screen game_window.blit(game_over_surface, game_over_rect) pygame.display.flip()
# after 2 seconds we will quit the program time.sleep(2)
# deactivating pygame library pygame.quit()
# quit the program quit()
# Main Function while True:
# handling key events for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: change_to = 'UP' if event.key == pygame.K_DOWN: change_to = 'DOWN' if event.key == pygame.K_LEFT: change_to = 'LEFT' if event.key == pygame.K_RIGHT: change_to = 'RIGHT'
# If two keys pressed simultaneously # we don't want snake to move into two # directions simultaneously if change_to == 'UP' and direction != 'DOWN': direction = 'UP' if change_to == 'DOWN' and direction != 'UP': direction = 'DOWN' if change_to == 'LEFT' and direction != 'RIGHT': direction = 'LEFT' if change_to == 'RIGHT' and direction != 'LEFT': direction = 'RIGHT'
# Moving the snake if direction == 'UP': snake_position[1] -= 10 if direction == 'DOWN': snake_position[1] += 10 if direction == 'LEFT': snake_position[0] -= 10 if direction == 'RIGHT': snake_position[0] += 10
# Snake body growing mechanism # if fruits and snakes collide then scores # will be incremented by 10 snake_body.insert(0, list(snake_position)) if snake_position[0] == fruit_position[0] and snake_position[1] == fruit_position[1]: score += 10 fruit_spawn = False else: snake_body.pop()
if not fruit_spawn: fruit_position = [random.randrange(1, (window_x//10)) * 10, random.randrange(1, (window_y//10)) * 10]
fruit_spawn = True game_window.fill(white)
for pos in snake_body: pygame.draw.rect(game_window, black,