Python开发文本冒险游戏运行报KeyError异常求助
文本冒险游戏KeyError报错排查
报错原因
KeyError由字典键不存在触发,问题点在rooms配置和get_item()逻辑不匹配:
- 你定义的
rooms字典中,Outside(初始出生点)、Main Hall两个中转房间的属性字典里,只配置了方向移动的键,没有设置Item键 - 但
get_item()函数没有做存在性校验,无论当前处于哪个房间,都会强制读取rooms[state]['Item'] - 程序启动后第一次进入主循环,玩家初始位置是
Outside,访问不存在的Item键直接抛出KeyError,后续玩家移动到Main Hall时如果不修复也会触发同样报错。
报错定位验证
触发报错的执行链路非常清晰:
- 初始状态
state = 'Outside' - 主循环执行到
item = get_item(state) - 函数内执行
rooms['Outside']['Item'],而rooms['Outside']实际值为{'South': 'Main Hall'},无Item键,直接触发键错误。
修复代码
第一步:修改物品获取函数,增加容错
把原有get_item()函数替换为以下写法,用字典get()方法做兼容,没有物品的房间返回None:
def get_item(state): return rooms[state].get('Item', None)
第二步:调整主循环逻辑,适配无物品房间
原有主循环默认所有房间都有物品,会在无物品房间打印异常内容、拾取逻辑判断失效,把主循环片段替换为如下代码即可:
while (1): print('You are in ', state) print('Inventory:', Inventory) item = get_item(state) if item: print('You see a ', item) else: print('There is no collectible item in this room.') print('--------------------') if item == 'Witch': print('YOU HAVE BEEN CAUGHT! GAME OVER') exit(0) direction = input('Enter your move: ') if direction in ('go East', 'go West', 'go North', 'go South'): direction = direction[3:] new_state = get_new_state(state, direction) if new_state == state: print('There is a wall there') else: state = new_state elif item and direction == f'get {item}': if item in Inventory: print('Item already taken, go to another room!') else: Inventory.append(item) else: print('Invalid input or move or item') if len(Inventory) == 6: print('Congratulations! After collecting all of those items, you have defeated the witch!') exit(0)
补充说明:这种写法不需要给
Outside、Main Hall硬塞空的Item配置,逻辑更简洁,后续新增无物品的中转房间也不需要额外改配置。
内容的提问来源于stack exchange,提问作者Brett
相关产品推荐
相关产品推荐

