用python写一个简单的贪吃蛇小游戏的代码,写完整
时间: 2023-03-22 14:00:24 浏览: 85
好的,以下是一个简单的贪吃蛇游戏的Python代码,使用了Pygame库实现游戏窗口和游戏逻辑:
```python
import pygame
import random
# 游戏区域大小和方块大小
WIDTH = 500
HEIGHT = 500
BLOCK_SIZE = 10
# 颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# 初始化Pygame
pygame.init()
# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('贪吃蛇')
# 定义蛇的初始位置和初始长度
snake = [(WIDTH/2, HEIGHT/2)]
snake_len = 1
# 定义蛇的移动方向
direction = 'right'
# 生成食物的初始位置
food_x = random.randint(0, WIDTH/BLOCK_SIZE - 1) * BLOCK_SIZE
food_y = random.randint(0, HEIGHT/BLOCK_SIZE - 1) * BLOCK_SIZE
# 定义游戏结束标志
game_over = False
# 定义计时器和速度控制变量
clock = pygame.time.Clock()
speed = 10
# 游戏循环
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'
# 移动蛇的位置
head = snake[-1]
if direction == 'up':
new_head = (head[0], head[1] - BLOCK_SIZE)
elif direction == 'down':
new_head = (head[0], head[1] + BLOCK_SIZE)
elif direction == 'left':
new_head = (head[0] - BLOCK_SIZE, head[1])
elif direction == 'right':
new_head = (head[0] + BLOCK_SIZE, head[1])
snake.append(new_head)
# 如果吃到了食物,则长度加一,并生成新的食物
if new_head[0] == food_x and new_head[1] == food_y:
snake_len += 1
food_x = random.randint(0, WIDTH/BLOCK_SIZE - 1) * BLOCK_SIZE
food_y = random.randint(0, HEIGHT/BLOCK_SIZE - 1) * BLOCK_SIZE
# 如果蛇撞到了边界或者自己的身体,则游戏结束
if new_head[0] < 0 or new_head[0] >= WIDTH or new_head[1] < 0 or new_head[1] >= HEIGHT or new_head in snake[:-1]:
game_over = True
# 如果蛇的长度超过了snake_len,则删除尾部,使蛇的长度不变
if len(snake) > snake_len:
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)