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

Python文本游戏Inventory添加物品名的双重问题排查

Python文本游戏物品获取问题解决方案

问题梳理

  • 使用command.lower().split()[1]提取物品名时,多词物品(如energy potion)仅能提取第一个词,无法将完整名称加入背包
  • 修改为split(maxsplit=1)[1]后,单个词物品(如Skull)无法被识别添加

核心原因

  1. 初始代码的split()会分割所有空格,多词物品被拆分为多个元素,[1]只能取到第一个词
  2. 修改后的代码未处理大小写不匹配问题(比如房间内物品存为Skull,而提取的物品名是skull),同时缺少输入合法性校验(如仅输入get时会触发索引错误)

解决方案代码

elif command.lower().split()[0] == 'get':
    # 拆分命令,仅分割第一个空格,保留完整物品名
    cmd_parts = command.lower().split(maxsplit=1)
    
    # 校验是否输入了物品名
    if len(cmd_parts) < 2:
        print("请指定要获取的物品!")
        continue
    
    target_obj = cmd_parts[1]
    current_items = rooms[current_room]['item']
    
    # 处理房间物品为列表的情况(多数游戏的设计)
    if isinstance(current_items, list):
        # 忽略大小写匹配物品
        matched = next((item for item in current_items if item.lower() == target_obj), None)
        if matched:
            current_items.remove(matched)
            inventory.append(matched)
            print(f"已获取 {matched}")
        else:
            print("当前房间没有这个物品")
    # 处理房间物品为单个值的情况
    else:
        if current_items.lower() == target_obj:
            del rooms[current_room]['item']
            inventory.append(current_items)
            print(f"已获取 {current_items}")
        else:
            print("当前房间没有这个物品")

关键优化点

  • 用split(maxsplit=1)确保完整提取多词物品名,同时兼容单词物品
  • 增加输入校验,避免空物品名导致的程序报错
  • 采用忽略大小写的匹配逻辑,解决物品名大小写不一致的问题
  • 同时兼容房间物品为列表或单个值的两种常见设计

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:15:24