Day 27: Text-Based Adventure Game

Objective

Create an interactive text-based adventure game where the user navigates through a story by making choices. Each decision will lead to different outcomes, branching paths, or even the end of the game!

For example:

  • Prompt: “You are in a dark forest. Do you want to go left (1) or right (2)?”
  • User Input: 1 → “You encounter a bear! Do you run (1) or fight (2)?”
  • User Input: 2 → “The bear chases you down. Game over!”

Why This Challenge Is Important

This challenge introduces you to:

  • Conditional logic to create multiple story paths.
  • The concept of state management as the game progresses.
  • Using loops for continuous interaction until the story ends.
  • Writing creative, engaging, and reusable code.

Steps to Solve

1. Understand the Problem

The program should:

  1. Present a story and prompt the user to make decisions.
  2. Use the user’s input to guide them to different outcomes.
  3. End the game when the player reaches a conclusion (win, lose, or neutral).

2. Plan Your Solution

  1. Write a simple story structure with branching decisions.
  2. Use if-else statements (or a dictionary/map) to determine the next step based on the user’s choices.
  3. Create a loop to continue the game until the user reaches an endpoint.
  4. Add replayability by letting the user restart after finishing.

3. Enhancements to Consider

  • Add inventory management, where the player collects items to use later.
  • Introduce random events to make each playthrough unique.
  • Include a backstory and descriptive text to make the game immersive.

Code Examples

Python Example

def adventure_game():
    print("Welcome to the Text-Based Adventure Game!")
    print("Your goal is to survive and find the treasure!")
    print("Let the adventure begin!\n")

    # Starting point
    while True:
        print("You are standing in front of a dark cave.")
        print("Do you want to:")
        print("1. Enter the cave.")
        print("2. Walk away.")
        choice = input("Enter 1 or 2: ")

        if choice == "1":
            print("\nYou step into the cave and see two tunnels.")
            print("Do you:")
            print("1. Take the left tunnel.")
            print("2. Take the right tunnel.")
            choice = input("Enter 1 or 2: ")

            if choice == "1":
                print("\nYou encounter a sleeping dragon!")
                print("Do you:")
                print("1. Try to sneak past it.")
                print("2. Attack the dragon.")
                choice = input("Enter 1 or 2: ")

                if choice == "1":
                    print("\nYou sneak past the dragon and find a treasure chest! You win!")
                else:
                    print("\nThe dragon wakes up and breathes fire! Game over!")
            else:
                print("\nThe tunnel collapses behind you, trapping you. Game over!")
        elif choice == "2":
            print("\nYou walk away safely. Maybe next time you'll find the courage to enter. Game over!")
        else:
            print("\nInvalid choice. Please enter 1 or 2.")
            continue

        # Ask if the user wants to play again
        replay = input("\nWould you like to play again? (yes/no): ").lower()
        if replay != "yes":
            print("\nThanks for playing! Goodbye!")
            break

adventure_game()

Java Example

import java.util.Scanner;

public class AdventureGame {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Welcome to the Text-Based Adventure Game!");
        System.out.println("Your goal is to survive and find the treasure!");
        System.out.println("Let the adventure begin!\n");

        while (true) {
            System.out.println("You are standing in front of a dark cave.");
            System.out.println("Do you want to:");
            System.out.println("1. Enter the cave.");
            System.out.println("2. Walk away.");
            System.out.print("Enter 1 or 2: ");
            int choice = scanner.nextInt();

            if (choice == 1) {
                System.out.println("\nYou step into the cave and see two tunnels.");
                System.out.println("Do you:");
                System.out.println("1. Take the left tunnel.");
                System.out.println("2. Take the right tunnel.");
                System.out.print("Enter 1 or 2: ");
                choice = scanner.nextInt();

                if (choice == 1) {
                    System.out.println("\nYou encounter a sleeping dragon!");
                    System.out.println("Do you:");
                    System.out.println("1. Try to sneak past it.");
                    System.out.println("2. Attack the dragon.");
                    System.out.print("Enter 1 or 2: ");
                    choice = scanner.nextInt();

                    if (choice == 1) {
                        System.out.println("\nYou sneak past the dragon and find a treasure chest! You win!");
                    } else {
                        System.out.println("\nThe dragon wakes up and breathes fire! Game over!");
                    }
                } else {
                    System.out.println("\nThe tunnel collapses behind you, trapping you. Game over!");
                }
            } else if (choice == 2) {
                System.out.println("\nYou walk away safely. Maybe next time you'll find the courage to enter. Game over!");
            } else {
                System.out.println("\nInvalid choice. Please enter 1 or 2.");
                continue;
            }

            System.out.print("\nWould you like to play again? (yes/no): ");
            String replay = scanner.next();
            if (!replay.equalsIgnoreCase("yes")) {
                System.out.println("\nThanks for playing! Goodbye!");
                break;
            }
        }
    }
}

JavaScript Example

function adventureGame() {
    alert("Welcome to the Text-Based Adventure Game!");
    alert("Your goal is to survive and find the treasure!");

    while (true) {
        const choice1 = prompt("You are standing in front of a dark cave.\n1. Enter the cave.\n2. Walk away.\nEnter 1 or 2:");

        if (choice1 === "1") {
            const choice2 = prompt("You step into the cave and see two tunnels.\n1. Take the left tunnel.\n2. Take the right tunnel.\nEnter 1 or 2:");

            if (choice2 === "1") {
                const choice3 = prompt("You encounter a sleeping dragon!\n1. Try to sneak past it.\n2. Attack the dragon.\nEnter 1 or 2:");

                if (choice3 === "1") {
                    alert("You sneak past the dragon and find a treasure chest! You win!");
                } else {
                    alert("The dragon wakes up and breathes fire! Game over!");
                }
            } else {
                alert("The tunnel collapses behind you, trapping you. Game over!");
            }
        } else if (choice1 === "2") {
            alert("You walk away safely. Maybe next time you'll find the courage to enter. Game over!");
        } else {
            alert("Invalid choice. Please enter 1 or 2.");
            continue;
        }

        const replay = prompt("Would you like to play again? (yes/no):");
        if (replay.toLowerCase() !== "yes") {
            alert("Thanks for playing! Goodbye!");
            break;
        }
    }
}

adventureGame();

Extensions to Explore

  1. Add Multiple Endings: Introduce more story paths for a richer experience.
  2. Inventory System: Let the player collect items and use them in key moments.
  3. Random Events: Add unpredictability, such as random encounters with enemies or treasures.
  4. Save/Load Feature: Allow the player to save progress and resume later.

What You’ve Learned

  • How to use conditional logic for branching narratives.
  • Managing user interaction through loops and input validation.
  • Structuring a program for creative, dynamic storytelling.

Next Steps

In Day 28: File Reader and Writer, you’ll dive into file operations, learning to read and write data, which is crucial for handling more complex projects!