以下是一个使用 Python 的 Pygame 库来实现简单贪食蛇游戏的示例代码,你可以根据需要进一步完善和美化,以达到更酷的形象、华丽的画面和流畅的操作效果。 ```python import pygame import random # 基础设置 # 屏幕高度 SCREEN_HEIGHT = 480 # 屏幕宽度 SCREEN_WIDTH = 600 # 小方格大小 GRID_SIZE = 20 # 颜色定义 WHITE = (255, 255, 255) BLACK = (0, 0, 0) GREEN = (0, 255, 0) # 初始化 Pygame pygame.init() # 创建屏幕 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("贪食蛇游戏") # 游戏时钟 clock = pygame.time.Clock() # 蛇的初始位置和速度 snake_pos = [200, 100] snake_speed = [0, 0] # 食物的初始位置 food_pos = [random.randint(0, SCREEN_WIDTH // GRID_SIZE - 1) * GRID_SIZE, random.randint(0, SCREEN_HEIGHT // GRID_SIZE - 1) * GRID_SIZE] # 蛇的身体列表 snake_body = [[snake_pos[0], snake_pos[1]]] # 游戏结束标志 game_over = False # 得分 score = 0 # 游戏主循环 while not game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP and snake_speed[1]!= GRID_SIZE: snake_speed = [0, -GRID_SIZE] elif event.key == pygame.K_DOWN and snake_speed[1]!= -GRID_SIZE: snake_speed = [0, GRID_SIZE] elif event.key == pygame.K_LEFT and snake_speed[0]!= GRID_SIZE: snake_speed = [-GRID_SIZE, 0] elif event.key == pygame.K_RIGHT and snake_speed[0]!= -GRID_SIZE: snake_speed = [GRID_SIZE, 0] # 根据速度移动蛇头 snake_pos[0] += snake_speed[0] snake_pos[1] += snake_speed[1] # 判断蛇是否吃到食物 if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]: food_pos = [random.randint(0, SCREEN_WIDTH // GRID_SIZE - 1) * GRID_SIZE, random.randint(0, SCREEN_HEIGHT // GRID_SIZE - 1) * GRID_SIZE] score += 1 else: # 移除蛇尾 del snake_body[0] # 添加蛇头到蛇身 snake_body.append(list(snake_pos)) # 判断蛇是否撞到自己或边界 if [snake_pos[0], snake_pos[1]] in snake_body[1:]: game_over = True elif snake_pos[0] < 0 or snake_pos[0] >= SCREEN_WIDTH or snake_pos[1] < 0 or snake_pos[1] >= SCREEN_HEIGHT: game_over = True # 绘制背景 screen.fill(BLACK) # 绘制食物 pygame.draw.rect(screen, GREEN, [food_pos[0], food_pos[1], GRID_SIZE, GRID_SIZE]) # 绘制蛇 for pos in snake_body: pygame.draw.rect(screen, WHITE, [pos[0], pos[1], GRID_SIZE, GRID_SIZE]) # 显示得分 font = pygame.font.SysFont(None, 36) text = font.render("Score: " + str(score), 1, WHITE) screen.blit(text, [10, 10]) # 刷新屏幕 pygame.display.flip() # 控制游戏帧率 clock.tick(10) # 退出游戏 pygame.quit() ``` 要实现更酷的形象、华丽的画面,你可以: 1. 使用更复杂的图形绘制来替代简单的矩形表示蛇和食物。 2. 添加动画效果,例如蛇的移动动画。 3. 设计更精美的背景和界面元素。 4. 优化代码结构,提高性能,以确保操作流畅。 [2024-09-04 21:03:00 | 字节-豆包 | 1047字解答]