输出一个python可以运行的贪吃蛇代码
时间: 2024-06-08 17:11:23 浏览: 132
以下是一个基于Python的简单贪吃蛇游戏代码,你可以运行它并玩一下:
```python
import pygame
import random
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
# 初始化Pygame
pygame.init()
# 设置游戏窗口大小
dis_width = 800
dis_height = 600
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('贪吃蛇游戏')
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义字体
font_style = pygame.font.SysFont(None, 50)
# 定义蛇的大小和速度
snake_block = 10
snake_speed = 15
# 定义函数,用于输出信息
def message(msg, color):
mesg = font_style.render(msg, True, color)
dis.blit(mesg, [dis_width / 6, dis_height / 3])
# 定义函数,用于显示蛇的长度
def your_score(score):
value = font_style.render("Score: " + str(score), True, white)
dis.blit(value, [0, 0])
# 定义主函数
def gameLoop():
game_over = False
game_close = False
x1 = dis_width / 2
y1 = dis_height / 2
x1_change = 0
y1_change = 0
# 随机生成食物的位置
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
# 循环,直到游戏结束
while not game_over:
while game_close == True:
dis.fill(blue)
message("You Lost! Press Q-Quit or C-Play Again", red)
your_score(snake_length - 1)
pygame.display.update()
# 监听按键事件
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
gameLoop()
# 监听按键事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
# 边界检测
if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
game_close = True
# 更新蛇的位置
x1 += x1_change
y1 += y1_change
dis.fill(blue)
# 绘制食物
pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
# 绘制蛇
pygame.draw.rect(dis, black, [x1, y1, snake_block, snake_block])
pygame.display.update()
# 如果蛇吃到了食物,增加蛇的长度
if x1 == foodx and y1 == foody:
print("Yummy!!")
pygame.display.update()
# 更新食物的位置
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
# 更新蛇的长度
your_score(snake_length - 1)
pygame.display.update()
# 设置蛇的速度
clock.tick(snake_speed)
# 退出Pygame
pygame.quit()
# 退出Python
quit()
# 开始游戏
gameLoop()
```
阅读全文