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

Python文本游戏get命令故障求助:物品无法加入inventory且显示异常

Python文本游戏问题求助:物品拾取功能异常

为完成这个Python文本类游戏作业我花了不少功夫,反复调试代码但找不到问题所在。我想实现get命令让玩家拾取房间内物品,但物品没法添加到定义好的空inventory列表里,而且物品输出只显示'item',不是房间里的实际物品。因为时间限制只能提交这个没法正常运行的版本,希望大家帮忙找出错误并给出修改建议。

原代码

main_menu = 'Move commands: North, East, South, West, Exit.'

def showinstructions():
    print('Death to the Lich')  # Name of game
    print('Collect all items in order to defeat the evil Lich in his spooky Mansion')  # Goal of game
    print(main_menu)  # Show move commands
    print("Add item to inventory: get 'item name'")  # Add item to inventory: get 'item name'


def player_status(inventory, location, rooms):
    print('Inventory:', inventory)
    print('YOu are in here:', location)
    if 'item' in rooms[location]:
        print('Ah, look what you have found!', rooms[location]['item'])

def main():
    inventory = []
    rooms = {
        'Living Room': {'South': 'Bedroom', 'North': 'Dungeon', 'East': 'Alchemy Room', 'West': 'Library'},
        'Bedroom': {'North': 'Living Room', 'East': 'Cellar', 'item': 'Shiny Armor'},
        'Cellar': {'West': 'Bedroom', 'item': 'Shiny Helmet'},
        'Dungeon': {'South': 'Living Room', 'East': 'Gallery', 'item': 'Silver Sword'},
        'Gallery': {'West': 'Dungeon', 'item': 'Magic Potion'},
        'Alchemy Room': {'West': 'Living Room', 'North': 'Dining Room', 'item': 'Silver Sword'},
        'Dining Room': {'South': 'Alchemy Room', 'item': 'Shiny Gloves'},
        'Library': {'East': 'Living Room', 'item': 'Lich'}
    }


    # The main function:
    location = 'Living Room'

    showinstructions()




    while True:
        print('\nYou are in the', location)

        move_options = rooms[location].keys()
        print('Move options:', *move_options)

        command = input('Which direction will you go?').strip()
        print('You entered:', command)

        if 'item' in 'location':
            print('You see this in the room:', rooms[location]['item'])
        if command == 'get':
            item = input()
            inventory.append(item)
        else:
            print('There is no item here')

        if location == 'Library':
            print('I am the Evil Lich! Prepare to die!')
            if len(inventory) >= 6:
                print('You are the hero of these Lands! YOU WON!')
            else:
                print('Sadly you werent not strong enough to defeat the Lich. YOU LOSE')
                break
        if command == "Exit":
            print('Thanks for playing!')
            break
        elif command in move_options:
            location = rooms[location][command]
        else:
            print('Wrong direction!')



main()

错误分析与修复方案

  • 物品检测逻辑错误:原代码中if 'item' in 'location':是检查字符串"location"里是否包含"item",这永远为False。正确写法是if 'item' in rooms[location]:,用来判断当前房间是否存在物品。
  • get命令处理逻辑混乱:原代码输入get后要求用户再输入物品名,但未验证物品是否在当前房间,且非get命令时会错误输出"There is no item here"。应改为识别以get 开头的命令,提取物品名后验证是否存在于当前房间,添加到背包后从房间移除物品,避免重复拾取。
  • 未调用玩家状态函数:定义了player_status但未在主循环中调用,导致无法正确显示背包和房间物品信息。
  • 胜利条件与物品数量不匹配:房间内包含两把"Silver Sword",共7件物品,但胜利条件是背包物品数≥6,可调整物品或胜利条件消除歧义。
  • 拼写错误:player_status函数中的YOu are in here应修正为You are in here。

修改后的完整代码

main_menu = 'Move commands: North, East, South, West, Exit.'

def showinstructions():
    print('Death to the Lich')  # Name of game
    print('Collect all items in order to defeat the evil Lich in his spooky Mansion')  # Goal of game
    print(main_menu)  # Show move commands
    print("Add item to inventory: get 'item name'")  # Add item to inventory: get 'item name'


def player_status(inventory, location, rooms):
    print('Inventory:', inventory)
    print('You are in here:', location)
    if 'item' in rooms[location]:
        print('Ah, look what you have found!', rooms[location]['item'])

def main():
    inventory = []
    rooms = {
        'Living Room': {'South': 'Bedroom', 'North': 'Dungeon', 'East': 'Alchemy Room', 'West': 'Library'},
        'Bedroom': {'North': 'Living Room', 'East': 'Cellar', 'item': 'Shiny Armor'},
        'Cellar': {'West': 'Bedroom', 'item': 'Shiny Helmet'},
        'Dungeon': {'South': 'Living Room', 'East': 'Gallery', 'item': 'Silver Sword'},
        'Gallery': {'West': 'Dungeon', 'item': 'Magic Potion'},
        'Alchemy Room': {'West': 'Living Room', 'North': 'Dining Room', 'item': 'Silver Dagger'},  # 修改物品避免重复
        'Dining Room': {'South': 'Alchemy Room', 'item': 'Shiny Gloves'},
        'Library': {'East': 'Living Room', 'item': 'Lich'}
    }


    # The main function:
    location = 'Living Room'

    showinstructions()

    while True:
        # 调用状态显示函数
        player_status(inventory, location, rooms)
        print('\n')

        move_options = [key for key in rooms[location].keys() if key != 'item']
        print('Move options:', *move_options)

        command = input('Enter your command:').strip()
        print('You entered:', command)

        # 处理get命令
        if command.lower().startswith('get '):
            target_item = command[4:].strip()
            if 'item' in rooms[location] and rooms[location]['item'] == target_item:
                inventory.append(target_item)
                del rooms[location]['item']
                print(f'You picked up {target_item}!')
            else:
                print('That item is not in this room!')
        # 处理Exit命令
        elif command == "Exit":
            print('Thanks for playing!')
            break
        # 处理移动命令
        elif command in rooms[location]:
            location = rooms[location][command]
            # 进入图书馆触发战斗
            if location == 'Library':
                print('I am the Evil Lich! Prepare to die!')
                if len(inventory) >= 6:
                    print('You are the hero of these Lands! YOU WON!')
                else:
                    print('Sadly you weren\'t strong enough to defeat the Lich. YOU LOSE')
                break
        else:
            print('Invalid command!')

main()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 15:12:04