用python中的pygame库写一个贪吃蛇游戏,游戏规则如下:
时间: 2023-06-24 11:09:12 浏览: 112
好的,以下是一个简单的贪吃蛇游戏代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 定义一些常量
WIDTH = 600
HEIGHT = 480
GRID_SIZE = 20
SPEED = 10
# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.body = [(WIDTH / 2, HEIGHT / 2)]
self.direction = random.choice(["up", "down", "left", "right"])
def move(self):
if self.direction == "up":
self.body.insert(0, (self.body[0][0], self.body[0][1] - GRID_SIZE))
elif self.direction == "down":
self.body.insert(0, (self.body[0][0], self.body[0][1] + GRID_SIZE))
elif self.direction == "left":
self.body.insert(0, (self.body[0][0] - GRID_SIZE, self.body[0][1]))
elif self.direction == "right":
self.body.insert(0, (self.body[0][0] + GRID_SIZE, self.body[0][1]))
# 删除尾部
self.body.pop()
def draw(self):
for pos in self.body:
pygame.draw.rect(screen, GREEN, (pos[0], pos[1], GRID_SIZE, GRID_SIZE))
def check_collision(self):
# 检查是否碰到边界
if self.body[0][0] < 0 or self.body[0][0] >= WIDTH or self.body[0][1] < 0 or self.body[0][1] >= HEIGHT:
return True
# 检查是否碰到自己
for pos in self.body[1:]:
if pos == self.body[0]:
return True
return False
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"
# 定义食物类
class Food:
def __init__(self):
self.pos = (random.randint(0, WIDTH // GRID_SIZE - 1) * GRID_SIZE,
random.randint(0, HEIGHT // GRID_SIZE - 1) * GRID_SIZE)
def draw(self):
pygame.draw.rect(screen, RED, (self.pos[0], self.pos[1], GRID_SIZE, GRID_SIZE))
# 创建贪吃蛇和食物对象
snake = Snake()
food = Food()
# 游戏循环
clock = pygame.time.Clock()
running = True
while running:
# 设置帧率
clock.tick(SPEED)
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
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")
# 移动贪吃蛇
snake.move()
# 检查是否碰撞
if snake.check_collision():
running = False
# 检查是否吃到食物
if snake.body[0] == food.pos:
snake.body.append(snake.body[-1])
food = Food()
# 绘制游戏界面
screen.fill(BLACK)
snake.draw()
food.draw()
pygame.display.update()
# 退出游戏
pygame.quit()
```
这个代码实现了一个基本的贪吃蛇游戏,可以通过上下左右键来控制贪吃蛇的移动方向,当贪吃蛇碰到边界或者自己时游戏结束。
阅读全文