这是一个简单的游戏,主要是使用了函数的定义,不同的分支调用
from sys import exit #exit(0)无错误退出,exit(1)有错误退出
def gold_room():
print("This room is full of gold,how much do you want to take?")
next = input('>')
if '0' in next or '1' in next:
how_much = int(next) #把next改为整型
else:
dead("Man,learn to type a number.")
if how_much < 50:
print("Great,you're not greedy.")
exit(0)
else:
dead("You greedy bastard.")
def bear_room():
print("There is a bear here with lots of money.")
print("The fat bear is in front of another door,how are you going to move the bear?")
bear_moved = False #把bear_moved定义成false,也即熊在前面
while True: #这里可以重复下面的循环,直到dead或gold_room才有exit
next = input('>')
if next == "take money":
dead("The bear looks at you and 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 #此时熊已经离开,将其定义为离开即可,但是这个True只在这个elif里面生效
elif next == "taunt bear" and bear_moved: #恐吓熊,但它并没有离开
dead("The bear will eat your leg.")
elif next == "open door" and bear_moved: #这里要确保taunt bear使得bear_moved为True之后才能执行gold_room函数
gold_room()
else:
print("I got no idea what the means.")
def cthulhu_room():
print("Here you see the great evil Cthulhu.")
print("You are dangerous.")
print("Do you flee for your life or eat your head?")
next = input('>')
if "flee" in next:
start() #调用start函数
elif "head" in next:
dead("It's tasty!")
else: #输入其他内容则重新执行函数
cthulhu_room()
#dead()是被调用到的函数
def dead(why): #dead函数的作用是返回参数本身,然后退出
print(why,"Good job.")
exit(0)
def start():
print("You are in a dark room.")
print("There is a door to your left and right.")
print("Which one do you take?")
next = input('>')
if next == "left":
bear_room()
elif next == "right":
cthulhu_room()
else:
print("You stumble around the room until you starve")
start()
运行结果
PS E:\tonyc\Documents\Vs workspace> cd ‘e:\tonyc\Documents\Vs workspace’; ${env:PYTHONIOENCODING}=‘UTF-8’; ${env:PYTHONUNBUFFERED}=‘1’; & ‘D:\Anboot\Python\python.exe’ ‘c:\Users\tonyc.vscode\extensions\ms-python.python-2019.3.6558\pythonFiles\ptvsd_launcher.py’ ‘–default’ ‘–client’ ‘–host’ ‘localhost’ ‘–port’ ‘49227’ ‘e:\tonyc\Documents\Vs workspace\The Hard Way\ex35(分支和
函数).py’
You are in a dark room.
There is a door to your left and right.
Which one do you take?
left
There is a bear here with lots of money.
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 want to take?
30
Great,you’re not greedy.
当然,还有很多一些情况没有完全体现出来,具体流程如下