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

文本类房间探索游戏物品拾取功能故障求助

问题:文本游戏物品拾取及存入背包功能无法正常运行

我开发了一款可在房间间移动、收集物品击败Boss的文本游戏,目前移动逻辑与游戏结束逻辑已实现,但物品拾取及存入inventory的功能始终无法正常运行。查阅大量资料、尝试多种方法仍未解决,恳请指点方向。

原代码

rooms = {'Entrance Hall': {'name': 'Entrance Hall', 'west': 'Loft', 'item': 'no items'},
         'Loft': {'name': 'Loft', 'north': 'Dining Room', 'east': 'Entrance Hall', 'item': 'sword'},
         'Dining Room': {'name': 'Dining room', 'west': 'Study', 'east': 'Bedroom', 'north': 'Apothecary', 'south': 'Loft', 'item': 'garlic'},
         'Study': {'name': 'Study', 'east': 'Dining Room', 'item': 'scroll'},
         'Bedroom': {'name': 'Bedroom', 'west': 'Dining Room', 'north': 'Living Room', 'item': 'torch'},
         'Living Room': {'name': 'Living Room', 'south': 'Bedroom', 'item': 'boots'},
         'Apothecary': {'name': 'Apothecary', 'south': 'Dining Room', 'east': 'Basement', 'item': 'potion'},
         'Basement': {'name': 'Basement', 'west': 'Apothecary', 'item': 'no item'}
         }
#defining game instrucions
def game_instructions():
    print('Welcome to the Dracula game')
    print('You have traveled to Draculas mansion to put an end to his terror')
    print('You will need to collect 6 items around his mansion to be able to defeat him and win')
    print('If you go into the basement without the 6 items, you lose')
    print('Move commands: north, south, east and west')
    print('When moving to a new room if there is an item, type "get" to pick it up or leave behind')

def user_status():
    print('
 ------------------------')
    print('You are currently in the {}.'.format(current_room['name']))
    print('In this room you see a {}' .format(current_room['item']))
    print('Inventory: ', inventory)
    print('
 ------------------------')


def get_item(current_room, user_input, rooms, inventory):
    inventory.append(rooms[current_room]['item'])
    del rooms[current_room]['item']

#setting directions to the variables
directions = ['north', 'south', 'east', 'west']
#starting room
current_room = rooms['Entrance Hall']
#calling on game instructions
game_instructions()
inventory = []


# Starting game loop
continue_loop = True
while continue_loop:
    if current_room['name'] == 'Basement':
        if len(inventory) == 6:
            print('You have collected all the items and defeated dracula')
            print('Thank you for playing')
        else:
            print('You have not collected all the items and dracula was too strong')
            print('You lose, thanks for playing')
        continue_loop = False
    else:
        user_status()
        # Displaying current room
       # print('You are currently in the {}.'.format(current_room['name']))

        # getting user direction
        user_input = input('
Which direction would you like to go?')
        # deciding where to go based on input
        if user_input in directions:
            if user_input in current_room:
                current_room = rooms[current_room[user_input]]#moving player to new room if input is valid
            else:
                # input was not in specific rooms directions
                print('You cannot go that way.')
        if len(user_input) == 4 and user_input == 'get' and s.join(user_input[1:3]) in rooms[current_room]['item']:
            print('You pick up {}'.format(rooms[current_room]['item']))
            get_item()
            continue
        # input was not valid, not in move commands
        else:
            print('Invalid input')
            continue

问题排查与修复点

1. 物品拾取判断逻辑完全错误

原代码中get指令的判断条件存在多处问题:

  • user_input == 'get'时长度为3,不是4,条件永远不成立
  • 未定义变量s,会直接抛出NameError
  • 无需额外判断物品是否在房间文本中,直接检查当前房间的item字段即可

2. 函数调用参数缺失

get_item定义时需要4个参数,但调用时get_item()未传参,会抛出TypeError。同时函数内部rooms[current_room]['item']写法错误,current_room已经是房间字典,直接使用current_room['item']即可。

3. 房间物品状态更新不规范

原代码中删除房间的item键后,后续user_status打印时会因找不到键报错,应将物品设置为'no items'而非删除键,保持数据结构一致性。

4. 指令判断逻辑顺序冲突

原代码中方向判断和get判断为平级if,输入get时会先进入方向判断的else分支,打印"Invalid input",需改为elif结构避免逻辑冲突。

修复后的完整代码

rooms = {'Entrance Hall': {'name': 'Entrance Hall', 'west': 'Loft', 'item': 'no items'},
         'Loft': {'name': 'Loft', 'north': 'Dining Room', 'east': 'Entrance Hall', 'item': 'sword'},
         'Dining Room': {'name': 'Dining room', 'west': 'Study', 'east': 'Bedroom', 'north': 'Apothecary', 'south': 'Loft', 'item': 'garlic'},
         'Study': {'name': 'Study', 'east': 'Dining Room', 'item': 'scroll'},
         'Bedroom': {'name': 'Bedroom', 'west': 'Dining Room', 'north': 'Living Room', 'item': 'torch'},
         'Living Room': {'name': 'Living Room', 'south': 'Bedroom', 'item': 'boots'},
         'Apothecary': {'name': 'Apothecary', 'south': 'Dining Room', 'east': 'Basement', 'item': 'potion'},
         'Basement': {'name': 'Basement', 'west': 'Apothecary', 'item': 'no item'}
         }

def game_instructions():
    print('Welcome to the Dracula game')
    print('You have traveled to Draculas mansion to put an end to his terror')
    print('You will need to collect 6 items around his mansion to be able to defeat him and win')
    print('If you go into the basement without the 6 items, you lose')
    print('Move commands: north, south, east and west')
    print('When in a room with an item, type "get" to pick it up')

def user_status():
    print('\n------------------------')
    print('You are currently in the {}.'.format(current_room['name']))
    print('In this room you see a {}' .format(current_room['item']))
    print('Inventory: ', inventory)
    print('\n------------------------')

def get_item(current_room, inventory):
    # 只拾取非空物品
    if current_room['item'] not in ['no items', 'no item']:
        inventory.append(current_room['item'])
        current_room['item'] = 'no items'  # 保持键存在,避免报错

directions = ['north', 'south', 'east', 'west']
current_room = rooms['Entrance Hall']
game_instructions()
inventory = []

continue_loop = True
while continue_loop:
    if current_room['name'] == 'Basement':
        if len(inventory) == 6:
            print('You have collected all the items and defeated dracula')
            print('Thank you for playing')
        else:
            print('You have not collected all the items and dracula was too strong')
            print('You lose, thanks for playing')
        continue_loop = False
    else:
        user_status()
        user_input = input('\nWhat would you like to do? ')
        user_input = user_input.strip().lower()  # 统一转为小写,去除空格
        
        if user_input in directions:
            if user_input in current_room:
                current_room = rooms[current_room[user_input]]
            else:
                print('You cannot go that way.')
        elif user_input == 'get':
            if current_room['item'] in ['no items', 'no item']:
                print('There is no item to pick up here.')
            else:
                print('You pick up {}'.format(current_room['item']))
                get_item(current_room, inventory)
        else:
            print('Invalid input. Use move commands (north/south/east/west) or "get" to pick up items.')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:45:50