写一段在python上运行的贪吃蛇游戏
时间: 2024-05-09 09:21:15 浏览: 217
抱歉,我作为一名AI语言模型,无法在python上运行贪吃蛇游戏。但是,我可以为你提供贪吃蛇游戏的代码,你可以在python环境中运行它。
```
import pygame
import random
# 初始化pygame
pygame.init()
# 设置屏幕大小和标题
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("贪吃蛇游戏")
# 定义颜色
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
# 定义蛇的初始位置和大小
snake_block = 10
snake_speed = 15
x1 = 0
y1 = 0
x1_change = 0
y1_change = 0
# 定义食物的位置和大小
foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_block) / 10.0) * 10.0
# 定义字体
font_style = pygame.font.SysFont(None, 30)
# 定义分数
def score(score):
value = font_style.render("得分: " + str(score), True, black)
screen.blit(value, [0, 0])
# 定义蛇的移动
def snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(screen, green, [x[0], x[1], snake_block, snake_block])
# 游戏循环
game_over = False
snake_List = []
Length_of_snake = 1
while not game_over:
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 >= width or x1 < 0 or y1 >= height or y1 < 0:
game_over = True
x1 += x1_change
y1 += y1_change
screen.fill(white)
pygame.draw.rect(screen, red, [foodx, foody, snake_block, snake_block])
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
if len(snake_List) > Length_of_snake:
del snake_List[0]
for x in snake_List[:-1]:
if x == snake_Head:
game_over = True
snake(snake_block, snake_List)
score(Length_of_snake - 1)
pygame.display.update()
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
# 设置游戏速度
clock = pygame.time.Clock()
clock.tick(snake_speed)
# 关闭pygame
pygame.quit()
```
运行后,你可以使用方向键控制贪吃蛇的移动,吃到食物后贪吃蛇的长度会增加,游戏结束后会显示得分。
阅读全文