生成一段贪吃蛇代码
时间: 2023-07-10 11:13:19 浏览: 67
贪吃蛇的代码
好的,以下是一段基于 Python 的贪吃蛇代码,你可以运行它来体验一下游戏:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 定义游戏窗口的大小
WINDOW_WIDTH = 480
WINDOW_HEIGHT = 480
# 定义蛇头和食物的大小
BLOCK_SIZE = 20
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 创建时钟对象,用于控制游戏帧率
clock = pygame.time.Clock()
# 定义蛇的初始位置和移动方向
snake_head_x = WINDOW_WIDTH / 2
snake_head_y = WINDOW_HEIGHT / 2
snake_head_direction = "right"
# 定义食物的初始位置
food_x = random.randrange(0, WINDOW_WIDTH - BLOCK_SIZE, BLOCK_SIZE)
food_y = random.randrange(0, WINDOW_HEIGHT - BLOCK_SIZE, BLOCK_SIZE)
# 定义蛇的身体
snake_body = []
snake_length = 1
# 游戏循环
while True:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
# 获取键盘事件
keys = pygame.key.get_pressed()
# 根据键盘事件更新蛇的移动方向
if keys[pygame.K_LEFT] and snake_head_direction != "right":
snake_head_direction = "left"
elif keys[pygame.K_RIGHT] and snake_head_direction != "left":
snake_head_direction = "right"
elif keys[pygame.K_UP] and snake_head_direction != "down":
snake_head_direction = "up"
elif keys[pygame.K_DOWN] and snake_head_direction != "up":
snake_head_direction = "down"
# 根据移动方向更新蛇的位置
if snake_head_direction == "right":
snake_head_x += BLOCK_SIZE
elif snake_head_direction == "left":
snake_head_x -= BLOCK_SIZE
elif snake_head_direction == "up":
snake_head_y -= BLOCK_SIZE
elif snake_head_direction == "down":
snake_head_y += BLOCK_SIZE
# 判断是否撞墙
if snake_head_x < 0 or snake_head_x >= WINDOW_WIDTH or snake_head_y < 0 or snake_head_y >= WINDOW_HEIGHT:
pygame.quit()
exit()
# 判断是否吃到了食物
if snake_head_x == food_x and snake_head_y == food_y:
food_x = random.randrange(0, WINDOW_WIDTH - BLOCK_SIZE, BLOCK_SIZE)
food_y = random.randrange(0, WINDOW_HEIGHT - BLOCK_SIZE, BLOCK_SIZE)
snake_length += 1
# 更新蛇的身体
snake_body.insert(0, (snake_head_x, snake_head_y))
if len(snake_body) > snake_length:
snake_body.pop()
# 绘制游戏画面
window.fill(WHITE)
pygame.draw.rect(window, RED, (food_x, food_y, BLOCK_SIZE, BLOCK_SIZE))
for block in snake_body:
pygame.draw.rect(window, BLACK, (block[0], block[1], BLOCK_SIZE, BLOCK_SIZE))
# 刷新游戏画面
pygame.display.update()
# 控制游戏帧率
clock.tick(10)
```
这段代码实现了一个基本的贪吃蛇游戏,你可以在其中尝试添加一些新的功能,比如计分、加速等,来让游戏更加丰富有趣。
阅读全文