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

文本游戏中无法同时添加单/双字词物品至库存的问题

问题描述

我开发的文本类游戏里,没法同时支持添加单字词和双字词物品到库存。比如想在一个地点放skull(头骨),另一个地点放energy potion(能量药水),现在用.split(maxsplit=1)或.split(' ', 1)解决了双字词的添加问题,但单字词物品又加不了。

相关代码如下:

while True:
    instructions()
    player_status(rooms, current_room, inventory)
    time.sleep(0.5)

    # 处理玩家在房间间移动的指令
    command = input('\nWhat do you want to do?\n>').title().strip()
    if command in rooms[current_room]:
        current_room = rooms[current_room][command]
        time.sleep(0.5)

    # 将物品添加到库存并从房间移除的指令
    elif command.lower().split()[0] == 'get':
        obj = command.lower().split(maxsplit=1)[1]
        if obj in rooms[current_room]['item']:
            del rooms[current_room]['item']
            inventory.append(obj)
        else:
            print("I don't see that here.")

    # 退出游戏指令
    elif command.lower() in ('q', 'quit'):
        time.sleep(0.5)
        print('\nThanks for playing.')
        break

    # 无效指令处理
    else:
        time.sleep(0.5)
        print('\nYou can\'t go that way!')

示例错误输出:

You are at occult bookstore.
There is a Skull
You have: ['energy potion']

What do you want to do?
>get skull
I don't see that here.
问题原因

核心问题是大小写不匹配:你先把整个输入转成了title()格式(比如输入get skull变成Get Skull),之后拆分取物品名时又转成小写的skull,但房间里存储的物品是Skull(首字母大写),导致匹配失败。另外原代码没有处理输入get后无参数的情况,容错性不足。

解决方案

修改代码,统一处理输入的大小写,确保单/双字词物品都能正确匹配:

while True:
    instructions()
    player_status(rooms, current_room, inventory)
    time.sleep(0.5)

    # 先统一转小写并去空格,避免大小写干扰
    raw_input = input('\nWhat do you want to do?\n>').strip().lower()
    command_parts = raw_input.split(maxsplit=1)
    action = command_parts[0]

    # 处理移动:转回首字母大写适配房间字典的键(比如'North')
    if action.title() in rooms[current_room]:
        current_room = rooms[current_room][action.title()]
        time.sleep(0.5)

    # 处理拿取物品
    elif action == 'get':
        # 检查是否输入了物品名
        if len(command_parts) < 2:
            print("Get what?")
            continue
        
        target_obj = command_parts[1]
        room_item = rooms[current_room].get('item')
        
        # 统一用小写匹配,成功后保留原物品名存入库存
        if room_item and target_obj == room_item.lower():
            del rooms[current_room]['item']
            inventory.append(room_item)
            print(f"You picked up the {room_item}!")
        else:
            print("I don't see that here.")

    # 退出游戏
    elif action in ('q', 'quit'):
        time.sleep(0.5)
        print('\nThanks for playing.')
        break

    # 无效指令
    else:
        time.sleep(0.5)
        print('\nYou can\'t go that way!')
修改说明
  1. 先把输入整体转小写拆分,避免用户输入大小写不一致导致的匹配问题;
  2. 移动指令单独转回首字母大写,适配房间字典里的方向键格式;
  3. 增加了get指令无参数的判断,给出明确提示;
  4. 物品匹配时统一用小写对比,成功后保留原物品名(比如Skull)存入库存,显示更自然。

内容的提问来源于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:20:43