《笨方法学 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()

猜你喜欢

转载自blog.csdn.net/waitan2018/article/details/82916008