Python房间移动文本游戏输入go south触发KeyError:South报错求解
问题原因梳理
- KeyError直接诱因:
move_rooms函数逻辑完全颠倒,首次输入go south时,函数先强制把当前房间赋值为Bedroom,再尝试读取rooms['Bedroom']['South'],但Bedroom的连通方向里根本没有South键,直接抛出错误。 - 逻辑判断语法错误:所有形如
if room == 'Great Hall' or 'Cellar'的写法都是无效的,Python会将其判定为if (room == 'Great Hall') or (bool('Cellar')),非空字符串布尔值恒为True,导致所有方向合法性判断永久失效。 - 循环语法结构错误:
while循环后的elif、else与while同级,属于语法错误,房间判定逻辑全部没有缩进在while代码块内,永远不会执行。 - 代码冗余问题:硬编码每个房间的合法方向,完全没有用到已经定义好的
rooms字典的连通关系配置,后续新增房间需要大幅修改代码。
修复后完整代码
rooms = { 'Great Hall': {'South': 'Bedroom'}, 'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'}, 'Cellar': {'West': 'Bedroom'} } def show_instructions(): print('操作指令:go north, go south, go east, go west') def move_rooms(direction, current_room): # 提取方向关键词,比如将go south转换为South dir_key = direction.split()[-1].capitalize() # 判断当前房间是否支持该方向移动 if dir_key in rooms[current_room]: return rooms[current_room][dir_key] else: return 'Invalid direction please try again.' currentRoom = 'Great Hall' print('操作指令:go north, go south, go east, go west') print(f'当前位置:{currentRoom}') while True: userDirection = input("选择移动方向,或输入exit退出游戏:").strip() # 处理退出逻辑 if userDirection == 'exit': print('感谢游玩!') break # 处理移动逻辑 move_result = move_rooms(userDirection, currentRoom) if move_result == 'Invalid direction please try again.': print('无效方向,请重新选择。') show_instructions() else: currentRoom = move_result print(f'当前位置:{currentRoom}')
内容的提问来源于stack exchange,提问作者Joseph Booth
相关产品推荐
相关产品推荐

