Python房间移动程序触发invalid()函数后陷入无限循环求助
解决房间移动代码的无限循环问题
问题根源
触发invalid()函数后,程序获取新输入时没有调用.split()方法,导致move变量从列表类型变成了字符串类型。后续循环中,字符串的长度判断逻辑完全失效:
- 即使输入合法指令(如
go North),move是字符串,len(move)会是字符串的字符数(比如"go North"长度为7),进入len(move)>=2分支 - 此时
move[1]取的是字符串第二个字符(如"o"),永远不会匹配方向列表['North', 'South', 'East', 'West'],因此反复触发invalid(),陷入无限循环
修复方案
所有获取用户输入的位置,统一使用.split()处理输入,确保move始终保持列表类型。修改后的完整代码如下:
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 directions will remind you of the move commands') 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) move = input('What will you do next?\n>').split() directions = ['North', 'South', 'East', 'West'] while True: if len(move) < 2: if 'exit' in move: print('\nThanks for playing!') break if 'instructions' in move: instruction() print('------------') print('\nYou are in the', current_room) # 修复:添加.split()保持列表类型 move = input('\nWhat will you do next?\n>').split() else: invalid() print('You are still in the', current_room) # 修复:添加.split()保持列表类型 move = input('What will you do next?\n>').split() if 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) move = input('What will you do next?\n>').split() elif move[1] not in rooms[current_room]: print('------------') print('Oh no it seems to be a dead end') # 修复笔误:dead in -> dead end print('You are still in the', current_room) move = input('What will you do next?\n>').split() else: invalid() print('You are still in the', current_room) # 修复:添加.split()保持列表类型 move = input('What will you do next?\n>').split() instruction() print('------------') if __name__ == '__main__': main()
额外说明:代码中顺便修正了一处语义笔误dead in为dead end,不影响核心功能,但表述更准确。
内容的提问来源于stack exchange,提问作者chaoshunter
相关产品推荐
相关产品推荐

