《笨方法学 Python 3》35.分支和函数

本文介绍了一个使用Python编写的文本冒险游戏,玩家通过选择不同的行动来探索房间、与熊互动并解决谜题,最终找到充满黄金的房间。游戏设计包含无限循环、条件判断和函数调用等编程概念。

基础练习: 

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()

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值