Python选择式冒险游戏选择模板函数实现问题求助
问题分析与解决方案
你的思路完全可行,用选项列表+对应函数列表的方式替代嵌套判断,是冒险游戏开发中非常高效的写法。下面直接指出代码中的问题并给出修正后的实现:
核心错误点
函数被提前执行:
你写的outcome = [theinn(), refusal(), guards()]会立即调用每个函数(因为加了()),正确的做法是存储函数对象本身(不带括号),这样只有主动调用时才会执行:outcome = [theinn, refusal, guards]输入类型错误:
input()返回的是字符串,直接执行-1会触发类型错误,必须先转为整数:mychoice = int(input()) - 1循环逻辑与笔误:
- 代码中的
carrion()是明显笔误,应删除; - 有效选择执行后需要跳出循环,否则会无限重复;
- 全局变量完全可以替换为局部变量,避免全局污染;
- 缺少对非数字输入的异常处理,会导致程序崩溃。
- 代码中的
修正后的完整代码
# 定义各个剧情分支的处理函数 def refusal(): print("You stop at the roadsign you passed on your way into town. There are only two directions - towards Tarroway, or towards Angion, the town from whence you came.") def guards(): print("The guards stop you.") def theinn(): print("You follow the joyful chatter down the deserted street. Its source is a squat, one story building. A sign above the door reads \"The Forked Tongue\"") # 选项文本列表与对应的处理函数列表 choose = [ "I walk towards the merry sounds.", "I turn on my heels and head back where I came from.", "I stay where I am and watch the night quietly." ] outcome = [theinn, refusal, guards] def multitemplate(choices, outcomes): # 遍历打印所有选项 for idx, option in enumerate(choices, start=1): print(f"{idx}) {option}") while True: try: # 获取用户输入并转换为索引 choice_idx = int(input("Enter the number of your choice: ")) - 1 # 验证索引有效性 if 0 <= choice_idx < len(choices): # 调用对应的处理函数 outcomes[choice_idx]() break # 执行完成后退出循环 else: print(f"Please enter a number between 1 and {len(choices)}.") except ValueError: # 处理非数字输入的情况 print("Please enter a valid number.") # 调用模板函数启动选择 multitemplate(choose, outcome)
思路扩展性说明
这种设计的优势非常明显:
- 新增剧情分支时,只需要添加新的选项文本到
choose列表,同时添加对应的处理函数到outcome列表即可,完全不需要修改multitemplate的核心逻辑; - 函数与选项的对应关系清晰,比嵌套的if-elif-else更易维护和阅读。
内容的提问来源于stack exchange,提问作者Reelback96
相关产品推荐
相关产品推荐

