写一个python实现贪吃蛇
时间: 2023-03-11 10:18:51 浏览: 200
python实现贪吃蛇
答:可以这样写一个python实现贪吃蛇:import pygame
import random # 初始化游戏
pygame.init() # 创建一个游戏窗口
width = 500
height = 500
screen = pygame.display.set_mode((width, height)) # 设置窗口标题
pygame.display.set_caption('贪吃蛇') # 定义一个方块的大小
block_size = 10 # 设置帧率
fps = 10 # 定义一种颜色
white = (255, 255, 255) # 定义一个贪吃蛇的长度
snake_length = 10 # 定义贪吃蛇的位置
x1 = 250
y1 = 250 # 定义贪吃蛇走的方向
x1_change = 0
y1_change = 0 # 定义食物的位置
food_x = round(random.randrange(0, width - block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, height - block_size) / 10.0) * 10.0 # 定义一个贪吃蛇的列表
snake_list = [] # 定义一个得分
score = 0 # 开始游戏的主循环
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 = -block_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = block_size
y1_change = 0
elif event.key == pygame.K_UP:
x1_change = 0
y1_change = -block_size
elif event.key == pygame.K_DOWN:
x1_change = 0
y1_change = block_size # 计算贪吃蛇的新位置
x1 += x1_change
y1 += y1_change # 绘制贪吃蛇的新位置
screen.fill(white)
pygame.draw.rect(screen, (255, 0, 0), [food_x, food_y, block_size, block_size]) # 计算贪吃蛇的头部
head = []
head.append(x1)
head.append(y1)
snake_list.append(head) # 如果贪吃蛇的长度大于它的长度,则删除最后一个方块
if len(snake_list) > snake_length:
del snake_list[0] # 绘制贪吃蛇
for x in snake_list:
pygame.draw.rect(screen, (0, 0, 255), [x[0], x[1], block_size, block_size]) # 如果贪吃蛇吃到食物,则更新贪吃蛇的长度,更新食物的位置
if x1 == food_x and y1 == food_y:
score += 1
snake_length += 1
food_x = round(random.randrange(0, width - block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, height - block_size) / 10.0) * 10.0 # 判断游戏是否结束
if x1 > width - block_size or x1 < 0 or y1 > height - block_size or y1 < 0:
game_over = True # 判断贪吃蛇是否吃到自己
for x in snake_list[:-1]:
if x == head:
game_over = True # 更新屏幕
pygame.display.update() # 设置帧率
clock.tick(fps)
阅读全文