我正在学习一个教程,它在python上创建一个基于文本的游戏来练习使用类和属性。
基本结构是Scene将成为超类,Engine将运行以进入下一个场景。
我无法理解命令的最后三行是如何工作的。
据我了解。
a_map = Map('central_corridor')
创建了一个类Map
的实例,它在__init__
中运行Map
函数,从而打印start_scene in __init__ central corridor
。
然后a_game = Engine(a_map)
创建Engine
的实例并运行__init__
Engine
,从而打印Engine __init__ has scene map, scene_map
现在我不明白打印的最后一部分
start_scene in opening_scene
start_scene in next_scene
next_scene returns _____
然后它运行a_game.play()
如果你能解释两者之间发生的事情,那就太棒了。
from sys import exit
from random import randint
class Scene(object):
def enter(self):
pass
class Engine(object):
def __init__(self, scene_map):
print "Engine __init__ has scene map", scene_map
self.scene_map = scene_map`
def play(self):
current_scene = self.scene_map.opening_scene()
print "Plays first scene", current_scene
while True:
print "\n------------"
next_scene_name = current_scene.enter()
print "next scene", next_scene_name
current_scene = self.scene_map.next_scene(next_scene_name)
class CentralCorridor(Scene):
pass
class LaserWeaponArmory(Scene):
pass
class Bridge(Scene):
pass
class EscapePod(Scene):
pass
class Death(Scene):
pass
class Map(object):
scenes = {
'central_corridor' : CentralCorridor(),
'laserweaponarmory' : LaserWeaponArmory(),
'Bridge' : Bridge(),
'escape_pod' : EscapePod(),
'Death' : Death()
}
def __init__(self, start_scene):
self.start_scene = start_scene
print "start_scene in __init__", self.start_scene
def next_scene(self, scene_name):
print "start_scene in next_scene"
val = Map.scenes.get(scene_name)
print "next_scene returns", val
return val
def opening_scene(self):
print "start_scene in opening_scene"
return self.next_scene(self.start_scene)
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()
答案 0 :(得分:1)
澄清:
start_scene in opening_scene
start_scene in next_scene
next_scene returns _____
由于
而运行a_game.play()
引擎和地图如下所示:
Engine
- scene_map <- Scene
- start_scene <- String
+ __init__()
+ next_scene()
+ opening_scene()
Map
- start_scene <- String
- scenes <- Dictionary of Scene
+ __init__()
+ play()
play()调用scene_map上的opening_scene():
self.scene_map.opening_scene()
opening_scene()使用&#34; central_corridor&#34;
调用next_scene()self.next_scene(self.start_scene)
next_scene()使用键&#34; central_corridor&#34;查找场景词典中的相关场景。这是通过
Map.scenes.get(scene_name)
场景通过方法调用链返回并存储在current_scene
中current_scene = self.scene_map.opening_scene()