0

我有 2 个类,一个用于移动单位的机器人类和一个用于跟踪它们所在位置的地图类。一个图集有一个图集类和多个机器人类。我如何使用机器人类的 Atlas 中的函数。

class Atlas:
    def __init__(self):
        self.robots = []
        self.currently_occupied = {}

    def add_robot(self, robot):
        self.robots.append(robot)
        self.currently_occupied = {robot:[]}   

    def all_occupied(self):
        return self.currently_occupied

    def occupy_spot(self, x, y, name):
        self.currently_occupied[name] = [x, y]


class Robot():
    def __init__(self, rbt):
        self.xpos = 0
        self.ypos = 0
        atlas.add_robot(rbt)  #<-- is there a better way than explicitly calling this atlas
        self.name = rbt

    def step(self, axis):
        if axis in "xX":
            self.xpos += 1 
        elif axis in "yY":
            self.ypos += 1
        atlas.occupy_spot(self.xpos, self.ypos, self.name)

    def walk(self, axis, steps=2):
        for i in range(steps):
            self.step(axis)



atlas = Atlas()  #<--  this may change in the future from 'atlas' to 'something else' and would break script
robot1 = Robot("robot1")
robot1.walk("x", 5)
robot1.walk("y", 1)
print atlas.all_occupied()

我今年 14 岁,刚接触编程。这是一个练习程序,我在 google 或 yahoo 上找不到。请帮忙

4

2 回答 2

5

您只能访问您引用的对象的方法。也许您应该将 的实例传递Atlas给初始化程序。

class Robot():
  def __init__(self, rbt, atlas):
    self.atlas = atlas
     ...
    self.atlas.add_robot(rbt)
于 2012-05-16T02:48:05.533 回答
0

这是您可以做到的一种方法

class Atlas:
    def __init__(self):
        self.robots = []
        self.currently_occupied = {}

    def add_robot(self, robot):
        self.robots.append(robot)
        self.currently_occupied[robot.name] = []
        return robot

    def all_occupied(self):
        return self.currently_occupied

    def occupy_spot(self, x, y, name):
        self.currently_occupied[name] = [x, y]


class Robot():
    def __init__(self, rbt):
        self.xpos = 0
        self.ypos = 0
        self.name = rbt

    def step(self, axis):
        if axis in "xX":
            self.xpos += 1 
        elif axis in "yY":
            self.ypos += 1
        atlas.occupy_spot(self.xpos, self.ypos, self.name)

    def walk(self, axis, steps=2):
        for i in range(steps):
            self.step(axis)



atlas = Atlas()
robot1 = atlas.add_robot(Robot("robot1"))
robot1.walk("x", 5)
robot1.walk("y", 1)
print atlas.all_occupied()
于 2012-05-16T05:12:40.293 回答