Python 将对象作为列表移动
因此,在下面的代码中,我试图给出一个指示菜单。我遇到的问题是调用MakeTurtle()函数的“N”命令部分。我试图将所有海龟添加到一个列表中(children[]),因此当我遍历列表时,它会使所有海龟同时移动。问题是我只能移动一只乌龟(我创造的第一只)。以前我可以让它们全部移动,但如果我做一个新的,它就会停止工作。有人能帮忙吗Python 将对象作为列表移动,python,list,object,Python,List,Object,因此,在下面的代码中,我试图给出一个指示菜单。我遇到的问题是调用MakeTurtle()函数的“N”命令部分。我试图将所有海龟添加到一个列表中(children[]),因此当我遍历列表时,它会使所有海龟同时移动。问题是我只能移动一只乌龟(我创造的第一只)。以前我可以让它们全部移动,但如果我做一个新的,它就会停止工作。有人能帮忙吗 home = makeWorld() children = [] def MakeTurtle(): newborn = makeTurtle(home)
home = makeWorld()
children = []
def MakeTurtle():
newborn = makeTurtle(home)
children.append(newborn)
return newborn
def RoamingTurtles():
command = raw_input("---> ")
if command == 'N':
MakeTurtle()
RoamingTurtles()
if command == 'R':
for i in children:
i.turn(90)
RoamingTurtles()
if command == 'L':
for i in children:
i.turn(-90)
RoamingTurtles()
if command == 'M':
for i in children:
i.forward()
RoamingTurtles()
if command == 'Q':
print 'End'
您的问题似乎是,在调用
RoamingTurtle
函数之前,您没有等到所有子项上的循环完成。这就是为什么只有一个海龟更新。例如,您有:
for i in children:
i.forward()
RoamingTurtles()
但是,你想要:
for i in children:
i.forward()
RoamingTurtles()
我认为这是对问题的正确诊断,但我建议使用
while True
循环作为递归的替代。当然,我同意@Blckknght,在这种情况下while
循环是一个更好的选择。如果我能吻你,我会的。我是多毛的,所以这不好!但是谢谢你。我在方框上打了勾。我想这意味着你回答了我的问题。