import pygame import time import random # 初始化 Pygame 库 pygame.init() # 定义游戏窗口大小 WINDOW_WIDTH = 500 WINDOW_HEIGHT = 500 # 定义游戏速度 SPEED = 15 # 创建游戏窗口 screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) # 设置游戏标题 pygame.display.set_caption("贪吃蛇游戏") # 定义颜色 BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) # 游戏字符大小 FONT_STYLE = pygame.font.SysFont(None, 30) # 显示分数 def show_score(score): score_text = FONT_STYLE.render("分数: " + str(score), True, WHITE) screen.blit(score_text, [0, 0]) # 绘制蛇 def draw_snake(snake_block, snake_list): for x in snake_list: pygame.draw.rect(screen, GREEN, [x[0], x[1], snake_block, snake_block]) # 主函数 def game_loop(): # 设置蛇的初始位置和长度 snake_block = 10 snake_speed_x = 0 snake_speed_y = 0 # 初始位置 (x,y) 坐标 x1 = WINDOW_WIDTH / 2 y1 = WINDOW_HEIGHT / 2 # 蛇的初始长度 snake_List = [] Length_of_snake = 1 # 食物的位置 foodx = round(random.randrange(0, WINDOW_WIDTH - snake_block) / 10.0) * 10.0 foody = round(random.randrange(0, WINDOW_HEIGHT - snake_block) / 10.0) * 10.0 # 游戏是否结束的标志位 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_LEFT: snake_speed_x = -snake_block snake_speed_y = 0 elif event.key == pygame.K_RIGHT: snake_speed_x = snake_block snake_speed_y = 0 elif event.key == pygame.K_UP: snake_speed_y = -snake_block snake_speed_x = 0 elif event.key == pygame.K_DOWN: snake_speed_y = snake_block snake_speed_x = 0 # 更新蛇头的位置 x1 += snake_speed_x y1 += snake_speed_y # 判断是否吃到食物 if x1 == foodx and y1 == foody: foodx = round(random.randrange(0, WINDOW_WIDTH - snake_block) / 10.0) * 10.0 foody = round(random.randrange(0, WINDOW_HEIGHT - snake_block) / 10.0) * 10.0 Length_of_snake += 1 score += 10 # 游戏结束的条件 if x1 < 0 or x1 >= WINDOW_WIDTH or y1 < 0 or y1 >= WINDOW_HEIGHT: game_over = True # 更新蛇的列表 snake_Head = [] snake_Head.append(x1) snake_Head.append(y1) snake_List.append(snake_Head) if len(snake_List) > Length_of_snake: del snake_List[0] for x in snake_List[:-1]: if x == snake_Head: game_over = True # 绘制游戏界面 screen.fill(BLACK) pygame.draw.rect(screen, RED, [foodx, foody, snake_block, snake_block]) draw_snake(snake_block, snake_List) show_score(score) pygame.display.update() # 控制游戏速度 clock = pygame.time.Clock() clock.tick(SPEED) # 退出 Pygame 库 pygame.quit() quit() if __name__ == '__main__': game_loop()