帮我写个贪吃蛇小游戏代码
时间: 2023-09-01 07:07:51 浏览: 41
好的,以下是贪吃蛇小游戏的 Python 代码:
```
import pygame
import random
# 定义常量
WIDTH = 640
HEIGHT = 480
SIZE = 20
BG_COLOR = (50, 50, 50)
SNAKE_COLOR = (255, 255, 255)
FOOD_COLOR = (0, 255, 0)
# 初始化 Pygame
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇小游戏")
# 定义 Snake 类
class Snake:
def __init__(self):
self.body = []
self.direction = "right"
for i in range(4):
self.body.append((SIZE * (i + 1), SIZE))
# 获取蛇头坐标
def head(self):
return self.body[-1]
# 移动方法
def move(self):
x, y = self.head()
if self.direction == "up":
y -= SIZE
elif self.direction == "down":
y += SIZE
elif self.direction == "left":
x -= SIZE
elif self.direction == "right":
x += SIZE
self.body.append((x, y))
self.body.pop(0)
# 改变方向方法
def change_direction(self, direction):
if direction == "up" and self.direction != "down":
self.direction = "up"
elif direction == "down" and self.direction != "up":
self.direction = "down"
elif direction == "left" and self.direction != "right":
self.direction = "left"
elif direction == "right" and self.direction != "left":
self.direction = "right"
# 绘制蛇方法
def draw(self):
for x, y in self.body:
rect = pygame.Rect(x, y, SIZE, SIZE)
pygame.draw.rect(screen, SNAKE_COLOR, rect)
# 定义 Food 类
class Food:
def __init__(self):
self.pos = self.new_pos()
# 生成新的食物位置
def new_pos(self):
x = random.randint(0, WIDTH // SIZE - 1) * SIZE
y = random.randint(0, HEIGHT // SIZE - 1) * SIZE
return (x, y)
# 绘制食物方法
def draw(self):
x, y = self.pos
rect = pygame.Rect(x, y, SIZE, SIZE)
pygame.draw.rect(screen, FOOD_COLOR, rect)
# 创建 Snake 和 Food 对象
snake = Snake()
food = Food()
# 创建时钟对象
clock = pygame.time.Clock()
# 游戏循环
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_UP:
snake.change_direction("up")
elif event.key == pygame.K_DOWN:
snake.change_direction("down")
elif event.key == pygame.K_LEFT:
snake.change_direction("left")
elif event.key == pygame.K_RIGHT:
snake.change_direction("right")
# 判断是否吃到食物
if snake.head() == food.pos:
food.pos = food.new_pos()
else:
snake.body.pop(0)
# 判断是否死亡
if snake.head()[0] < 0 or snake.head()[0] >= WIDTH:
pygame.quit()
exit()
if snake.head()[1] < 0 or snake.head()[1] >= HEIGHT:
pygame.quit()
exit()
for x, y in snake.body[:-1]:
if snake.head() == (x, y):
pygame.quit()
exit()
# 绘制背景
screen.fill(BG_COLOR)
# 绘制蛇和食物
snake.move()
snake.draw()
food.draw()
# 刷新屏幕
pygame.display.update()
# 控制帧率
clock.tick(10)
```
希望你喜欢这个贪吃蛇小游戏!