Python作业求助:实现物品从字典转移至inventory的方法
解决方案
问题分析
现有代码存在以下核心问题:
inventory被错误定义为字典,实际应使用集合存储玩家物品search_for_items函数缺少当前房间参数,无法定位玩家所在位置的物品- 函数内存在语法错误(如
if room has_item = true:),且未实现正确的物品转移逻辑 - 未处理物品取走后,对应房间物品集合的清空逻辑
修改后的完整代码
rooms = { 'Main Entry': {'East': 'Main Floor'}, 'Main Floor': {'North': 'North Hall', 'South': 'South Hall', 'East': 'Clothes Store', 'West': 'Main Entry'}, 'South Hall': {'East': 'Food Court', 'North': 'Main Floor'}, 'North Hall': {'East': 'Storage Room', 'South': 'Main Floor'}, 'Clothes Store': {'North': 'Theater', 'West': 'Main Floor'}, 'Theater': {'South': 'Clothes Store'} } # 所有物品的总览集合(可选保留) items = { 'Gas Mask', 'Stuffed Shark', 'Bubble Wrap', 'Knowledge of Toaster Store', 'Block of Old Cheese', 'Baseball Bat' } has_item = { 'Main Floor': {'Gas Mask'}, 'North Hall': {'Stuffed Shark'}, 'Storage Room': {'Bubble Wrap'}, 'South Hall': {'Knowledge of Toaster Store'}, 'Food Court': {'Block of Old Cheese'}, 'Clothes Store': {'Baseball Bat'} } # 修正为集合,用于存储玩家收集到的物品 inventory = set() def search_for_items(current_room): # 检查当前房间是否有未被取走的物品 if current_room in has_item and has_item[current_room]: # 取出房间内的物品(每个房间仅一个物品,用pop()直接获取) collected_item = has_item[current_room].pop() # 将物品添加到玩家背包 inventory.add(collected_item) print(f'Got item: {collected_item}') # 可选:若要彻底移除房间的物品记录,可添加 del has_item[current_room] else: print('No items here') # 测试示例:模拟玩家在Main Floor搜索 search_for_items('Main Floor') print('Current Inventory:', inventory) # 再次搜索同一房间,会提示无物品 search_for_items('Main Floor')
关键修改说明
- 数据结构调整:把
inventory改为集合,契合物品存储的需求(无重复、无序) - 函数参数补充:为
search_for_items添加current_room参数,明确玩家所在位置 - 物品转移逻辑:
- 判断当前房间是否存在有效物品记录
- 用
pop()取出房间内的物品,同时清空该房间的物品集合 - 将物品添加到玩家的
inventory中
- 语法修正:替换原函数中不符合Python规范的错误语句
内容的提问来源于stack exchange,提问作者The Trickster
相关产品推荐
相关产品推荐

