【问题标题】:Gather all turtles together把所有的乌龟聚集在一起
【发布时间】:2012-05-27 11:33:50
【问题描述】:

我有以下代码。代码的最后一个函数应该将孩子聚集到他们的母亲那里。

class MotherTurtle(Turtle):  
    def __init__(self, home):
        Turtle.__init__(self, home)
        self.children = []
        self.home = home
        self.setName("Mum")
        
    def giveBirth(self, name):
        newborn = Turtle(self.home)
        newborn.setName (name)
        self.children.append(newborn)
        return newborn
        
    def greetChildren(self):
        for child in self.children:
            print "Hi %s" %(child.name)
                
    def gatherChildren(self):
        for child in self.children:
            child.moveTo(self.home)

我需要把孩子们带到他们的妈妈身边。

这是我运行程序时遇到的错误:

======= Loading Progam =======
>>> world = makeWorld()
>>> mum = MotherTurtle(world)
>>> mary = mum.giveBirth("Mary")
>>> jimmy = mum.giveBirth("Jimmy")
>>> mum.greetChildren()
Hi Mary
Hi Jimmy
>>> mary.turn(-45)
>>> mary.forward(120)
>>> jimmy.turn(90)
>>> jimmy.forward()
>>> mum.gatherChildren()

错误是:

'list' 对象没有属性 'moveTo' 未找到属性。 您正在尝试访问不存在的对象的一部分。 请检查 C:\Users\user\Desktop\159171 的第 21 行

【问题讨论】:

  • 错误是否有堆栈跟踪?可以分享一下吗?
  • 你也应该去接受一些关于你其他问题的答案。

标签: python turtle-graphics


【解决方案1】:

方法如下:

def gatherChildren(self):
    
    # get the position of the mother turtle    
    mumX = self.getXPos()
    mumY = self.getYPos()
    # use an offset so not all turtles are on top of each other
    spacing = 10
    offset = spacing
    # loop through the list of children to place each child close to the mother
    for child in self.children:
      child.moveTo(mumX + offset, mumY + offset)
      offset = offset + spacing

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多