帮我写一个贪吃蛇游戏
时间: 2023-07-01 14:06:58 浏览: 88
好的,下面是一个简单的贪吃蛇游戏的Python代码示例:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 游戏窗口的尺寸和标题
WINDOW_WIDTH = 640
WINDOW_HEIGHT = 480
WINDOW_TITLE = '贪吃蛇'
# 定义颜色常量
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption(WINDOW_TITLE)
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义贪吃蛇的初始位置和大小
snake_x = 100
snake_y = 100
snake_size = 20
# 定义贪吃蛇每一节的大小
snake_block_size = 20
# 定义贪吃蛇的移动速度
snake_speed = 5
# 定义食物的初始位置和大小
food_x = random.randrange(0, WINDOW_WIDTH - snake_size, snake_block_size)
food_y = random.randrange(0, WINDOW_HEIGHT - snake_size, snake_block_size)
food_size = 20
# 定义贪吃蛇的初始方向
snake_direction = 'right'
# 定义贪吃蛇的初始长度和身体
snake_length = 1
snake_body = []
# 定义游戏结束标志
game_over = False
# 游戏循环
while not game_over:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 处理方向控制
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and snake_direction != 'right':
snake_direction = 'left'
elif keys[pygame.K_RIGHT] and snake_direction != 'left':
snake_direction = 'right'
elif keys[pygame.K_UP] and snake_direction != 'down':
snake_direction = 'up'
elif keys[pygame.K_DOWN] and snake_direction != 'up':
snake_direction = 'down'
# 根据方向移动贪吃蛇的头部
if snake_direction == 'left':
snake_x -= snake_speed
elif snake_direction == 'right':
snake_x += snake_speed
elif snake_direction == 'up':
snake_y -= snake_speed
elif snake_direction == 'down':
snake_y += snake_speed
# 判断贪吃蛇是否吃到了食物
if snake_x == food_x and snake_y == food_y:
food_x = random.randrange(0, WINDOW_WIDTH - snake_size, snake_block_size)
food_y = random.randrange(0, WINDOW_HEIGHT - snake_size, snake_block_size)
snake_length += 1
# 绘制游戏界面
window.fill(BLACK)
pygame.draw.rect(window, GREEN, (food_x, food_y, food_size, food_size))
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
snake_body.append(snake_head)
if len(snake_body) > snake_length:
del snake_body[0]
for block in snake_body:
pygame.draw.rect(window, WHITE, (block[0], block[1], snake_block_size, snake_block_size))
# 判断贪吃蛇是否碰到了边界或自己的身体
if snake_x < 0 or snake_x >= WINDOW_WIDTH or snake_y < 0 or snake_y >= WINDOW_HEIGHT:
game_over = True
for block in snake_body[:-1]:
if block == snake_head:
game_over = True
pygame.display.update()
# 控制游戏的帧率
clock.tick(30)
# 退出 Pygame
pygame.quit()
```
该代码使用 Pygame 库实现了一个简单的贪吃蛇游戏,界面使用黑色背景和白色方块代表贪吃蛇的身体,绿色方块代表食物。贪吃蛇的移动方向由方向键控制,当贪吃蛇吃到食物时,贪吃蛇的长度会增加。游戏结束的条件为贪吃蛇碰到边界或自己的身体。
阅读全文