所以我正在使用Python在Sublime的一个项目中工作,试图制作一个贪吃蛇游戏,它一直给我这个错误:"UnboundLocalError:分配前引用的局部变量'pos'"。我已经在其他论坛上搜索了答案,但找不到任何有用的东西。请你们帮助我 到目前为止,我已经完成了代码:
import turtle
import time
import random
global pos
delay = 0.1
wn = turtle.Screen()
wn.title("Snake")
wn.bgcolor("purple")
wn.setup(width=600, height=600)
head=turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("orange")
head.penup()
head.goto(0, 0)
head.direction = "stop"
def move():
if head.direction == "up":
y = head.ycor()
head.sety(y + 20)
if head.direction == "down":
y = head.ycor()
head.sety(y - 20)
if head.direction == "left":
x = head.xcor()
head.setx(x - 20)
if head.direction == "right":
x = head.xcor()
head.setx(x + 20)
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("green")
food.penup()
food.goto(-110, 70)
def ball_move():
if head.distance("food")<20:
x = random.randit(-290, 290)
y = random.randit(-290, 290)
food.goto(x, y)
def go_up():
head.direction = "up"
def go_down():
head.direction = "down"
def go_left():
head.direction = "left"
def go_right():
head.direction = "right"
wn.listen()
wn.onkey(go_up, "Up")
wn.listen()
wn.onkey(go_down, "Down")
wn.listen()
wn.onkey(go_left, "Left")
wn.listen()
wn.onkey(go_right, "Right")
while True:
wn.update()
move()
ball_move()
time.sleep(delay)
turtle.mainloop()
完整的错误消息
Traceback (most recent call last):
File "test3.py", line 88, in <module>
ball_move()
File "test3.py", line 51, in ball_move
if head.distance("food")<20:
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/turtle.py", line 1858, in distance
return abs(pos - self._position)
UnboundLocalError: local variable 'pos' referenced before assignment
指向以下行的问题:
if head.distance("food")<20:
distance()
方法期望一个位置或另一个作为参数,而不是字符串。 在您的代码中,它应为:
if head.distance(food) < 20:
修复后,会立即失败并出现下一个错误:
random.randit()
->random.randint()