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

Python文本游戏Inventory功能故障求助:去重与交互逻辑优化

Python文本冒险游戏物品拾取功能修复与优化

问题排查

原代码存在以下核心问题:

  • get item命令被错误嵌套在移动指令分支中,永远无法触发
  • 房间物品存储为列表,但判断时用字符串'none'对比,逻辑失效
  • 缺少当前房间物品提示,玩家无法知晓可拾取物品
  • 无拾取确认交互,也未实现非药水物品的重复拾取限制

修复优化后的代码

def instructions():
    print("-------------Instructions-------------")
    print("Collect the Fire Sword, Shield, and Magic key to defeat the Demon King Nox and save Princess Calista. ")
    print("Find the Magic Ring and Healing potions to assist you but be careful of the traps King Nox has set up!")
    print("To move type: north, south, east, or west.")
    print("To pick up items type 'get item'.")
    print("To stop playing type 'quit'.")
    print('-' * 38)


def game_sum():
    print("\n        Text Adventure Game")
    print('-' * 38)
    print("The princess of the kingdom Chrysanthemum was kidnapped by the Demon King, Nox.")
    print("King Nox wants to steal Princess Calista's magic and life force to take over her kingdom.")
    print("Her loyal knight must save the princess from the Demon King before it is too late.")
    print(' ' * 38)

game_sum()
instructions()

# data setup
rooms = {'Great Hall': {'name': 'Great Hall', 'item': None, 'south': 'Vendetta Room', 'east': 'Kitchen',
                        'north': 'Potion Lab', 'west': 'Armory',
                        'text': 'You are in the Great Hall.'},

         'Armory': {'name': 'the Armory', 'item': 'Fire Sword', 'east': 'Great Hall', 'north': 'Treasure Room',
                    'text': 'You are in the Armory.'},

         'Treasure Room': {'name': 'the Treasure Room', 'item': 'Magic Ring', 'south': 'Armory',
                           'text': 'You are in the Treasure Room.'},

         'Potion Lab': {'name': 'the Potion Lab', 'item': 'Healing Potion', 'east': 'Bedroom', 'south': 'Great Hall',
                        'text': 'You are in the Potion Lab.'},

         'Bedroom': {'name': 'the Bedroom', 'item': 'Magic Key', 'west': 'Potion Lab',
                     'text': 'You are in the Bedroom.'},

         'Kitchen': {'name': 'the Kitchen', 'item': 'Sandwich', 'south': 'Storage', 'west': 'Great Hall',
                     'text': 'You are in the Kitchen.'},

         'Storage': {'name': 'Storage', 'item': 'Shield', 'east': 'Mystery Room',
                     'text': 'You are in Storage.'},

         'Mystery Room': {'name': 'the Mystery Room', 'item': None, 'west': 'Storage', 'north': 'Kitchen',
                          'text': 'You are in the Mystery Room.'},

         # villain
         'Vendetta Room': {'name': 'the Vendetta Room', 'item': None, 'west': 'Dungeon', 'north': 'Great Hall',
                           'text': 'You are in the Vendetta Room.'},

         # Princess
         'Dungeon': {'name': 'the Dungeon', 'item': None, 'east': 'Vendetta Room',
                     'text': 'You are in the Dungeon.'}
         }

directions = ['north', 'south', 'east', 'west']
current_room = rooms['Great Hall']
inventory = []

# game loop
while True:
    # 通关判断
    if current_room['name'] == 'the Dungeon':
        print('Congratulations! You have reached the Dungeon and saved the Princess!')
        break

    # 显示当前状态
    print(f"You are in {current_room['name']}.")
    # 提示当前房间物品
    if current_room['item']:
        print(f"Notice: There's a {current_room['item']} here!")
    print(f"Your current inventory: {inventory}\n")

    # 获取用户指令
    command = input('Enter Move: ').strip().lower()

    # 移动指令处理
    if command in directions:
        if command in current_room:
            current_room = rooms[current_room[command]]
        else:
            print('You cannot go that way.')
    # 拾取物品指令处理
    elif command == 'get item':
        room_item = current_room['item']
        if not room_item:
            print("No items to collect in this room.")
            continue
        
        # 非药水物品重复拾取判断
        if room_item != 'Healing Potion' and room_item in inventory:
            print(f"You already have the {room_item}!")
            continue
        
        # 询问是否拾取
        confirm = input(f"Do you want to pick up the {room_item}? (yes/no): ").strip().lower()
        if confirm == 'yes':
            inventory.append(room_item)
            # 拾取后移除房间内的物品,防止重复拾取
            current_room['item'] = None
            print(f"You acquired: {room_item}")
        else:
            print("You chose not to pick up the item.")
    # 退出游戏
    elif command == 'quit':
        print('Thanks for playing!')
        break
    # 无效指令
    else:
        print('Invalid input. Try moving, "get item", or "quit".')

关键修改说明

  • 调整物品存储结构:将房间的item从列表改为单个字符串/None,简化判断逻辑
  • 修正指令分支:将get item指令从移动分支中移出,单独处理,确保能被触发
  • 添加物品提示:进入房间后自动显示当前存在的可拾取物品
  • 实现拾取交互:询问玩家是否确认拾取物品
  • 重复拾取限制:非药水物品已在背包中时,禁止再次拾取;拾取后清空房间物品,避免重复触发
  • 优化指令提示:在说明中添加get item指令的使用提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:45:34