用python编写一个贪吃蛇游戏
时间: 2023-09-16 21:10:22 浏览: 53
Python编写一个贪吃蛇游戏
好的,下面是一个简单的 Python 贪吃蛇游戏:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 定义一些常量
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
BLOCK_SIZE = 20
APPLE_SIZE = 20
SNAKE_COLOR = (0, 255, 0)
APPLE_COLOR = (255, 0, 0)
# 创建游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('贪吃蛇')
# 定义蛇的初始位置和长度
snake = [(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)]
snake_direction = 'right'
snake_length = 1
# 定义苹果的位置
apple = (random.randint(0, SCREEN_WIDTH / BLOCK_SIZE - 1) * BLOCK_SIZE,
random.randint(0, SCREEN_HEIGHT / BLOCK_SIZE - 1) * BLOCK_SIZE)
# 游戏循环
while True:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if 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'
# 根据蛇的方向移动蛇头
if snake_direction == 'up':
snake_head = (snake[0][0], snake[0][1] - BLOCK_SIZE)
elif snake_direction == 'down':
snake_head = (snake[0][0], snake[0][1] + BLOCK_SIZE)
elif snake_direction == 'left':
snake_head = (snake[0][0] - BLOCK_SIZE, snake[0][1])
else:
snake_head = (snake[0][0] + BLOCK_SIZE, snake[0][1])
# 将蛇头加入蛇身
snake.insert(0, snake_head)
# 如果蛇头碰到边界或者碰到自己的身体,游戏结束
if snake_head[0] < 0 or snake_head[0] >= SCREEN_WIDTH or \
snake_head[1] < 0 or snake_head[1] >= SCREEN_HEIGHT or \
snake_head in snake[1:]:
pygame.quit()
quit()
# 如果蛇头碰到苹果,蛇长度加 1,重新生成苹果位置
if snake_head == apple:
snake_length += 1
apple = (random.randint(0, SCREEN_WIDTH / BLOCK_SIZE - 1) * BLOCK_SIZE,
random.randint(0, SCREEN_HEIGHT / BLOCK_SIZE - 1) * BLOCK_SIZE)
# 如果蛇长度超过了 snake_length,就删掉蛇尾
if len(snake) > snake_length:
snake.pop()
# 绘制游戏界面
screen.fill((0, 0, 0))
# 绘制蛇
for block in snake:
pygame.draw.rect(screen, SNAKE_COLOR, (block[0], block[1], BLOCK_SIZE, BLOCK_SIZE))
# 绘制苹果
pygame.draw.rect(screen, APPLE_COLOR, (apple[0], apple[1], APPLE_SIZE, APPLE_SIZE))
# 刷新界面
pygame.display.update()
# 控制游戏帧率
pygame.time.Clock().tick(10)
```
这个游戏相对比较简单,如果你想让游戏更有趣,可以添加一些特殊的道具或者障碍物。
阅读全文