Python文本游戏房间移动指令大小写输入报错调试问题
问题现象
课程作业开发的文本冒险游戏基础版本,常规运行无异常,调试时输入大小写混合(如GO WEst)、全大写格式的移动指令会触发报错,同时存在其他同类输入触发的报错场景,暂未掌握调试器排查方法。
附原始实现代码:
# The dictionary links a room to other rooms. # saving for items = {} inventory for next step. Rooms = { 'Upper Room1': {'west': 'Upstairs'}, 'Upstairs': {'south': 'The Counter', 'east': 'Upper Room1'}, 'Side Room': {'east': 'The Counter'}, 'The Counter': {'south': 'Backroom', 'west': 'Side Room', 'east': 'Storage Room', 'north': 'Upstairs'}, 'Storage Room': {'west': 'The Counter', 'north': 'Hidden Storage',}, 'Hidden Storage': {'south': 'Storage Room'}, 'Backroom': {'north': 'The Counter', 'east': 'The Villain'}, 'The Villain': {'west': 'Bedroom'} } # Start the player in the first room currentRoom = 'The Counter' print('Welcome to the Drink Quest!') # Welcomes player to the game print("Move commands: go North, go East, go West, go South, exit") # Informs the player of the commands of the game # loop forever while True: if currentRoom.lower() == 'exit': break # print current status print(' ---------------------------') print('You are in ' + currentRoom) # get action from user print("Where do you want to go? ") navigate = input('>') navigate = navigate.split() # Navigation if navigate[0].lower() == 'go': if navigate[1].lower() in Rooms[currentRoom]: currentRoom = Rooms[currentRoom][navigate[1]] else: print('You can\'t go that way!') elif navigate[0].lower() == 'exit': currentRoom = 'exit' else: print("Invalid Choice choose a different path!") print("Thanks for playing Drink Quest!!")
报错根因
一共两个核心问题,覆盖所有提到的报错场景:
- 大小写处理逻辑不一致:判断方向是否合法时,代码对输入的方向做了
.lower()转小写,去匹配全是小写key的房间出口字典,但实际取对应房间时,用的是未转小写的原始输入值作为key。比如输入GO WEst,判断时'WEst'.lower() == 'west'能匹配到出口,但取值时用'WEst'查字典,字典中不存在这个key,直接触发KeyError。 - 缺失输入长度校验:代码默认用户输入一定符合格式,直接取
navigate[0]、navigate[1],如果用户输入空内容、只输入go不跟方向,split()得到的列表长度不足,会直接触发IndexError,对应提到的其他同类报错。
修复方法
- 拿到用户输入拆分后,先做非空、长度校验,不符合格式直接提示无效,避免索引越界
- 对指令、方向参数统一做小写归一化,杜绝半处理的逻辑漏洞
修复后的核心逻辑参考:
while True: if currentRoom.lower() == 'exit': break print(' ---------------------------') print('You are in ' + currentRoom) print("Where do you want to go? ") raw_input = input('>').strip() # 处理空输入 if not raw_input: print("Invalid input, please enter valid command!") continue navigate = raw_input.split() # 统一把指令转小写 cmd = navigate[0].lower() if cmd == 'go': # 校验go指令后是否携带方向参数 if len(navigate) < 2: print("Please specify direction after 'go'!") continue # 统一把方向转小写 direction = navigate[1].lower() if direction in Rooms[currentRoom]: currentRoom = Rooms[currentRoom][direction] else: print('You can\'t go that way!') elif cmd == 'exit': currentRoom = 'exit' else: print("Invalid Choice choose a different path!")
替换原循环内的导航逻辑即可,修复后无论输入是大小写混合、全大写、全小写的指令,还是空输入、不完整指令,都不会触发运行报错。
内容的提问来源于stack exchange,提问作者HYBRDF1R3 _
相关产品推荐
相关产品推荐

