自研文本类冒险游戏:物品无法存入Inventory问题求助
问题分析与解决方案
核心错误点
- 命令逻辑与提示不符:游戏提示告知直接输入物品名拾取,但代码仅在输入
get时才触发拾取流程,导致用户按提示操作时被判定为无效命令。 - 物品存在性判断错误:误用
rooms(current_room)(函数调用语法)替代字典访问rooms[current_room]['item'],且未处理用户输入的大小写差异(用户输入会被转成小写,但物品名是大写开头)。 - 未移除已拾取物品:拾取后房间内的物品仍保留,导致可重复拾取同一物品。
- 房间映射错误:
Great Mother Tree的west指向Armory,但房间字典中对应的房间是Armory Room,会引发移动报错。 - 无物品房间处理不当:
Bathroom的item设为字符串'None',会误导用户尝试拾取该字符串,应设为None空值。
修正后的代码
def user_instructions(): print('--------------') print('你是一只猴子,醒来发现部落正遭受Sakado部落的袭击 ') print('你的目标是收集全部6件物品,带到伟大母树拯救部落!') print('部落的命运掌握在你手中!') print('\n使用命令 "north", "east", "south", "west" 在房间间移动') print('每个房间有一件物品可拾取,直接输入物品名称即可获取') print('\n不要辜负你的部落!') # 定义各房间的可行动命令与物品 rooms = { 'Great Hall': {'east': 'Shower Hall', 'south': 'Armory Room', 'west': 'Bedroom', 'north': 'Chow Hall', 'item': 'Armor of the Hacoa Tribe'}, 'Bedroom': {'east': 'Great Hall', 'item': 'Tribe Map'}, 'Chow Hall': {'east': 'Bathroom', 'south': 'Great Hall', 'item': 'Golden Banana'}, 'Shower Hall': {'west': 'Great Hall', 'north': 'Branding Room', 'item': 'Sword of a 1000 souls'}, 'Bathroom': {'west': 'Chow Hall', 'item': None}, 'Branding Room': {'south': 'Shower Hall', 'item': 'Sacred Key'}, 'Armory Room': {'north': 'Great Hall', 'east': 'Great Mother Tree', 'item': 'Spear of the Unprotected'}, 'Great Mother Tree': {'west': 'Armory Room'} } def user_status(): # 显示当前房间与背包内容 print('\n-------------------------') print('你现在在 {}'.format(current_room)) room_item = rooms[current_room]['item'] print('这个房间里有 {}'.format(room_item if room_item else '没有物品')) print('背包:', inventory_items) print('-------------------------------') user_instructions() inventory_items = [] # 初始背包为空 current_room = 'Bedroom' # 从卧室开始 while current_room != 'Great Mother Tree': user_status() command = input('输入你的下一步操作:\n').strip() # 处理移动命令 if command in rooms[current_room]: current_room = rooms[current_room][command] # 处理物品拾取 else: room_item = rooms[current_room]['item'] if room_item and command.lower() == room_item.lower(): inventory_items.append(room_item) rooms[current_room]['item'] = None # 拾取后移除房间内的物品 print(f'你获得了 {room_item}!') else: print('无效命令,请重新输入') # 到达终点后判定胜负 if len(inventory_items) == 6: print('你成功收集了所有物品,拯救了部落!你赢了!') else: print('你没有收集全所有物品,部落覆灭了。你输了。')
关键改进说明
- 对齐命令逻辑与提示:直接输入物品名即可完成拾取,无需先输入
get。 - 修复物品判断:通过
room_item.lower() == command.lower()处理大小写差异,提升输入容错性。 - 拾取后移除物品:将房间的
item设为None,避免重复拾取同一物品。 - 修正房间映射:把
Great Mother Tree的west改为Armory Room,解决移动报错问题。 - 优化无物品提示:当房间物品为
None时,显示“没有物品”,避免用户混淆。
内容的提问来源于stack exchange,提问作者TEsco
相关产品推荐
相关产品推荐

