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

文本类游戏中拾取物品触发TypeError问题求助

文本游戏拾取物品TypeError问题修复

错误原因及修复点

1. 库存类型错误

inventory = () 被定义为元组,元组属于不可变类型,无法执行append添加操作,直接触发TypeError。
修复: 将库存改为可变的列表:

inventory = []

2. 拾取函数参数与调用不匹配

  • 原pickupItem函数仅定义1个参数,但处理拾取命令时传入了2个参数,导致参数数量不匹配报错
  • 调用pickupItem(startRoom)时,传入的是房间名字符串,而非rooms字典中的房间对象,无法正确判断物品是否存在

修复:
重构拾取函数,适配参数并完善逻辑:

def pickupItem(current_room, item_name):
    room_data = rooms[current_room]
    # 校验房间存在目标物品且未被拾取
    if 'Item' in room_data and room_data['Item'] == item_name:
        if item_name in inventory:
            print(f"你已经拥有{item_name}了!")
        else:
            inventory.append(item_name)
            print(f"你拾取了{item_name}!")
            # 移除房间物品,避免重复拾取
            del room_data['Item']
    else:
        print("这个房间里没有这个物品!")

3. 冗余函数逻辑混乱

原game函数存在变量名错误(如大写Item、字符串判断'item' in inventory),且未被正确调用,直接删除该函数,将逻辑整合到pickupItem中。

4. 主函数中的错误调用

  • 删除print(pickupItem(startRoom)):该函数无返回值,会打印无效的None
  • 修正退出命令判断:将command[0] == 'Escape!'改为command[0] == 'exit',与游戏提示一致
  • 优化状态显示:清晰展示当前房间、库存及房间内物品

5. 特殊房间逻辑处理

Outside of the Armory房间的Item为恐怖分子,进入该房间直接判定游戏失败,无需处理物品拾取。

完整修复代码

# Trevor Anderson

# 房间与方向、物品的映射字典
rooms = {
    'Orderly Room': {'North': 'Admin Office', 'East': 'Recruiters Office', 'South': 'Supply Room', 'West': 'Drill Hall'},
    'Admin Office': {'East': 'First Sergeant Office', 'South': 'Orderly Room', 'Item': 'Grip'},
    'First Sergeant Office': {'West': 'Admin Office', 'Item': 'Magazine'},
    'Recruiters Office': {'South': 'Outside of the Armory', 'West': 'Orderly Room', 'Item': 'Ammunition'},
    'Outside of the Armory': {'North': 'Recruiters Office', 'Item': 'Terrorists'},
    'Drill Hall': {'North': 'Kitchen', 'East': 'Orderly Room', 'Item': 'Bolt'},
    'Kitchen': {'South': 'Drill Hall', 'West': 'Pantry', 'Item': 'Charging Handle'},
    'Pantry': {'East': 'Kitchen', 'Item': 'Crayons'},
    'Supply Room': {'North': 'Orderly Room', 'West': 'Cold Storage', 'Item': 'Receiver'},
    'Cold Storage': {'East': 'Supply Room', 'West': 'Weapons Room', 'Item': 'Trigger'},
    'Weapons Room': {'East': 'Cold Storage', 'Item': 'Stock'}
}

startGame = True
inventory = []  # 改为列表,支持动态修改

# 移动角色到指定方向的房间
def move(soldier, direction):
    startRoom = soldier
    if direction in rooms[startRoom]:
        startRoom = rooms[startRoom][direction]
    else:
        print('你不能往那个方向走!')
        return soldier
    return startRoom

# 显示游戏规则
def gameRules():
    print('移动命令:go North、go East、go West、go South\n收集全部8件物品获胜,否则会被恐怖分子抓住!\n输入exit可退出游戏')

# 拾取物品逻辑
def pickupItem(current_room, item_name):
    room_data = rooms[current_room]
    if 'Item' in room_data and room_data['Item'] == item_name:
        if item_name in inventory:
            print(f"你已经拥有{item_name}了!")
        else:
            inventory.append(item_name)
            print(f"你拾取了{item_name}!")
            del room_data['Item']
    else:
        print("这个房间里没有这个物品!")

def main():
    gameRules()
    soldier = 'Orderly Room'

    while startGame:
        current_room = soldier
        room_data = rooms[current_room]

        # 显示当前状态
        print(f'\n你现在在:{current_room}')
        print(f'背包:{inventory if inventory else "空"}')
        # 显示当前房间的物品(恐怖分子房间除外)
        if 'Item' in room_data and room_data['Item'] != 'Terrorists':
            print(f"你看到了:{room_data['Item']}")

        # 遇到恐怖分子,游戏结束
        if current_room == 'Outside of the Armory':
            print('糟糕!你被恐怖分子抓住了!\n感谢游玩,下次好运!')
            break

        # 输入命令
        print('---------------------')
        soldier_move = input('输入你的操作:\n')

        if 'go' in soldier_move or 'exit' in soldier_move:
            command = soldier_move.split(' ')
            if command[0] == 'go':
                if len(command) < 2:
                    print('请输入正确的移动命令,比如go North')
                    continue
                soldier = move(soldier, command[1])
            elif command[0] == 'exit':
                if len(inventory) == 8:
                    print('装备好你的M4步枪!快撤!')
                else:
                    print('你还缺一些物品!')
                break  # 退出游戏循环
            else:
                print('无效命令!')
        elif 'pickup' in soldier_move:
            command = soldier_move.split(' ')
            if len(command) < 2:
                print('请输入正确的拾取命令,比如pickup Grip')
                continue
            pickupItem(current_room, command[1])
        else:
            print('无效命令!')

# 启动游戏
main()

修复后验证

  • 执行pickup [物品名]可正确将物品添加至背包
  • 重复拾取同一物品会提示已拥有
  • 库存使用列表,不再触发TypeError
  • 移动、退出、失败判定逻辑均正常运行

内容的提问来源于stack exchange,提问作者T.A

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 05:30:58