{{tag>projects cloud club computing virtualization machines VMs AWS Azure GCP}} [[python_club|About the Club]]\\ ==== Python Club Topics - Exercise: Adventure Game ==== ==== Exercise: Adventure Game ==== - Output: The player is set in a cave. Present directional options and exit when they type 'quit'. - What you learn from the example: - Multiline comment that explains the purpose and functionality of the program - Get input from a user - Use a dictionary variable - Use if, then, else statements - Use a loop ==== Solution ==== ''' 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!')