Python文本类游戏故障:无法切换房间及添加物品至库存
文本游戏:房间切换与物品拾取问题修复
问题定位
1. 物品拾取逻辑错误
原代码中物品判断和添加的逻辑存在两处硬伤:
- 条件语句
if item in rooms[current_room] and ['item']:完全不符合语法逻辑,既没正确校验物品是否在当前房间,['item']作为布尔值永远为真,导致判断彻底失效。 - 添加物品时
inventory_items.append(current_room['item'])错误地将字符串类型的current_room当作字典调用,应该引用rooms字典中当前房间对应的物品。
2. 房间切换逻辑潜在问题
假设你的rooms字典结构是每个房间包含方向键(如'north')和物品键(如'item'),原代码中elif command in rooms[current_room]:会把'item'也当作有效切换命令,输入'item'时会触发无效切换报错。必须明确区分方向指令和物品字段。
修复后的代码
# 示例rooms字典(请根据你的游戏场景调整) rooms = { 'Kitchen': { 'north': 'Living Room', 'south': 'Dining Room', 'item': 'knife' }, 'Living Room': { 'south': 'Kitchen', 'east': 'Bedroom', 'item': 'lamp' }, 'Dining Room': { 'north': 'Kitchen', 'item': 'plate' }, 'Bedroom': { 'west': 'Living Room' } } def user_instructions(): print("游戏指令:输入方向(north/south/east/west)切换房间;输入take拾取物品") def user_status(): print(f"\n当前房间:{current_room}") if 'item' in rooms[current_room]: print(f"房间内物品:{rooms[current_room]['item']}") print(f"当前库存:{inventory_items}") user_instructions() inventory_items = [] current_room = 'Kitchen' command = '' while current_room != 'Bedroom': user_status() command = input('Enter your next move.\n').lower() if command == 'take': item = input('What do you want to take? ').lower() # 正确校验物品是否存在于当前房间 if 'item' in rooms[current_room] and rooms[current_room]['item'].lower() == item: inventory_items.append(item) # 拾取后移除房间内物品,避免重复拾取 del rooms[current_room]['item'] print(f"你拾取了{item}!") else: print(f"There's no {item} here.") # 仅允许有效方向指令切换房间 elif command in ['north', 'south', 'east', 'west'] and command in rooms[current_room]: current_room = rooms[current_room][command] else: print('Invalid command')
关键修复说明
- 物品拾取:修正条件判断逻辑,确保只有当前房间存在指定物品时才添加到库存,同时拾取后移除房间内的物品,避免重复操作。
- 房间切换:明确限定方向指令范围,避免将物品字段误判为切换命令,保证只有输入有效方向时才执行房间切换。
- 补充了
rooms字典示例和user_instructions()、user_status()的基础实现,确保代码可直接运行(可根据实际需求调整)。
内容的提问来源于stack exchange,提问作者Jackie
相关产品推荐
相关产品推荐

