帮我写个可运行的贪吃蛇python代码
时间: 2023-12-02 11:04:03 浏览: 99
以下是一个简单的贪吃蛇Python代码,可在Python 3中运行:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 定义窗口大小
WINDOW_WIDTH = 400
WINDOW_HEIGHT = 400
# 创建窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('贪吃蛇')
# 设置帧率
clock = pygame.time.Clock()
FPS = 10
# 定义贪吃蛇和食物
snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
food_pos = [random.randrange(1, (WINDOW_WIDTH//10)) * 10, random.randrange(1, (WINDOW_HEIGHT//10)) * 10]
food_spawn = True
# 定义方向
direction = 'RIGHT'
change_to = direction
# 定义字体
font_style = pygame.font.SysFont(None, 30)
def message(msg, color):
"""
显示消息
"""
mesg = font_style.render(msg, True, color)
window.blit(mesg, [WINDOW_WIDTH/6, WINDOW_HEIGHT/3])
def game_over():
"""
游戏结束
"""
message('你输了,再试一次吧', RED)
pygame.display.update()
pygame.time.delay(2000)
game_loop()
def draw_snake(snake_body):
"""
绘制贪吃蛇
"""
for pos in snake_body:
pygame.draw.rect(window, GREEN, pygame.Rect(
pos[0], pos[1], 10, 10))
def draw_food(food_pos):
"""
绘制食物
"""
pygame.draw.rect(window, RED, pygame.Rect(
food_pos[0], food_pos[1], 10, 10))
def game_loop():
"""
游戏循环
"""
# 定义全局变量
global direction, change_to, snake_pos, snake_body, food_pos, food_spawn
# 游戏循环标志
game_exit = False
while not game_exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and direction != 'DOWN':
change_to = 'UP'
elif event.key == pygame.K_DOWN and direction != 'UP':
change_to = 'DOWN'
elif event.key == pygame.K_LEFT and direction != 'RIGHT':
change_to = 'LEFT'
elif event.key == pygame.K_RIGHT and direction != 'LEFT':
change_to = 'RIGHT'
# 改变方向
direction = change_to
# 移动贪吃蛇
if direction == 'UP':
snake_pos[1] -= 10
elif direction == 'DOWN':
snake_pos[1] += 10
elif direction == 'LEFT':
snake_pos[0] -= 10
elif direction == 'RIGHT':
snake_pos[0] += 10
# 增加贪吃蛇长度
snake_body.insert(0, list(snake_pos))
if snake_pos == food_pos:
food_spawn = False
else:
snake_body.pop()
# 生成食物
if not food_spawn:
food_pos = [random.randrange(
1, (WINDOW_WIDTH//10)) * 10, random.randrange(1, (WINDOW_HEIGHT//10)) * 10]
food_spawn = True
# 绘制游戏界面
window.fill(BLACK)
draw_snake(snake_body)
draw_food(food_pos)
pygame.display.update()
# 碰撞检测
if snake_pos[0] < 0 or snake_pos[0] > WINDOW_WIDTH-10:
game_over()
elif snake_pos[1] < 0 or snake_pos[1] > WINDOW_HEIGHT-10:
game_over()
for block in snake_body[1:]:
if snake_pos == block:
game_over()
# 设置帧率
clock.tick(FPS)
# 关闭pygame
pygame.quit()
quit()
# 开始游戏循环
game_loop()
```
运行代码后,会弹出一个窗口,贪吃蛇会自动移动,你需要控制贪吃蛇的方向,让它吃到食物,不要碰到墙壁或自己的身体,否则游戏失败。
阅读全文