User Tools

Site Tools


clubs:python_club:python_club_ex_adventure_game
Home | clubs :: cloud club :: python_club :: 3D-Printing | projects :: Proxmox | Kubernetes | scripting | utilities | games

About the Club

Python Club Topics - Exercise: Adventure Game

Exercise: Adventure Game

  1. Output: The player is set in a cave. Present directional options and exit when they type 'quit'.
  2. What you learn from the example:
    1. Multiline comment that explains the purpose and functionality of the program
    2. Get input from a user
    3. Use a dictionary variable
    4. Use if, then, else statements
    5. Use a loop

Solution

[1] code:python show
'''
A very simple adventure game written in Python 3.
The 'world' is a data structure that describes the game
world we want to explore. It's made up of key/value fields
that describe locations. Each location has a description
and one or more exits to other locations. Such records are
implemented as dictionaries.

The code at the very end creates a game 'loop' that causes
multiple turns to take place in the game. Each turn displays
the user's location, available exits, asks the user where
to go next and then responds appropriately to the user's
input.
'''

world = {
    'cave': {
        'description': 'You are in a mysterious cave.',
        'exits': {
          'up': 'courtyard',
        },
    },
    'tower': {
        'description': 'You are at the top of a tall tower.',
        'exits': {
            'down': 'gatehouse',
        },
    },
    'courtyard': {
        'description': 'You are in the castle courtyard.',
        'exits': {
            'south': 'gatehouse',
            'down': 'cave'
        },
    },
    'gatehouse': {
        'description': 'You are at the gates of a castle.',
        'exits': {
            'south': 'forest',
            'up': 'tower',
            'north': 'courtyard',
        },
    },
    'forest': {
        'description': 'You are in a forest glade.',
        'exits': {
            'north': 'gatehouse',
        },
    },
}

# Set a default starting point.
place = 'cave'
# Start the game 'loop' that will keep making new turns.
while True:
    # Get the current location from the world.
    location = world[place]
    # Print the location's description and exits.
    print(location['description'])
    print('Exits:')
    print(', '.join(location['exits'].keys()))
    # Get user input.
    direction = input('Where now? ').strip().lower()
    # Parse the user input…
    if direction == 'quit':
        print('Bye!')
        break # Break out of the game loop and end.
    elif direction in location['exits']:
        # Set new place in world.
        place = location['exits'][direction]
    else:
        # That exit doesn't exist!
        print('I do not understand!')
clubs/python_club/python_club_ex_adventure_game.txt · Last modified: by 127.0.0.1