学习Python的硬方式ex43循环问题



我目前正在努力学习Python中的这一练习,并且正在为一个小问题而挣扎。每当我到达LaserWeaponArmory(scene)部分,它将在执行实际死亡场景之前循环两次。从本质上讲,我可以尝试20次猜测门的代码,而不是10次。在接下来的10次尝试之前,它将循环回到场景的开始。之后,它将正常退出。

对象和类对我来说开始更有意义了,但我现在只是在寻找解决这个问题的方向。如果有人能给我任何建议,我将不胜感激!

我已经在下面提供了我认为与我的问题相关的代码,但我仍然是一个n00b,所以如果你需要看到更多来回答我的问题,请告诉我!

class Scene(object):
    def enter(self):
         print "This scene is not yet configured. Subclass it and implement enter()."
         exit(1)
class Engine(object):
    def __init__(self, scene_map):
        self.scene_map = scene_map
    def play(self):
        current_scene = self.scene_map.opening_scene()
        last_scene = self.scene_map.next_scene('finished')
        while current_scene != last_scene:
            next_scene_name = current_scene.enter()
            current_scene = self.scene_map.next_scene(next_scene_name)
            # be sure to print out the last scene
            current_scene.enter()
class Death(Scene):
    quips = [
        "You died. You kind suck at this.",
        "Your mom would be proud...if she were smarter.",
        "Such a luser.",
        "I have a small puppy that's better at this."
    ]
    def enter(self):
        print Death.quips[randint(0, len(self.quips)-1)]
        exit(1)
class LaserWeaponArmory(Scene):
    def enter(self):
        print "You do a dive roll into the Weapon Armory, crouch and scan the room"
        print "for more Gothons that might be hiding. It's dead quiet, too quiet."
        print "You stand up and run to the far side of the room and find the"
        print "neutron bomb and it's container. There's a keypad lock on the box"
        print "and you need the code to get the bomb out. If you get the code"
        print "wrong 10 times then lock closes forever and you can't"
        print "get the bomb. The code is 3 digits."
        code = "%d%d%d" % (randint(1, 9), randint(1,9), randint(1,9))
        guesses = 0
        attempt = 1
        print "Attempt number %s." % attempt
        guess = raw_input("[keypad]> ")

        while guess != code and guesses != 9:
            print "BZZZZZZEDDD!"
            guesses += 1
            attempt += 1
            print "Attempt number %s." % attempt
            guess = raw_input("[keypad]> ")
        if guess == code:
            print "The container clicks open and the seal breaks, letting gas out."
            print "You grab the neutron bomb and run as fast as you can to the"
            print "bridge where you must place it in the right spot."
            return 'the_bridge'
        else:
            print "The lock buzzes one last time and then you hear a sickening"
            print "melting sound as the mechanism is fused together."
            print "You decide to sit there, and finally the Gothons blow up the"
            print "ship from their ship and you die."
            return 'death'

Engine循环中,每个场景enter两次。第一次是最后一行:

current_scene.enter()

第二次是当你重新进入循环时:

next_scene_name = current_scene.enter()

我认为最后一行应该在while循环之外。只需取消缩进即可:)

最新更新