What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More
Building Anagram Game using Python (with Code)
  • Siddhartha
  • Sep 08, 2020

 

In this post, we will be developing the first project from our list of best beginner python projects– ‘The Anagram Game’. An anagram of a word is another word obtained by shuffling its letters. For example, the words God and dog are anagrams of each other. This is what the anagram game is all about.

The basic idea of this project is to read a file that contains words and their meaning like a dictionary, pick a random word from this dictionary, shuffle it and ask the user to guess the correct word from its anagram and the original meaning of the word.

Importing the Libraries

For this project, we will be using the json and random packages that are built into Python. JSON stands for Java Script Object Notation which is a file format used to store data in key-value pairs. This is similar to the Python ‘dictionary’ data structure. The json package provides methods to handle such data. The random package does exactly what the name suggests and has methods for generating random numbers, making random choices, and shuffling a list, among others.

import json
import random

 

Loading the Data

As mentioned before, we will need a dataset of words and their associated meanings. You can download a version of Webster’s Unabridged English Dictionary from this repository: click here. As we can see, the file format of this data is a json file and hence we will use the load function of the json package to load this data into a dictionary data structure in Python. 

 

filename = 'dictionary_data.json'
file = open(filename)
data = json.load(file)

The data is now stored as key-value pairs in the variable named data which is an instance of the dictionary class. A key-value pair in a dictionary is represented as {key : value}. In our data, the keys of the dictionary are 102217 different words and their values are the associated meaning of the respective words.

 

Picking a Random Word

Let us write a function that will pick a random word from the 102217 available words. The function will take two arguments – data and length. The data represents the dictionary of words and length is something determined by the programmer to decide the maximum length of words that should be returned from this function. We first have to make a list of all the possible words from the dictionary which can be accessed using the keys method of the dictionary class. We then pick a random word using the choice function and check if the length of the selected word is less than the maximum length specified in the arguments and the greater than two. Since, this can take multiple attempts we put this code in an infinite loop. When a word satisfying the length requirements is picked, the function returns the word. No code inside the function is executed once the function returns a value. The logic is given by the word_prompt function specified below.

 

def word_prompt(data, length):
    all_words = list(data.keys())
    while True:
        word = random.choice(all_words)
        if len(word) < length and len(word) > 2:
            return word

 

Shuffling the Word

Next, let us implement a function that will return a shuffled version i.e. an anagram of the word that we have selected. First, the word is converted into a list of characters. Next, we shuffle this list of characters using the shuffle function of the random package. The shuffled list of letters is converted back into a word using the join function that joins a collection of iterables together. Lastly, we run this code in an infinite loop to check that the shuffled word is not equal to the original word itself. If this condition is true the anagram of the word is returned. This logic is given by the shuffle_word function given below.

 

def shuffle_word(word):
    array = list(word)
    shuffled = word
    while True:
        random.shuffle(array)
        shuffled = ''.join(array)
        if shuffled != word:
            return shuffled

 

Building the Anagram Game

Now let’s move on the last part – building an interactive version of the game for the user to play with. We use our functions defined above to get a word and its anagram form to question the player. We also access the meaning of the word using the data dictionary. We will be giving the user five attempts to guess the correct answer and for that we have used a for loop that starts from 5 goes to 1 decrementing by 1 every loop. Every loop we ask the player to make a guess and check if it is equal to the expected word. If it is, the player is correct and we can break from the loop. Otherwise, the loop continues. Finally, when we reach the last iteration, we give the correct answer to the user. After for loop, we provide an option to allow the player to play the game again. To ensure that the game continues until the player decides to stop, we put the code in an infinite loop and break from it when the player enters ‘n’. The logic described is implemented in the code below.

 

print("Welcome to the Anagram Game!")
while(True):
    word = word_prompt(data, 5)
    question = shuffle_word(word)
    meaning = data[word]
    
    question = question.lower()
    word = word.lower()
    
    print("\nSolve:", question)
    print("Hint:", meaning)
 
    for i in range(5, 0, -1):
        print("\nAttempts Left:", i)
        guess = input('Make a guess: ').lower()
        if guess == word:
            print("Correct!")
            break
        if i == 1:
            print("\nCorrect Answer:", word)
    
    choice = input("\nContinue? [y/n]: ")
    print('-'*50)
    if choice == 'n':
        print("\nThank you for playing!")
        break

 

Anagram Game Output

 

Complete Code

Finally, the complete code is given below. The code’s script is placed in a '__main__' scope, which is used when reading from standard input such as the command-line interface. It is good practice to style the code according to conventional standards. You can go forward and build on this project through a scoring system or even a graphical user interface.

 

import json
import random
 
def word_prompt(data, length):
    all_words = list(data.keys())
    while True:
        word = random.choice(all_words)
        if len(word) < length and len(word) > 2:
            return word
 
def shuffle_word(word):
    array = list(word)
    shuffled = word
    while True:
        random.shuffle(array)
        shuffled = ''.join(array)
        if shuffled != word:
            return shuffled
        
if __name__ == "__main__":
    filename = 'dictionary_data.json'
    file = open(filename)
    data = json.load(file)
    
    print("Welcome to the Anagram Game!")
    while(True):
        word = word_prompt(data, 5)
        question = shuffle_word(word)
        meaning = data[word]
        
        question = question.lower()
        word = word.lower()
        
        print("\nSolve:", question)
        print("Hint:", meaning)
 
        for i in range(5, 0, -1):
            print("\nAttempts Left:", i)
            guess = input('Make a guess: ').lower()
            if guess == word:
                print("Correct!")
                break
            if i == 1:
                print("\nCorrect Answer:", word)
        
        choice = input("\nContinue? [y/n]: ")
        print('-'*50)
        if choice == 'n':
            print("\nThank you for playing!")
            break

 

Hopefully this post has introduced some basic concepts in Python such as conditional statements, looping statements, and file handling. As a beginner, it is expected that you have doubts about such concepts and if you need any clarification, we at FavTutor are always here to provide you help from expert tutors 24/7. Get started by sending a message through the chat on the bottom right. Happy programming!

Siddhartha

As a technological enthusiast, I am not only passionate about exploring the latest innovations but also firmly believe in promoting its applications. As such, I write about various projects involving Python, Data Science, and Artificial Intelligence