Implementing the Hangman Game in Python

-

, Hangman was a very fun game in our home. We’d grab a pen and paper and take turns selecting words for the opposite to guess. Today, it’s utilized in classroom settings to assist kids practice their spellings, understand strategic decision making by selecting vowels first, and brainstorm possible words from hints.

In this text, we’ll undergo the Hangman Game by implementing it in Python. This can be a beginner-friendly project where we’ll learn the fundamentals of the Python language, corresponding to defining variables, commonly used functions, loops, and conditional statements.

Understanding the Project

First, we’ll understand the sport and get into the depths of how our code should work.

In a typical 2-player Hangman Game, Player 1 chooses a word, hiding it from Player 2, and generates blanks corresponding to the variety of letters within the word he selected for guessing. Player 2 has to guess the word by guessing one letter at a time. Player 2 has an outlined variety of lives originally, and with each mistaken guess of letters, they lose a life (to the purpose where the person is hanged). With each right guess, the lives remain the identical as before. If Player 2 loses all their lives without guessing the word, the sport is over, and so they lose. In the event that they manage to guess the word, they win the sport. That is the outline of the sport in its traditional sense.

On this project, the pc might be Player 1, generating the word to guess, while we, the user, might be Player 2. Allow us to implement the above using a flowchart for higher comprehension.

Image by Writer

Drawing a flowchart and defining each step helps in turning our thought process into code, so its at all times a great practice to attract one. Now allow us to start with coding the issue!

Step 1: List of Words and the Random Module

Step one on this project is for the pc to decide on a random word that the user can have to guess. For this purpose, we’ll need each an inventory of words from which the pc picks one word to be guessed, and a Python function called random, which is able to randomly select that word from the given list.

To generate the list, I googled the 100 commonest nouns utilized in the English language and located a list. I used these words and created a Python list with it to be utilized in this project.

Because the name suggests, a Python List is a datatype that stores in itself a set of things. An inventory of colours might be defined in Python as colours = ["red", "yellow", "green", "blue", "pink"]. You possibly can try the List syntax and extra information from the Python official page on List.

word_list = [
    "time",
    "year",
    "people",
    "way",
    "day",
    "man",
    "thing",
    ...
    ]

You possibly can access the project files from my GitHub repository. hangman_words.py is the Python file that accommodates the list of words from which the pc will randomly select a word for the sport.

Now, once our list is created, we’d like the pc to decide on a random word from the given list of words word_list. Python has a module especially for this purpose called “random”. We are going to import the module and use it to permit the pc to randomly select a word word_to_guess from the list words_list. You possibly can print the word_to_guess while coding the project to reinforce understanding, and comment it out when twiddling with the pc!

import random
word_to_guess = random.alternative(word_list)
print(word_to_guess)

For more information on the random.alternative() function, click here.

Step 2: Generating Blanks

The subsequent step is to generate blanks equal to the variety of letters within the word_to_guess in order that the user gets an idea of the variety of letters within the word he has to guess. For this, we’ll define a variable called blanks which is able to act as a container for the unguessed letters of the word. It would contain the variety of “_” equal to the variety of letters within the word_to_guess.

To calculate the variety of letters within the word_to_guess that has been randomly picked by the pc from the words_list, we’ll use the Python function len()that calculates the length of a string. More information on this in-built function will be accessed through this link.

blanks = ""
word_length = len(word_to_guess)

As we now know the variety of letters in word_to_guess, we’ll use this number so as to add an equal variety of “_” within the variable blanks. For this purpose, we’ll use the for loop, a Python functionality that enables us to iterate over items in a sequence, in our case, the string that’s stored within the variable word_to_guess. Click here to learn more about for loop and its syntax.

for i in range(word_length):
    blanks = blanks + " _"
print("Word to guess: " + blanks)

The above block of code will iterate over the variety of letters within the word_to_guess string and generate a blank for every letter. It would print out as many _ because the variety of letters, each blank as a placeholder for the letter of the word to guess. So for the word “time”, the output printed on the screen might be :

Word to guess: _ _ _ _

Step 3: Prompting the User to Guess a Letter

Now the sport actually starts! The pc has picked a word, generated blank placeholders for the letters in that word. Now comes the time for the user to start out guessing the word by guessing one letter at a time.

To ask the user for a letter, we’ll use the input function in Python and store it within the variable guess:

guess = input("Guess a letter").lower()

Click here to learn more in regards to the Python built-in function input().

Step 4: Check if the Letter is within the Word

Once the user has guessed a letter, we’ll check whether the user has guessed it right and check whether it is within the word_to_guess.

To do that, we’ll use a for loop. Furthermore, we will even create one other variable, your_word, which is able to update with the guessed letters and an empty list called,letters_guessed which is able to store the letters guessed accurately by the user (this might be useful as we’ll see later).

So, for instance, if the pc has picked the word “cheesecake”, as the sport progresses and the user has guessed the letters “c”, “e”, and “a”, that is what each your_word and letters_guessed would appear to be:

your_word = c_ee_eca_e

letters_guessed = [“c”, “e”, “a”]

letters_guessed = []
your_word = ""

for letter in word_to_guess:
    if letter == guess:
        your_word  = your_word + letter
        letters_guessed.append(guess)
    elif letter in letters_guessed:
        your_word  = your_word + letter
    else:
        your_word = your_word + "_"

So mainly what the above loop does is that it iterates through the word_to_guess one letter at a time, and checks:

  • If the letter guessed by the user guess is within the word_to_guess, the code will update the variable your_word so as to add the letter guessed at its appropriate location. We’d like to grasp that in Python, strings are in actual fact a sequence of characters, and plenty of list functions are applicable to strings as well. Furthermore, we will even add this letter guessed accurately to the list letters_guessed.
  • If the letter that the user has guessed, guess, is within the letters_guessed, which implies the user has already suggested this letter before, then we won’t must add this to the letters_guessed, but just must add the letter within the your_word at its appropriate location.
  • Else, if the letter guessed by the user will not be within the word_to_guess, and due to this fact won’t be within the letters_guessed, we’ll easy generate blanks in places.

If the code above seems a bit overwhelming, be happy to simply run the above for loop while defining the variables and printing each of the variables: word_to_guess, guess, guessed_letters, and your_word and printing the variables where they’re modified.

Image by AltumCode on Unsplash

Step 5: Creating the While Loop that runs until the Game is Over

Allow us to refer back to the flowchart we created to assist us understand the project. With a view to code this project, we’d like to bear in mind the next points:

  • The user has an outlined variety of lives originally
  • For every letter guessed mistaken, the lives are reduced by 1
    • If the user runs out of lives, the user loses and the sport is over
    • If the user has lives left, the pc will ask the user to guess one other letter
  • For every letter guessed right, the lives remain unchanged, and a blank is replaced by a letter within the placeholder blanks
    • If the variable your_word is all filled, the user wins the sport, and the sport is over
    • If the variable your_word has blank spaces left, then the pc will again ask the user to guess the following letter

Since we now have created the for loop previously that caters to the guessed letter, now’s the time to include the thought of lives, and reduce it when the user has guessed a letter mistaken.

Allow us to define the variety of lives for the user with the variable number_of_lives. The user has 6 possibilities to suggest the mistaken letter in guessing the word.

number_of_lives = 6

Now, considering the points mentioned above, we also need a variable or a condition that tells us to stop asking the user to guess when the sport is over. Allow us to code it with the assistance of a Boolean variable.

Simply stating, a Boolean is a datatype in Python that stores either True or False. We are going to use this Boolean variable to proceed the sport while it’s False and vice versa. Initially, while the sport starts, this variable might be False, meaning the sport will not be over.

game_over = False

Now we’ll introduce a while loop with the condition that it’s going to run so long as the sport will not be over, and we’ll include the conditions mentioned above on this while loop. Try more in regards to the while loop from the Python official documentation here.

while not game over:
     print("nYou have ", number_of_lives, " lives remaining!")
     guess = input("Guess a letter: ").lower()

     your_word = ""

     for letter in word_to_guess:
        if letter == guess:
            your_word  = your_word + letter
            letters_guessed.append(guess)
        elif letter in letters_guessed:
            your_word  = your_word + letter
        else:
            your_word = your_word + "_"
     print("Word to guess: ", your_word)

Within the above piece of code, we now have added the input statement in addition to the print statement, which is able to output the letters guessed thus far in accordance with their position within the word_to_guess.

Step 6: Handling Situations

The last step is to handle different circumstances. What happens if the letter the user has guessed has already been suggested by the user, or the letter will not be within the word? Also, what if all of the letters have been guessed and there aren’t any more blanks in your_word? This might mean that the user has guessed the word and thus won.

We are going to add this example within the code with he following lines:

if guess in letters_guessed:
    print(f"nYou've already guessed {guess}")

if "_" not in your_word:
    game_over = True
    print("nYou have guessed the word! YOU WIN!")
Image by Giorgio Trovato on Unsplash

Furthermore, if the letter guessed by the user will not be within the word_to_guess, the user’s guess is inaccurate, then their lives might be reduced by 1, and we’ll inform the user that their guessed letter will not be within the word. If reducing the lives by a mistaken guess finishes all of the user’s lives, then our boolean variable game_over might be set as True , and the sport will end, with the user losing the sport.

if guess not in word_to_guess:
    number_of_lives -= 1
    print(f"nYou guessed {guess}, that is not within the word. You lose a life.")

    if number_of_lives == 0:
        game_over = True
        print(f"nIT WAS {word_to_guess}! YOU LOSE!")

Remember so as to add the above blocks of code contained in the while loop that runs until the sport will not be over. An entire code together with useful comments will be accessed through this GitHub repository for a greater understanding.

Conclusion

The above coding project was done with the fundamentals of the Python language. We got here across some built-in functions, like print(), and input(), we used the random module to generate random words to guess and used for and while loops in various iterations in accordance with need. We also went through the conditional if, elif and else statements. These are all the fundamental tools that each beginner must know before they jump into complex coding. We could even have defined and called functions on this program, but this was meant to be a beginner-friendly introduction to the Python language. When you are a professional in Python, be happy to share various other ways we could have approached this project!

ASK ANA

What are your thoughts on this topic?
Let us know in the comments below.

0 0 votes
Article Rating
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Share this article

Recent posts

0
Would love your thoughts, please comment.x
()
x