将游戏指针传递给单位(周期性包括,python)

时间:2011-07-07 21:24:57

标签: python logic main

编辑:我正在寻求建议/正确的代码结构

目前的布局(可能是错误的)是:

  • Game存储playerscreenunits
  • Game处理顶级逻辑,用户输入等
  • screenplayer用于整个程序范围
  • units列表在游戏中被修改(添加+删除)

如果我想访问units列表,Game.spawn_foo()Game.width,我应该如何重新构建代码?

  1. 这样,units.py可以访问Game()实例吗?
  2. 代码:(已更新)

    game.py

    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()
    

    unit.py,使用func或方法

    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)
    

1 个答案:

答案 0 :(得分:0)

是否有任何理由不在每个单元中保留对游戏的引用 - 即向Unit.__init__(...)添加一行,如self.game = game,然后在你的传送方法中使用它。

我能想到的唯一原因是你可能会担心创建不会被垃圾收集的循环引用,在这种情况下你可以查看 weakref 包,尽管它可能不会在你的例子中是一个很大的问题。