python生成贪吃蛇小游戏
时间: 2023-05-12 18:06:26 浏览: 113
可以使用 Python 的 Pygame 模块来生成贪吃蛇小游戏。以下是一个简单的示例代码:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 游戏窗口大小
WINDOW_WIDTH = 640
WINDOW_HEIGHT = 480
# 贪吃蛇方块大小
BLOCK_SIZE = 20
# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('贪吃蛇')
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.body = [(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2)]
self.direction = random.choice(['up', 'down', 'left', 'right'])
def move(self):
x, y = self.body[0]
if self.direction == 'up':
y -= BLOCK_SIZE
elif self.direction == 'down':
y += BLOCK_SIZE
elif self.direction == 'left':
x -= BLOCK_SIZE
elif self.direction == 'right':
x += BLOCK_SIZE
self.body.insert(0, (x, y))
self.body.pop()
def draw(self):
for x, y in self.body:
pygame.draw.rect(window, GREEN, (x, y, BLOCK_SIZE, BLOCK_SIZE))
# 定义食物类
class Food:
def __init__(self):
self.x = random.randint(0, WINDOW_WIDTH // BLOCK_SIZE - 1) * BLOCK_SIZE
self.y = random.randint(0, WINDOW_HEIGHT // BLOCK_SIZE - 1) * BLOCK_SIZE
def draw(self):
pygame.draw.rect(window, RED, (self.x, self.y, BLOCK_SIZE, BLOCK_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_UP and snake.direction != 'down':
snake.direction = 'up'
elif event.key == pygame.K_DOWN and snake.direction != 'up':
snake.direction = 'down'
elif event.key == pygame.K_LEFT and snake.direction != 'right':
snake.direction = 'left'
elif event.key == pygame.K_RIGHT and snake.direction != 'left':
snake.direction = 'right'
# 移动贪吃蛇
snake.move()
# 判断是否吃到食物
if snake.body[0] == (food.x, food.y):
snake.body.append(snake.body[-1])
food = Food()
# 判断游戏是否结束
if snake.body[0][0] < 0 or snake.body[0][0] >= WINDOW_WIDTH or \
snake.body[0][1] < 0 or snake.body[0][1] >= WINDOW_HEIGHT or \
snake.body[0] in snake.body[1:]:
pygame.quit()
exit()
# 绘制游戏界面
window.fill(BLACK)
snake.draw()
food.draw()
pygame.display.update()
```
这个代码使用 Pygame 模块创建了一个窗口,然后定义了贪吃蛇和食物两个类,通过游戏循环不断移动贪吃蛇和检测是否吃到食物,最后绘制游戏界面。
阅读全文