将所有海龟聚集在一起

时间:2012-05-27 11:33:51

标签: python turtle-graphics

我有以下代码。代码的最后一个功能是将孩子们聚集到他们的母亲身上。

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)

我需要将孩子们聚集到他们的母亲身边。

enter image description here

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

======= 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' object has no attribute 'moveTo'
Attribute not found.
You are trying to access a part of the object that doesn't exist.
Please check line 21 of C:\Users\user\Desktop\159171

1 个答案:

答案 0 :(得分:0)

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