我很困惑地图和引擎类是如何一起运行这个冒险类游戏的(完整代码在这里:http://learnpythonthehardway.org/book/ex43.html)。我想我理解Map类中发生的事情,但是我真的很困惑Engine()中发生的事情以及为什么需要scene_Map变量。
class Map(object):
scenes = {
'central_corridor': CentralCorridor(),
'laser_weapon_armory': LaserWeaponArmory(),
'the_bridge': TheBridge(),
'escape_pod': EscapePod(),
'death': Death()
}
def __init__(self, start_scene):
self.start_scene = start_scene
def next_scene(self, scene_name):
return Map.scenes.get(scene_name)
def opening_scene(self):
return self.next_scene(self.start_scene)
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
while True:
print "\n--------"
next_scene_name = current_scene.enter()
current_scene = self.scene_map.next_scene(next_scene_name)
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()
谢谢你的帮助。
最佳答案
Engine
实例的scene_map
是Map
类的实例,正如全局a_map
一样。实际上,a_game.scene_map
与a_map
是同一个实例。
因此,无论您在顶层使用a_map
做什么,Engine.play
代码都可以使用self.scene_map
做。在交互式解释器中输入到a_map
定义中的所有内容并使用一个图来确保您知道它到底能为您做些什么是值得的。
那么,为什么Engine
需要self.scene_map
?为什么它不能使用globala_map
?
好吧,可以。问题是,如果你这样做了,你就不能创建两个Engine
实例,而不让它们为同一个a_map
进行斗争。(这与您不想在函数中使用全局变量的原因相同。对象不会添加新的问题事实上,对象的大部分功能是解决全局变量问题。)