2017-02-28 116 views
-1

我真的没有得到什么功能bear_moved是?为什么需要“bear_moved”?

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: 
     choice = raw_input("> ") 

     if choice == "take honey": 
      dead("The bear looks at you then slaps your face off.") 
     elif choice == "taunt bear" and not bear_moved: 
      print "The bear has moved from the door. You can go through it now." 
      bear_moved = True 
     elif choice == "taunt bear" and bear_moved: 
      dead("The bear gets pissed off and chews your leg off.") 
     elif choice == "open door" and bear_moved: 
      gold_room() 
     else: 
      print "I got no idea what that means." 

这是学习Python坚硬方式,锻炼35

+3

请注意,我强烈建议你找一本不同的书,因为现在LPTHW已经过时了(现在Python 2已经成为一种传统语言了)。 –

+3

bear_moved不是函数,它是一个指示熊是否已移动的变量。 当你嘲讽这只熊时,这个变量被设置为True,然后你可以打开门。 – sobek

+0

这看起来像一个非常腥的程序流程,因为没有任何可能的方式来打破这个循环,并且最终会越过兔子洞。你不明白布尔的什么部分? – Sayse

回答

2

这三个elif测试可以挑选其中之一的bear_moved布尔标志的影响:

elif choice == "taunt bear" and not bear_moved: 
    # ... 
elif choice == "taunt bear" and bear_moved: 
    # ... 
elif choice == "open door" and bear_moved: 
    # ... 

在你进入while环,bear_moved标志是False,所以输入taunt bear不能选择第二个选项,因为and bear_moved为false。这同样适用于open door选项;如果您在开始时输入open door,您会收到一条I got no idea what that means消息。因此该标志确保只有第一个选项可以由Python输入。

所以,当你在taunt bear键入拳头的时候,匹配elif块打印出消息(The bear has moved...),并设置bear_moved = True,之后就回到while循环的顶部。在此之后,再次输入taunt bear将Python带到第二个elif分支,因为现在and not bear_moved为假(not TrueFalse)。

在游戏中,这意味着你只能嘲讽一旦。这会让你走到门口;如果你嘲笑这只熊,你会死。

+0

哇!我真的得到了我在问题中所要求的。非常感谢。你说过:找另外一本书来学习Python。但我是新手代码,所以我想把LPTHW作为Python的指导。也许你有更好的建议? –

+0

请参阅http://sopython.com/wiki/What_tutorial_should_I_read%3F了解一些建议。 –