1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| import pygame from snake_and_food import Snake, Food import game_config import time
def init_game(): """初始化 Pygame、窗口和时钟和字体""" pygame.init() screen = pygame.display.set_mode((game_config.WIDTH, game_config.HEIGHT)) pygame.display.set_caption("贪吃蛇") clock = pygame.time.Clock()
pygame.font.init() font = pygame.font.Font(None, 36) return screen, clock, font
def handle_events(snake_dir): """处理键盘事件""" for event in pygame.event.get(): if event.type == pygame.QUIT: return False, snake_dir
elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP and snake_dir != (0, 1): snake_dir = (0, -1) elif event.key == pygame.K_DOWN and snake_dir != (0, -1): snake_dir = (0, 1) elif event.key == pygame.K_LEFT and snake_dir != (1, 0): snake_dir = (-1, 0) elif event.key == pygame.K_RIGHT and snake_dir != (-1, 0): snake_dir = (1, 0) return True, snake_dir
def Ui_OVER(screen, font): for i in range(3): screen.fill(game_config.WHITE) pygame.display.flip() time.sleep(0.1) screen.fill(game_config.BLACK) pygame.display.flip() time.sleep(0.1)
screen.fill(game_config.BLACK) text_surface = font.render("GAME OVER", True, (255, 255, 255)) text_rect = text_surface.get_rect(center=(game_config.WIDTH // 2, game_config.HEIGHT // 2)) screen = pygame.display.set_mode((game_config.WIDTH, game_config.HEIGHT)) screen.fill(game_config.BLACK) screen.blit(text_surface, text_rect) pygame.display.flip() time.sleep(1)
def game_loop(): """主游戏循环""" screen, clock, font = init_game() snake = Snake() food = Food() running = True snake_dir = (1, 0)
while running: clock.tick(10) running, snake_dir = handle_events(snake_dir) screen.fill(game_config.BLACK) running = snake.move(snake_dir, food)
food_x = food.food[0] * game_config.GRID_SIZE food_y = food.food[1] * game_config.GRID_SIZE food_rect = (food_x, food_y, game_config.GRID_SIZE, game_config.GRID_SIZE)
pygame.draw.rect(screen, game_config.RED, food_rect)
for index, segment in enumerate(snake.body): segment_x = segment[0] * game_config.GRID_SIZE segment_y = segment[1] * game_config.GRID_SIZE segment_rect = (segment_x, segment_y, game_config.GRID_SIZE, game_config.GRID_SIZE)
color = game_config.BLUE if index == 0 else game_config.GREEN
pygame.draw.rect(screen, color, segment_rect)
score = len(snake.body) - 3 text_surface = font.render(f"Game Score: {score}", True, (255, 255, 255)) screen.blit(text_surface, (10, 10)) pygame.display.flip()
Ui_OVER(screen, font) pygame.quit()
if __name__ == "__main__": game_loop()
|