DEV Community

Cover image for Building an Interactive Mad Libs Game in Python: A Beginner's Guide
Scofield Idehen
Scofield Idehen

Posted on • Originally published at blog.learnhub.africa

Building an Interactive Mad Libs Game in Python: A Beginner's Guide

Have you ever found yourself giggling uncontrollably while filling in random words to create a hilariously absurd story? If so, you've likely experienced the joy of Mad Libs, a classic word game that has been entertaining people of all ages since the 1950s.

But what if I told you that this simple game could also be your gateway to the exciting world of Python programming?

What is Mad Libs?

Mad Libs, at its core, is a fill-in-the-blank storytelling game. Players are prompted to provide words of specific types (nouns, verbs, adjectives, etc.) without knowing the context of the story.

Python Loops: A Comprehensive Guide for Beginners

Learn about loops here: Python Loops: A Comprehensive Guide for Beginners

These words are then inserted into a pre-written narrative, often resulting in a comedic and nonsensical tale that sparks laughter and creativity.

But Mad Libs is more than just a source of amusement. When translated into a programming project, it becomes a powerful teaching tool, offering aspiring coders a fun and engaging way to learn fundamental programming concepts.

Setting Up Your Python Environment

To get started, make sure you have Python installed on your computer. You can download it from the official Python website. For this project, we'll be using Python 3.12.7.

Once Python is installed, open your favorite text editor or Integrated Development Environment (IDE). Popular choices for beginners include IDLE (which comes with Python), Visual Studio Code, or PyCharm.

For this project, i will be using Pycharm.

Building the Mad Libs Game: Step by Step

Let's break down our Mad Libs game into manageable steps. We'll start with a basic version and gradually add more features to make it more interactive and engaging.

You can find the complete code here.

To run this game, you'll need to install some dependencies and one of them is colorama library. You can do this by running:

pip install colorama
Enter fullscreen mode Exit fullscreen mode

Import some of the libraries we would need for this projects which include, ramdom, os colorama



    import random
    import os
    from colorama import init, Fore, Style


Enter fullscreen mode Exit fullscreen mode

Next we would use init() which allow us to use colored output for enhancing the user interface, such as displaying welcome messages in cyan, errors in red, and the completed story in white with a bright style.

  • Creating the Story Template

First, we'll define our story template. This will be a string with placeholders for the words we want the player to fill in. Here's an example:



    story_template = """
    Once upon a time, in a {adjective} {noun}, there lived a {adjective} {noun}.
    Every day, they would {verb} to the {noun} and {verb} with their {adjective} {noun}.
    One day, something {adjective} happened! They found a {adjective} {noun} that could {verb}!
    From that day on, their life became even more {adjective} and full of {noun}.
    """


Enter fullscreen mode Exit fullscreen mode
  • Collecting Word Types

Next, we'll create a list of the word types we need for our story:



    word_types = ["adjective", "noun", "adjective", "noun", "verb", "noun", "verb", "adjective", "noun", "adjective", "adjective", "noun", "verb", "adjective", "noun"]


Enter fullscreen mode Exit fullscreen mode
  • Prompting the Player for Words

Now, let's create a function to prompt the player for words:



    def get_word(word_type):
        return input(f"Enter a(n) {word_type}: ")

    def collect_words(word_types):
        return [get_word(word_type) for word_type in word_types]


Enter fullscreen mode Exit fullscreen mode
  • Filling in the Story

With the words collected, we can fill in our story template:



    def fill_story(template, words):
        for word in words:
            template = template.replace("{" + word_types[words.index(word)] + "}", word, 1)
        return template


Enter fullscreen mode Exit fullscreen mode
  • Putting It All Together

Let's create a main function to run our game:



    def play_mad_libs():
        print("Welcome to Mad Libs!")
        print("I'll ask you for some words to fill in the blanks of our story.")

        words = collect_words(word_types)
        completed_story = fill_story(story_template, words)

        print("\nHere's your Mad Libs story:\n")
        print(completed_story)

    if __name__ == "__main__":
        play_mad_libs()


Enter fullscreen mode Exit fullscreen mode

Now we have a basic working version of our Mad Libs game! But let's not stop here. We can make it even more engaging and user-friendly.

Enhancing the Game

Adding Multiple Story Templates
To keep the game interesting, let's add multiple story templates:



    import random

    story_templates = [
        # ... (add your original story template here)
        """
        In a {adjective} galaxy far, far away, a {adjective} {noun} embarked on a {adjective} quest.
        Armed with a {adjective} {noun}, they set out to {verb} the evil {noun} and save the {noun}.
        Along the way, they encountered a {adjective} {noun} who taught them to {verb} with great skill.
        In the end, they emerged {adjective} and ready to face any {noun} that came their way.
        """,
        # ... (add more story templates as desired)
    ]

    def choose_random_template():
        return random.choice(story_templates)


Enter fullscreen mode Exit fullscreen mode

Implementing a Play Again Feature
Let's add the option for players to play multiple rounds:



    def play_again():
        return input("Would you like to play again? (yes/no): ").lower().startswith('y')

    def mad_libs_game():
        while True:
            template = choose_random_template()
            word_types = extract_word_types(template)
            play_mad_libs(template, word_types)
            if not play_again():
                print("Thanks for playing Mad Libs!")
                break

    def extract_word_types(template):
        return [word.split('}')[0] for word in template.split('{')[1:]]


Enter fullscreen mode Exit fullscreen mode

Adding Error Handling
To make our game more robust, let's add some error handling:



    def get_word(word_type):
        while True:
            word = input(f"Enter a(n) {word_type}: ").strip()
            if word:
                return word
            print("Oops! You didn't enter anything. Please try again.")


Enter fullscreen mode Exit fullscreen mode

Improving User Experience
Let's add some color and formatting to make our game more visually appealing:



    from colorama import init, Fore, Style

    init()  # Initialize colorama

    def print_colored(text, color=Fore.WHITE, style=Style.NORMAL):
        print(f"{style}{color}{text}{Style.RESET_ALL}")

    def play_mad_libs(template, word_types):
        print_colored("Welcome to Mad Libs!", Fore.CYAN, Style.BRIGHT)
        print_colored("I'll ask you for some words to fill in the blanks of our story.", Fore.YELLOW)

        words = collect_words(word_types)
        completed_story = fill_story(template, words)

        print_colored("\nHere's your Mad Libs story:\n", Fore.GREEN, Style.BRIGHT)
        print_colored(completed_story, Fore.WHITE, Style.BRIGHT)

**Saving Stories**
Let's give players the option to save their stories:


    import os

    def save_story(story):
        if not os.path.exists("mad_libs_stories"):
            os.makedirs("mad_libs_stories")

        filename = f"mad_libs_stories/story_{len(os.listdir('mad_libs_stories')) + 1}.txt"
        with open(filename, "w") as file:
            file.write(story)

        print_colored(f"Your story has been saved as {filename}", Fore.GREEN)

    def play_mad_libs(template, word_types):
        # ... (previous code)

        if input("Would you like to save this story? (yes/no): ").lower().startswith('y'):
            save_story(completed_story)



Enter fullscreen mode Exit fullscreen mode

Run the Code

First, make sure you have Python installed on your system. You can check this by opening a terminal and typing.

python --version
Enter fullscreen mode Exit fullscreen mode

or

python3 --version
Enter fullscreen mode Exit fullscreen mode

This should return the version of Python installed on your system.
If Python is installed, you should run the script using the Python interpreter. Instead of running.

./first_test.py
Enter fullscreen mode Exit fullscreen mode

You should run:

python first_test.py
Enter fullscreen mode Exit fullscreen mode

or if you're using Python 3 specifically:

python3 first_test.py
Enter fullscreen mode Exit fullscreen mode

Also, ensure that the file has the correct permissions to be executed. You can set this with:

chmod +x first_test.py
Enter fullscreen mode Exit fullscreen mode




Conclusion

Congratulations! You've now created an interactive, colorful, and feature-rich Mad Libs game in Python. This project has introduced you to several important programming concepts:

  1. String manipulation
  2. User input and output
  3. Functions and modular programming
  4. Lists and list comprehensions
  5. File I/O operations
  6. Error handling
  7. Third-party libraries (colorama)
  8. Random selection
  9. While loops and control flow

By building this game, you've not only created something fun but also laid a solid foundation for more advanced Python projects. Remember, the key to becoming a proficient programmer is practice and experimentation. Don't be afraid to modify this game, add new features, or use these concepts to create entirely new projects!

As you continue your Python journey, consider exploring more advanced topics like object-oriented programming, graphical user interfaces (GUIs), or web development with frameworks like Django or Flask.

The skills you've learned here will serve as an excellent springboard for these more complex areas of software development.

Happy coding, and may your Mad Libs adventures be filled with laughter and learning!

Resource

Top comments (0)