Skip to content

Text-Based Adventure Game

Abstract

Build an engaging text-based adventure game featuring a fantasy story, player choices, inventory management, and multiple endings. This project demonstrates game logic, story branching, state management, and interactive narrative design using only text output and user input.

Prerequisites

  • Python 3.6 or above
  • Text Editor or IDE
  • Basic understanding of Python syntax
  • Knowledge of functions and control structures
  • Familiarity with lists and string manipulation
  • Understanding of game logic and state management

Getting Started

Create a new project

  1. Create a new project folder and name it textBasedAdventureGametextBasedAdventureGame.
  2. Create a new file and name it textbasedadventuregame.pytextbasedadventuregame.py.
  3. Open the project folder in your favorite text editor or IDE.
  4. Copy the code below and paste it into your textbasedadventuregame.pytextbasedadventuregame.py file.

Write the code

  1. Add the following code to your textbasedadventuregame.pytextbasedadventuregame.py file.
โš™๏ธ Text-Based Adventure Game
Text-Based Adventure Game
# Text Based Adventure Game
 
# Importing Modules
import time
import random
 
# Defining Functions
def print_pause(message_to_print):
    print(message_to_print)
    time.sleep(2)
    
def intro():
    print_pause("You find yourself standing in an open field, filled with grass and yellow wildflowers.")
    print_pause("Rumor has it that a wicked fairie is somewhere around here, and has been terrifying the nearby village.")
    print_pause("In front of you is a house.")
    print_pause("To your right is a dark cave.")
    print_pause("In your hand you hold your trusty (but not very effective) dagger.\n")
    
def house(items):
    print_pause("You approach the door of the house.")
    print_pause("You are about to knock when the door opens and out steps a wicked fairie.")
    print_pause("Eep! This is the wicked fairie's house!")
    print_pause("The wicked fairie attacks you!")
    if "Sword of Ogoroth" not in items:
        print_pause("You feel a bit under-prepared for this, what with only having a tiny dagger.")
    while True:
        choice = input("Would you like to (1) fight or (2) run away?")
        if choice == "1":
            if "Sword of Ogoroth" in items:
                print_pause("As the wicked fairie moves to attack, you unsheath your new sword.")
                print_pause("The Sword of Ogoroth shines brightly in your hand as you brace yourself for the attack.")
                print_pause("But the wicked fairie takes one look at your shiny new toy and runs away!")
                print_pause("You have rid the town of the wicked fairie. You are victorious!")
            else:
                print_pause("You do your best...")
                print_pause("but your dagger is no match for the wicked fairie.")
                print_pause("You have been defeated!")
            play_again()
            break
        if choice == "2":
            print_pause("You run back into the field. Luckily, you don't seem to have been followed.")
            field(items)
            break
        
def cave(items):
    print_pause("You peer cautiously into the cave.")
    if "Sword of Ogoroth" in items:
        print_pause("You've been here before, and gotten all the good stuff. It's just an empty cave now.")
        print_pause("You walk back out to the field.")
        field(items)
    else:
        print_pause("It turns out to be only a very small cave.")
        print_pause("Your eye catches a glint of metal behind a rock.")
        print_pause("You have found the magical Sword of Ogoroth!")
        print_pause("You discard your silly old dagger and take the sword with you.")
        print_pause("You walk back out to the field.")
        items.append("Sword of Ogoroth")
        field(items)
        
def field(items):
    print_pause("Enter 1 to knock on the door of the house.")
    print_pause("Enter 2 to peer into the cave.")
    while True:
        choice = input("What would you like to do?")
        if choice == "1":
            house(items)
            break
        elif choice == "2":
            cave(items)
            break
        
def play_again():
    while True:
        choice = input("Would you like to play again? (y/n)")
        if choice == "y":
            print_pause("Excellent! Restarting the game ...")
            play_game()
            break
        elif choice == "n":
            print_pause("Thanks for playing! See you next time.")
            break
        
def play_game():
    items = []
    intro()
    field(items)
    
# Calling Functions
play_game()
 
Text-Based Adventure Game
# Text Based Adventure Game
 
# Importing Modules
import time
import random
 
# Defining Functions
def print_pause(message_to_print):
    print(message_to_print)
    time.sleep(2)
    
def intro():
    print_pause("You find yourself standing in an open field, filled with grass and yellow wildflowers.")
    print_pause("Rumor has it that a wicked fairie is somewhere around here, and has been terrifying the nearby village.")
    print_pause("In front of you is a house.")
    print_pause("To your right is a dark cave.")
    print_pause("In your hand you hold your trusty (but not very effective) dagger.\n")
    
def house(items):
    print_pause("You approach the door of the house.")
    print_pause("You are about to knock when the door opens and out steps a wicked fairie.")
    print_pause("Eep! This is the wicked fairie's house!")
    print_pause("The wicked fairie attacks you!")
    if "Sword of Ogoroth" not in items:
        print_pause("You feel a bit under-prepared for this, what with only having a tiny dagger.")
    while True:
        choice = input("Would you like to (1) fight or (2) run away?")
        if choice == "1":
            if "Sword of Ogoroth" in items:
                print_pause("As the wicked fairie moves to attack, you unsheath your new sword.")
                print_pause("The Sword of Ogoroth shines brightly in your hand as you brace yourself for the attack.")
                print_pause("But the wicked fairie takes one look at your shiny new toy and runs away!")
                print_pause("You have rid the town of the wicked fairie. You are victorious!")
            else:
                print_pause("You do your best...")
                print_pause("but your dagger is no match for the wicked fairie.")
                print_pause("You have been defeated!")
            play_again()
            break
        if choice == "2":
            print_pause("You run back into the field. Luckily, you don't seem to have been followed.")
            field(items)
            break
        
def cave(items):
    print_pause("You peer cautiously into the cave.")
    if "Sword of Ogoroth" in items:
        print_pause("You've been here before, and gotten all the good stuff. It's just an empty cave now.")
        print_pause("You walk back out to the field.")
        field(items)
    else:
        print_pause("It turns out to be only a very small cave.")
        print_pause("Your eye catches a glint of metal behind a rock.")
        print_pause("You have found the magical Sword of Ogoroth!")
        print_pause("You discard your silly old dagger and take the sword with you.")
        print_pause("You walk back out to the field.")
        items.append("Sword of Ogoroth")
        field(items)
        
def field(items):
    print_pause("Enter 1 to knock on the door of the house.")
    print_pause("Enter 2 to peer into the cave.")
    while True:
        choice = input("What would you like to do?")
        if choice == "1":
            house(items)
            break
        elif choice == "2":
            cave(items)
            break
        
def play_again():
    while True:
        choice = input("Would you like to play again? (y/n)")
        if choice == "y":
            print_pause("Excellent! Restarting the game ...")
            play_game()
            break
        elif choice == "n":
            print_pause("Thanks for playing! See you next time.")
            break
        
def play_game():
    items = []
    intro()
    field(items)
    
# Calling Functions
play_game()
 
  1. Save the file.
  2. Run the following command to run the application.
command
C:\Users\username\Documents\textBasedAdventureGame> python textbasedadventuregame.py
You find yourself standing in front of a cave.
In your hand you hold your trusty (but not very effective) dagger.
 
Enter 1 to knock on the door of the house.
Enter 2 to peer into the cave.
Please enter 1 or 2.
2
 
You have found the magical Sword of Ogoroth!
You are victorious!
 
Would you like to play again? (y/n)
command
C:\Users\username\Documents\textBasedAdventureGame> python textbasedadventuregame.py
You find yourself standing in front of a cave.
In your hand you hold your trusty (but not very effective) dagger.
 
Enter 1 to knock on the door of the house.
Enter 2 to peer into the cave.
Please enter 1 or 2.
2
 
You have found the magical Sword of Ogoroth!
You are victorious!
 
Would you like to play again? (y/n)
  1. Play the Game
    • Read the story text carefully
    • Make choices by entering numbers (1 or 2)
     
     

Explanation

  1. The import timeimport time statement imports the time module for adding pauses between story elements.
  2. The def print_pause()def print_pause() function adds dramatic delays to create better story pacing.
  3. The def intro():def intro(): function sets up the initial game world and story context.
  4. The items = []items = [] list tracks the playerโ€™s inventory throughout the game.
  5. The def cave(items):def cave(items): function handles the cave exploration and item discovery.
  6. The def house(items):def house(items): function manages the house encounter and combat.
  7. The story branches based on whether the player has found the sword.
  8. The valid_inputsvalid_inputs list ensures players can only enter valid choices.
  9. The while True:while True: loops handle input validation and choice repetition.
  10. The def play_again():def play_again(): function allows players to restart the adventure.
  11. The game demonstrates consequence-based gameplay with different outcomes.
  12. Multiple endings depend on player preparation and choices made.

Next Steps

Congratulations! You have successfully created a Text-Based Adventure Game in Python. Experiment with the code and see if you can modify the application. Here are a few suggestions:

  • Add more locations and story branches
  • Implement character stats (health, strength, magic)
  • Create more complex inventory with multiple items
  • Add random events and encounters
  • Implement save/load game functionality
  • Create multiple characters to choose from
  • Add puzzle-solving elements
  • Implement dialogue trees with NPCs
  • Create a larger world map with navigation

Conclusion

In this project, you learned how to create a Text-Based Adventure Game in Python. You also learned about story branching, state management, inventory systems, and creating interactive narratives. You can find the source code on GitHub

Code Explanation

Story Pacing and Immersion

textbasedadventuregame.py
def print_pause(message_to_print):
    print(message_to_print)
    time.sleep(2)
textbasedadventuregame.py
def print_pause(message_to_print):
    print(message_to_print)
    time.sleep(2)

Adds dramatic pauses between story elements to create better pacing and immersion in the narrative.

Game Introduction

textbasedadventuregame.py
def intro():
    print_pause("You find yourself standing in an open field, filled with grass and yellow wildflowers.")
    print_pause("Rumor has it that a wicked fairie is somewhere around here...")
    print_pause("In your hand you hold your trusty (but not very effective) dagger.")
textbasedadventuregame.py
def intro():
    print_pause("You find yourself standing in an open field, filled with grass and yellow wildflowers.")
    print_pause("Rumor has it that a wicked fairie is somewhere around here...")
    print_pause("In your hand you hold your trusty (but not very effective) dagger.")

Sets up the game world, story context, and initial player state with atmospheric descriptions.

Inventory System

textbasedadventuregame.py
def cave(items):
    if "Sword of Ogoroth" in items:
        print_pause("You've been here before, and gotten all the good stuff.")
    else:
        print_pause("You have found the magical Sword of Ogoroth!")
        items.append("Sword of Ogoroth")
textbasedadventuregame.py
def cave(items):
    if "Sword of Ogoroth" in items:
        print_pause("You've been here before, and gotten all the good stuff.")
    else:
        print_pause("You have found the magical Sword of Ogoroth!")
        items.append("Sword of Ogoroth")

Implements item collection and inventory tracking that affects story outcomes and player capabilities.

Branching Combat System

textbasedadventuregame.py
if "Sword of Ogoroth" in items:
    print_pause("The Sword of Ogoroth shines brightly in your hand...")
    print_pause("You have rid the town of the wicked fairie. You are victorious!")
else:
    print_pause("Your dagger is no match for the wicked fairie.")
    print_pause("You have been defeated!")
textbasedadventuregame.py
if "Sword of Ogoroth" in items:
    print_pause("The Sword of Ogoroth shines brightly in your hand...")
    print_pause("You have rid the town of the wicked fairie. You are victorious!")
else:
    print_pause("Your dagger is no match for the wicked fairie.")
    print_pause("You have been defeated!")

Creates different story outcomes based on player preparation and choices, demonstrating consequence-based gameplay.

Choice Validation and Loops

textbasedadventuregame.py
while True:
    choice = input("Would you like to (1) fight or (2) run away?")
    if choice == "1":
        # Handle fight choice
        break
    if choice == "2":
        # Handle run choice
        break
textbasedadventuregame.py
while True:
    choice = input("Would you like to (1) fight or (2) run away?")
    if choice == "1":
        # Handle fight choice
        break
    if choice == "2":
        # Handle run choice
        break

Ensures valid input from players and provides clear choice options with proper loop handling.

Replay System

textbasedadventuregame.py
def play_again():
    while True:
        choice = input("Would you like to play again? (y/n)")
        if choice == "y":
            play_game()
            break
        elif choice == "n":
            print_pause("Thanks for playing! See you next time.")
            break
textbasedadventuregame.py
def play_again():
    while True:
        choice = input("Would you like to play again? (y/n)")
        if choice == "y":
            play_game()
            break
        elif choice == "n":
            print_pause("Thanks for playing! See you next time.")
            break

Allows players to restart the adventure without relaunching the program.

Features

  • Immersive Storytelling: Rich narrative with atmospheric descriptions
  • Player Choices: Multiple decision points affecting story outcomes
  • Inventory System: Item collection that changes gameplay possibilities
  • Multiple Endings: Different outcomes based on player preparation and choices
  • Replayability: Option to play again and try different strategies
  • Input Validation: Robust handling of user choices
  • Progressive Revelation: Story elements revealed based on player actions

Next Steps

Enhancements

  • Add more locations and story branches
  • Implement character stats (health, strength, magic)
  • Create more complex inventory with multiple items
  • Add random events and encounters
  • Include puzzle-solving elements
  • Implement save/load game functionality
  • Add character classes and skills
  • Create multiple story campaigns

Learning Extensions

  • Study advanced narrative design patterns
  • Explore procedural story generation
  • Learn about game state serialization
  • Practice with object-oriented game design
  • Understand random content generation
  • Explore text parsing for natural language input

Educational Value

This project teaches:

  • Game Logic Design: Creating rules and systems for interactive experiences
  • State Management: Tracking player progress and inventory across game sessions
  • Narrative Programming: Implementing story branching and choice consequences
  • Input Validation: Handling user input robustly and providing clear feedback
  • Function Organization: Structuring code for complex interactive systems
  • Flow Control: Managing program flow through different story paths
  • User Experience: Creating engaging and intuitive text-based interfaces
  • Story Design: Balancing player agency with narrative structure

Perfect for understanding game development fundamentals, interactive storytelling, and user-driven application design.

Was this page helpful?

Let us know how we did