这是chatGPT回答的一个问题,然后他直接给出了下面的代码,我没有测试过,不知道对不对。不过看还挺神的,连注释都有模有样。
import pygame
import random
# 初始化 Pygame
pygame.init()
# 游戏窗口大小
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 创建游戏窗口
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义蛇的初始位置和大小
snake_pos = [250, 250]
snake_body = [[250, 250], [240, 250], [230, 250]]
snake_direction = "RIGHT"
# 定义食物的位置
food_pos = [random.randrange(1, (WINDOW_WIDTH//10)) * 10,
random.randrange(1, (WINDOW_HEIGHT//10)) * 10]
# 定义字体
font_style = pygame.font.SysFont(None, 30)
# 定义游戏结束提示信息
def message(msg, color):
message = font_style.render(msg, True, color)
screen.blit(message, [WINDOW_WIDTH/6, WINDOW_HEIGHT/3])
# 游戏主循环
def gameLoop():
game_over = False
game_close = False
while not game_over:
while game_close:
screen.fill(WHITE)
message("游戏结束! 按 Q 退出,按 C 重新开始", RED)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
elif event.key == pygame.K_c:
gameLoop()
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_direction = "LEFT"
elif event.key == pygame.K_RIGHT:
snake_direction = "RIGHT"
elif event.key == pygame.K_UP:
snake_direction = "UP"
elif event.key == pygame.K_DOWN:
snake_direction = "DOWN"
# 移动蛇的位置
if snake_direction == "LEFT":
snake_pos[0] -= 10
elif snake_direction == "RIGHT":
snake_pos[0] += 10
elif snake_direction == "UP":
snake_pos[1] -= 10
elif snake_direction == "DOWN":
snake_pos[1] += 10
# 如果蛇头与食物位置相同,则添加食物并重新生成新的位置
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
food_pos = [random.randrange(1, (WINDOW_WIDTH//10)) * 10,
random.randrange(1, (WINDOW_HEIGHT//10)) * 10]
else:
snake_body.pop()
# 添加蛇的位置
snake_body.insert(0, list(snake_pos))
# 检查蛇是否碰到了边界或自己