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

Python文本冒险游戏物品获取功能故障排查求助

问题分析与修复方案

核心问题

  1. 函数定义语法错误:main()定义前缺少def关键字,直接运行会触发语法错误。
  2. 拾取逻辑嵌套错误:处理Get命令的代码被放在了if command in rooms[players_room](判断是否为房间移动指令)的分支里,但Get Notepad并不是房间方向键,导致这段代码永远不会被执行。
  3. Inventory存储逻辑错误:当前用房间名称作为字典键存储物品,玩家切换房间后无法查看已拾取的全部物品,应该改为用列表存储所有拾取的物品。
  4. 命令格式化问题:使用capitalize()会把输入的Get Notepad转为Get notepad,虽不影响startswith判断,但统一用小写处理更稳妥,避免大小写输入导致的识别问题。

修复后的完整代码

def main():
    while True:
        players_room = "Kitchen"
        inventory = []  # 改为列表存储所有拾取的物品

        print(
            "Welcome to Barbie’s Dream House! Collect six items to help Barbie defeat the brainwashing Ken by using "
            "the directions North, South, East, and West to move between the rooms. To add to inventory, "
            "type: Get 'item name'. Good luck!")

        rooms = {
            "Kitchen": {"East": "Pool", "South": "Dining Room"},
            "Pool": {"item": "Ken"},
            "Dining Room": {"South": "Living Room", "West": "Bathroom", "East": "Bedroom", "item": "Notepad"},
            "Bathroom": {"East": "Dining Room", "item": "Hairspray"},
            "Living Room": {"North": "Dining Room", "East": "Study", "item": "Laptop"},
            "Study": {"West": "Living Room", "item": "History Book"},
            "Bedroom": {"West": "Dining Room", "North": "Closet", "item": "Cellphone"},
            "Closet": {"South": "Bedroom", "item": "Studious Outfit"}
        }

        while players_room != "exit":
            print(f'You are in the {players_room}.')
            # 显示完整inventory
            if inventory:
                print(f'Inventory: {", ".join(inventory)}')
            else:
                print("Inventory: Empty")

            if "item" in rooms[players_room]:
                print(f'You see a {rooms[players_room]["item"]}')

            command = input('Enter your move: ').strip()
            command_low = command.lower()  # 统一转为小写处理,避免大小写问题

            # 先处理拾取物品命令
            if command_low.startswith("get "):
                item_name = command[4:].strip()
                item_name_low = item_name.lower()
                if "item" in rooms[players_room] and rooms[players_room]["item"].lower() == item_name_low:
                    picked_item = rooms[players_room]["item"]
                    print(f'You have picked up the {picked_item}.')
                    inventory.append(picked_item)
                    rooms[players_room].pop("item")
                    print(f'{picked_item} added to your inventory.')
                else:
                    print("There's no such item here.")
            # 处理房间移动命令
            elif command_low in [dir.lower() for dir in rooms[players_room].keys() if dir != "item"]:
                # 找到对应的正确大小写的方向键
                actual_dir = next(dir for dir in rooms[players_room] if dir.lower() == command_low)
                players_room = rooms[players_room][actual_dir]
                if players_room == "Pool":
                    print("Ken brainwashed Barbie - Game over!")
                    break
            # 处理退出命令
            elif command_low == "exit":
                players_room = "exit"
            # 无效命令
            else:
                print("Invalid command. Try again.")

        # 检查是否收集所有物品
        collected_count = sum(1 for room in rooms.values() if "item" not in room or room["item"] == "Ken")
        if collected_count == 6:  # 除了Ken之外的6个物品
            print("Congratulations! You have collected all six items! You helped Barbie defeat the brainwashing Ken!")

        play_again = input("Do you want to play again? (yes/no): ").lower()
        if play_again != "yes":
            break

    print('Thanks for playing!')


if __name__ == "__main__":
    main()

关键修改点说明

  • 补全main函数定义的def关键字,修复语法错误。
  • 将Get命令的处理逻辑移到最前面,优先判断拾取指令,不再嵌套在移动逻辑里。
  • 将inventory从字典改为列表,存储玩家拾取的所有物品,切换房间后仍能显示全部物品。
  • 统一用小写处理命令输入,避免大小写输入导致的识别错误,同时保留物品名称的原始大小写显示。
  • 修正物品收集完成的判断逻辑,确保只有收集完6个非Ken的物品后才触发胜利条件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 12:16:14