You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IT140项目:Python文本游戏物品无法加入inventory列表故障排查求助

问题:物品无法添加到inventory列表中

我正在完成IT140课程的项目,使用Python的字典、列表和函数开发一款文本类游戏。游戏规则为:在不同房间间移动,收集6件物品即可获胜;若进入反派所在房间则游戏结束。目前房间移动功能正常,但物品无法添加到inventory列表中。我已观看相关视频尝试解决,但未能找到有效修复方案。目前尚未完成全部代码,仅需排查物品添加至列表的问题。我仍在学习Python,欢迎提供建设性意见。

当前代码

def instructions():
    print('------------------------------------------------------------------')
    print('                   Mine Escape                    ')
    print('------------------------------------------------------------------')
    print('You must collect all 6 items to escape from the mine and save\n'
          'yourself and your boss. To move use the words south, east,\n'
          ' west, and north. To pickup items say get and the items name. \n'
          'if you enter the room with the lunatic and you have not \n'
          'collected all items, you will die. You win when you collect\n'
          'all 6 items. Good luck.')
    print('------------------------------------------------------------------')


def user_status():
    print(f'You are in the {current_room}')
    print(f'Inventory: {inventory}')
    print('You see ' + rooms[current_room]['Item'])



rooms = {
    'Top elevator shaft': {'South': 'Bottom elevator shaft', 'Item': 'nothing'},
    'Bottom elevator shaft': {'North': 'Top elevator shaft', 'West': 'Cart room',
                              'East': 'Cot room', 'Item': 'a flashlight'},
    'Cart room': {'East': 'Bottom elevator shaft', 'South': 'Extraction room', 'Item': 'a tourniquet'},
    'Extraction room': {'North': 'Cart room', 'Item': 'a bottle of rubbing alcohol'},
    'Cot room': {'West': 'Bottom elevator shaft', 'East': 'Map room', 'South': 'Tool room', 'Item': 'a roll of gauze'},
    'Map room': {'Villain': 'the lunatic', 'Item': 'nothing'},
    'Tool room': {'North': 'Cot room', 'South': 'Office room', 'Item': 'a can of food'},
    'Office room': {'North': 'Tool room', 'Item': 'a bottle of water'}
}


def move_rooms(direction, current_room):
    new_room = current_room
    if direction in rooms[current_room]:
        new_room = rooms[current_room][direction]
    else:
        print('There are no rooms this way.\n')
    return new_room


instructions()
current_room = 'Top elevator shaft'
inventory = []


while True:
    user_status()
    # direction
    direction = input('Enter a direction:\n').title()
    if direction == 'South' or direction == 'East' or direction == 'West' or direction == 'North':
        new_room = move_rooms(direction, current_room)
        current_room = new_room
    # item
    elif direction == 'Get ' + rooms[current_room]['Item']:
        if 'Item' not in inventory:
            inventory.append(rooms[current_room]['Item'])
        elif 'Item' in inventory:
            print('You have already picked this item up.\n')
        else:
            print('Cant find that item\n')
    elif direction == 'Exit':
        break
    else:
        print('Invalid direction.\n')
问题排查与修复

1. 输入匹配逻辑错误

你用.title()处理用户输入后,比如用户输入get a flashlight会变成Get A Flashlight,但代码中判断的是'Get ' + rooms[current_room]['Item'](比如Get a flashlight),两者大小写格式不匹配,导致永远触发不了物品收集分支。

修复方法:统一用小写格式做比较,避免大小写干扰:

# 替换原输入处理行
user_input = input('Enter a direction:\n').strip().lower()

# 方向判断改为小写匹配,传给move_rooms的保持首字母大写以匹配字典键
if user_input in ['south', 'east', 'west', 'north']:
    new_room = move_rooms(user_input.title(), current_room)
    current_room = new_room

# 物品收集判断改为小写匹配
elif user_input == 'get ' + rooms[current_room]['Item'].lower():
    # 后续收集逻辑...

2. 物品存在性判断错误

代码中用if 'Item' not in inventory:判断是否已收集物品,但'Item'是固定字符串,而inventory里存的是具体物品名称(比如'a flashlight'),这个判断永远为真,会重复添加同一物品。

修复方法:判断当前房间的物品是否在inventory中,同时排除'nothing'的情况:

current_item = rooms[current_room]['Item']
if current_item == 'nothing':
    print('这里没有可收集的物品!\n')
elif current_item not in inventory:
    inventory.append(current_item)
    print(f'你收集了{current_item}!\n')
    # 可选:收集后将房间物品设为nothing,避免重复提示
    rooms[current_room]['Item'] = 'nothing'
else:
    print('你已经拿过这个物品了!\n')

额外优化建议

  • 增加获胜条件:每次收集物品后检查len(inventory) == 6,如果满足则打印胜利信息并退出循环
  • 进入反派房间(Map room)时,判断物品数量,不足6则触发游戏结束逻辑
  • 可以把指令提示整合到user_status中,让用户更清楚可用操作

内容的提问来源于stack exchange,提问作者void

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 16:46:14