Hangman Game in Python – A Step-by-Step Guide

Have you ever played the hangman game before? It’s a classic word-guessing game that’s been around for decades. In this blog post, we’ll show you how to implement the hangman game in Python. We’ll go through the code and explain everything in detail, so even if you’re new to Python, you should be able to follow along.

Generating a Random Word

Firstly, I will show you how to generate a random word from the word list. We’ll use the random module to do this. In order to generate a random word, you need to have a list of words you want to use for the game. There can be two ways to get these words list:

  1. A file storing all the words you want to make available for this game. Like it is available in my github repository of Hangman game
  2. By using a python library english-words 2.0.0
import random
from english_words import get_english_words_set

wordsArray = list(get_english_words_set(["web2"], lower=True))
selected_word = random.choice(wordsArray)

Info:


get_english_words_set method returns a set of English words. In order to randomly pick any word from this word list, I have used randon.choice() method. This method requires a list data type and therefore, I have typecasted the wordsArray to list.

Hiding the letters of the chosen word

Now, we want to hide many of the letters from the word and replace them with underscore ( _ ). This way player will be sure about the number of letters there in the given word.

def hideCharacters(word):
    hidden_word = word
    num = random.randint(0, len(word) - 1)
    for i in range(0, len(word) - 1):
        if i != num:
            hidden_word = hidden_word.replace(word[i], "_")
    return hidden_word

In the above, function, I am randomly showing only one letter from the word, and the rest of the letters are replaced with an underscore. In case you want to show more than 1 letter randomly, you can make changes in the above function. For example, the below function will show more letters for bigger words.

def hideCharacters(word):
    hidden_word = word

    max_visible = len(word) // 4
    rand_places = []
    for i in range(max_visible):
        rand_places.append(random.randint(0, len(word) - 1))
    print(rand_places)
    for i in range(0, len(word) - 1):
        if i not in rand_places:
            hidden_word = hidden_word.replace(word[i], "_")
    return hidden_word

Handling letter guessed by players and deciding winner:

Now we’ll handle user input. We’ll ask the player to guess a letter and check if it’s in the word. We will keep on updating the displayed word based on the player’s input. If the player guesses correctly, we’ll replace the underscores with the correct letters. Note: If the letter guessed by the user is found at multiple places, then all the underscores will be replaced with that letter.

Also if the letter was already guessed before, you do not lose the chance, rather player will be informed that the letter has already been guessed. Finally, we’ll check if the player has won or lost the game. We’ll keep track of the number of incorrect guesses and end the game if the player runs out of guesses or correctly guesses the word.

import random
import re
from words import word_list
from english_words import get_english_words_set


def hideCharacters(word):
    hidden_word = word
    max_visible = len(word) // 4
    rand_places = []
    for i in range(max_visible):
        rand_places.append(random.randint(0, len(word) - 1))
    print(rand_places)
    for i in range(0, len(word) - 1):
        if i not in rand_places:
            hidden_word = hidden_word.replace(word[i], "_")
    return hidden_word


def startTheGame():
    print("Hello welcome to the new game... ")
    gamer = input("Enter your Name: ")
    print("Hello " + gamer + "! Welcome to hangman... Good luck!!")
    print("Let's begin...")
    print("************************")
    nextRound()


def nextRound():
    guesses = 6
    wordsArray = list(get_english_words_set(["web2"], lower=True))
    # selected_word = random.choice(word_list)
    selected_word = random.choice(wordsArray)
    print("Total Chances : 6")
    print("Here you go with your word...")
    hidden_word = hideCharacters(selected_word)
    print(hidden_word)
    startGuessing(guesses, hidden_word, selected_word)


def startGuessing(guesses, hidden_word, selected_word):
    guessed_letters = []
    guessed = False
    while not guessed and guesses > 0:
        l = input("Your next guess : ")
        if l in guessed_letters:
            print("Letter is already guessed !")
        elif l in selected_word:
            occurances = [pos.start() for pos in re.finditer(l, selected_word)]
            for i in occurances:
                hidden_word = hidden_word[:i] + l + hidden_word[i + 1 :]
            print(hidden_word)
        else:
            guesses = guesses - 1
            print("Wrong guess. Chances Left: " + str(guesses))
        guessed_letters.append(l)
        if hidden_word == selected_word:
            guessed = True

    if hidden_word != selected_word:
        print("The word was : " + selected_word)
        print("Sorry !! You lost this round !")
        if input("Do you want to know the word? (y/n):  ").upper() == "Y":
            print("The Word was:  " + selected_word)

    else:
        print("Congratulations!! You won!!")


def main():
    startTheGame()
    while input("Want to play again? (y/n) : ").upper() == "Y":
        nextRound()
    print("Thank you!! See you next time...")


if __name__ == "__main__":
    main()

Conclusion:

Congratulations! You’ve successfully implemented the hangman game in Python. We hope you found this tutorial helpful and enjoyed playing the game. Now that you have the basic hangman game code, you can customize it and make it your own. Happy coding!
You can find this entire code in github repository too.

Welcome to the Algo-World

Are you interested in learning about different types of algorithms and how they can be implemented in Python? Are you preparing for technical interviews with companies like Google, Facebook, Amazon, and other top tech companies? Then you’ve come to the right place! Welcome to our new blog on algorithms in Python.

You May Also Like…

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Welcome to Algo-world

You have Successfully Subscribed!