Python中如何在if语句内嵌套if实现文字冒险游戏多分支
Python文字冒险游戏分支逻辑修正方案
原代码存在的核心问题
- 输入捕获逻辑断裂:
try-except块捕获到非数字输入后,没有终止当前流程,块外额外写的Choice = int(input(...))会强制要求用户二次输入,若第二次输入仍为非数字会直接导致程序崩溃 - 条件判断完全无效:
if not 1、if not 2是对固定常量做判断,1和2的布尔值恒为真,这两个分支的提示永远不会触发;判断输入是否合法必须把用户输入的变量写入条件,不能直接对常量做判断 - 分支结构不互斥:多个独立
if判断没有做分支隔离,容易出现逻辑穿透;选点燃蜡烛后的子选项既没有写输入接收逻辑,也没有做缩进嵌套,自然无法触发后续分支 - 缺少输入合法性循环校验:用户输入超出选项范围时没有重新提示的机制,直接走空逻辑
正确嵌套分支实现方法
嵌套if完全可以实现多分支剧情,核心规则是:子分支的所有逻辑(输入接收、判断、剧情输出)必须严格缩进放在对应父分支的代码块内,同层级互斥选项用if-elif-else结构收拢,避免重复判断。
修正后的可运行代码如下:
Name = input("What is your name, visitor?") print(Name + ", you are being watched. Proceed carefully. A breeze of howling wind enters the room. Within the echo, something reaches out to you and offers a candle. Do you want to light the candle?") print("1 for YES") print("2 for NO") # 第一层选项输入校验,输入不合法时循环提示 while True: try: Choice = int(input("What do you choose?")) print("Choice:", Choice) if Choice in (1, 2): break print("Please enter either 1 or 2.") except ValueError: print("Please input 1 or 2 only...") if Choice == 1: print("A flickering candlelight bursts forth. You are blinded momentarily. When your eyes adjust, you see a table, drawer, and lamp in the room. You can check:") print("1 for Table") print("2 for Drawer") print("3 for Lamp") # 嵌套子选项:仅在用户选点燃蜡烛后才会触发 while True: try: sub_choice = int(input("What do you choose?")) print("Choice:", sub_choice) if sub_choice in (1, 2, 3): break print("Please enter 1, 2 or 3 only.") except ValueError: print("Please input valid number only...") # 子分支判断,和父选项逻辑保持缩进 if sub_choice == 1: print("You approach the table. A tattered diary lies on the dust-covered surface, its pages flipped open by the wind.") # 可继续往下嵌套更深的剧情分支 elif sub_choice == 2: print("You pull the drawer open. A rusted key rolls out and hits your shoe.") # 可继续扩展后续剧情 elif sub_choice == 3: print("You touch the lamp. It suddenly lights up on its own, revealing a shadow standing right behind you in the reflection. GAME OVER.") quit() elif Choice == 2: print("You sit in silence, wondering what to do. Without sight, you're losing options. Eventually, you muster up the courage to stand up. You can't hear your own steps. Fear climbs up your throat. The floor gives way under your feet. You are swallowed by the darkness. GAME OVER.") quit()
编写注意要点
- Python靠缩进区分代码块归属,子逻辑必须比父逻辑多缩进4个空格,才会在对应条件满足时执行
- 同层级互斥的选项不要写多个独立
if,用elif承接后续分支,最后用else处理非法输入即可 - 所有用户输入环节建议搭配
while True循环做校验,不满足输入要求时直接重输,避免程序崩溃或者逻辑跳错 - 判断变量值时必须把变量写入条件表达式,不要直接对数字、字符串这类常量做真假判断
内容的提问来源于stack exchange,提问作者sentimain
相关产品推荐
相关产品推荐

