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

Is it possible to use indexing in turtle objects?

我正在用 turtle 开发 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"

这个逻辑:

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)

我没有足够的代码来测试这个,所以这只是一个猜测。