开发者

passing game pointer to units (cyclical includes, python)

edit: I'm asking for advice / correct structure for code

The current layout (which is probably wrong), is:

  • Game stores player, screen, and units.
  • Game 开发者_开发技巧handles top level logic, user input, etc
  • screen and player are used entire-program-scope
  • units list is modified (added+removed) in game

If I want access to units list, or Game.spawn_foo() or Game.width, how should I restructure my code?

  1. So that units.py can have access to the Game() instance?

Code: (updated)

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 , uses func or methods

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)


Is there any reason not to keep a reference to game within each unit - ie adding a line to Unit.__init__(...) like self.game = game and then using this in your teleport method.

The only reason I can think of is that you might be worried about creating cyclic references which won't be garbage collected, in which case you could look at the weakref package, although it might not be much of an issue in your example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜