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

基于文本的房间探索游戏物品拾取功能故障排查求助

文本游戏物品拾取功能修复方案

我正在开发一款房间漫游拾取物品的简易文本游戏,玩家需收集全部6件物品后挑战最终Boss“Kevin the Shark!”才能获胜。目前房间导航功能正常,但物品拾取模块存在问题:无论输入物品名称或相关指令,系统都会提示“此处无{item}。无效指令”,无法正常拾取物品。以下是我的代码:

#setting up the gameplay
def game_instructions():
   print('---------------------------')
   print("Welcome to Devin's epic battle")
   print("Help Devin collect 6 items to defeat Kevin the Great White Shark")
   print("Move through the reef using: 'north', 'south', 'east', or 'west'")
   print("Each new room you enter will contain one item vital to help you defeat Kevin. \nUse command: 'take item'")
   print("\nGood Luck!")

rooms = {
   'Anemone House' : {'east': 'Crab Lagoon', 'south': 'Octopus Reef', 'item': 'no items'},
   'Crab Lagoon' : {'west': 'Anemone House', 'east': 'Shipwreck Cove', 'item': 'Josh the Crab'},
   'Shipwreck Cove' : {'west': 'Crab Lagoon', 'item': 'Golden Anchor'},
   'Octopus Reef' : {'north': 'Anemone House', 'east': 'Kelp Forest', 'south': 'Ocean Trench', 'item': 'Coral'},
   'Kelp Forest' : {'west': 'Octopus Reef', 'south': 'Shark Reef','item': 'Bottle with Map'},
   'Ocean Trench' : {'north': 'Octopus Reef', 'west': 'Spooky Cave', 'east': 'Shark Reef', 'item': 'Magic Net'},
   'Spooky Cave' : {'east': 'Ocean Trench', 'item': 'Mindy the Stingray'},
   'Shark Reef' : {'west': 'Ocean Trench', 'item': 'Kevin the Shark!'} #badguy
}


def player_status():   #room and inventory
   print('\n---------------------------')
   print('You are in the {}'.format(current_room))
   print('In this room, you find {}'.format(rooms[current_room]['item']))
   print('Inventory: {}'.format(inventory_item))
   print('---------------------------')

def invalid_move():
   print('You cannot go this way. Please try again.')

def invalid_item():
   print('Item is not found in this part of the reef')
   player_status()


game_instructions()

inventory_item = []
current_room = 'Anemone House'
command = ''

while current_room != 'Shark Reef':
   player_status()
   command = input('Enter next move.\n').lower()
   if command == 'take item':
      item = input('Which item do you want to take?').lower()
      if item in rooms[current_room]['item']:
         inventory_item.append(item)
         rooms[current_room]['item'] = 'no items'
      else:
         print(f"There's no {item} here.")
   elif command not in rooms[current_room]:
      invalid_move()
   elif 'item' in rooms[current_room] and command == 'take item':
      invalid_item()
   else:
      current_room = rooms[current_room][command]

if len(inventory_item) != 6:
   print('Oh no, Kevin defeated you!')
else:
   print('You did it! You defeated Kevin!')

问题根源

  1. 大小写不匹配:玩家输入的物品名称被转为小写,但房间存储的物品名称是首字母大写格式(如"Josh the Crab"),直接用item in rooms[current_room]['item']判断时,小写输入无法匹配原字符串,导致误判物品不存在。
  2. 判断逻辑错误:item in rooms[current_room]['item']是检查输入是否为物品名称的子串,而非完全匹配,不符合“输入完整名称才能拾取”的需求。
  3. 冗余条件:elif 'item' in rooms[current_room] and command == 'take item'分支永远不会触发,因为前面已经处理了command == 'take item'的情况,属于无效代码。

修复后的代码

# 设置游戏规则
def game_instructions():
    print('---------------------------')
    print("欢迎来到Devin的史诗之战")
    print("帮助Devin收集6件物品,击败大白鲨Kevin!")
    print("使用指令'north', 'south', 'east', 'west'在珊瑚礁间移动")
    print("每个新房间都有一件击败Kevin必需的物品。使用指令:'take item'拾取")
    print("\n祝你好运!")

rooms = {
    '海葵屋': {'east': '螃蟹泻湖', 'south': '章鱼礁', 'item': '无物品'},
    '螃蟹泻湖': {'west': '海葵屋', 'east': '沉船湾', 'item': '螃蟹Josh'},
    '沉船湾': {'west': '螃蟹泻湖', 'item': '金锚'},
    '章鱼礁': {'north': '海葵屋', 'east': '海藻森林', 'south': '海沟', 'item': '珊瑚'},
    '海藻森林': {'west': '章鱼礁', 'south': '鲨鱼礁', 'item': '带地图的瓶子'},
    '海沟': {'north': '章鱼礁', 'west': '幽灵洞穴', 'east': '鲨鱼礁', 'item': '魔法网'},
    '幽灵洞穴': {'east': '海沟', 'item': '黄貂鱼Mindy'},
    '鲨鱼礁': {'west': '海沟', 'item': '鲨鱼Kevin!'} # Boss房间
}

def player_status():   # 显示当前房间和背包状态
    print('\n---------------------------')
    print(f'你现在在:{current_room}')
    print(f'这个房间里有:{rooms[current_room]["item"]}')
    print(f'背包:{inventory_item}')
    print('---------------------------')

def invalid_move():
    print('这个方向走不通,请重新输入。')

game_instructions()

inventory_item = []
current_room = '海葵屋'
command = ''

while current_room != '鲨鱼礁':
    player_status()
    command = input('请输入下一步操作:\n').lower()
    if command == 'take item':
        # 先检查当前房间是否有可拾取物品
        if rooms[current_room]['item'] == '无物品':
            print('这个房间没有可拾取的物品!')
            continue
        item = input('你想拾取什么物品?').lower()
        # 将房间物品转为小写后完全匹配
        if item == rooms[current_room]['item'].lower():
            inventory_item.append(rooms[current_room]['item'])
            rooms[current_room]['item'] = '无物品'
            print(f'你拾取了:{inventory_item[-1]}')
        else:
            print(f'这里没有{item}。')
    elif command in ['north', 'south', 'east', 'west']:
        # 检查移动方向是否有效
        if command in rooms[current_room]:
            current_room = rooms[current_room][command]
        else:
            invalid_move()
    else:
        print('无效指令,请重新输入。')

if len(inventory_item) != 6:
    print('糟糕!Kevin击败了你!')
else:
    print('太棒了!你击败了Kevin!')

关键修改点

  • 将物品判断改为完全匹配(忽略大小写),确保输入正确名称时能成功拾取。
  • 增加房间无物品时的提示,避免玩家无效操作。
  • 优化指令判断逻辑,区分移动指令与其他无效指令,提示更清晰。
  • (可选)将游戏文本翻译成中文,提升玩家体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 03:50:09