将游戏指针传递给单元(循环包含,python)
编辑:我正在寻求建议/正确的代码结构
当前布局(可能是错误的)是:
Game
存储player
、screen
和单位
。Game
处理顶级逻辑、用户输入等screen
和player
使用整个程序范围units
列表在游戏中被修改(添加+删除)
如果我想访问 units
列表,或 Game.spawn_foo()
或 Game.width
,如何我应该重构我的代码吗?
- 这样units.py就可以访问Game()实例了?
代码:(更新)
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)
edit: I'm asking for advice / correct structure for code
The current layout (which is probably wrong), is:
Game
storesplayer
,screen
, andunits
.Game
handles top level logic, user input, etcscreen
andplayer
are used entire-program-scopeunits
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?
- 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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是否有任何理由不在每个单元中保留对游戏的引用 - 即向
Unit.__init__(...)
添加一行,如self.game = game
然后在你的传送方法中使用它。我能想到的唯一原因是您可能担心创建不会被垃圾收集的循环引用,在这种情况下您可以查看 weakref 包,尽管它可能不多你的例子中的一个问题。
Is there any reason not to keep a reference to game within each unit - ie adding a line to
Unit.__init__(...)
likeself.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.