Python Programming Tutorial - text-based game
To create a sprawling world with rooms that connect in multiple directions (North, South, East, West, Up, and Down), we need a data structure that can hold relationships.
The most powerful tool for this is the Nested Dictionary. This allows us to map out the Entrance, the Amethyst Garden, and the hidden paths beyond.
The Concept: We create a master dictionary where every key is a room name, and every value is another dictionary containing the exits and where they lead.
# The World Map rooms = { 'Entrance': {'E': 'Amethyst Garden'}, 'Amethyst Garden': { 'N': 'The Staircase', 'S': 'The Moss Room', 'E': 'The Rock Room', 'W': 'Entrance' }, 'The Staircase': {'W': 'Amethyst Garden', 'D': 'Deep Caves'}, 'The Moss Room': {'N': 'Amethyst Garden', 'S': 'Tunnel'}, 'Tunnel': {'N': 'The Moss Room', 'S': 'The Statues Room'}, 'The Statues Room': {'N': 'Tunnel', 'E': 'Hidden Vault'}, 'The Rock Room': {'W': 'Amethyst Garden'} }
The Concept: To move the player, we track a variable called current_room and use the user's input to look up the next location.
current_room = 'Entrance' move = input("Enter direction (N, S, E, W, U, D): ").upper() # Checking if the direction exists in the current room if move in rooms[current_room]: current_room = rooms[current_room][move] print(f"You enter the {current_room}.") else: print("There is no exit in that direction!")
.upper(), we ensure that if the player types 'e', it is converted to 'E' so it matches our dictionary keys perfectly.
Scenario: In the Statues Room, the exit is past the first of six statues. You can use your dictionary to manage visibility.
# Logic for a long room with hidden features if current_room == 'The Statues Room': print("You walk down the center of the room past 6 statues.") print("A single torch burns in a sconce near the entrance.")