0

我正在关注 Python 教程,但不了解此类。 http://learnpythonthehardway.org/book/ex43.html

有人可以向我解释 next_scene 方法是如何工作的。为什么会切换到下一个场景?

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

4 回答 4

0

在该方法中next_scene,您将传递一个scene_name变量。

test_map = Map('central_corridor')
test_map.next_scene('the_bridge')

传递它时the_bridge,它会检查类中的字典scenes并尝试从中获取您选择的场景。

使用该get方法,因此KeyError如果您使用无效的场景名称(例如test_map.next_scene('the_computer)调用该方法,则不会引发异常。在这种情况下,它只会返回None

于 2013-10-09T07:50:35.540 回答
0

这个next_scene名字具有误导性。它不会从某种内在顺序中给出“下一个”场景,而是返回一个您选择的场景,大概是您想要选择的下一个场景。

于 2013-10-09T07:51:32.953 回答
0

它根据您传递给它的关键字从字典中实例化一个场景对象scenes,并将其返回给您。

为什么会切换到下一个场景?

它切换到下一个场景的原因是因为在基类中,每个场景都扩展了在完成运行enter()功能后指定序列中的下一个场景:

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()  # returns next scene key
            current_scene = self.scene_map.next_scene(next_scene_name)  # initiates next scene and sets it as `current_scene`

例如最后的CentralCorridor场景取决于输入的动作返回下一个场景的键:

def enter(self):
    print "The Gothons of Planet Percal #25 have invaded your ship and destroyed"
    ...
    print "flowing around his hate filled body.  He's blocking the door to the"
    print "Armory and about to pull a weapon to blast you."

    action = raw_input("> ")

    if action == "shoot!":
        print "Quick on the draw you yank out your blaster and fire it at the Gothon."
        ...
        print "you are dead.  Then he eats you."
        return 'death'  # next scene `Death`

    elif action == "dodge!":
        print "Like a world class boxer you dodge, weave, slip and slide right"
        ...
        print "your head and eats you."
        return 'death'  # next scene `Death`

    elif action == "tell a joke":
        print "Lucky for you they made you learn Gothon insults in the academy."
        ...
        return 'laser_weapon_armory'  # next scene `LaserWeaponArmory`

    else:
        print "DOES NOT COMPUTE!"
        return 'central_corridor'  # next scene `CentralCorridor`

整个序列以enter()退出程序的死亡场景函数结束:

def enter(self):
    print Death.quips[randint(0, len(self.quips)-1)]
    exit(1)
于 2013-10-09T07:49:39.707 回答
0

return Map.scenes.get(scene_name)

Map.scenes是你的类中定义的字典。调用.get()它获取给定键的值。在这种情况下给出的键是scene_name。然后该函数返回一个场景的实例。

它类似于:

return scenes[scene_name]

除非如果密钥不存在,而不是引发 KeyError,None而是返回。

于 2013-10-09T07:49:48.897 回答