Skip to main content
 首页 » 编程设计

Python(艰难地学习 Python 练习 35)

2025年05月04日19zdz8207

我目前正在研究 Zed Shaw 的 Learn Python the Hard Way。

在exercise 35 , 找到一个包含这些行的程序:

def bear_room(): 
    print "There is a bear here." 
    print "The bear has a bunch of honey." 
    print "The fat bear is in front of another door." 
    print "How are you going to move the bear?" 
    bear_moved = False 
 
    while True: 
        next = raw_input("> ") 
 
        if next == "take honey": 
            dead("The bear looks at you then slaps your face off.") 
        elif next == "taunt bear" and not bear_moved: 
            print "The bear has moved from the door. You can go through it now." 
            bear_moved = True 
        elif next == "taunt bear" and bear_moved: 
            dead("The bear gets pissed off and chews your leg off.") 
        elif next == "open door" and bear_moved: 
            gold_room() 
        else: 
            print "I got no idea what that means." 

一切顺利。但我想在输掉比赛之前给玩家额外的生存机会和警告。我想到了这个:

def bear_room(): 
    print "There is a bear here." 
    print "There bear has a bunch of honey." 
    print "The fat bear is in front of another door." 
    print "How are you going to move the bear?" 
    bear_moved = False 
    bear_moved_again = False 
 
    while True: 
        next = raw_input("> ") 
 
        if next == "take honey": 
            dead("The bear looks at you then slaps your face off.") 
        elif next == "taunt bear" and not bear_moved: 
            print "The bear as moved from the door. You can go through it now." 
            bear_moved = True 
        elif next == "taunt bear" and bear_moved: 
            print "The bear is getting angry. Don't taunt him again." 
            bear_moved_again = True     
        elif next == "taunt bear" and bear_moved_again: 
            dead("The bear gets pissed off and chews your leg off.") 
        elif next == "open door" and bear_moved: 
            gold_room() 
        else: 
            print "I got no idea what that means." 

不起作用:如果我多次 mock 熊,我得到的只是:“熊生气了。不要再 mock 他了。”字符串,一遍又一遍,然而,我希望玩家在输掉之前只能 mock 动物两次(第一次移动它,第二次得到警告)。你知道为什么吗?

另一个问题:如果 bear_moved 设置为 False(第 6 行),并且(第 13 行)说:

elif next == "taunt bear" and not bear_moved: 

不会“并且不会”将 bear_moved 设置为 True 吗?

如有任何帮助,我们将不胜感激。

请您参考如下方法:

换行

elif next == "taunt bear" and bear_moved: 

到

elif next == "taunt bear" and bear_moved and not bear_moved_again: 

和线

elif next == "taunt bear" and bear_moved_again: 

到

elif next == "taunt bear" and bear_moved and bear_moved_again: 

在您的原始版本中,句子“elif next == “taunt bear”和 bear_moved:”在“elif next == “taunt bear”和 bear_moved_again”之前进行了测试。如果您多次输入“taunt bear”,“elif next == "taunt bear"and not bear_moved”和“elif next == “taunt bear” and bear_moved”之一将始终为真。测试“elif next == “taunt bear”和 bear_moved_again”将永远不会被采用。