请用Python写一个贪吃蛇的小游戏
时间: 2023-03-10 20:07:51 浏览: 143
好的,我可以给你一些示例代码,你可以基于它来开发一个贪吃蛇的小游戏:# 导入 pygame 库
import pygame# 初始化 pygame
pygame.init()# 设置屏幕尺寸
screen_width = 600
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))# 设置背景颜色
background_color = (0, 0, 0)
screen.fill(background_color)# 设置标题
title = '贪吃蛇'
pygame.display.set_caption(title)# 定义变量
block_size = 10
fps = 20# 定义贪吃蛇的初始位置
x_pos = 300
y_pos = 200# 定义贪吃蛇的移动方向
direction = 'right'# 定义贪吃蛇的颜色
snake_color = (0, 255, 0)# 定义贪吃蛇的身体
snake_body = [[x_pos, y_pos], [x_pos - 10, y_pos], [x_pos - 20, y_pos]]# 定义食物的位置
food_x = 200
food_y = 300# 定义食物的颜色
food_color = (255, 0, 0)# 定义游戏主循环
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
direction = 'right'
elif event.key == pygame.K_LEFT:
direction = 'left'
elif event.key == pygame.K_UP:
direction = 'up'
elif event.key == pygame.K_DOWN:
direction = 'down'
# 根据方向移动贪吃蛇
if direction == 'right':
x_pos += 10
elif direction == 'left':
x_pos -= 10
elif direction == 'up':
y_pos -= 10
elif direction == 'down':
y_pos += 10
# 贪吃蛇增长
snake_head = [x_pos, y_pos]
snake_body.append(snake_head)
# 判断是否吃到食物
if x_pos == food_x and y_pos == food_y:
# 重新生成食物
food_x = random.randint(0, screen_width // 10) * 10
food_y = random.randint(0, screen_height // 10) * 10
else:
# 删除贪吃蛇的尾部
snake_body.pop(0)
# 绘制贪吃蛇
for body in snake_body:
pygame.draw.rect(screen, snake_color, (body[0], body[1], block_size, block_size))
# 绘制食物
pygame.draw.rect(screen, food_color, (food_x, food_y, block_size, block_size))
# 更新显示
pygame.display.update()
# 延时
clock.tick(fps)# 退出
pygame.quit()
阅读全文