KeyError in text based adventure game python


I have just about completed my text based adventure game and for the most part it’s functioning as intended the only problem I have is that when the player moves into a room that has an item one of the possible moves becomes item. One of the actions that the player can take is to get said item the problem is that for whatever reason the player can also move into the item by typing go item. This throws a bug and then breaks the game.


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!')


#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 = rooms[current_room].keys()
    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}")

                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.')

            print('With the help of these powerful items you are able to slay the Dragon!n Congratulations you won!!')

#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":

            current_room = rooms[current_room][directions]
            print(f"You move {directions}")

            print('You cant go that way please try again.')

#gathering of the items

    elif action == "Get":

            if Item == rooms[current_room]["Item"]:

                if Item not in inventory:

                    print(f"You got a {Item}")

                    print('You already have that Item')

                print('You cant see any Items.')

            print('You cant see any Items.')

#exit function

    elif action == "Exit":
        print('Thank you for playing')

        print('invalid input please try again.')

Traceback (most recent call last):
  File "", line 43, in <module>
    possible_moves = rooms[current_room].keys()
KeyError: 'Castle Key'

This is my code and the error that is being thrown I’m not sure if there’s any other detail I need to give I’m still pretty new to Python And stack overflow so if you need any further detail please ask and I will try my best to answer thank you.

as far as I can tell this line of code is the problem

print("possible moves: ", *possible_moves)

From my understanding of what it does it actually takes the whole dictionary and any of the keys involved and makes it a possible move in the print which is causing the problem of having go item as a command. The issue is I just don’t know how to fix it.

Asked By: Foify



You can explicitly forbid player to call Go Item.

Replace if action == "Go": with if action == "Go" and directions != "Item":

Answered By: Alderven
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.