1. 程式人生 > >笨方法學Python 習題 35: 分支和函式

笨方法學Python 習題 35: 分支和函式

#!usr/bin/python
# -*-coding:utf-8-*-

from sys import exit

def gold_room():
	print("This room is full of gold.  How much do you take?")

	next = input("> ")
	if "0" in next or "1" in next:
		how_much = int(next)
	else:
		dead("Man, learn to type a number.")

	if how_much < 50:
		print("Nice, you're not greedy, you win!")
		exit(0)
	else:
		dead("You greedy bastard!")

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 = 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 cthulhu_room():
	print ("Here you see the great evil Cthulhu.")
	print ("He, it, whatever stares at you and you go insane.")
	print ("Do you flee for your life or eat your head?")

	next = input("> ")

	if "flee" in next:
		start()
	elif "head" in next:
		dead("Well that was tasty!")
	else:
		cthulhu_room()

def dead(why):
	print(why,"Good job")
	exit(0)

def start():
	print ("You are in a dark room.")
	print ("There is a door to your right and left.")
	print ("Which one do you take?")

	next = input("> ")

	if next == "left":
		bear_room()
	elif next == "right":
		cthulhu_room()
	else:
		dead("You stumble around the room until you starve.")

start()	

執行結果如下:

You are in a dark room.
There is a door to your right and left.
Which one do you take?
> left
There is a bear here.
The bear has a bunch of honey.
The fat bear is in front of another door.
How are you going to move the bear?
> taunt bear
The bear has moved from the door. You can go through it now.
> open door
This room is full of gold.  How much do you take?
> asf
Man, learn to type a number. Good job!

加分習題

把這個遊戲的地圖畫出來,把自己的路線也畫出來。


改正你所有的錯誤,包括拼寫錯誤。

為你不懂的函式寫註解。記得文件註解該怎麼寫嗎?

為遊戲新增更多元素。通過怎樣的方式可以簡化並且擴充套件遊戲的功能呢?

這個 gold_room 遊戲使用了奇怪的方式讓你鍵入一個數字。這種方式會導致什麼樣的 bug? 你可以用比檢查 0、1 更好的方式判斷輸入是否是數字嗎?int() 這個函式可以給你一些頭緒。

常見問題回答

救命啊!太難了我搞不懂!

當你搞不懂的時候,就在*每一行*程式碼的上方寫下註解,向自己解釋這一行的功能。在這個過程中如果有了新的理解,就隨時修正自己前面的註解。註解完後,就畫一個工作原理的示意圖,或者寫一段文字表述一下。這樣你就能弄懂了。

為什麼是 while True:?

這樣可以建立一個無限迴圈。

exit(0) 有什麼功能?

在很多型別的作業系統裡,``exit(0)`` 可以中斷某個程式,而其中的數字引數則用來表示程式是否是碰到錯誤而中斷。 exit(1) 表示發生了錯誤,而 exit(0) 則表示程式是正常退出的。這和我們學的布林邏輯 0==False 正好相反,不過你可以用不一樣的數字表示不同的錯誤結果。比如你可以用 exit(100) 來表示另一種和 exit(2)` 或 exit(1) 不同的錯誤。

為什麼 raw_input() 有時寫成 raw_input('> ')?

raw_input 的引數是一個會被打印出來的字串,這個字串一般用來提示使用者輸入。