【发布时间】:2014-01-27 15:55:11
【问题描述】:
我正在使用 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
任何关于通常如何处理的建议或见解都会很棒。
【问题讨论】:
-
这里并没有真正看到循环性。你能解释更多吗?
-
不确定您在问什么,但 (1) 在
Player.handle_collision中仅处理玩家的碰撞结果,而不是其他对象(处理他们handle_collision方法); (2) 为“动作”或“更新”创建一个队列,并在检测到所有冲突后应用这些。 -
具体来说,依赖来自回调中的 if 检查。例如if isinstance(other_object, "Wall"):
-
我想从技术上讲,我可以向处理程序传递一个字符串,指示它与哪个对象发生碰撞?
-
当两个对象发生碰撞时,调用两者的处理程序,另一个作为参数。仍然看不到周期性。也许您应该包括依赖关系的双方以使其清楚。
标签: python collision-detection game-engine circular-dependency