文本类游戏物品拾取功能实现求助(Python)
文本游戏物品拾取功能修复方案
你的get_item函数存在逻辑错误,导致Python报错找不到item变量,以下是具体问题和修复方案:
问题分析
- 函数参数
item未传递有效数据,混淆了字典键名与变量名 - 判断逻辑错误:
current_room是房间名称字符串,需检查当前房间的字典数据中是否包含'item'键,而非item变量是否在current_room中 - 未处理拾取后移除房间物品的逻辑,会导致重复拾取
修复后的完整代码
rooms = { 'Entrance': {'west': 'Catacombs A', 'north': 'Main Hall'}, 'Catacombs A': {'east': 'Entrance', 'item': 'Lesser Artifact'}, 'Main Hall': {'north': 'Great Hall', 'east': 'Catacombs B', 'south': 'Entrance', 'west': 'Necron Tomb', 'item': 'Dog Tags'}, 'Necron Tomb': {'east': 'Main Hall', 'item': 'Supplies'}, 'Catacombs B': {'west': 'Main Hall', 'north': 'Storage Room', 'item': 'Lesser Artifact'}, 'Storage Room': {'south': 'Catacombs B', 'item': 'Supplies'}, 'Great Hall': {'east': 'Repair Hub', 'south': 'Main Hall', 'item': 'Dog Tags'}, 'Repair Hub': {'west': 'Great Hall', 'item': 'Necron Lord'} # Villain } current_room = 'Entrance' inventory = [] print('You are a member of a squad of Ultramarines that has been tasked with retrieving 6 items from a ' 'Necron facility on the orbiting planet before reaching the Necron Lord. You and your brothers breach the entrance, which way do you go first?') def move_rooms(current_room, direction): return rooms[current_room][direction] def get_item(current_room_name, inventory): current_room_data = rooms[current_room_name] if 'item' in current_room_data: item = current_room_data['item'] inventory.append(item) del current_room_data['item'] print(f'You picked up the {item}!') print(f'Current inventory: {inventory}') else: print('There is no item to pick up here.') while True: print(f'\nYou are in the {current_room}') print(f'Inventory: {inventory}') user_input = input('Enter a direction: north, east, south, west, get item, or exit. ').strip().lower() if user_input in ['north', 'east', 'south', 'west']: if user_input in rooms[current_room]: current_room = move_rooms(current_room, user_input) else: print('You cannot go that way.') elif user_input == 'get item': get_item(current_room, inventory) elif user_input == 'exit': print('You have failed the Emperor and your brothers...') break else: print('Invalid command, please try again.')
关键修改点
- 重构
get_item函数:接收当前房间名称和背包列表,从rooms字典中读取房间数据,检查'item'键是否存在 - 拾取物品后删除房间内的
'item'键,防止重复拾取 - 优化主循环输入处理:统一转为小写避免大小写问题,拆分输入分支让逻辑更清晰
- 添加实时背包状态显示,方便玩家查看已拾取物品
内容的提问来源于stack exchange,提问作者John Smith
相关产品推荐
相关产品推荐

