Python:类;“谈话”;互相

Python:类;“谈话”;互相,python,class,communication,Python,Class,Communication,我是一名大学生。我在上第二节comp-sci课程,我们还没有太多的过去,只是简单地在其中创建类和函数,所以我还没有真正能够充分利用我在互联网上找到的复杂术语 我正在制作一个蟑螂侵扰的sim卡,我需要有一个“蟑螂”类能够探测到窗口中的“食物”类。我的老师告诉我,我最好的办法可能是让另一个像班主任一样的人成为介于两者之间的中间人,但我真的不知道这是怎么回事。有人能帮我吗?我通过印花布使用Python。下面是我对roach类的了解(编辑:我想我也应该显示main()等): 类蟑螂: 定义初始(自我、胜

我是一名大学生。我在上第二节comp-sci课程,我们还没有太多的过去,只是简单地在其中创建类和函数,所以我还没有真正能够充分利用我在互联网上找到的复杂术语

我正在制作一个蟑螂侵扰的sim卡,我需要有一个“蟑螂”类能够探测到窗口中的“食物”类。我的老师告诉我,我最好的办法可能是让另一个像班主任一样的人成为介于两者之间的中间人,但我真的不知道这是怎么回事。有人能帮我吗?我通过印花布使用Python。下面是我对roach类的了解(编辑:我想我也应该显示main()等):

类蟑螂:
定义初始(自我、胜利、地点、地点):
self.timer=320+(10*(int(10*random.random()))
自身速度=0.2
自航向=360
self.win=win
self.x=placex
self.y=placey
self.body=self.makeBody()
self.body.draw(self.win)
定义(自我):
t=“Roach at(“+str(self.x)+”、“+str(self.y)+”)
返回t
def makeBody(自身):
主体=矩形(-5,-5,(5,5))
body.setFill(颜色('Brown'))
body.moveTo(self.x,self.y)
返回体
def移动(自我,赢):
self.x=self.x+self.speed*sin(self.heading)
self.y=self.y+self.speed*cos(self.heading)
self.body.moveTo(self.x,self.y)
避免(赢)
def避免(自我,赢):
边框=假
如果self.x>=win.getWidth():
自设置标题(随机随机随机范围(91269))
self.x=win.getWidth()-1
边框=真
elif self.x=win.getHeight():
自设置标题(随机随机随机范围(1179))
self.y=win.getHeight()-1
边框=真

elif self.y这里有一个大概的轮廓,你可以使用一个额外的“Master”类来允许另外两个类进行交流,正如OP中提到的:

class Master():
    ...
    def is_food_there(self, coords):
        for food_instance in self.food_instances:
            if coords == food_instance.coords:
                return True

class Food():
    def __init__(self, master_instance):
        self.coords = ###some coordinates or whatever
        master_instance.food_instances.append(self) ### register this food with master

class Roach():
    def __init__(self, master_instance):
        self.master_instance = master_instance
    ...
    def move(self, newlocation):
        if( self.master_instance.is_food_there(newlocation) ): ### check with master for food coords
            ###do something

其思想是我们有一个主类,它本质上是一个食品实例列表的容器,Roach类知道它属于哪个主实例,因此它可以访问该主类的“is_Food_there”函数,该函数反过来查看属于它的食品实例。在这个例子中,大师班是“中间人”。

谢谢你。只是一个简单的问题:“master_instance”是指“master=master()”还是指master类的一个属性(对于食物也是这个问题)?我只是在理解如何重新格式化代码时遇到了一点小问题。是的,我想你已经有了
master=master()
将创建名为
master
master
类的实例。对于
Roach
类,每个
Roach
实例将有一个属性
master\u实例
,该属性指向
Roach
实例所属的
master
类的实例
class Master():
    ...
    def is_food_there(self, coords):
        for food_instance in self.food_instances:
            if coords == food_instance.coords:
                return True

class Food():
    def __init__(self, master_instance):
        self.coords = ###some coordinates or whatever
        master_instance.food_instances.append(self) ### register this food with master

class Roach():
    def __init__(self, master_instance):
        self.master_instance = master_instance
    ...
    def move(self, newlocation):
        if( self.master_instance.is_food_there(newlocation) ): ### check with master for food coords
            ###do something