您好,代码如下:
import pygame
import random
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption('Змейка')
clock = pygame.time.Clock()
x = 250
y = 250
appleWidth = 10
appleHeight = 10
width = 7
height = 7
speed = 7
direction = "right"
parts = []
apple = {}
snake = ''
isApple = False
def drawWindow():
part = []
win.fill((0, 0, 0))
snake = pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
part.append(snake)
part.append(x)
part.append(y)
parts.append(part)
pygame.display.update()
def move():
global x, y
if direction == 'right':
x += speed
elif direction == 'left':
x -= speed
elif direction == 'up':
y -= speed
elif direction == 'down':
y += speed
if x < 0:
x = 500
elif x > 500:
x = 0
if y < 0:
y = 500
elif y > 500:
y = 0
def create_apple():
global isApple
global apple
xApple = random.randint(0, 500)
yApple = random.randint(0, 500)
for part in parts:
if parts[part][1] == x and parts[part][2] == y:
create_apple()
break
pygame.draw.rect(win, (0, 255, 0), (xApple, yApple, appleWidth, appleHeight))
isApple = True
apple['x'] = x
apple['y'] = y
run = True
while run:
pygame.time.delay(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if isApple == False:
create_apple()
keys = pygame.key.get_pressed()
move()
if direction == 'right' or direction == 'left':
if keys[pygame.K_w]:
direction = "up"
elif keys[pygame.K_s]:
direction = "down"
else:
if keys[pygame.K_a]:
direction = "left"
elif keys[pygame.K_d]:
direction = "right"
drawWindow()
底线是:这些是我创造一条蛇的尝试。我正在尝试通过 create_apple() 函数创建一个蛇苹果。我运行代码,但苹果没有出现。可能是什么问题呢?如何解决?
代码中的错误不止一个,所以我只是重写了要点:
让我们从绊脚石开始,这是行
win.fill((0, 0, 0))。此功能在蛇每次移动前清屏,苹果也随之消失。为了解决这个问题,我将它更改为另一个函数,而不是完全清除它,而是绘制前一个蛇帧,但已经是黑色(该函数在尝试中被框起来,因为第一次访问数组时发生错误,前一帧还不存在)其次,现在苹果坐标是全局变量,这是必要的,这样吃苹果的检查在 body 中持续进行
while run:,而不是在苹果创建函数本身中。检查本身查看蛇是否在距离苹果为 7 的圆内,如果是,则创建一个新苹果。我把删除旧苹果框架的功能留给了你,因为它与蛇的差别不大。否则,我看不到任何特殊问题(除了不准确地使用类似的 x 和 xApple 变量,因为你对它们感到困惑)