Moving Between Rooms v5

Moving Between Rooms v5

I have code that Instant Feedback - Sense recognizes as working, but doesn't work when ran in PyCharm. It reads as follows:

# First is the Room Dictionary, containing all of the Room IDs and the directions linked to them
rooms = {
    'Main Entry': {'East': 'Main Floor'},
    'Main Floor': {'North': 'North Hall', 'South': 'South Hall', 'East': 'Clothes Store', 'West': 'Main Entry'},
    'South Hall': {'East': 'Food Court', 'North': 'Main Floor'},
    'North Hall': {'East': 'Storage Room', 'South': 'Main Floor'},
    'Clothes Store': {'North': 'Theater', 'West': 'Main Floor'},
    'Theater': {'South': 'Clothes Store'}
}

#The current_room function tracks which "room" the user is in, and starts them in the Main Entry
current_room = 'Main Entry'

#The while loop plays until the user enters exit, to which it then ends the game.
while current_room != 'exit':
    print(f"You are currently in the {current_room}")
    command = input("Enter command: ")
#The commands are what moves the player around. If a direction is input that leads to another room, the current room
#is changed to match that direction. If the direction goes nowhere, the program will have the user input something else.
#Finally, if the input is neither a direction nor exit, it will output the error message
    if command == 'exit':
        current_room = 'exit'
    elif command in ['North', 'South', 'East', 'West']:
        direction = command.split(' ')[1]
        if direction in rooms[current_room]:
            current_room = rooms[current_room][direction]
        else:
            print("Can't go that way")
    else:
        print("No can do")

print("You have exited the game.")

The specific error message I'm getting is as follows:

Traceback (most recent call last):
  File "C:\Users\patri\PycharmProjects\PythonProject\.venv\ModuleSixMilestone.py", line 26, in <module>
    direction = command.split(' ')[1]
                ~~~~~~~~~~~~~~~~~~^^^
IndexError: list index out of range

What is causing this error and how can I fix it? Are there related errors that I'll need to patch out as well?

Answer

I am not fully sure what did you want to achieve, but your code is bugged and direction handling just can't work. If command is one of ['North', 'South', 'East', 'West'] , command.split(' ') is always going to return a single element list, as none of these strings contains a whitespace. Therefore, trying to access a 2nd element using index [1] is always going to cause an IndexError. I guess that if command is one of 4 directions, your direction is just a command, so you can just do direction = command (or just use command variable directly) and then your code would work fine.

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles