DEV Community

Cover image for Building Tiny Hero: A Text-Based RPG Adventure with Python for Beginners and Intermediates
Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Building Tiny Hero: A Text-Based RPG Adventure with Python for Beginners and Intermediates

Hey there, fellow coders and game dev enthusiasts! In this article, I’m taking you on a deep dive into the creation of Tiny Hero, a simple yet exciting text-based role-playing game (RPG) I built using Python and the Rich library. This project is perfect for beginners or intermediate coders looking to level up their skills with a fun, manageable challenge. I’ll walk you through my learning journey, the design and development process, the hurdles I faced, and the lessons I learned, all with plenty of details to give you a real sense of building something from scratch. My goal is to inspire you to create your own game, even if you’re just starting out. Let’s grab our swords and dive in! ⚔️


🎮 What is Tiny Hero?

Tiny Hero is a text-based RPG where you play as a brave hero battling foes like goblins, orcs, and archers. It’s packed with features that make it both fun to play and a great learning tool for coders. Here’s what makes it tick:

  • Turn-Based Combat: You and your enemy take turns attacking, with a random chance to go first, adding a dash of unpredictability to each fight.
  • Weapon Management: Choose between fists, an iron sword, or a short bow, with options to swap or drop weapons during the game.
  • Strategic Actions: Pick from normal attacks, strong attacks (with a 30% chance to miss), healing, or managing your inventory to build your strategy.
  • Engaging UI: Thanks to the Rich library, the game features colorful menus, ASCII art animations, and emoji, enhanced messages that bring the adventure to life.
  • Dynamic Health Bars: Visual health bars change colors (green for high, yellow for medium, red for low) to show your and your enemy’s status.

Want to see it in action? Check out the demo video on YouTube. The full source code is available in the GitHub repository.


📚 My Learning Journey: From Idea to Tiny Hero

About five months ago, I decided to dive back into learning Python with a fresh focus. I was already familiar with basics like loops, conditionals, functions, and data structures like lists and dictionaries. I had zero experience with RPG game development. One day, while searching for a unique way to practice object-oriented programming (OOP), classes, and structured coding, I got the idea to build a simple RPG game. That spark became Tiny Hero.

How I Prepared

To get ready for this project, I focused on a few key skills:

  • Mastering OOP: I wanted my project to have a clean structure, so I studied OOP concepts like classes, inheritance, encapsulation, and composition. Online resources like Corey Schafer’s YouTube tutorials and freeCodeCamp’s Python courses were lifesavers for understanding how to organize characters and weapons with classes.
  • Discovering Rich: I needed a way to make the terminal UI more engaging than plain text. After some research, I found the Rich library, which let me add colorful tables, panels, and ASCII animations. The official Rich documentation and Stack Overflow posts helped me get started.
  • Exploring Text-Based Games: I checked out open-source text-based games on GitHub to see how others handled combat systems and inventory management. These projects gave me ideas for structuring Tiny Hero’s gameplay.
  • Practicing with Small Projects: Before jumping into Tiny Hero, I built simple programs like a text-based calculator and a to-do list app to get comfortable with code organization and user input handling.

Why Tiny Hero?

I wanted a project that was:

  • Approachable for beginners, with readable and modifiable code.
  • A practical showcase of OOP principles.
  • Immersive, with a fun adventure vibe thanks to a polished UI.
  • Simple enough to complete in a reasonable time but challenging enough to teach me new skills.

🛠 The Building Process: How Tiny Hero Came to Life

Creating Tiny Hero felt like embarking on a quest of my own, full of learning, debugging, and those “Aha!” moments when something finally clicked. Here’s how I built it, step by step.

1. Project Structure

From the start, I aimed for a modular, clean codebase to make future additions and debugging easier. I organized the project into these main components:

  • main.py and cli.py: The entry point and game flow controller. main.py is a simple wrapper to launch the game, while cli.py handles the intro sequence and enemy progression.
  • src/character.py: Defines the Character base class, Hero (player with inventory), and Enemy (AI-controlled foes).
  • src/weapon.py: Manages weapons like fists, iron sword, and short bow using a factory pattern.
  • src/actions.py: Handles player and enemy actions (attack, heal, equip, etc.).
  • src/battle.py: Implements the turn-based combat system.
  • src/health_bar.py: Tracks and updates character health bars.
  • src/ui/: Contains UI modules like fancy_ui.py (overall UI management), display.py (messages and health bars), menu.py (action/weapon menus), and animations.py (ASCII animations).

This modular structure ensured each file had a clear purpose, making the code easier to maintain.

2. Tools Used

  • Python 3: My go-to language for its simplicity and versatility.
  • Rich: Enabled vibrant terminal UI with tables, colors, and ASCII art.
  • Git and GitHub: For version control and sharing the project.
  • VS Code: My editor of choice, with Python and GitLens extensions for smooth coding and debugging.

3. Key Features Implementation

Characters

In character.py, I created a Character base class to handle shared attributes like name, health, and weapon. The Hero class extends it with an inventory, while Enemy is simpler for AI foes. Here’s a snippet of the attack logic:

class Character:
    def __init__(self, name, health):
        self.name = name
        self.health = health
        self.health_max = health
        self.weapon = fists

    def attack(self, target):
        crit = random.random() < 0.2  # 20% chance for critical hit
        damage = self.weapon.damage * (2 if crit else 1)
        target.health = max(target.health - damage, 0)
        target.health_bar.update()
        return damage, crit
Enter fullscreen mode Exit fullscreen mode

This code calculates damage with a 20% chance for a critical hit, updating the target’s health bar.

Combat System

In battle.py, I built a turn-based combat system where a random character starts each round. Players choose actions via a menu, while enemies perform basic attacks.

User Interface

The ui/fancy_ui.py module is the heart of the UI, combining DisplayManager (for messages and health bars), MenuManager (for interactive menus), and AnimationManager (for ASCII animations).


🎨 Diving Deeper: Exploring ui/animations.py

Let’s take a closer look at animations.py, which brings Tiny Hero’s adventurous vibe to life with ASCII art and visual effects. This module makes the game feel less like a terminal app and more like a real RPG.

class AnimationManager:
    def __init__(self):
        self.console = Console()

    def show_intro(self):
        self.clear_screen()
        self.show_ascii(TITLE_BANNER, "bright_cyan")
        time.sleep(1.5)
        self.console.print("\n[bold yellow]Press Enter to begin...[/bold yellow]", justify="center")
        input()
        self.clear_screen()
        self.show_ascii(INTRO_TEXT, "bright_magenta")
        time.sleep(5)
        self._show_loading_bar()
Enter fullscreen mode Exit fullscreen mode

What’s Happening Here?

  • Intro Sequence: The game starts with a cyan-colored ASCII logo, followed by a magenta intro text and a loading bar made of and characters to build anticipation.
  • Attack Animations: Different weapons (e.g., sword, bow) trigger unique ASCII animations, like a slashing motion for swords.
  • Special Effects: Critical hits display a bold yellow “CRITICAL HIT!” message, and the game-over screen features a skull ASCII art for dramatic effect.

Suggestion: To make this section more engaging, consider adding a GIF of the intro sequence or a critical hit animation from the game. This would break up the text and give readers a visual taste of the UI.


📺 Watch Tiny Hero in Action!

To see the game’s colorful menus, ASCII animations, and combat system, check out the demo video on YouTube. It’s a quick way to feel the game’s vibe and see what you can build with Python!


⚡ Challenges Faced

Building Tiny Hero wasn’t all smooth sailing. Here are some hurdles I hit:

  • Learning Rich: Figuring out Rich’s tables and panels took time, but experimenting with small examples helped.
  • Game Balance: Tuning health, weapon damage, and action limits (e.g., strong attacks) required lots of playtesting to avoid making the game too easy or too hard.
  • Game Flow: Ensuring seamless transitions (e.g., from action selection to combat resolution) involved debugging issues like the game freezing after a player’s death.
  • ASCII Art: Crafting ASCII for characters and effects was tedious. Online tools like ASCII Art Generator saved the day, but aligning them in the terminal was tricky.
  • Input Validation: Making sure user inputs didn’t crash the game meant adding robust error handling.

📝 Lessons Learned

This project was a goldmine of insights:

  • OOP in Action: I learned how to apply inheritance (e.g., Character as a base class) and composition (e.g., FancyUIManager) in a real project.
  • Clean Code Matters: Modularizing the code made it easier to debug and expand.
  • Rich’s Power: Even a text-based game can feel modern with colors and animations.
  • Testing is Key: Playtesting and friend feedback ensured a smooth experience.
  • Project Management: I got better at taking an idea from concept to a finished product.

🚀 How to Try Tiny Hero

Ready to jump in? Follow these steps:

  1. Clone the Project:
   git clone https://github.com/Sherouz/tiny-hero.git
Enter fullscreen mode Exit fullscreen mode
  1. Install Dependencies:
   pip install rich
Enter fullscreen mode Exit fullscreen mode
  1. Run the Game:
   cd tiny-hero
   python main.py
Enter fullscreen mode Exit fullscreen mode
  1. Start Your Adventure: Pick up your sword and face those enemies! 🗡️

🌌 Future Ideas for Tiny Hero

Tiny Hero is just the beginning. Here are some ways to expand it:

  • Deeper Story: Add a narrative with missions and side characters.
  • More Items: Introduce armor or potions for richer gameplay.
  • Sound Effects: Use libraries like playsound for audio.
  • Graphical Version: Port the game to Pygame for a visual upgrade.
  • Leveling System: Add experience points and character upgrades.

⭐ Final Thoughts

Building Tiny Hero was one of my most rewarding coding experiences. It showed me that with Python, a bit of creativity, and tools like Rich, anyone can create a fun game. Whether you’re a beginner or an intermediate coder, I encourage you to try a similar project. Start small, maybe a single character and enemy, and build from there. Got questions or ideas to improve Tiny Hero? Drop a comment below or reach out on GitHub, or connect with me on Twitter @Shahrouzlogs. And don’t forget to check out the YouTube demo to see the game in action!

Please give the project repository a star to show your support and help others discover it! 🌟
Links:

⚔️ Time to awaken your inner hero and start your own coding adventure! 🛡️

Top comments (0)