Search justacoding.blog. [Enter] to search. Click anywhere to close.

November 30th, 2022

Build A Python Anagram Guessing Game

Let’s build a simple anagram guessing game in Python!

This is a simple project, and the final program is a short one, as you’ll see.

You can play this anagram guessing game directly via the terminal, and the difficulty of the game is configurable based upon your own inputs (easy, medium or hard anagram options are available).

The idea of the game is to “unscramble” the presented word to find the original word before the letters were shuffled around.

This game idea is great for Python beginners or first-timers to work on given it’s length and complexity to implement.

With that said, let’s begin!

The anagram guessing game script

Here’s the anagram guessing game script in it’s entirety:

import random

word_lists_by_difficulty_index = {
    1: ['cat', 'red', 'dog'],
    2: ['apple', 'chair', 'tiger'],
    3: ['legislate', 'technique', 'parallel']
}

while True: 
    try:
        difficulty_index = int(input("Easy (1), medium (2) or hard (3)? "))
        if (difficulty_index < 1 or difficulty_index > 3):
            raise ValueError
    except ValueError:
        print("Please enter a valid difficulty between 1 and 3")
        continue
    else:
        break

target_word = random.choice(word_lists_by_difficulty_index[difficulty_index])

letters = list(target_word)
random.shuffle(letters)
shuffled_word = "".join(letters)

print("Here's your shuffled word: " + shuffled_word)

answer = input("What do you think the target word is? ")

print("You answered " + answer)

if answer == target_word:
    print("Correct!")
else:
    print("That's not correct! The correct answer was " + target_word)

As you can see, it’s a fairly short Python script.

You can run the script by writing this in your terminal:

python3 anagram-game.py

(Remember to substitute the .py filename with whatever you name the file, and if you aren’t using Python 3 you’ll need to modify that part accordingly too!)

Within the program, we will be dealing with some important Python fundamentals and functionalities: more specifically, working with strings as well as utilising the commonly-used random module.

Let’s break the script down bit by bit.

Defining the available target words

For the sake of demonstration, there will be a limited amount of words that can be jumbled up into anagrams for this game. More specifically, there will be 9 words, and these words will be divided by difficulty (3 sets of 3 words).

word_lists_by_difficulty_index = {
    1: ['cat', 'red', 'dog'],
    2: ['apple', 'chair', 'tiger'],
    3: ['legislate', 'technique', 'parallel']
}

The concept of difficulty in this game is fairly rudimentary; it’s purely based on the length of the word.

The shorter words are deemed to be “easy” words, whereas longer words are deemed to be “harder” ones.

As you can see, we’re storing the word lists in an object. This is to more easily correlate each list of words with it’s actual intended difficulty (read: length).

  • The value at the key of 1 is a list of easy words.
  • The value at the key of 2 is a list of medium words.
  • The value at the key of 3 is a list of hard words.

When we prompt the user for their input later on, we’ll expect them to pick one of these difficulty indexes (1, 2 or 3).

Based on this, we’ll know which list we need to select our (random) word from!

Prompting for user input

Once the user accesses the program via the terminal, the first thing they’ll encounter is a prompt for their difficult selection.

We’ll effectively ask the user to select a difficulty rating of either 1, 2 or 3.

As explained above, this numeric value correlates with the structure of our object (word_lists_by_difficulty_index) referenced above.

So if the user selects number 2, we can simply fetch our list of “medium” words based on this, using the key of 2:

word_lists_by_difficulty_index[difficulty_index]

Some simple validation of the user input

As you can also see, there’s some simple validation on the user’s input.

We want the user to supply a valid integer, and we want it to fall within the bounds between 1 and 3:

while True: 
    try:
        difficulty_index = int(input("Easy (1), medium (2) or hard (3)? "))
        if (difficulty_index < 1 or difficulty_index > 3):
            raise ValueError
    except ValueError:
        print("Please enter a valid difficulty between 1 and 3")
        continue
    else:
        break

To summarise this functionality: there’s a while loop that’s only broken (using break) when we know the input is valid/as expected. If the input isn’t valid, the prompt is presented back to the user in perpetuity.

This is a fairly common pattern when receiving and validating user input within the terminal in Python.

Now, the next step is to pick a random word from our selected list of words.

Selecting a random word from the list

Given a list of words of appropriate difficulty, which we now have, we’ll need to pick only one of these words at random so that the user doesn’t receive the same word each time they play the game.

Later on, we’ll shuffle that word to create our jumbled word. But for now, let’s just select a random word.

We can do this using random.choice:

target_word = random.choice(word_lists_by_difficulty_index[difficulty_index])

This selects a random word for us from the given list, which is what we need. Great.

Shuffling the word

Of course, we now need to modify the order of the letters in the selected word. This forms the actual basis of our game (the user must unravel these letters to win the game).

To shuffle the word, however, it’s necessary to firstly convert it to a list. The converted list is simply a collection of each of the letters in the given word.

We can now use random.shuffle to shuffle around these letters, and then convert the shuffled list back to a string:

letters = list(target_word)
random.shuffle(letters)
shuffled_word = "".join(letters)

As you may have noticed, random.shuffle doesn’t return the shuffled list — it instead modifies the original list. That’s why we’re not assigning it to a new variable here, but instead, using letters again directly when building the final string.

Python’s join method is used to formulate the array or list items in to the string in this case.

So this leaves us with our target word; the word the user should try to unravel!

Allowing the user to supply their answer

Now we need to do two things:

  • present the generated jumbled up word to the user
  • allow them to guess what the target word is based on the presented word

We can do this using the input function like we used above.

answer = input("What do you think the target word is? ")

Simply ask for the user’s answer, and then compare it to the original target word.

if answer == target_word:
    print("Correct!")
else:
    print("That's not correct! The correct answer was " + target_word)

If the answer matches the target word, we know that the user guessed correctly.

If not, we know that the user didn’t guess correctly.

We can notify the user of this accordingly using Python’s print function, as you can see above.

And that just about concludes the explanation of our simple Python anagram guessing game!

What next?

Hopefully you’ve gained some insight into some of the fundamentals of Python when following along with this tutorial.

You can find other project ideas that are also suitable for Python beginners over here: 10 Python Project Ideas For Beginners, so feel free to check those out!

Thanks for reading!

Have any questions? Ping me over at @justacodingblog
← Back to blog