Python Adventure Game Sample Code
This guide will help you make a basic adventure game in Python. Follow each section to build your game step-by-
step!
1. Setting Up a Welcome Message and Player Name
In this part, we’ll set up a welcome message and ask for the player’s name.
Example Code:
# Ask the player for their name
player_name = input("What is your name? ")
# Show a welcome message
print("Welcome, “ + player_name + “ Your adventure begins now.")
Explanation:
- The input() function is used to ask the player their name. This gets stored in `player_name` so we can use it later.
2. Making Choices with If Statements
Now, let’s give the player a choice to go left or right. Based on their choice, the game will show a different message.
Example Code:
# Ask the player to make a choice
choice = input("Do you want to go left or right? ")
# Use if statements to make the game respond based on the choice
if choice == "left":
print("You walk down a spooky path.")
elif choice == "right":
print("You find a peaceful clearing.")
else:
print("You stay where you are, unsure of what to do.")
Explanation:
- The IF checks if the player typed 'left'. If they did, it shows a message about going down a spooky path.
- The ELIF checks if the player typed 'right'. If they did, it shows a message about a peaceful clearing.
- The ELSE is used if the player typed something other than 'left' or 'right'. This message appears if their input
doesn’t match either choice.
3. Advanced Challenge: Using a While Loop for More Interaction
For students ready for an extra challenge, here’s how you can use a while loop to keep the game going until the
player types 'exit'.
Example Code:
# Set up a variable to keep the game going
game_active = True
while game_active:
choice = input("Type 'left', 'right', or 'exit' to make your choice: ")
if choice == "left":
print("You venture down a dark path.")
elif choice == "right":
print("You find a quiet lake.")
elif choice == "exit":
print("You have chosen to end your adventure.")
game_active = False
else:
print("Invalid choice. Please try again.")
Explanation:
- `game_active = True` sets up a variable to control the loop.
- `while game_active:` means the code inside the loop will keep going as long as `game_active` is `True`.
- `if choice == 'exit':` lets the player end the game by setting `game_active` to `False`, which stops the loop.
Tips:
- Type your code exactly as shown.
- Make sure each line is in the right place (especially lines inside loops and `if` statements).