《笨方法學 Python 3》35.分支和函數

基礎練習: 

from sys import exit

def gold_room():
	print("This room is full of gold. How much do you take?///這個房間裏滿是金子。你要多少錢?")
	
	choice = input("> ")
	if "1" or "0" in choice:
		how_much = int(choice)
	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:
		choice = 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.///熊已經離開了門。")
			print("You can go through it now.///你現在可以通過了。")
			bear_moved = True
		elif choice == "open door" and not bear_moved:
			dead("The bear gets pissed off and chews your face off.")
		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.///我不知道那是什麼意思。")


def cthulhu_room():
	print("Here you see the great evil Cthulhu.///在這裏你可以看到巨大的邪惡的克魯斯。")
	print("He, it, whatever starts at you and you go insane.///不管你從哪裏開始,你都是極愚蠢的。")
	print("Do you flee for your life or eat your head?///你是爲了你的生命而逃跑還是讓它喫你的頭?")
	
	choice = input("> ")
	
	if "flee" in choice:
		start()
	elif "head" in choice:
		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 you right and left.///你的左右手各有一扇門。")
	print("Which one do you take?///你選哪一個?")
	
	choice = input("> ")
	
	if choice == "left":
		bear_room()
	elif choice == "right":
		cthulhu_room()
	else:
		dead("You stumble arount the room untill you starve.///你在房間四處徘徊,直到餓死。")


start()

結果:

1. 遊戲路線:去左邊房間→嘲諷熊→打開門→49金幣


 注意:代碼中有一個 while True ,它可以創建一個無限循環的代碼塊,而在這個語句中,終止循環的方法有很多,只要調用了dead函數和gold_room函數就會終止,只要未調用這兩個函數,那它就會一直執行下去。

注意:gold_room 函數中 有一段判斷代碼:if "1" or "0" in choice ,用來判斷輸入是否爲數字的,這個方法有段不太明白,還有另外的方法可以用來判斷是否爲數字: if choice.isdigit()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章