帮我写一段贪吃蛇的程序
时间: 2023-05-23 11:06:58 浏览: 46
答案:下面是一段贪吃蛇程序:# 引入必要的模块
import pygame
import time
import random# 初始化pygame
pygame.init()# 创建游戏窗口
window_width = 500
window_height = 500
window = pygame.display.set_mode((window_width, window_height))# 创建游戏标题
pygame.display.set_caption("贪吃蛇")# 设置游戏变量
x_pos = 50
y_pos = 50
width = 10
height = 10
velocity = 25# 创建一个定时器,用于控制贪吃蛇的移动速度
clock = pygame.time.Clock()# 定义三种颜色
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)# 生成贪吃蛇的食物
food_x_pos = random.randint(0, window_width - width)
food_y_pos = random.randint(0, window_height - height)# 创建贪吃蛇身体的初始长度
snake_body = []
snake_length = 1# 定义游戏结束函数
game_over = False# 创建游戏主循环
while not game_over:
# 将游戏窗口填充为白色
window.fill(white) # 遍历所有事件,以响应键盘输入
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:
x_pos -= velocity
if event.key == pygame.K_RIGHT:
x_pos += velocity
if event.key == pygame.K_UP:
y_pos -= velocity
if event.key == pygame.K_DOWN:
y_pos += velocity # 将贪吃蛇的位置放入身体列表
snake_head = []
snake_head.append(x_pos)
snake_head.append(y_pos)
snake_body.append(snake_head) # 如果贪吃蛇身体超过指定长度,则删除最旧的节点
if len(snake_body) > snake_length:
del snake_body[0] # 绘制贪吃蛇
for position in snake_body:
pygame.draw.rect(window, green, pygame.Rect(position[0], position[1], width, height)) # 绘制贪吃蛇的食物
pygame.draw.rect(window, red, pygame.Rect(food_x_pos, food_y_pos, width, height)) # 检测贪吃蛇是否吃到了食物
if x_pos == food_x_pos and y_pos == food_y_pos:
food_x_pos = random.randint(0, window_width - width)
food_y_pos = random.randint(0, window_height - height)
snake_length += 1 # 检测贪吃蛇是否撞到了墙
if x_pos < 0 or x_pos > window_width - width or y_pos < 0 or y_pos > window_height - height:
game_over = True # 检测贪吃蛇是否自撞
for body in snake_body[:-1]:
if x_pos == body[0] and y_pos == body[1]:
game_over = True # 让游戏窗口更新
pygame.display.update()
# 设置游戏速度
clock.tick(15)# 退出游戏
pygame.quit()