1. 程式人生 > >笨辦法學Python(三十一)

笨辦法學Python(三十一)

raw 冒險遊戲 utils splay oba log through nested cut

習題 31: 作出決定

這本書的上半部分你打印了一些東西,而且調用了函數,不過一切都是直線式進行的。你的腳本從最上面一行開始,一路運行到結束,但其中並沒有決定程序流向的分支點。現在你已經學了 if, else, 和 elif ,你就可以開始創建包含條件判斷的腳本了。

上一個腳本中你寫了一系列的簡單提問測試。這節的腳本中,你將需要向用戶提問,依據用戶的答案來做出決定。把腳本寫下來,多多鼓搗一陣子,看看它的工作原理是什麽。

技術分享
 1 print "You enter a dark room with two doors.  Do you go through door #1 or door #2?
" 2 3 door = raw_input("> ") 4 5 if door == "1": 6 print "There‘s a giant bear here eating a cheese cake. What do you do?" 7 print "1. Take the cake." 8 print "2. Scream at the bear." 9 10 bear = raw_input("> ") 11 12 if bear == "1": 13 print "The bear eats your face off. Good job!
" 14 elif bear == "2": 15 print "The bear eats your legs off. Good job!" 16 else: 17 print "Well, doing %s is probably better. Bear runs away." % bear 18 19 elif door == "2": 20 print "You stare into the endless abyss at Cthulhu‘s retina." 21 print "1. Blueberries.
" 22 print "2. Yellow jacket clothespins." 23 print "3. Understanding revolvers yelling melodies." 24 25 insanity = raw_input("> ") 26 27 if insanity == "1" or insanity == "2": 28 print "Your body survives powered by a mind of jello. Good job!" 29 else: 30 print "The insanity rots your eyes into a pool of muck. Good job!" 31 32 else: 33 print "You stumble around and fall on a knife and die. Good job!"
View Code

這裏的重點是你可以在“if 語句”內部再放一個“if 語句”。這是一個很強大的功能,可以用來創建嵌套(nested)的決定,其中的一個分支將引向另一個分支的子分支。

你需要理解 if 語句 包含 if 語句 的概念。做一下加分習題,這樣你會確信自己真正理解了它們。

你應該看到的結果

我在玩一個小冒險遊戲,我玩的水平不怎麽好:

技術分享

加分習題

  為遊戲添加新的部分,改變玩家做決定的位置。盡自己的能力擴展這個遊戲,不過別把遊戲弄得太怪異了。

習題練習

笨辦法學Python(三十一)