Creating Text-Based Games with Python

Loading

Text-based games are a great starting point for game development, allowing you to focus on storytelling, logic, and interactivity without dealing with graphics. Python provides an excellent platform for building these games due to its simplicity and readability.


1. What is a Text-Based Game?

A text-based game is an interactive fiction game where players make choices through text inputs. The game responds by presenting different scenarios based on the player’s actions.

Examples of text-based games:

  • Adventure Games (Zork, Dwarf Fortress)
  • Role-Playing Games (D&D-inspired games)
  • Mystery Games (Detective stories)
  • Survival Games (Text-based zombie apocalypse)

2. Setting Up Your Python Environment

Before starting, ensure you have Python installed. You can download it from python.org.

To check if Python is installed, run:

python --version

For text-based games, you’ll only need Python’s built-in functions, but you can use libraries like:

  • random (for randomness)
  • time (for delays)
  • sys (for exiting the game)

3. Basic Structure of a Text-Based Game

A simple text-based game consists of:

  1. Introduction & Instructions
  2. Player Input (Choices)
  3. Game Logic (Decisions and Outcomes)
  4. Loops (Replay or Progression)
  5. Ending Scenarios

Example: Basic Text Adventure

import time

def start_game():
print("\nWelcome to the Mysterious Dungeon!")
time.sleep(1)
print("You find yourself in a dark cave. There are two paths ahead.")

choice = input("Do you go LEFT or RIGHT? ").strip().lower()

if choice == "left":
print("\nYou walk into a trap! Game Over.")
elif choice == "right":
print("\nYou found a treasure chest! You win!")
else:
print("\nInvalid choice. Try again.")
start_game() # Restart the game

start_game()

Explanation:

  • The start_game() function introduces the player to the story.
  • input() takes player choices.
  • if-else statements determine outcomes.
  • time.sleep(1) creates a small delay for immersion.

4. Adding More Features

1. Using Functions for Game Events

def forest_path():
print("\nYou enter a dense forest. A wolf blocks your way.")
action = input("Do you FIGHT or RUN? ").strip().lower()

if action == "fight":
print("\nThe wolf overpowers you. Game Over.")
elif action == "run":
print("\nYou escape safely and find a hidden village.")
village_path()
else:
print("\nInvalid choice. Try again.")
forest_path()

def village_path():
print("\nThe village elders welcome you and offer guidance.")
print("Congratulations! You have completed the journey!")

def start_adventure():
print("\nYou arrive at a crossroad.")
direction = input("Do you go to the FOREST or the MOUNTAINS? ").strip().lower()

if direction == "forest":
forest_path()
elif direction == "mountains":
print("\nA rockslide crushes your path. Game Over.")
else:
print("\nInvalid choice. Try again.")
start_adventure()

start_adventure()

What’s Improved?

Multiple paths to explore
Functions for different locations
Better user interaction


2. Adding a Player Character

We can track the player’s name, health, and inventory.

player = {"name": "", "health": 100, "inventory": []}

def start_game():
print("\nWelcome to the Adventure!")
player["name"] = input("Enter your name: ").strip().title()
print(f"\nHello, {player['name']}! Your journey begins now.")

first_choice()

def first_choice():
print("\nYou wake up in a small village. A stranger offers you a sword.")
choice = input("Do you TAKE the sword or DECLINE? ").strip().lower()

if choice == "take":
player["inventory"].append("sword")
print("\nYou took the sword. It might be useful later!")
elif choice == "decline":
print("\nYou politely decline the sword.")
else:
print("\nInvalid choice. Try again.")
first_choice()

print("\nYou head towards the mountains.")
mountain_path()

def mountain_path():
print("\nA wild bandit appears!")

if "sword" in player["inventory"]:
print("\nYou use your sword to fight and win!")
else:
print("\nYou have no weapon! The bandit overpowers you.")
player["health"] -= 50

print(f"\nYour health: {player['health']}")
if player["health"] <= 0:
print("\nYou have died. Game Over.")
else:
print("\nYou continue your adventure!")

start_game()

New Features:

Player Name & Stats
Inventory System
Health System & Combat


5. Expanding Your Game

1. Adding Random Events

import random

events = ["You find a health potion!", "A thief steals some of your gold!", "You encounter a talking cat."]

def random_event():
event = random.choice(events)
print(f"\n{event}")

random_event()

2. Adding a Shop System

shop_items = {"Potion": 10, "Shield": 20}

def visit_shop():
print("\nWelcome to the shop! Items available:")
for item, price in shop_items.items():
print(f"{item}: {price} gold")

choice = input("What do you want to buy? ").strip().title()

if choice in shop_items:
print(f"\nYou bought {choice}!")
else:
print("\nInvalid choice.")

visit_shop()

3. Implementing a Save & Load System

import json

def save_game():
with open("savefile.json", "w") as file:
json.dump(player, file)
print("\nGame Saved!")

def load_game():
global player
with open("savefile.json", "r") as file:
player = json.load(file)
print("\nGame Loaded!")

save_game()
load_game()

4. Using Classes for a More Advanced System

class Player:
def __init__(self, name):
self.name = name
self.health = 100
self.inventory = []

def take_damage(self, amount):
self.health -= amount
if self.health <= 0:
print("\nYou have died. Game Over.")

hero = Player("Knight")
print(f"\nWelcome, {hero.name}! Your health is {hero.health}.")
hero.take_damage(30)
print(f"\nHealth left: {hero.health}")

Leave a Reply

Your email address will not be published. Required fields are marked *