Python控制台游戏:退出Inventory后返回并重新运行调用函数
Python控制台游戏背包退出返回原场景解决方案
问题描述
我正在用Python开发一款控制台游戏,其中introScene()函数用于启动游戏,玩家可从任意场景进入背包(Inventory)。当前遇到的问题是:当玩家在背包函数openInventory()中选择“exit”选项时,如何回到并重新运行调用openInventory()的函数。
原代码如下:
def introScene(): options = ["chest","stairway","inventory"] userInput = "" while userInput not in options: print("\nOptions: %s" % options) userInput = input() if userInput.lower() == "chest": chest() elif userInput.lower() == "staircase": cprint("\nYou walk down the staircase and see three doors that connect to a hallway ahead of you.", "magenta\n") staircase() elif userInput.lower() == "inventory": openInventory() else: cprint("\nPlease choose a valid option.", "black") introScene() def openInventory(): cprint("\nWhat would you like to do in your inventory?", "blue") options = ["equip","unequip","drop","view","exit"] print("\nOptions: %s" % options) command = input() if command.lower() == "view": charInv.printInv() openInventory() elif command.lower() == ("equip" or "unequip"): handleEquips(command) elif command.lower() == "drop": handleDrop() elif command.lower() == "exit": # (What do i put here?)
解决方案
核心思路是用循环替代递归,让背包函数执行完退出逻辑后自然返回调用它的场景函数,同时修复原代码中的逻辑错误:
1. 修改introScene():移除递归,改用循环避免栈溢出
原代码中else分支递归调用introScene()会导致函数栈不断堆积,改用while True循环维持场景交互,调用openInventory()后函数会自动回到循环继续运行。
def introScene(): options = ["chest", "stairway", "inventory"] while True: print("\nOptions: %s" % options) userInput = input().lower() if userInput == "chest": chest() elif userInput == "staircase": cprint("\nYou walk down the staircase and see three doors that connect to a hallway ahead of you.", "magenta") staircase() elif userInput == "inventory": openInventory() # 背包退出后自动回到此处 else: cprint("\nPlease choose a valid option.", "black")
2. 修改openInventory():用循环实现背包交互,退出时直接返回
在背包函数内部用while True循环维持菜单,选择"exit"时执行break跳出循环,函数自然结束,回到调用它的场景函数。同时修复原代码中装备选项的判断错误。
def openInventory(): while True: cprint("\nWhat would you like to do in your inventory?", "blue") options = ["equip", "unequip", "drop", "view", "exit"] print("\nOptions: %s" % options) command = input().lower() if command == "view": charInv.printInv() # 无需递归,循环会自动回到背包菜单 elif command in ["equip", "unequip"]: handleEquips(command) # 处理完装备操作后回到菜单 elif command == "drop": handleDrop() # 处理完丢弃操作后回到菜单 elif command == "exit": break # 退出循环,函数返回原场景 else: cprint("\nPlease choose a valid option.", "black")
关键说明
- 当用户在背包中选择"exit"时,
break会终止背包的循环,openInventory()函数执行完毕,自动回到调用它的introScene()循环中,继续显示场景选项。 - 原代码中的递归调用会引发栈溢出风险,改用循环结构更稳定,也符合控制台游戏的交互逻辑。
- 原代码中
command.lower() == ("equip" or "unequip")是错误逻辑,因为("equip" or "unequip")会直接返回"equip",永远无法匹配"unequip",必须改成command in ["equip", "unequip"]才能正确判断。
内容的提问来源于stack exchange,提问作者BigShrimpin14
相关产品推荐
相关产品推荐

