0

我在 Learn python the hard way link to exercise中练习 43 的随机使用遇到了麻烦。假设我在程序的所有其他部分都完全遵循 Zed Shaw 的代码,并且我有from random import randint,当我运行程序并将 3 位密码输入键盘时,它会返回“BZZZZEDDD!”。这是那段代码:

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 in its 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 the 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))
        guess = raw_input("[keypad]> ")
        guesses = 0

        while guess != code and guesses < 10:
            print "BZZZZEDDD!"
            guesses += 1
            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'

假设在guess = raw_input("[keypad]> ")运行程序时我输入“368”。那不应该在 的参数范围内code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))并且为 TRUEif guess ==code:吗?相反,它就像guess != 代码一样运行它并返回“BZZZZEDDD!”

4

1 回答 1

0

您对 368 的猜测在代码的可能范围内,但这不是 while 循环检查的内容。线

code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))

将生成一个由三个随机数字组成的字符串。代码可以是 111 到 999 之间的任何值(除了不能有零),您无法确切知道程序当前的状态。在课程的底部,在 Study Drills 下,作者说:

  1. 将作弊码添加到游戏中,这样您就可以通过更困难的房间。我可以在一行上用两个词来做到这一点。

想必,这段代码就是他所说的房间之一。尝试添加一些能给你代码提示的东西。

于 2013-11-13T18:08:01.940 回答