是否可以在乌龟对象中使用索引?

时间:2019-04-25 14:03:34

标签: python turtle-graphics

我正在研究乌龟的Agar.io游戏。我循环食物对象以避免编写单独的代码行。对象显示在屏幕上,但是在主循环中调用它们时,在负责碰撞的部分中,循环中只有一个对象起作用。如果我逐行创建对象,则可以正常工作,但效果并不理想。

我收到UnboundLocalError:分配前引用了本地变量'pos'

#food
dist = 20 #### distance between agario and food
food = ['af','af2','af3','af4']
food2 = []
for z in range(4):
    food[z] = t.Turtle()
    food[z].shape("square")
    food[z].turtlesize(0.8,0.8,0.8)
    food[z].color("green")
    food[z].speed(0)
    food[z].penup()
    x = r.randint(-290, 290)
    y = r.randint(-240, 240)
    food[z].goto(x, y)
    food2.append(food[z])

while True:
#contact with food
    if a.distance(food2) < dist:
        dist = dist + 1
        x = r.randint(-290, 290)
        y = r.randint(-240, 240)
        food2.goto(x,y)

回溯:

Traceback (most recent call last):
  File "c:/projects/agario.py", line 118, in <module>
    kb.setx(kb.xcor() + kb.dx)
  File "C:\Python37\lib\turtle.py", line 1808, in setx
    self._goto(Vec2D(x, self._position[1]))
  File "C:\Python37\lib\turtle.py", line 3158, in _goto
    screen._pointlist(self.currentLineItem),
  File "C:\Python37\lib\turtle.py", line 755, in _pointlist
    cl = self.cv.coords(item)
  File "<string>", line 1, in coords
  File "C:\Python37\lib\tkinter\__init__.py", line 2469, in coords
    self.tk.call((self._w, 'coords') + args))]
_tkinter.TclError: invalid command name ".!canvas"

1 个答案:

答案 0 :(得分:0)

此逻辑:

food = ['af','af2','af3','af4']
food2 = []
for z in range(4):
    food[z] = t.Turtle()

正在有效地尝试:

'af2' = t.Turtle()

这是行不通的。如果需要'af2'之类的符号,则应使用字典,否则,请清理数组逻辑:

# food
dist = 20  # distance between agario and food
food = []

for _ in range(4):
    morsel = t.Turtle("square")
    morsel.turtlesize(0.8, 0.8, 0.8)
    morsel.color("green")
    morsel.speed('fastest')
    morsel.penup()
    x = r.randint(-290, 290)
    y = r.randint(-240, 240)
    morsel.goto(x, y)
    food.append(morsel)

while True:
    # contact with food
    for morsel in food:
        if a.distance(morsel) < dist:
            dist += 1
            x = r.randint(-290, 290)
            y = r.randint(-240, 240)
            morsel.goto(x, y)

我没有足够的代码来对此进行测试,因此只是一个猜测。