此错误是什么意思:“ UnboundLocalError:分配前已引用本地变量'pos'”

时间:2019-12-09 13:40:02

标签: python turtle-graphics

因此,我正在使用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()

1 个答案:

答案 0 :(得分:0)

完整的错误消息

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()