Text Based Adventure Game
Text Based Adventure Game
Problem Statement
This code implements a simple text-based adventure game. The player is presented with a
series of scenes, each containing a description of the situation and a set of choices. The
player's choices determine the next scene, leading to different outcomes and potentially multiple
endings.
def get_player_choice(scene):
"""Gets and validates the player's choice."""
while True: # Keep asking until a valid choice is made
try:
choice = input("Enter your choice: ")
if choice in scene["choices"]: # Check if the choice is valid
return choice
else:
print("Invalid choice. Please try again.")
except ValueError: # Handle cases where the input is not a number
print("Invalid input. Please enter a number.")
# Define the story structure (using a dictionary)
story = {
# Each scene is a key in the dictionary
"start": {
"text": "You find yourself in a dark forest. You can go North or
East.",
"choices": { # Dictionary of choices for this scene
"1": ("Go North", "north_path"), # Choice number: (Choice
text, Next scene key)
"2": ("Go East", "east_path")
}
},
# ... other scenes defined similarly
}
Key Points:
● display_scene function:
○ Takes a scene dictionary as input.
○ Prints the scene's text.
If the scene has choices, it iterates through them and prints each choice
○
number and text.
● get_player_choice function:
○ Takes a scene dictionary as input.
○ Uses a while loop to repeatedly ask for input until a valid choice is made.
○ Handles ValueError in case the input is not a number.
○ Returns the valid choice number.
● story dictionary:
○ Stores the entire game's structure.
○ Each scene is a key with a dictionary value containing:
■ text: The scene's description.
■ choices (optional): A dictionary of choices, where each key is the choice
number and the value is a tuple of (choice text, next scene key).
● Main game loop:
○ Initializes current_scene to "start".
○ Runs a while loop until an ending scene is reached (a scene without choices).
○ In each iteration:
■ Displays the current scene using display_scene.
■ Gets the player's choice using get_player_choice.
■ Updates current_scene based on the chosen path.