初学者Python:如何在while循环中给ELSE提供不同的响应

时间:2014-08-07 23:38:37

标签: python python-2.7

所以,我正在通过学​​习Python艰难的方式,我在第36课,在那里我根据他在第35课中所做的那样制作我自己的BBS文本风格的游戏。

http://learnpythonthehardway.org/book/ex36.html

http://learnpythonthehardway.org/book/ex35.html

所以,我做了一份体面的工作,但是我注意到当我模仿他永恒的while循环时,玩家不能在任何特定情况下离开房间,循环总是给出相同的响应。否则......除非他们说正确的话,否则他们会永远陷入困境。

这是我的代码:

def sleeping_giant():
    print "There is a single door, with a giant sleeping in front of it."
    print "How can you get the giant to move?"
    print "Should you wake him?"
    giant_moved = False

    while True:
        choice = raw_input("> ")

        if choice == "Yes":
            dead("The giant rips you into four pieces and uses your quartered body as a      stack of pillows.")
        elif choice == "No" and not giant_moved: 
            print "The giant rolls in his sleep, clearing an easy path to the door."
            giant_moved = True 
        elif "Open" or "Go" in choice and giant_moved:
            treasure_room()
        else:
            print "I have no idea what the fuck you are trying to say to me.  English.     Do you speak it?!"

如果该格式转换不好,请道歉。

无论如何,只要用户输入不满足if或elif的内容,他们就会收到相同的其他回复。

我该如何改变?如同,使它更具动态性,以便如果他们继续搞砸响应,那么else响应会改变吗?

我无法弄清楚如何让代码说出来(用非文字术语,我的意思是,我无法说出逻辑),'如果使用了else,那么响应应该是新的,并且一旦使用了它,它应该是另一个其他响应'。

如果这没有意义,请告诉我。

2 个答案:

答案 0 :(得分:3)

这个条件:

    elif "Open" or "Go" in choice and giant_moved:

解析如下(根据operator precedence):

    elif "Open" or (("Go" in choice) and giant_moved):

由于"Open"被视为True,因此此条件将始终匹配。听起来你可能想要:

    elif ("Open" in choice or "Go" in choice) and giant_moved:

要选择不同的回复,请尝试以下内容:

    else:
        responses = [
            "Nice try. Try again.",
            "Sorry, what was that?",
            "I don't know what that means.",
        ]
        print random.choice(responses)

答案 1 :(得分:3)

这是Greg使用计数器的答案的增量版本,因此您可以获得可预测的响应顺序:

global responses = [ "Nice try. Try again.",
        "Sorry, what was that?",
        "I don't know what that means."]
def sleeping_giant():
   counter = 0
   print "There is a single door, with a giant sleeping in front of it."
   print "How can you get the giant to move?"
   print "Should you wake him?"
   giant_moved = False

   while True:
       choice = raw_input("> ")

       if choice == "Yes":
           dead("The giant rips you into four pieces and uses your quartered body as a      stack of pillows.")
       elif choice == "No" and not giant_moved: 
           print "The giant rolls in his sleep, clearing an easy path to the door."
           giant_moved = True 
       elif ("Open" in choice or "Go" in choice) and giant_moved:
           treasure_room()
       else:
           print responses[counter]
           if counter < 2:
              counter += 1