目前的布局(可能是错误的)是:
Game
存储player
,screen
和units
。 Game
处理顶级逻辑,用户输入等screen
和player
用于整个程序范围units
列表在游戏中被修改(添加+删除)如果我想访问units
列表,Game.spawn_foo()
或Game.width
,我应该如何重新构建代码?
Game()
实例吗?class Game(object):
def __init__(self):
self.screen = # video
self.player = Player()
self.units = [Unit(), Unit()]
def loop(self):
while True:
self.screen.blit( self.player.sprite, self.player.location )
for u in self.units:
self.screen.blit( u.sprite, u.location )
def spawn_foo(self):
# tried to call from Unit() or Player()
self.units.append( ...rand Unit()... )
if __name__ == '__main__':
game = Game()
game.loop()
class Unit(object):
def __init__(self, game):
self.sprite = # image
self.location = (0, 0)
def teleport(self):
# attempt to use game here
x = game.width / 2,
y = game.height / 2
self.location = (x, y)
答案 0 :(得分:0)
是否有任何理由不在每个单元中保留对游戏的引用 - 即向Unit.__init__(...)
添加一行,如self.game = game
,然后在你的传送方法中使用它。
我能想到的唯一原因是你可能会担心创建不会被垃圾收集的循环引用,在这种情况下你可以查看 weakref 包,尽管它可能不会在你的例子中是一个很大的问题。