请你编写一段代码,功能是实现贪吃蛇小游戏
时间: 2024-03-21 11:37:43 浏览: 46
好的,以下是一个简单的 Python 贪吃蛇小游戏代码:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 定义游戏画面大小
WIDTH, HEIGHT = 640, 480
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 设置游戏标题
pygame.display.set_caption("贪吃蛇游戏")
# 定义蛇的初始位置和大小
snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
# 定义食物的初始位置
food_pos = [random.randrange(1, (WIDTH//10)) * 10, random.randrange(1, (HEIGHT//10)) * 10]
food_spawn = True
# 定义蛇的移动方向
direction = "RIGHT"
change_to = direction
# 定义蛇的移动速度
snake_speed = 10
# 定义游戏结束的函数
def game_over():
font_style = pygame.font.SysFont(None, 50)
message = font_style.render("Game Over", True, RED)
screen.blit(message, [WIDTH/2 - 100, HEIGHT/2 - 50])
pygame.display.update()
pygame.time.delay(2000)
pygame.quit()
quit()
# 游戏循环
while True:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
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 snake_pos == food_pos:
food_spawn = False
else:
snake_body.pop()
# 生成新的食物
if not food_spawn:
food_pos = [random.randrange(1, (WIDTH//10)) * 10, random.randrange(1, (HEIGHT//10)) * 10]
food_spawn = True
# 移动蛇的位置
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"
if direction == "RIGHT":
snake_pos[0] += snake_speed
elif direction == "LEFT":
snake_pos[0] -= snake_speed
elif direction == "UP":
snake_pos[1] -= snake_speed
elif direction == "DOWN":
snake_pos[1] += snake_speed
# 更新蛇的身体
snake_body.insert(0, list(snake_pos))
# 判断游戏是否结束
if snake_pos[0] < 0 or snake_pos[0] > WIDTH-10:
game_over()
elif snake_pos[1] < 0 or snake_pos[1] > HEIGHT-10:
game_over()
for block in snake_body[1:]:
if snake_pos == block:
game_over()
# 绘制游戏画面
screen.fill(BLACK)
pygame.draw.rect(screen, GREEN, [food_pos[0], food_pos[1], 10, 10])
for block in snake_body:
pygame.draw.rect(screen, WHITE, [block[0], block[1], 10, 10])
pygame.display.update()
```
这段代码用 Pygame 库实现了贪吃蛇小游戏,玩家可以通过方向键控制蛇的移动方向。游戏的规则是让蛇吃到食物,每吃到一个食物就会增加一个身体块,蛇不能碰到墙壁或自己的身体,否则游戏结束。
阅读全文