我正在使用 pygame 开发一个简单的 python 游戏(作为一种语言,我对它还很陌生),似乎 python 真的很讨厌循环依赖(尽管我知道有一些方法可以解决这个问题)。
一般来说,对于碰撞检测,我会有一个回调函数,一旦检测到碰撞,就会为碰撞中涉及的每个对象调用该回调函数。问题是这样做时,碰撞中涉及的每个对象都需要了解另一个对象,以便以正确的方式解决碰撞,从而导致循环依赖,我希望避免这种情况(见下文)。
这是 Enemy.py 模块:
from Player include * #dependency on player
class Enemy():
def handle_collision(other_object):
if isinstance(other_object,Player) #this check requires the Enemy class to know about Player
这是 Player.py 模块:
from enemy include * #dependency on enemy
class Player():
def handle_collision(other_object):
if isinstance(other_object,Wall):
#do what we need to do to resolve a wall collision
elif isinstance(other_object,Enemy): #this check requires that we include the Enemy class
#do what we need to do to resolve an enemy collision
任何有关通常如何处理的建议或见解都会很棒。
请您参考如下方法:
像这样的循环依赖,其中模块 player.py 导入模块 enemy.py 反之亦然,在 Python 中确实相当棘手。但是(至少)有两种方法可以解决这些问题:
首先,您无需导入模块即可使用该模块中的类。即使不导入 enemy.py 模块,您也可以使用 Enemy 类的实例,例如在它被其他模块作为参数传递给 handle_collision 方法之后。然后,您可以通过检查例如解决您的问题对于 other_object.__class__.__name__ == 'Enemy'。
这可行,但不是很好,并且会导致问题,例如 Enemy 的子类。
其次,您不必将每个类放在它自己的模块/文件中,因为它在 Java 中很常见。在 Python 中,将许多相关的类放在同一个模块中是完全正常和良好的做法。 (在 Python 中不鼓励模块之间的循环依赖的原因之一是因为需要它们被认为是糟糕的系统设计的标志。)
所以我的建议是将所有“实体”类放入同一个模块中,例如实体.py
class Entity:
def handle_collision(self, other_object):
pass
class Player(Entity):
def handle_collision(self, other_object):
if isinstance(other_object, Enemy):
# do stuff
class Enemy(Entity):
def handle_collision(self, other_object):
if isinstance(other_object, Player):
# do other stuff
请注意,循环导入在 Python 中实际上是可行的,但应谨慎使用。有关更多信息,您可以查看these。 two相关帖子。
