
本文详解在基于字典的文本冒险游戏中,如何正确从当前房间字典中提取物品并安全添加到玩家背包列表,同时避免键错误、重复获取和逻辑冲突。
本文详解在基于字典的文本冒险游戏中,如何正确从当前房间字典中提取物品并安全添加到玩家背包列表,同时避免键错误、重复获取和逻辑冲突。
在 Python 文本冒险游戏中,房间通常用嵌套字典表示,其中每个房间是键,对应值是一个包含移动方向(如 'North', 'East')和可拾取物品('item')的字典。初学者常犯的关键错误是:误判 'item' 是否为房间字典的有效键,或错误地检查 rooms[current_room]['item'] 的值而非键的存在性——这会导致 KeyError 或“无效输入”误报。
✅ 正确获取物品的核心逻辑
判断一个房间是否有物品,应使用 'item' in rooms[current_room](检查键是否存在),而非 if 'item' in rooms[current_room]['item'](后者试图在字符串中查找子串,且会因键不存在而崩溃)。一旦确认键存在,即可安全读取并添加:
if move == 'Get Item':
if 'item' in rooms[current_room]: # ✅ 安全检查:键是否存在
item = rooms[current_room]['item']
inventory.append(item)
print(f"You picked up the {item}.")
del rooms[current_room]['item'] # ✅ 拾取后移除,防止重复获取
else:
print("There's no item here.")
⚠️ 注意:原代码中
if 'item' in rooms[current_room]['item']是严重错误——它把rooms[current_room]['item']当作字符串(如'Golden Eggs')来遍历,而该值根本不是字典;更糟的是,若该房间根本没有'item'键,此行直接抛出KeyError,导致程序中断。
? 同时修复其他关键问题
-
user_status()中的健壮性增强
原user_status()直接访问rooms[current_room]['item'],若该房间无'item'键(如'Magnificent Caverns'),会崩溃。应改为:if 'item' in rooms[current_room]: print(f"In this room you see {rooms[current_room]['item']}.") else: print("This room is empty.") -
villain判断逻辑需同步更新
当前代码写成if villain in rooms[current_room].keys(),但'Dragon'是物品值('item': 'Dragon'),不是键。正确写法应为:if 'item' in rooms[current_room] and rooms[current_room]['item'] == villain:
这样才能准确识别进入
Villain's Lair时是否遭遇 Boss。
macOS UI 自动化技能包 —— 用 Python 控制你的 Mac下载让 macOS 自动化像说话一样简单 —— 用代码控制你的 Mac,无需学习 AppleScript 系统要求 macOS 14+ (Sonoma) Python 3.9+ 需要开启:辅助功能 + 屏幕录制权限
输入处理优化
str(input(...)).title().strip()多余——input()返回字符串,.title()会将'get item'变为'Get Item',但'Get Item'已在directions列表中,无需额外转换;建议统一用.strip()防空格即可,提升可读性与稳定性。
? 完整修正片段(整合关键部分)
def user_status():
print('\n-------------------------')
print(f'You are in the {current_room}.')
print(f'Your inventory is {inventory}.')
if 'item' in rooms[current_room]:
print(f"In this room you see {rooms[current_room]['item']}.")
else:
print("This room is empty.")
print('-------------------------------')
# 主循环内 Get Item 分支(修正后)
if move == 'Get Item':
if 'item' in rooms[current_room]:
item = rooms[current_room]['item']
inventory.append(item)
print(f"You picked up the {item}.")
del rooms[current_room]['item'] # 物品被拾取后从房间移除
else:
print("There's no item here.")
# 检查是否遭遇 Boss(注意:villain 是物品值,不是键)
if 'item' in rooms[current_room] and rooms[current_room]['item'] == villain:
if len(inventory) <h3>✅ 总结</h3>
- ✅ 使用
'key' in dict检查字典键存在性,永远优于直接索引访问; - ✅ 获取物品后立即
del rooms[room]['item'],确保单次拾取; - ✅
user_status()和Get Item逻辑必须统一使用相同键存在性检查; - ✅ Boss 判断应基于物品值匹配(
== villain),而非键名匹配; - ✅ 输入标准化只需
.strip(),避免.title()引发意外大小写转换(如'GET ITEM' → 'Get Item'可能干扰调试)。
掌握这些模式,不仅能解决当前问题,更为构建健壮的状态驱动游戏逻辑打下坚实基础。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










