Python文本游戏实现答错返回上一题功能的问题求助
文本游戏错题重选功能的问题分析与修复方案
问题分析
你的代码存在三个核心问题:
- 缩进错误:
if quit == "q"的缩进层级错误,导致它不属于question_1 == "1"的分支逻辑;即便触发重新输入,新的second变量也没有后续判断逻辑,所以选2不会有输出。 - 未覆盖所有错误分支:只处理了选1的情况,完全忽略了选3的错误选项逻辑。
- 无循环机制:没有实现重复显示题目的循环逻辑,仅靠单次输入和分支无法实现"答错后返回原题重选"的需求。
修复方案
使用while True循环来实现题目重复显示,直到用户选择正确选项;错误选项统一处理,提供返回重选的交互,具体代码如下:
while True: choice = input("You have three options 1) Try to break the window and escape. 2) Search the house for supplies. 3) Try to contact local authorities. Which do you choose?\n ") if choice == "1": print("You manage to break the window, but the glass cuts your hand and your face, you scream in pain and as the glass cuts through your face, and eventually die from the wounds.") retry = input("Press 'q' to go back to the question and try again: ") if retry != "q": break # 用户不选q则退出循环,可根据游戏需求调整 elif choice == "3": print("You try to contact authorities, but the phone line is dead and your cell has no signal. You're stuck and eventually starve to death.") retry = input("Press 'q' to go back to the question and try again: ") if retry != "q": break elif choice == "2": print("You find an array of supplies in your basement, everything from hammers, tools, weapons and food and water. You then safely break the window and jump out.") break # 选对后退出循环,衔接后续游戏内容 else: print("Invalid input! Please enter 1, 2, or 3.")
代码说明
while True创建无限循环,直到用户选对选项(执行break)或主动退出。- 每个错误选项(1、3)都有对应的剧情提示,然后询问是否返回重选;若用户输入非"q",可退出循环(逻辑可按需修改)。
- 正确选项(2)触发成功剧情后,执行
break退出循环,方便继续后续游戏流程。 - 增加了无效输入的处理,提示用户输入合法选项。
内容的提问来源于stack exchange,提问作者David Hoffman
相关产品推荐
相关产品推荐

