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

Python文本游戏get指令拾取物品失败无法加入Inventory修复

问题描述

开发文本类游园主题冒险游戏时,全方向移动功能运行正常,但输入get指令拾取房间内物品时,程序始终触发else分支返回提示:I don't see that here.,拾取的物品无法正常添加到Inventory背包列表中。

核心问题原因
  • 多词物品读取逻辑错误:原有代码用command.lower().split()[1]提取物品名,仅会获取get后第一个空格前的内容,而游戏内所有可拾取物品均为带空格的多词名称(如balloon animal、big red shoes),提取到的片段和完整物品名无法匹配,直接触发错误提示
  • 房间字典键名不统一:初始房间Entrance存储物品的键为content(少末尾s),其余房间均为contents,后续统一调用contents键时会触发键错误
  • 拾取逻辑缺失关键步骤:匹配到物品后未将物品从当前房间移除,会导致同一物品可重复拾取;拾取成功的提示打印整个房间物品列表,而非当前拾取的单个物品
  • 胜负判定位置错误:FunHouse的胜负结算逻辑写在主游戏循环外,玩家进入FunHouse时不会触发结算,游戏会卡在输入等待状态
修正后的完整代码
#Start

rooms = {
    'Entrance': {'name': 'Entrance', 'North': 'Food Area', 'East': 'Carousel', 'West': 'Game Area',
                 'contents': [], 'text': 'The Entrance'},

    'Carousel': {'name': 'Carousel', 'West': 'Entrance', 'contents': ['balloon animal'],
                 'text': 'This is the Carousel. Grab the Balloon Animal.'},

    'Game Area': {'name': 'Game Area', 'North': 'FunHouse', 'East': 'Entrance', 'contents': ['big red shoes'],
                  'text': 'This is the Game Area. Grab the Big Red Shoes.'},

    'Food Area': {'name': 'Food Area', 'South': 'Entrance', 'East': 'Tilt-O-Whirl', 'North': 'Ferris Wheel',
                  'contents': ['red nose'], 'text': 'This is the Food Area. Grab the Red Nose.'},

    'Ferris Wheel': {'name': 'Ferris Wheel', 'South': 'Food Area', 'contents': ['clown suit'],
                     'text': 'This is the Ferris Wheel. Grab the Clown Suit.'},

    'Roller Coaster': {'name': 'Roller Coaster', 'South': 'Tilt-O-Whirl', 'contents': ['blow torch'],
                       'text': 'This is the Roller Coaster. Grab the Blow Torch.'},

    'Tilt-O-Whirl': {'name': 'Tilt-O-Whirl', 'North': 'Roller Coaster', 'West': 'Food Area',
                     'contents': ['rainbow wig'], 'text': 'This is the Tilt-O-Whirl. Grab the Rainbow Wig.'},

    'FunHouse': {'name': 'FunHouse', 'South': 'Game Area', 'contents': ['clown'],
                 'text': 'This is the FunHouse. Beat the Clown!'}
}
directions = ['North', 'South', 'East', 'West']
currentRoom = rooms['Entrance']
Inventory = []


def show_instructions():
    # 打印主菜单和操作说明
    print('-------------------------------------------------------')
    print("Welcome to A Day at the Fair")
    print("Collect all 6 items while avoiding the clown or be captured by Nickel Knowing")
    print("Move commands: South, North, East, West")
    print("Add to Inventory: get 'item name'")
    print('-------------------------------------------------------')


show_instructions()

while True:
    # 展示当前房间信息和已有背包
    print('You are in {}.'.format(currentRoom['text']))
    if currentRoom['contents']:
        print(f'Items here: {", ".join(currentRoom["contents"])}')
    print(f'Your Inventory: {", ".join(Inventory) if Inventory else "empty"}')
    
    # 获取用户输入
    command = input('\nWhat do you do? ').strip()
    # 移动逻辑
    if command in directions:
        if command in currentRoom:
            currentRoom = rooms[currentRoom[command]]
        else:
            print("You cant go that way.")
    # 退出游戏
    elif command.lower() in ('q', 'quit'):
        break
    # 拾取物品逻辑
    elif command.lower().startswith('get '):
        item_input = ' '.join(command.lower().split()[1:]).strip()
        room_items_lower = [item.lower() for item in currentRoom['contents']]
        if item_input in room_items_lower:
            # 匹配到物品,获取原格式名称
            target_item = currentRoom['contents'][room_items_lower.index(item_input)]
            Inventory.append(target_item)
            currentRoom['contents'].remove(target_item)
            print(f'You grabbed the {target_item}.')
        else:
            print("I don't see that here.")
    # 非法指令兜底
    else:
        print("Invalid command, try again.")

    # 每次操作后判断是否进入FunHouse触发结算
    if currentRoom == rooms['FunHouse']:
        if len(Inventory) == 6:
            print('You collected all of the items, and defeated Nickel Knowing the Clown!')
        else:
            print('It looks like you have not found everything, you lose!')
        break
关键修改说明
  • 统一所有房间的物品存储键:将Entrance的content键改为contents,赋值为空列表,避免键不存在报错
  • 修复多词物品解析逻辑:用' '.join(command.lower().split()[1:])拼接get后的所有内容,支持带空格的物品名匹配
  • 完善拾取流程:匹配到物品后同步将物品从当前房间的物品列表中移除,防止重复拾取;修正拾取提示为当前获取的单个物品名
  • 调整结算逻辑位置:将FunHouse的胜负判断移入主循环,每次操作后检测当前房间,进入FunHouse立刻触发结算
  • 新增体验优化:每次进入房间展示当前房间可拾取物品、玩家当前背包内容,新增非法指令兜底提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 14:15:30