Pyhton Move Between Rooms

Question:

I am trying to move between rooms using a dict and I can navigate if the room only has 1 location to move to but when it has more than one I get an error.

# The dictionary links a room to other rooms.
rooms = {
    'Great Hall': {'South': 'Bedroom'},
    'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
    'Cellar': {'West': 'Bedroom'}
}


def instructions():
    print("Milestone for Module 6.")
    print("Type 'go' and then the direction want to move in lowercase")
    print("You can type exit to leave the game after this menu")

current_room = 'Great Hall'
direction = ''

while True:
    print('nYou are in:', current_room)

    direction = input('Move which direction?')
    print('You entered:', direction)

    if direction == 'quit':
        print('Game Exited')
        break

    elif direction == 'go north':
        if 'North' in rooms[current_room].keys():
            current_room = str(*rooms[current_room].values())
        else:
            print('Unable to move to that location, try again.')

    elif direction == 'go south':
        if 'South' in rooms[current_room].keys():
            current_room = str(*rooms[current_room].values())
        else:
            print('Unable to move to that location, try again.')

    elif direction == 'go east':
        if 'East' in rooms[current_room].keys():
            current_room = str(*rooms[current_room].values())
        else:
            print('Unable to move to that location, try again.')

    elif direction == 'go west':
        if 'West' in rooms[current_room].keys():
            current_room = str(*rooms[current_room].values())
        else:
            print('Unable to move to that location, try again.')
    else:
        print('Invalid, please try again.')

Would like to resolve this error and move rooms correctly.

Traceback (most recent call last):
  line 40, in <module>
    current_room = str(*rooms[current_room].values())
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: decoding str is not supported
Asked By: midokite

||

Answers:

When you use str(*rooms[current_room].values()) and if it has more than one value in the dictionary, it will result in a TypeError. So, you should be store the values in the dict and use index to access a particular room, like this:

.
.
elif direction == 'go north':
    if 'North' in rooms[current_room].keys():
        current_room = rooms[current_room]['North']
    else:
        print('Unable to move to that location, try again.')
Answered By: Subhash Prajapati
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.