下面是一个使用 Python 的 pygame 库编写的简单贪吃蛇游戏的示例代码: ```python import pygame import sys import random # 初始化pygame pygame.init() # 设置屏幕大小 screen_width = 480 screen_height = 480 screen = pygame.display.set_mode((screen_width, screen_height)) # 设置颜色 black = (0, 0, 0) white = (255, 255, 255) red = (213, 50, 80) green = (0, 255, 0) blue = (50, 153, 213) # 设置帧率 clock = pygame.time.Clock() snake_speed = 15 # 设置蛇的大小和位置 snake_size = 10 snake_pos = [100, 50] snake_body = [[100, 50], [90, 50], [80, 50]] # 设置食物的位置 food_pos = [random.randrange(1, (screen_width//10)) * 10, random.randrange(1, (screen_height//10)) * 10] food_spawn = True # 设置方向 direction = 'RIGHT' change_to = direction # 游戏结束函数 def game_over(): my_font = pygame.font.SysFont('times new roman', 90) go_surface = my_font.render('Your Score is: ' + str(len(snake_body) - 3), True, red) go_rect = go_surface.get_rect() go_rect.midtop = (screen_width/2, screen_height/4) screen.fill(black) screen.blit(go_surface, go_rect) pygame.display.flip() time.sleep(2) pygame.quit() sys.exit() # 主循环 while True: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: change_to = 'UP' elif event.key == pygame.K_DOWN: change_to = 'DOWN' elif event.key == pygame.K_LEFT: change_to = 'LEFT' elif event.key == pygame.K_RIGHT: change_to = 'RIGHT' if event.type == pygame.QUIT: pygame.quit() sys.exit() # 确保蛇不能直接反向移动 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' # 根据方向移动蛇头 if direction == 'UP': snake_pos[1] -= 10 if direction == 'DOWN': snake_pos[1] += 10 if direction == 'LEFT': snake_pos[0] -= 10 if direction == 'RIGHT': snake_pos[0] += 10 # 蛇身体增长机制 snake_body.insert(0, list(snake_pos)) if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]: food_spawn = False else: snake_body.pop() # 重新生成食物 if not food_spawn: food_pos = [random.randrange(1, (screen_width//10)) * 10, random.randrange(1, (screen_height//10)) * 10] food_spawn = True # 填充和绘制蛇和食物 screen.fill(black) for pos in snake_body: pygame.draw.rect(screen, green, pygame.Rect(pos[0], pos[1], snake_size, snake_size)) pygame.draw.rect(screen, white, pygame.Rect(food_pos[0], food_pos[1], snake_size, snake_size)) # 检查是否撞墙或撞到自己 if snake_pos[0] < 0 or snake_pos[0] > screen_width-snake_size: game_over() if snake_pos[1] < 0 or snake_pos[1] > screen_height-snake_size: game_over() for block in snake_body[1:]: if snake_pos[0] == block[0] and snake_pos[1] == block[1]: game_over() # 更新屏幕并设置帧率 pygame.display.update() clock.tick(snake_speed) ``` [2024-11-19 07:28:25 | AI写代码神器 | 1274点数解答]