基于文本的Python游戏选择‘right’后陷入无限循环问题求助
问题解决:文本游戏无限循环与缩进错误修复
核心问题分析
- 无限循环根源:
Continue()函数的while循环中未添加用户输入获取语句,userinput始终为初始空字符串,永远无法匹配选项列表,导致循环无法终止。 - 缩进错误:
Continue()内的条件判断代码缩进层级混乱,不符合Python语法规范,触发缩进报错。 - 递归调用风险:
NoReturn()等函数直接递归调用entrance(),会不断加深函数调用栈,最终可能触发栈溢出错误。
修正后的完整代码
import os import sys def entrance(): print('hello please type your name in') name = input('').strip() print('hello', name) print(''' .___. /) ,-^ ^-. // / \ |WMWMWMW| |>>>>>>>>>> | />>\ />>\ |>>>>>>>>>>>>>>>>>>>>>:> `-------| |--------------| \__/ \__/ |-------------------'^^ \\ \ /|\ / \) \ \_/ / | | |+H+H+H+| \ / ^-----^ ''') print("Welcome to Run Run Run", name) print("Your mission is to find your way out of an abandoned hospital.") directions = ["left", "right", "back"] print('You awaken in what looks like the reception of the hospital. You feel like something is watching you but you ignore it. there are cobwebs and everything is in ruins. there are two doors which one do you go through?') userinput = "" while userinput not in directions: print('options: left/right/back') userinput = input().strip() if userinput == "right": TheHall() break elif userinput == "left": death1() break elif userinput == "back": NoReturn() break else: print('type a valid option') def NoReturn(): print('the door is locked you cant get out') entrance() def TheHall(): print('Continuing through the door, you have come upon a beam in the hallway. Beyond the beam, the floor appears to turn into blood. If you choose to continue down the blood path,') Continue() def Continue(): directions = ["forward", "back"] print('You have continued down the hall. It turns out blood isnt as big of a deal as the movies make it out to be. The trail leads you to a room. There is rickety wooden plank leading to the other side. At the foot of the plank there are 3 beautiful feathers. To your left there is, nothing.') userinput = "" while userinput not in directions: print('options: forward/back') userinput = input().strip() if userinput == "forward": bridge() break elif userinput == "back": entrance() break # 补全缺失函数,避免运行报错 def death1(): print("You opened the wrong door and encountered 'it'... Game Over!") entrance() def bridge(): print("You carefully cross the plank. What's next? (后续逻辑待补充)") entrance() # 启动游戏 if __name__ == "__main__": entrance()
关键修改说明
- 将
import语句移到函数外部,避免重复导入模块。 - 在
Continue()的while循环内添加userinput = input().strip(),获取用户输入并去除多余空格,解决无限循环问题。 - 给每个条件分支添加
break,退出当前循环,避免无效重复判断。 - 补全原代码缺失的
death1()和bridge()函数,避免运行时未定义错误。 - 用
strip()处理输入,去除前后空格,提升输入匹配的容错性。
内容的提问来源于stack exchange,提问作者Xtinct
相关产品推荐
相关产品推荐

