Building a Mad Libs Word Game in Python
Tags: python, programming, beginners, tutorial
Published: 2024-02-16 16:10:40

Mad Libs is a classic word game where one player prompts others for various words like nouns, verbs, adjectives, etc. without providing any context. The prompt words are then inserted into a story template full of blanks to create a hilarious or nonsensical story that the players read aloud for laughs.

Mad Libs has entertained generations of kids and adults since it was invented in the 1950s. Numerous television shows and games have also adapted the concept as an interactive storytelling format. Let’s learn how to code our text-based Mad Libs game in Python.


![Python Loops: A Comprehensive Guide for Beginners](https://blog.learnhub.africa/wp-content/uploads/2024/02/Python-Loops-A-Comprehensive-Guide-for-Beginners-1024x535.png)


Learn about loops here: [Python Loops: A Comprehensive Guide for Beginners](https://blog.learnhub.africa/2024/02/15/python-loops-a-comprehensive-guide-for-beginners/)


## Step 1 – Setting up the game template 

First, we must create our Mad Libs story template as a string in Python. This will contain the full story text with placeholders for where player input must be inserted, like `{noun}`, `{verb},` etc.

For example:

    story = “The other day my friend and I spotted a/an {adjective} looking {noun} on the sidewalk. My friend decided to {verb} it while I {verb}-ed.”


## Step 2 - Prompt for words from a player

We will use Python’s input() function to prompt the player to enter words for each placeholder in the story template string. Let’s store each input in separate variables like:


    adjective = input(“Enter an adjective: “)
    noun = input(“Enter a noun:”) 
    verb1 = input(“Enter a verb: “)
    verb2 = input(“Enter another verb: “)


## Step 3 – Insert words into the story template

Next, we insert the words stored in the variables into the story template using string concatenation to replace each `{placeholder}`.
For example:


    story = “The other day my friend and I spotted a/an “ + adjective + “ looking “ + noun + “ on the sidewalk. My friend decided to “ + verb1 + “ it while I “ + verb2 + “-ed.”


## Step 4 - Print out the full story

Finally, print out the full Mad Libs story to display to the player!

    print(story)

At this point, we have built the basic functionality. Let’s look at some ways to expand the program next.

## Adding Loops

Using loops, we can fill multiple blanks in the story without repeatedly prompting the player manually for each one.

For example:
```python
    adjectives = []
    for i in range(3):
       adj = input("Enter an adjective: ")
       adjectives.append(adj)
    
    story = "...a/an " + adjectives[0] + "..." + adjectives[1] + "...extremely " + 
    adjectives[2] + ..." 
```
## Creating a GUI

Instead of a text interface, we can use the tkinter module to build a graphical user interface for a more interactive visual experience.


![10 Jobs Requiring Little Formal Education](https://blog.learnhub.africa/wp-content/uploads/2024/02/10-Jobs-Requiring-Little-Formal-Education-1024x535.png)


There are a lot of tech jobs you do not need coding skills, find out more in this guide: [10 Jobs Requiring Little Formal Education](https://blog.learnhub.africa/2024/02/09/10-jobs-requiring-little-formal-education/)

We first import tkinter to allow us to create GUI elements.

```python
    import tkinter as tk
```
## Create the main window

Using tkinter, we create a Tk() object, which will be the main window of our GUI.

```python
    root = tk.Tk()
    root.title("Mad Libs")
```
## Adding input fields

We use the Entry widget to create input fields to collect words from the user.

```python
    noun_entry = tk.Entry(root) 
    noun_entry.pack()
  ``` 
    # Repeat for other word types (verb, adjectives, etc)
## Adding a text display box

We use a Text widget to display the final mad lib story to the user.

```python
    story_text = tk.Text(root, height=8, width=40)
    story_text.pack()
```
## Adding a Play Again button

We use a Button widget to create a clickable Play Again button to restart the game.

```python
    play_button = tk.Button(root, text="Play Again", command=play_again) 
    play_button.pack()
    
    def play_again():
       # Reset game
```
       ...
## Putting it together

We arrange all the GUI widgets using .grid() and .pack() for our layout.
We can now prompt the user for input, build the story, and display it in the GUI instead of just text printouts. The full code would connect the GUI elements to the game logic.

```python
    import tkinter as tk
    
    # Main story template 
    story = "One day my friend and I found a {adjective} looking {noun} on the {noun}. My friend decided to {verb} it while I {verb}ed."  
    
    # Functions
    def play_again():
       # Clear entries
       adj_entry.delete(0, tk.END)
       noun_entry1.delete(0, tk.END)
       
       # Clear story  
       story_text.delete(1.0, tk.END)
       
    def generate_story():
       # Get values
       adjective = adj_entry.get()
       noun1 = noun_entry1.get()  
       noun2 = noun_entry2.get()
       verb1 = verb_entry1.get()
       verb2 = verb_entry2.get()
       
       # Create full story
       story_text.insert(tk.END, story.format(adjective=adjective, noun=noun1, noun2=noun2, verb=verb1, verb2=verb2))
    
    # GUI Setup
    root = tk.Tk() 
    root.title("Mad Libs")  
       
    # Input fields
    adj_entry = tk.Entry(root)
    adj_entry.pack()
    
    noun_entry1 = tk.Entry(root)  
    noun_entry1.pack()
    
    noun_entry2 = tk.Entry(root)
    noun_entry2.pack()
    
    verb_entry1 = tk.Entry(root)
    verb_entry1.pack()
    
    verb_entry2 = tk.Entry(root) 
    verb_entry2.pack()
      
    # Text display box 
    story_text = tk.Text(root, height=8, width=40)
    story_text.pack()
       
    # Play again button  
    play_button = tk.Button(root, text="Play Again", command=play_again)
    play_button.pack()
    
    # Run main loop
    root.mainloop()
```
Let me know if you need any clarification or have additional questions!

## Conclusion

Building games like Mad Libs is an engaging way to learn Python programming. The key concepts we applied here were:

- String manipulation
- Variables
- User input
- Print output
- Functions
- Logic
    

This combines core programming principles with creativity. These skills provide a foundation for developing more advanced games, apps, and Python tools.

If you find this post exciting, find more exciting posts on [Learnhub Blog](https://blog.learnhub.africa/); we write everything tech from [Cloud computing](https://blog.learnhub.africa/category/cloud-computing/) to [Frontend Dev](https://blog.learnhub.africa/category/frontend/), [Cybersecurity](https://blog.learnhub.africa/category/security/), [AI](https://blog.learnhub.africa/category/data-science/), and [Blockchain](https://blog.learnhub.africa/category/blockchain/).

## **Resource**
- [Getting started with Folium](https://realpython.com/lessons/python-folium-get-started/)
- [20 Essential Python Extensions for Visual Studio Code](https://blog.learnhub.africa/2023/05/26/20-essential-python-extensions-for-visual-studio-code/)
- [Using Python for Web Scraping and Data Extraction](https://blog.learnhub.africa/2023/04/27/using-python-for-web-scraping-and-data-extraction/)
- [Getting Started with Python](https://www.python.org/about/gettingstarted/)
- [Creating Interactive Maps with Folium and Python](https://blog.learnhub.africa/2023/10/04/creating-interactive-maps-with-folium-and-python/)