请使用python编写一个贪吃蛇游戏
时间: 2023-09-16 22:13:41 浏览: 84
好的,以下是一个基于Python的简单贪吃蛇游戏示例。游戏使用`pygame`库实现,需要先安装该库。
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 定义游戏区域大小和格子大小
window_width = 800
window_height = 600
grid_size = 20
# 创建游戏窗口
window = pygame.display.set_mode((window_width, window_height))
# 定义颜色
black = (0, 0, 0)
white = (255, 255, 255)
green = (0, 255, 0)
red = (255, 0, 0)
# 设置游戏标题
pygame.display.set_caption("Snake Game")
# 定义字体
font = pygame.font.SysFont(None, 25)
# 定义蛇的初始位置和大小
snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
# 定义食物的初始位置
food_pos = [random.randrange(1, (window_width//grid_size)) * grid_size,
random.randrange(1, (window_height//grid_size)) * grid_size]
food_spawned = True
# 定义蛇的初始移动方向
direction = "RIGHT"
change_to = direction
# 定义游戏结束状态和得分
game_over = False
score = 0
# 定义游戏时钟
clock = pygame.time.Clock()
# 定义蛇移动的函数
def move_snake(direction, snake_body):
if direction == "RIGHT":
snake_pos[0] += grid_size
elif direction == "LEFT":
snake_pos[0] -= grid_size
elif direction == "UP":
snake_pos[1] -= grid_size
elif direction == "DOWN":
snake_pos[1] += grid_size
snake_body.insert(0, list(snake_pos))
# 游戏循环
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_RIGHT:
change_to = "RIGHT"
elif event.key == pygame.K_LEFT:
change_to = "LEFT"
elif event.key == pygame.K_UP:
change_to = "UP"
elif event.key == pygame.K_DOWN:
change_to = "DOWN"
# 检查蛇的移动方向是否合法
if change_to == "RIGHT" and direction != "LEFT":
direction = "RIGHT"
elif change_to == "LEFT" and direction != "RIGHT":
direction = "LEFT"
elif change_to == "UP" and direction != "DOWN":
direction = "UP"
elif change_to == "DOWN" and direction != "UP":
direction = "DOWN"
# 移动蛇
move_snake(direction, snake_body)
# 检查蛇是否吃到食物
if snake_pos == food_pos:
food_spawned = False
score += 1
else:
snake_body.pop()
# 重新生成食物
if not food_spawned:
food_pos = [random.randrange(1, (window_width//grid_size)) * grid_size,
random.randrange(1, (window_height//grid_size)) * grid_size]
food_spawned = True
# 绘制游戏界面
window.fill(black)
for pos in snake_body:
pygame.draw.rect(window, white, pygame.Rect(
pos[0], pos[1], grid_size, grid_size))
pygame.draw.rect(window, green, pygame.Rect(
food_pos[0], food_pos[1], grid_size, grid_size))
# 检查是否撞墙
if snake_pos[0] < 0 or snake_pos[0] > window_width-grid_size or snake_pos[1] < 0 or snake_pos[1] > window_height-grid_size:
game_over = True
# 检查是否撞到自己
for block in snake_body[1:]:
if snake_pos == block:
game_over = True
# 绘制得分
score_text = font.render("Score: " + str(score), True, white)
window.blit(score_text, [0, 0])
# 刷新游戏界面
pygame.display.update()
# 控制游戏帧率
clock.tick(10)
# 结束游戏
pygame.quit()
```
在运行游戏之前,需要安装`pygame`库:
```
pip install pygame
```
运行上述代码,即可开始游戏。玩家通过方向键控制蛇的移动方向,蛇吃到食物后得分加1。当蛇撞墙或撞到自己时,游戏结束。
阅读全文