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

Python文字冒险游戏KeyError问题及移动逻辑修复求助

Python文字冒险游戏KeyError问题修复

问题描述

开发的文字冒险游戏接近完成,但存在崩溃问题:当玩家进入包含物品的房间时,possible_moves会把Item列为可移动选项,玩家输入go item后触发KeyError: 'Castle Key',直接导致游戏崩溃。

问题根源

  1. 错误展示可选项:原代码中possible_moves = rooms[current_room].keys()会把房间字典的所有键(包括Item、Boss这类非方向键)都当作移动选项展示,误导玩家输入无效指令。
  2. 输入处理逻辑漏洞:当玩家输入go item时,代码会将directions赋值为'Item',随后执行current_room = rooms[current_room]['Item']——这会把当前房间替换为物品名称(比如Castle Key),而下一次循环访问rooms[current_room]时,rooms字典中根本不存在以物品名为键的条目,因此触发KeyError。

修复方案

1. 过滤有效移动方向

修改possible_moves的生成逻辑,只保留方位类键(North/South/East/West),避免展示非移动选项:

# 替换原possible_moves赋值行
possible_moves = [key for key in rooms[current_room].keys() if key in ['North', 'South', 'East', 'West']]

2. 加固移动指令校验

在处理Go动作时,先判断输入的方向是否属于当前房间的有效方位,避免错误修改current_room:

# 替换原Go动作的处理代码
if action == "Go":
    valid_directions = [key for key in rooms[current_room].keys() if key in ['North', 'South', 'East', 'West']]
    if directions in valid_directions:
        current_room = rooms[current_room][directions]
        print(f"You move {directions}")
    else:
        print('You cant go that way please try again.')

修复后完整代码

#dictionary

rooms = {
    'Foyer': {'South': 'Great Hall'},
    'Great Hall': {'North': 'Foyer', 'East': 'The Solar', 'South': 'Chapel',
                   'West': 'Bed Chamber', 'Item': 'Castle Key'},
    'Chapel': {'North': 'Great Hall', 'East': 'Guardrooms', 'South': 'Castle Keep',
               'West': 'The Kitchen', 'Item': 'Blessed Amulet'},
    'Bed Chamber': {'East': 'Great Hall', 'South': 'The Kitchen', 'Item': 'Shield'},
    'The Solar': {'West': 'Great Hall', 'South': 'Guardrooms', 'Item': 'Book On Dragons'},
    'The Kitchen': {'North': 'Bed Chamber', 'East': 'Chapel', 'Item': 'Potion Of Frost'},
    'Guardrooms': {'North': 'The Solar', 'West': 'Chapel', 'Item': 'Sword'},
    'Castle Keep': {'North': 'Chapel', 'Boss': 'Dragon'}
    }

#opening prompt to explain controls and objective

def prompt():
    print('Welcome adventure!\n'
      'For this game you will use the cardinal directions in order to move about the rooms or enter exit to quit!\n'
      'You can do this by typing go north, go south, go east, go west.\n'
      'In this game you must collect all of the items before you enter the Castle Keep to slay the Dragon to win!\n'
          "To grab an item simply type get 'item name'.\n")
    input('Please press any key to begin!')

prompt()

#setting the opening setting
current_room = 'Foyer'
inventory = []
directions = ['Go North', 'Go south', 'Go East', 'Go West']

#Gameplay loop defining what the player has what room they are in and what is around them
while True:
    print("\nYou are in the", current_room)
    # 过滤有效移动方向
    possible_moves = [key for key in rooms[current_room].keys() if key in ['North', 'South', 'East', 'West']]
    print("possible moves: ", *possible_moves)
    print(f"Inventory : {inventory}")

    if 'Item' in rooms[current_room].keys():
        close_item = rooms[current_room]["Item"]
        if close_item not in inventory:
            if close_item[-1] == 's':
                print(f"You see {close_item}")
            else:
                print(f"You see a {close_item}")

#Boss encounter and ending of the game
    if "Boss" in rooms[current_room].keys():
        if len(inventory) != 6:
            print('With out the help of all the items you are defeated by the Dragon.')
            break
        else:
            print('With the help of these powerful items you are able to slay the Dragon!\n Congratulations you won!!')
            break

#movement of the player
    user_input = input("Enter your move:\n")
    next_move = user_input.split(' ')
    action = next_move[0].title()

    if len(next_move) > 1:
        Item = next_move[1:]
        directions = next_move[1].title()
        Item = ' '.join(Item).title()

    if action == "Go":
        # 校验方向有效性
        valid_directions = [key for key in rooms[current_room].keys() if key in ['North', 'South', 'East', 'West']]
        if directions in valid_directions:
            current_room = rooms[current_room][directions]
            print(f"You move {directions}")
        else:
            print('You cant go that way please try again.')

#gathering of the items
    elif action == "Get":
        try:
            if Item == rooms[current_room]["Item"]:
                if Item not in inventory:
                    inventory.append(rooms[current_room]["Item"])
                    print(f"You got a {Item}")
                else:
                    print('You already have that Item')
            else:
                print('You cant see any Items.')
        except:
            print('You cant see any Items.')

#exit function
    elif action == "Exit":
        print('Thank you for playing')
        break
    else:
        print('invalid input please try again.')

验证效果

修复后:

  • 玩家进入带物品的房间时,只会看到方位类移动选项,不会再出现Item
  • 即使玩家误输入go item,游戏会提示无法前往该方向,不会崩溃
  • 物品收集、Boss战等核心功能正常运行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 04:45:03