如何实现Python冒险游戏失败后的重玩功能?代码调试求助
修复后的冒险游戏代码及问题解析
原代码核心问题
- 函数内部代码未缩进,触发语法错误
- 多行输入字符串未正确处理,直接换行导致语法报错
- 失败后先调用重启函数,后续重玩询问逻辑被完全跳过
- 重玩循环未处理
no的退出逻辑,且终止循环后未退出程序 - 路径判断条件与提示文本不匹配:提示让输入
cross it,判断却用cross the lake,玩家操作无法触发失败分支 - 存在未使用的无效变量
afdfdf
修复后的完整代码
def your_adventure(): start = input("Do you want to play? ") deep_voice = "-deep voice:" # 处理初始游戏选择 while start.lower() != "yes": if start.lower() == "no": exit() start = input("Please answer with yes or no: ") name = input(f"{deep_voice} Hello adventurer, tell me your name.\n-adventurer: my name is ") path_choice = input(f"""{deep_voice} {name}, you find yourself in a jungle facing a lake without any memory — this is your story. You can "cross it", "walk around it", or "head back". What do you want to do?\n-{name}: """) # 失败分支处理 if path_choice.lower() == "cross it": print("Brave adventurer who faces problems directly!\nI like it, but unfortunately you've been eaten by an alligator.\nGAME OVER") # 重玩询问循环 while True: response = input("Wanna play again? ").lower() if response == "yes": your_adventure() break elif response == "no": exit() else: print("Please answer with yes or no.") # 可扩展其他路径逻辑 elif path_choice.lower() == "walk around it": print(f"{deep_voice} You walk around the lake and find a hidden path forward. Your adventure continues!") elif path_choice.lower() == "head back": print(f"{deep_voice} You turn back and stumble upon a mysterious village. New challenges await!") else: print("Invalid choice, please try again.") your_adventure() # 启动游戏 your_adventure()
关键修复说明
- 语法修正:统一函数内部代码缩进,用三重引号处理多行输入提示,避免语法错误
- 重玩逻辑调整:将重玩询问放在失败提示之后,确保代码执行顺序正确,玩家先看到失败提示再选择是否重玩
- 输入兼容性:用
lower()统一输入大小写,避免因大小写差异导致判断失效 - 路径匹配修复:将判断条件改为与提示文本一致的
cross it,确保玩家操作能触发对应逻辑 - 完善退出机制:用
exit()替代quit()(更规范),明确处理no的退出逻辑 - 扩展路径逻辑:补充了其他路径的基础反馈,让游戏逻辑更完整
内容的提问来源于stack exchange,提问作者TUSK ACT 4
相关产品推荐
相关产品推荐

