生成一段python代码,实现贪吃蛇
时间: 2023-03-30 15:00:31 浏览: 94
python实现贪吃蛇 代码
很高兴回答你的问题。以下是一段简单的 Python 代码,可以实现贪吃蛇游戏:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 定义颜色
white = (255, 255, 255)
black = (, , )
red = (255, , )
# 定义游戏窗口大小
width = 600
height = 400
# 创建游戏窗口
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("贪吃蛇")
# 定义蛇的初始位置和大小
snake_block = 10
snake_speed = 15
x1 = width / 2
y1 = height / 2
# 定义蛇的移动方向
x1_change =
y1_change =
# 定义食物的初始位置
foodx = round(random.randrange(, width - snake_block) / 10.) * 10.
foody = round(random.randrange(, height - snake_block) / 10.) * 10.
# 定义字体
font_style = pygame.font.SysFont(None, 30)
# 定义显示分数的函数
def message(msg, color):
mesg = font_style.render(msg, True, color)
screen.blit(mesg, [width / 6, height / 6])
# 游戏循环
game_over = False
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 =
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change =
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change =
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change =
# 判断蛇是否撞墙
if x1 >= width or x1 < or y1 >= height or y1 < :
game_over = True
# 移动蛇的位置
x1 += x1_change
y1 += y1_change
# 绘制蛇和食物
screen.fill(black)
pygame.draw.rect(screen, red, [foodx, foody, snake_block, snake_block])
pygame.draw.rect(screen, white, [x1, y1, snake_block, snake_block])
# 判断蛇是否吃到食物
if x1 == foodx and y1 == foody:
print("Yummy!!")
pygame.display.update()
# 显示分数
message("Your Score: ", white)
# 控制游戏速度
clock = pygame.time.Clock()
clock.tick(snake_speed)
# 退出 Pygame
pygame.quit()
```
阅读全文