虽然循环似乎没有正确检查条件

时间:2014-01-07 18:44:19

标签: python while-loop

我正在构建游戏,作为学习代码教程的一部分。

下面的类有一个while循环,它应该返回'finished',或者离开循环并返回'death'(这些是运行游戏的dict条目),但似乎甚至没有运行。我正在查看def guess:

之后的while循环

循环旨在要求用户猜测1到3之间的数字。如果他们猜错了三次以上他们“失败”并且“死亡”被退回,否则“完成”。

但是,当我玩游戏时,我甚至没有提示输入数字,而是“太多失败的猜测,你输了!”即使猜测为0,也会打印出来。

class Smaug(Scene):

    def enter(self):
        print "Smaug is a terrifying huge fire breathing dragon, but you must get the Arkenstone from him for Thorin"       
        print "In Smaug's cave, the Lonely Mountain, Smaug notices your presence and challenges you to a game"
        print "He says \"Guess a number between 1 and 3\""
        smaugNum = random.randint(1, 3)
        print "Smaugs number cheat:", smaugNum
        guesses = 0

        def guess():

            while guesses < 4:
                print "Guess a number between 1 and 3"
                numb = raw_input("> ")

                if numb == smaugNum:
                    print "Well done! You win."
                    Player.BilbosStuff.append('arkenstone')
                    print "Now Bilbo has", Player.BilbosStuff
                    return 'finished'

                else:
                    print "You lose!"
                    guesses += 1
                    guess()

        print "Too many failed guesses, you lose!"
        return 'death'

查看代码块的嵌套,是否在while循环中返回'finished'时,是否自动将其作为更广泛类的一部分返回?换句话说,如果numb == smaugNum,那么我需要Smaug类返回完成。

3 个答案:

答案 0 :(得分:3)

问题是你根本没有调用guess()函数。你有guess()作为一个函数,根本没有被调用。因此,控件直接跳转到函数后的下一行。最好的方法是删除该函数并使用如下代码:

guesses = 0
while guesses < 4:
   print "Guess a number between 1 and 3"
   numb = raw_input("> ")
   if numb == smaugNum:
        print "Well done! You win."
        Player.BilbosStuff.append('arkenstone')
        print "Now Bilbo has", Player.BilbosStuff
        return 'finished'
  else:
        print "You lose!"
        guesses += 1

print "Too many failed guesses, you lose!"
return 'death'

答案 1 :(得分:2)

您正在guess中间定义enter smack dab,但您永远不会调用它。

块就像

class Smaug:
    def enter:
        #here's what to do when enter() is called
        def guess:
            #here's what to do when guess() is called
        #here's some more stuff to do when enter() is called

答案 2 :(得分:1)

这里的问题是你无限地递归猜测函数,并且从不首先调用guess()。

在增加猜测计数器之后,您不需要再次调用guess(),因为由于猜测次数小于4,执行仍将在while循环内,只需信任while循环即可进行比较。避免手动调用guess()。