使用python完成贪吃蛇小游戏
时间: 2023-07-20 15:24:50 浏览: 102
好的,以下是一个简单的Python实现贪吃蛇小游戏的代码,运行需要Pygame库的支持:
```python
import pygame
import random
# 定义颜色常量
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 定义屏幕大小和格子大小
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
GRID_SIZE = 10
# 初始化Pygame
pygame.init()
# 创建游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Snake Game')
# 创建游戏时钟
clock = pygame.time.Clock()
# 定义贪吃蛇的初始位置和长度
snake = [(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)]
snake_length = 1
# 定义贪吃蛇的初始方向
direction = 'right'
# 定义食物的初始位置
food = (random.randint(0, SCREEN_WIDTH / GRID_SIZE - 1) * GRID_SIZE,
random.randint(0, SCREEN_HEIGHT / GRID_SIZE - 1) * GRID_SIZE)
# 定义游戏结束标志
game_over = False
# 定义游戏循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and direction != 'down':
direction = 'up'
elif event.key == pygame.K_DOWN and direction != 'up':
direction = 'down'
elif event.key == pygame.K_LEFT and direction != 'right':
direction = 'left'
elif event.key == pygame.K_RIGHT and direction != 'left':
direction = 'right'
# 移动贪吃蛇
if direction == 'up':
head = (snake[0][0], snake[0][1] - GRID_SIZE)
elif direction == 'down':
head = (snake[0][0], snake[0][1] + GRID_SIZE)
elif direction == 'left':
head = (snake[0][0] - GRID_SIZE, snake[0][1])
elif direction == 'right':
head = (snake[0][0] + GRID_SIZE, snake[0][1])
snake.insert(0, head)
# 判断是否吃到食物
if head == food:
food = (random.randint(0, SCREEN_WIDTH / GRID_SIZE - 1) * GRID_SIZE,
random.randint(0, SCREEN_HEIGHT / GRID_SIZE - 1) * GRID_SIZE)
snake_length += 1
# 判断是否撞到墙或自己
if head[0] < 0 or head[0] >= SCREEN_WIDTH or head[1] < 0 or head[1] >= SCREEN_HEIGHT or head in snake[1:]:
game_over = True
# 删除多余的尾部
if len(snake) > snake_length:
snake.pop()
# 清屏
screen.fill(BLACK)
# 绘制贪吃蛇
for s in snake:
pygame.draw.rect(screen, GREEN, (s[0], s[1], GRID_SIZE, GRID_SIZE))
# 绘制食物
pygame.draw.rect(screen, RED, (food[0], food[1], GRID_SIZE, GRID_SIZE))
# 刷新屏幕
pygame.display.flip()
# 控制游戏帧率
clock.tick(10)
# 退出Pygame
pygame.quit()
```
这个代码实现了一个简单的贪吃蛇小游戏,通过键盘控制贪吃蛇的移动方向,吃到食物可以增加长度,撞到墙或自己则游戏结束。可以根据自己的需要进行修改和扩展。
阅读全文