Creating Mad Libs Game Using Python

Creating Mad Libs Game Using Python

Mad Libs is a word game which consists of blanks with keywords underneath for the players to fill. The keywords could be a ‘noun’, ‘pronoun’, ‘place’, ‘celebrity name,’ etc.

image.png

In this article, instead of blanks, capital letters of the keywords would be used. The text would be displayed and players would be prompted to input words to replace the keywords, and then the word is displayed again on the screen with players' input. Also, in this article, you would learn how to import another python script created by you.

List of Sentences for Game Play

Create a python script and name it mad_libs_library.py and input the following (or create your own list of sentences).

# mad_libs_library.py - A python script containing a list of sentences to be used in a Mad Libs game.

mad_libs = ['The dog VERB to the NOUN, barked at the NOUN, and the NOUN was ADJECTIVE',
            'The ADJECTIVE cloud caused a big ADJECTIVE, and all NOUN closed early',
            'If you watch horror movies at night, you might have ADJECTIVE dreams and be VERB',
            'Sleep early to VERB early, for it is in the ADVERB that you have more ADJECTIVE',
            'When you are ADJECTIVE, walk away, and keep your NOUN shut, least you VERB something wrong',
            'What you VERB first thing in the morning, determines your NOUN.',
            'To be great in NOUN, you need to VERB hard at your NOUN.',
            'Reading opens you to ADJECTIVE ideas, and makes you see the world ADVERB.',
            'To receive, you must first VERB; for that is how the world VERB.',
            'It takes NOUN to build a friendship.',
            'Programming is ADJECTIVE.',
            'The best time to VERB your life is when you are ADJECTIVE.',
            'Fruits VERB the body.',
            'Knowing oneself is one of first to great NOUN.',
            'When you stop learning, you start VERB.']

Mad Lib Game Script

Create another script named mad_libs_game.py and input the following.

# mad_libs_game.py - A Mad Libs game.

import string                       # For string.punctuation
from re import findall              # To create a list of words from sentences

import mad_libs_library as mlib     # Script containing the sentences for the game
import random                       # For random.shuffle

# Shuffle the sentences in mad_libs_library
random.shuffle(mlib.mad_libs)

key_words = ['ADJECTIVE', 'NOUN', 'PRONOUN', 'INTERJECTION', 'EXCLAMATION', 'VERB', 'ADVERB']

for sentence in mlib.mad_libs:
    print(sentence)

    # List containing words and punctuation marks of the current sentence on the screen
    words = findall(r'\w+|["!#$()\[\]%&\'./:?;,<=>]', sentence)
    key_words_found = []            # List to contain keywords found in current sentence

    # Adding keywords found in the sentence to key_words_found list
    for word in words:
        if word in key_words:
            key_words_found.append(word)

    # Ask for user's input and replace the keywords with user's input
    for word in key_words_found:
        user_choice = input('Enter a(n) ' + word + ': ')
        words.insert(words.index(word), user_choice)
        words.remove(word)

    # Combine words and print new sentence
    new_sentence = ''       # Variable to contain sentence formed based on user's input
    for word in words:
        if word in string.punctuation or word is words[0]:
            new_sentence += word

        else:
            new_sentence += ' ' + word

    print(new_sentence, '\n')

I would explain the above code in bits throughout this article.

Importing Modules

First, we import the modules we would be using and our script, mad_libs_library, which contains our sentences for the game. The string module would be used to check if a list item is a punctuation mark when creating our new sentence from the user’s input. Next, from our re module, we import the findall() function, which we would use to create a list of the words and punctuation of the printed sentence, so as to easily take out the keywords and replace them with the players’ inputs. Next, we import our mad_libs_library script and name it as mlibs for easy usage in the code. Finally, we import the random module which we use to shuffle the sentences from our script.

import string
from re import findall

import mad_libs_library as mlib
import random

Shuffling Sentences and Creating a List of Keywords

Next, we shuffle the sentence gotten from the script we imported and create a list of keywords that would be found in the sentences.

random.shuffle(mlib.mad_libs)

key_words = ['ADJECTIVE', 'NOUN', 'PRONOUN', 'INTERJECTION', 'EXCLAMATION', 'VERB', 'ADVERB']

We then create a for loop which would loop all the sentences in the script we imported and shuffled, and we print the current sentence to the screen.

Creating Lists of Words and Keywords from Current Sentence

for sentence in mlib.mad_libs:
    print(sentence)

Using the findall() function, we create a list of all the words and punctuations. We create an empty list, key_words_found, and using a for loop we append the keywords found in the sentence.

    words = findall(r'\w+|["!#$()\[\]%&\'./:?;,<=>]', sentence)
    key_words_found = []            # List to contain keywords found in current sentence

    for word in words:
        if word in key_words:
            key_words_found.append(word)

For example, if we have What you VERB first thing in the morning, determines your NOUN. printed to the screen, words and key_words_found would form the lists below.

['What', 'you', 'VERB', 'first', 'thing', 'in', 'the', 'morning', ',', 'determines', 'your', 'NOUN', '.']
['VERB', 'NOUN']

Replacing Keywords with Players’ Inputs

For each keyword found, we prompt the players for input to replace the keywords.

    for word in key_words_found:
        user_choice = input('Enter a(n) ' + word + ': ')
        words.insert(words.index(word), user_choice)
        words.remove(word)

Printing New Sentence Based On Player's Input

Finally, we create a variable, new_sentence, which would contain the words of the players which replaced the keywords, which would be printed to the screen before the main for loop moves to the next sentence. If and else statements are used to create spacing between words as they are joined, while we ensure that there is no spacing between words and punctuations.

# Combine words and print new sentence
new_sentence = '' 
for word in words:
    if word in string.punctuation or word is words[0]:
        new_sentence += word

    else:
        new_sentence += ' ' + word

print(new_sentence, '\n')

You could increase the number of sentences in the mad_libs_library. You could also make the whole game be in a singular script (thus, we won’t be importing any script); in other words, our list of sentences could be in our game script.
Play the game on Replit