帮我生成一个贪吃蛇的python代码
时间: 2023-08-20 14:30:18 浏览: 90
好的,下面是一个简单的贪吃蛇游戏的Python代码,使用Pygame模块实现:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置游戏窗口大小
WINDOW_WIDTH = 640
WINDOW_HEIGHT = 480
CELL_SIZE = 10
# 设置颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 创建时钟对象
clock = pygame.time.Clock()
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.body = [(50, 50), (40, 50), (30, 50)]
self.direction = "right"
def move(self):
# 计算蛇头位置
if self.direction == "right":
new_head = (self.body[0][0] + CELL_SIZE, self.body[0][1])
elif self.direction == "left":
new_head = (self.body[0][0] - CELL_SIZE, self.body[0][1])
elif self.direction == "up":
new_head = (self.body[0][0], self.body[0][1] - CELL_SIZE)
elif self.direction == "down":
new_head = (self.body[0][0], self.body[0][1] + CELL_SIZE)
# 插入新蛇头
self.body.insert(0, new_head)
# 移除蛇尾
self.body.pop()
def grow(self):
# 在蛇尾插入新块
self.body.append(self.body[-1])
def draw(self):
for cell in self.body:
pygame.draw.rect(window, GREEN, (cell[0], cell[1], CELL_SIZE, CELL_SIZE))
pygame.draw.rect(window, RED, (self.body[0][0], self.body[0][1], CELL_SIZE, CELL_SIZE))
# 定义食物类
class Food:
def __init__(self):
self.position = (0, 0)
self.generate_position()
def generate_position(self):
x = random.randint(0, WINDOW_WIDTH - CELL_SIZE)
y = random.randint(0, WINDOW_HEIGHT - CELL_SIZE)
self.position = (x // CELL_SIZE * CELL_SIZE, y // CELL_SIZE * CELL_SIZE)
def draw(self):
pygame.draw.rect(window, WHITE, (self.position[0], self.position[1], CELL_SIZE, CELL_SIZE))
# 创建贪吃蛇和食物对象
snake = Snake()
food = Food()
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT and snake.direction != "left":
snake.direction = "right"
elif event.key == pygame.K_LEFT and snake.direction != "right":
snake.direction = "left"
elif event.key == pygame.K_UP and snake.direction != "down":
snake.direction = "up"
elif event.key == pygame.K_DOWN and snake.direction != "up":
snake.direction = "down"
# 移动贪吃蛇
snake.move()
# 判断是否吃到食物
if snake.body[0] == food.position:
snake.grow()
food.generate_position()
# 绘制游戏界面
window.fill(BLACK)
snake.draw()
food.draw()
pygame.display.update()
# 控制游戏帧率
clock.tick(10)
```
这个游戏使用了Pygame模块创建游戏窗口和处理游戏逻辑。在游戏中,你需要控制贪吃蛇不停地移动并吃到食物,每吃到一块食物,贪吃蛇就会变长。如果贪吃蛇碰到了边界或者自己的身体,游戏就会结束。
阅读全文