文本冒险游戏起始房间West Gate Entrance触发KeyError问题求助
问题排查与修复方案
1. 触发KeyError的核心原因
起始房间West Gate Entrance在items字典中没有对应的条目,代码执行到print("In this room you see a", items[state])时,会因找不到对应键抛出KeyError。
2. 其他隐藏问题
- 房间名称大小写不一致:
rooms里的"library"是小写,而items里的键是"Library",后续访问时也会触发KeyError - 房间跳转指向错误:
Great Hall的West方向指向"Start",但rooms字典中不存在该房间,应改为"West Gate Entrance"
3. 修复后的完整代码
rooms = { "West Gate Entrance": {"East": "Great Hall"}, "Great Hall": { "North": "Library", # 修正为大写,与items中的键保持一致 "South": "Solar", "East": "Kitchen", "West": "West Gate Entrance", # 修正跳转目标 }, "Library": {"East": "Bed Chambers", "South": "Great Hall"}, # 修正为大写 "Bed Chambers": {"West": "Library"}, "Kitchen": {"West": "Great Hall", "North": "Lost Room"}, "Lost Room": {"South": "Kitchen"}, "Solar": {"North": "Great Hall", "East": "East Tower"}, } items = { "West Gate Entrance": "Iron Key", # 给起始房间添加对应物品 "Great Hall": "Castle Map", "Library": "Sword", "Bed Chambers": "Lost Key", "Lost Room": "Heart Container", "Kitchen": "Potion", "Solar": "Shield", "East Tower": "Ghost Knight", } state = "West Gate Entrance" inventory = [] def get_new_state(state, direction): new_state = state # 简化逻辑,直接通过字典访问替代循环,提升效率 if direction in rooms.get(state, {}): new_state = rooms[state][direction] return new_state while True: print("You are now in the ", state) if state == "East Tower": print("You have entered battle with the Ghost Knight!", end="") for i in range(50): print(".", end="", flush=True) print() if len(inventory) == 7: # 新增起始房间物品后,总数变为7 print("Congratulations! You have located all 7 items and slain the Ghost Knight") else: print("You have succumbed to your wounds...GAME OVER!") break print("In this room you see a", items[state]) print("You now have", inventory) direction = input("Enter item you want OR direction to go OR exit to give up: ") if direction.lower() == items[state].lower(): if items[state] not in inventory: inventory.append(items[state]) continue direction = direction.capitalize() if direction == "Exit": exit(0) if direction in ["East", "West", "North", "South"]: new_state = get_new_state(state, direction) if new_state == state: print("There is no move in that direction!") # 移除重复单词 else: state = new_state else: print("Please input a valid direction!")
4. 额外优化点
- 简化
get_new_state函数逻辑,直接通过字典访问替代循环 - 移除原代码中无意义的嵌套循环延迟,改用直接打印省略号
- 修正提示文本中的重复单词("direction direction")
- 调整胜利条件的物品数量,适配新增的起始房间物品
内容的提问来源于stack exchange,提问作者Nick Mercer
相关产品推荐
相关产品推荐

