Contact FutureLearn for Support
Skip main navigation
We use cookies to give you a better experience, if that’s ok you can close this message and carry on browsing. For more info read our cookies policy.
We use cookies to give you a better experience. Carry on browsing if you're happy with this, or read our cookies policy for more information.

Skip to 0 minutes and 1 secondFinally, let's add another method to move between rooms. Go into the room.py file and add another method below the get details method. This method takes an argument for the direction the player would like to move. If this direction is one of the directions linked to in the dictionary, it returns the Room object that is in that direction. If there is no room in the dictionary in that direction, the method returns self-- i.e., the player is linked back to the same room they were already in. Now, go back to the main.py file and add some code at the bottom to let the player move between rooms.

Skip to 0 minutes and 37 secondsHere we are creating an infinite loop to ask the player for a command, which is going to be a direction to move in, and then to move in that direction.

Skip to 0 minutes and 51 secondsRun your program. Type in some directions-- for example, south-- to move between rooms. Don't forget to also try some directions that won't work to see whether your game handles these correctly.

Moving between rooms

Finally, let’s add a method to allow the player to move between rooms.

blueprint

Go to the room.py file and add another method below the get_details method. This move method has a parameter for the direction in which the player would like to move. If this direction is one of the directions linked to, the method returns the room object that is in that direction. If there is no room in the dictionary in that direction, the method returns self – i.e. the player is linked back to the room they were already in!

def move(self, direction):
    if direction in self.linked_rooms:
        return self.linked_rooms[direction]
    else:
        print("You can't go that way")
        return self

Now go back to main.py and remove any code still left from where you tested the get_details() method.

2.8screenshot

Add some code at the bottom of the script to create a loop, letting the player move between rooms.

current_room = kitchen          

while True:		
    print("\n")         
    current_room.get_details()         
    command = input("> ")    
    current_room = current_room.move(command)  

Save and run your program. Type in some directions (e.g. “south”) to move between rooms. Don’t forget to also try directions that won’t work to see whether your game handles these correctly.

Share this video:

This video is from the free online course:

Object-oriented Programming in Python: Create Your Own Adventure Game

Raspberry Pi Foundation