帮我写一个python的贪吃蛇小游戏
时间: 2023-07-01 16:21:29 浏览: 89
好的,下面是一个简单的 Python 贪吃蛇小游戏的实现,使用了 Pygame 库,您可以在安装 Pygame 库之后运行代码来体验游戏的过程。
```python
import pygame
import random
# 初始化 Pygame 库
pygame.init()
# 游戏窗口的宽度和高度
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
# 贪吃蛇的初始位置和大小
SNAKE_INIT_POSITION = (WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2)
SNAKE_INIT_SIZE = 5
# 食物的初始位置和大小
FOOD_INIT_POSITION = (random.randint(0, WINDOW_WIDTH - 10), random.randint(0, WINDOW_HEIGHT - 10))
FOOD_INIT_SIZE = 10
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
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.position = SNAKE_INIT_POSITION
self.size = SNAKE_INIT_SIZE
self.direction = random.choice([pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP, pygame.K_DOWN])
self.body = []
for i in range(self.size):
x = self.position[0] + (self.size - i) * 10
y = self.position[1]
self.body.append((x, y))
def move(self):
if self.direction == pygame.K_LEFT:
self.position = (self.position[0] - 10, self.position[1])
elif self.direction == pygame.K_RIGHT:
self.position = (self.position[0] + 10, self.position[1])
elif self.direction == pygame.K_UP:
self.position = (self.position[0], self.position[1] - 10)
elif self.direction == pygame.K_DOWN:
self.position = (self.position[0], self.position[1] + 10)
self.body.insert(0, self.position)
if len(self.body) > self.size:
self.body.pop()
def eat(self):
self.size += 1
# 定义食物类
class Food:
def __init__(self):
self.position = FOOD_INIT_POSITION
self.size = FOOD_INIT_SIZE
def generate(self):
self.position = (random.randint(0, WINDOW_WIDTH - 10), random.randint(0, WINDOW_HEIGHT - 10))
# 创建贪吃蛇和食物对象
snake = Snake()
food = Food()
# 游戏主循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and snake.direction != pygame.K_RIGHT:
snake.direction = pygame.K_LEFT
elif event.key == pygame.K_RIGHT and snake.direction != pygame.K_LEFT:
snake.direction = pygame.K_RIGHT
elif event.key == pygame.K_UP and snake.direction != pygame.K_DOWN:
snake.direction = pygame.K_UP
elif event.key == pygame.K_DOWN and snake.direction != pygame.K_UP:
snake.direction = pygame.K_DOWN
# 移动贪吃蛇
snake.move()
# 判断是否吃到食物
if snake.body[0] == food.position:
snake.eat()
food.generate()
# 清空屏幕
window.fill(BLACK)
# 绘制贪吃蛇和食物
for pos in snake.body:
pygame.draw.rect(window, WHITE, (pos[0], pos[1], 10, 10))
pygame.draw.rect(window, RED, (food.position[0], food.position[1], food.size, food.size))
# 更新屏幕
pygame.display.update()
# 控制帧率
clock.tick(10)
# 退出 Pygame 库
pygame.quit()
```
这个代码中我们创建了一个 Snake 类来表示贪吃蛇,一个 Food 类来表示食物。在游戏主循环中,我们处理了键盘事件,移动贪吃蛇,判断是否吃到食物,绘制贪吃蛇和食物等。您可以运行代码来体验游戏的过程。
阅读全文