文本类游戏中exit语句执行异常问题排查
文本游戏退出异常问题修复
当输入instructions后直接输入exit时,第一次输入的exit会触发无效指令提示,必须第二次输入exit才能正常退出游戏。
问题根源
原代码中处理输入的三个判断是独立的if语句,而非if-elif-else关联结构。当完成第一个len(move) < 2分支的处理后,程序会继续执行后续的判断逻辑:
- 比如输入
instructions后,程序更新move为新输入的['exit'],接着会跳过len(move)==2的判断,直接进入最后的else分支,触发无效指令提示。只有进入下一次循环时,才会重新处理len(move) < 2的分支,执行退出逻辑。
修复方案
将三个判断改为if-elif-else结构,确保每次循环只处理一个输入分支;同时把输入获取的代码移到循环开头,减少冗余代码:
修复后的完整代码:
rooms = { 'Great Hall': {'South': 'Bedroom'}, 'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'}, 'Cellar': {'West': 'Bedroom'} } def instruction(): """Function to give instructions on how to play the game""" print('Welcome to Module 6 Milestone') print('Move commands are go North, go South, go East, go West') print('Typing exit will exit the game') print('Inputting instructions will remind you of the game instructions') print('Good luck may the odds be in your favor') def invalid(): """Function for if an invalid input is entered""" print('------------') print('Whoops invalid command, try again') print('------------') def main(): """Main function that runs the movement between rooms""" current_room = 'Great Hall' print('\nYou are starting in the', current_room) directions = ['North', 'South', 'East', 'West'] # directions in the dictionary while True: # 统一在循环开头获取输入,避免重复代码 move = input('\nWhat will you do next?\n>').split() if len(move) < 2: # 处理单字输入 if 'exit' in move: # 退出游戏 print('\nThanks for playing!') break elif 'instructions' in move: # 重新打印指令 instruction() print('------------') print('\nYou are in the', current_room) else: invalid() print('You are still in the', current_room) elif len(move) == 2: # 处理双字移动指令 if move[1] in directions: # 检查是否为有效方向词 if move[1] in rooms[current_room]: # 检查当前房间是否支持该方向移动 current_room = rooms[current_room][move[1]] print('------------') print('You have found the', current_room) else: # 方向有效但当前房间无法移动 print('------------') print('Oh no it seems to be a dead end') # 修复原代码拼写错误:dead in -> dead end print('You are still in the', current_room) else: # 非有效移动指令 invalid() print('You are still in the', current_room) else: # 输入字数过多,视为无效指令 invalid() print('You are still in the', current_room) instruction() # 游戏启动时先打印指令 print('------------') if __name__ == '__main__': # 直接运行脚本时执行主函数 main()
额外优化说明
- 把输入获取逻辑移到循环开头,避免在每个分支重复编写相同代码;
- 修复了原代码中的拼写错误:
dead in改为dead end; - 通过
elif关联所有输入判断分支,确保每次循环只处理一个逻辑,避免无效分支触发。
内容的提问来源于stack exchange,提问作者chaoshunter
相关产品推荐
相关产品推荐

