
本文详解如何修复因数据类型误用导致的 TypeError,并构建健壮的房间物品拾取逻辑,涵盖字典键检测、库存管理、方向移动优化及可扩展地图设计。
本文详解如何修复因数据类型误用导致的 `typeerror`,并构建健壮的房间物品拾取逻辑,涵盖字典键检测、库存管理、方向移动优化及可扩展地图设计。
在文字冒险类游戏中,“搜索房间获取物品”是核心交互之一。你当前代码报错:
TypeError: 'in <string>' requires string as left operand, not set</string>
根本原因在于:你将 item 定义为一个集合(set):
item = {
'Gas Mask',
'Stuffed Shark',
'Bubble Wrap',
'Knowledge of Toaster Store',
'Block of Old Cheese',
'Baseball Bat'
}
却试图执行 if item in room[current_room]['item'] —— 这相当于用整个集合去判断是否“存在于一个字符串中”(如 'Gas Mask'),Python 明确禁止该操作。
✅ 正确做法是:先检查房间是否定义了 'item' 键,再安全地获取其值并加入库存。同时,inventory 当前是空字典 {},但你需要的是列表(list) 来支持 .append() 操作。
以下是修复后的完整可运行逻辑(关键部分已重构并注释):
# ✅ 1. 房间结构:保留原有嵌套字典,但确保 'item' 是可选键(非所有房间都有)
room = {
'Main Entry': {'East': 'Main Floor'},
'Main Floor': {'North': 'North Hall', 'South': 'South Hall', 'East': 'Clothes Store', 'West': 'Main Entry', 'item': 'Gas Mask'},
'South Hall': {'East': 'Food Court', 'North': 'Main Floor', 'item': 'Knowledge of Toaster Store'},
'North Hall': {'East': 'Storage Room', 'South': 'Main Floor', 'item': 'Stuffed Shark'},
'Food Court': {'West': 'South Hall', 'item': 'Block of Old Cheese'},
'Clothes Store': {'North': 'Theater', 'West': 'Main Floor', 'item': 'Baseball Bat'},
'Theater': {'South': 'Clothes Store'} # ❗无 'item' 键 → 搜索时自动跳过
}
# ✅ 2. 库存必须是列表(不是字典!)
inventory = [] # ← 关键修正:初始化为空列表
# ✅ 3. 当前位置与游戏主循环
current_room = 'Main Entry'
print('Allister & Doodle enter the mall. The word was, one of their recurring enemies-Lumina the jellyfish lady-was putting'
'together a makeshift doomsday device! They figured it was unlikely to do actual doomsday levels of damage, but they had the day'
'off and figured they might as well try and put a stop to it. Because they\'re just that nice!'
'Input "Search" to look for items! You\'ll need Bubble Wrap, a Baseball Bat, and a Block of Old Cheese to win the game.'
'Once—and only once—you have all three, make your way to the Theater (North of the Clothes Store) for the final showdown!'
'Input North, South, East, or West to move. Or type "exit" to quit.')
while current_room != 'exit':
print(f"\nAllister & Doodle are in the {current_room}")
command = input("Enter command: ").strip().capitalize() # 统一大小写,防输入误差
if command == 'Exit':
current_room = 'exit'
break
elif command == 'Search':
# ✅ 安全检查:房间是否有 'item' 键,且值不为空
if 'item' in room[current_room]:
found_item = room[current_room]['item']
inventory.append(found_item)
print(f"✓ You picked up: {found_item}")
# ? 可选:拾取后移除房间物品(避免重复获取)
del room[current_room]['item']
else:
print("Nothin'.")
elif command in ['North', 'South', 'East', 'West']:
if command in room[current_room]:
current_room = room[current_room][command]
print(f"→ Moved {command} to {current_room}")
else:
print("Can't go that way.")
else:
print("No can do. Try North/South/East/West/Search/exit.")
print("\nYou have exited the game.")
print(f"Final inventory: {inventory}")
? 关键修复点总结:
-
item集合完全移除——它在此逻辑中冗余;房间字典本身已明确声明物品; - 使用
'item' in room[current_room]判断是否存在物品,安全、高效、无类型错误; -
inventory改为list,支持.append(); - 拾取后通过
del room[current_room]['item']防止重复获取(增强游戏性); - 输入标准化(
.strip().capitalize())提升鲁棒性。
? 进阶建议:用坐标系替代硬编码方向(推荐长期维护)
如答案中所提,当房间数增加时,基于 (x, y) 的网格系统更易扩展:
# 示例:二维坐标映射(简化版)
grid = {
(0, 0): 'Main Entry',
(0, 1): 'Main Floor',
(1, 1): 'North Hall',
(-1, 1): 'South Hall',
(0, 2): 'Clothes Store',
(1, 2): 'Theater',
}
directions = {'North': (1, 0), 'South': (-1, 0), 'East': (0, 1), 'West': (0, -1)}
x, y = 0, 0 # 起始坐标
# 移动逻辑示例:
if command in directions:
dx, dy = directions[command]
nx, ny = x + dx, y + dy
if (nx, ny) in grid:
x, y = nx, ny
current_room = grid[(x, y)]
else:
print("Wall! Can't go there.")
这种设计让新增房间只需添加坐标映射,无需修改每个房间的 North/South 字段,大幅降低维护成本。
掌握这些模式,你的文字冒险引擎就拥有了坚实、可扩展、少 Bug 的交互基础。










