Sentence Rearrangement Game using Python

Sentence Rearrangement Game using Python

Introduction

During your childhood, you might have done this exercise where you were required to rearrange words to make a meaningful sentence. I cannot say anything about you, but I had done this quite a lot in my English classes.

In this blog post, we're going to build a CLI-Based Sentence Rearrangement Game using Python.

Optional Library

In the project, we'll be using the Rich library to make the terminal colorful. If you don't wish to use it, you can ignore it. To install Rich, use the command:

$ pip install Rich

To know more about Rich, read this tutorial.

Let's Code It!

Let us jump directly to the coding part and discuss what we have done.

First of all, create a text file called sentences.txt and add the following content there:

I have three cats
I am on a very tight budget
Being fashionable is easy
It looks like you have bigger problems
The hailstones were as big as tennis balls
They fell asleep on the couch
I've never voted with him on anything
We need congressional support
I broke my phone
I must have my TV set checked
I wish I could give you a big birthday hug
The concert was a real disappointment
Nostalgia isn't what it used to be
They're almost three times as big as we are
I miss my boyfriend
A small town lies between the big cities
School violence is a major problem
Tom is just a farm boy living in a big city
She is with another man
We have a dinner setup for us
Tom used to be a fancy lawyer
This company's profit margin is very big
The sunset was breathtaking
My small pet mouse escaped from his cage
An ENT removed the bug from his ear
I'm crying
I made bacon
I made a smoothie for you
I made a mistake in choosing my wife
We will walk in the garden later
It's time to watch TV
When you are in your twenties you read Hegel
The big building was blazing with lights
She said nothing and left the room
The doctor diagnosed her with diabetes
She wasn't sure if she wanted to go or not
My big brother shared his cake with me
I like open spaces
You're just going to take it
Those pants are too tight
I don't owe you anything
People love Chicago
I need to pack for my trip
They lived in Germany until 1939
That's a wrap for me
She liked to wear a lot of rings
They had a very bad breakup
I'm the designated driver
She was starting to run out of things to say
Good location choice
Utensils are useful
I am going to make my bed first
The course starts next Sunday
Tom wants a discount
He wears suspenders instead of a belt
She is eating a midnight snack
I think I could fall asleep really quickly
The laptop became warm
This way you can start to heal
I just walked on the furriest lawn
They employed him as a consultant
After the heavy rain, there was a big flood
There were so many cookies leftover
My dad killed my houseplants
Those are big watermelons
She washed the tomatoes
Being late is okay, but only sometimes
My sister works at the theater
I'm going to take a break
Being late is never okay
Tom's house is at least twice as big as mine
I've got rough hands
It enhanced what he did vocally
It's been keeping me up at night
I beg your pardon
He hung a picture on the wall
Tom's name was at the top of the list
I miss my best friend
You make me so happy
The security is the safest around
Tigers are gorgeous
My father is in the office
I have nowhere to go
Pandas should come hug me
I need to stir the soup
I am going to make my bed first
His eyes were glazed over
A penny saved is a penny earned
I don't like visiting cities
Rania is his own dearest enemy
I have a first name and a surname
I am having his baby
He's in a class of his own
I have something to tell you
I want to have a pink bed this year
Once you begin you must continue
You're the best person I know
I love land
Water damage sucks
Yesterday's board meeting was a big success

We'll be using the above sentences further.

Next, create a main.py file and add the following content in it.

from typing import List
from random import shuffle, choice
from rich.console import Console

console = Console()

def get_sentences(filename: str) -> List:
    with open(filename) as f:
        sentences = list(set(f.read().splitlines()))
        return sentences

def get_jumbled(sentence: str) -> str:
    splitted_words = sentence.split()
    shuffle(splitted_words)
    jumbled_sentence = " / ".join(splitted_words)
    return jumbled_sentence

def game(number_of_questions: int) -> int:
    game_is_continued = True
    score = 0
    count = 0
    while game_is_continued:
        correct_sentence = choice(get_sentences("sentences.txt"))
        jumbled_sentence = get_jumbled(correct_sentence)
        console.print(f"\nHere's your sentence: \n[cyan]{jumbled_sentence}[/cyan]")
        user_sentence = input("\nWrite your answer answer below\n")
        if user_sentence.lower() == correct_sentence.lower():
            score += 1
            console.print('[green]Hooray! Correct Answer[/green]')
        else:
            console.print('[red]Oops! Incorrect Answer[/red]')
            console.print(f'Correct Answer : [blue]{correct_sentence}[/blue]')
        count += 1
        if count == number_of_questions:
            game_is_continued = False
    return score

if __name__ == " __main__":
    console.print('[magenta]Welcome to the GAME!![/magenta]\n')
    number_of_questions = int(input("Please enter number of questions : "))
    if number_of_questions > 0:
        final_score = game(number_of_questions)

    console.print(f'\n[green]Your final score is {final_score}[/green]')
    print("Adi贸s, Amigo")

Here we have three functions : get_sentences(), get_jumbled() and game(). Let's discuss each of them now.

get_sentences() function

This function takes a filename as the parameter. It then reads the text file and creates a list of unique sentences and returns it. We are using the set() function to remove duplicates from the list. There are several other methods to do the same too.

get_jumbled() function

This function takes a sentence as the parameter. First, it splits the sentence and shuffles it using the shuffle() function from the random library. Then it joins the shuffled words using ' / '.

For example, if we pass a sentence like " This is a sweet mango.". It can return something like " mango / a / sweet / is / This". Thus we obtain a jumbled sentence.

game() function

This function takes a number_of_questions parameter for the total number of questions to be asked. We have used three variables - game_is_continued for the while loop, score for the total score calculation and count to count the number of questions that have been asked. Now, we start a while loop. Inside the while loop, first of all, we randomly choose a sentence from the sentences list obtained from the get_sentences() function and store it in a correct_sentence variable. Then we create the jumbled sentence for it using the get_jumbled() function. Next, we ask the user for the answer and store it in a user_sentence variable. Then we compare the user's answer with the correct answer (ignoring the case). If it's correct, we increase the score by 1. Since one iteration (or question) is complete, we increase our counter variable count by 1. At this stage, we check if the count is equal to the number_of_questions, i.e., the number of questions already asked is equal to the number of questions to be asked, then we break the loop by setting the game_is_continued variable to False. In the end, we just return the score.

Notice that we have used console.print() at most places. If you don't wish to use Rich, you can replace those statements with simple print() statements.

Main Function

In the main() function, we first ask the user for the number of questions. If the number of questions is greater than 0, we call the game() function with the argument number_of_questions. Else we stop there itself.

Demo

Oops, looks like I made a typo in the second answer 馃槶. Didn't notice it? Look at the spelling of lawyer in my answer.

Anyways, our code is working fine!!

Conclusion

Hope you liked this mini tutorial where we built a CLI-based game.

Share with your mates!

Did you find this article valuable?

Support Ashutosh Krishna by becoming a sponsor. Any amount is appreciated!