How to Create a Hangman Game Using Python

Publish date: 2024-05-23

Are you in the mood to play a game that you've written yourself? Well, you're in the right place. Hangman is a popular word-guessing game and you can create your own version with minimal effort.

This game is a perfect entertainer, familiar from popular TV game shows and series such as Wheel of Fortune, Letterbox, and Party Time. And Python is a convenient language to use to build a Hangman clone.

How to Play the Hangman Game

Hangman is a well-known game where one player thinks of a word and the other player tries to guess it by suggesting letters with a fixed number of guesses. One player (in this case the program) presents a sequence of dashes representing each letter of the word, along with a character as a starting point. The other player (or user) guesses the characters present in the word, one by one.

If the letter they guess is in the target word, the program fills the dash with the character. Otherwise, the player loses one chance, and the program draws an element of a stick figure as a tally. In a total of seven chances, if the user guesses the word correctly, they win the game. If not, the program completes its drawing of a stick man.

You can create a list of your favorite words or download one like Mieliestronk's list of more than 58,000 English words. You can also explore and build other fun text-based games such as an interactive quiz game or a text-based adventure game in Python.

How to Build the Hangman Game

The source code of this Hangman game, along with the word list file, is present in this GitHub repository and is free to use.

Import the random module and define a function, get_random_word_from_wordlist(), to pick a random word from the file. The text file may contain common nouns, or names of places, animals, movies, and more based on your liking. Define a list using the rectangular brackets([]).

Use the with statement to open the file and pass the mode as 'r' indicating read-only mode. This automatically takes care of closing the file at the end of the block even in cases of errors. If you view the hangman_wordlist.txt file, you'll notice there's one word present on every line, so the file separates each word with a newline character.

Pass the escape character for a newline (\n) to the split() function to store each word in the list you defined earlier. Use random.choice() to return a random word from the list.

import random
 
def get_random_word_from_wordlist():
    wordlist = []
 
    with open("hangman_wordlist.txt", 'r') as file:
        wordlist = file.read().split("\n")
 
    word = random.choice(wordlist)
    return word

Next, define a function, get_some_letters(), that takes the randomly selected word as a parameter. This function will display a sequence of blank dashes (_) and some letters to the user.

Define empty list letters to store all the characters present in the word. Use the temp variable to store a string that contains the number of blank dashes equaling the length of the word. Use list() to convert the string into a list of characters and iterate over it. Use append() to add the character to the list if not already present.

Use random.choice() to choose a random character that you are going to present to the user along with the blank dashes. Iterate over the characters of the word using enumerate to keep a track of the index of each character.

When you find the randomly selected character, replace the blank dash with it. Use join() to unify the list of characters into a complete string and return it.

def get_some_letters(word):
    letters = []
    temp = '_' * len(word)
 
    for char in list(word):
        if char not in letters:
            letters.append(char)
 
    character = random.choice(letters)
 
    for num, char in enumerate(list(word)):
        if char == character:
            templist = list(temp)
            templist[num] = char
            temp = ''.join(templist)
 
    return temp

Define a function draw_hangman() that takes the number of chances as a parameter. This function provides a figure of the hanging man. As the number of chances keeps on decreasing, so do the chances of survival. When exhausted, the figure is complete and the game finishes.

def draw_hangman(chances):
    if chances == 6:
        print("________ ")
        print("| | ")
        print("| ")
        print("| ")
        print("| ")
        print("| ")
    elif chances == 5:
        print("________ ")
        print("| | ")
        print("| 0 ")
        print("| ")
        print("| ")
        print("| ")
    elif chances == 4:
        print("________ ")
        print("| | ")
        print("| 0 ")
        print("| / ")
        print("| ")
        print("| ")
    elif chances == 3:
        print("________ ")
        print("| | ")
        print("| 0 ")
        print("| /| ")
        print("| ")
        print("| ")
    elif chances == 2:
        print("________ ")
        print("| | ")
        print("| 0 ")
        print("| /|\ ")
        print("| ")
        print("| ")
    elif chances == 1:
        print("________ ")
        print("| | ")
        print("| 0 ")
        print("| /|\ ")
        print("| / ")
        print("| ")
    elif chances == 0:
        print("________ ")
        print("| | ")
        print("| 0 ")
        print("| /|\ ")
        print("| / \ ")
        print("| ")

Declare a function, start_hangman_game(), that defines the main logic of the program. Get a random word by calling the get_random_word_from_wordlist() function and get the sequence to display to the user using the get_some_letters() function.

Set the number of chances to seven and initialize a variable, found, as false. You'll set this to true if the guessed letter is present in the word.

def start_hangman_game():
    word = get_random_word_from_wordlist()
    temp = get_some_letters(word)
    chances = 7
    found = False

Declare a loop that terminates when the user guesses the word correctly or runs out of chances. Begin the game by displaying the sequence, the number of letters in the word, and the chances left. Ask the user to guess a letter and receive it using the input() function. Validate the user input by checking the length of the character and whether it is an alphabet.

    while True:
        if chances == 0:
            print(f"Sorry! You Lost, the word was: {word}")
            print("Better luck next time")
            break
 
        print("=== Guess the word ===")
        print(temp, end='')
        print(f"\t(word has {len(word)} letters)")
        print(f"Chances left: {chances}")
        character = input("Enter the character you think the word may have: ")
 
        if len(character) > 1 or not character.isalpha():
            print("Please enter a single alphabet only")
            continue

If the input is valid, check if the character is present in the word and replace it using the process seen earlier and update the value of found. If the character is not present decrease the number of chances. If present, turn the value of found back to the initial value false.

If there are no blank dashes left, display that the user won along with the number of guesses taken otherwise display the hangman graphic according to the number of chances left.

        else:
            for num, char in enumerate(list(word)):
                if char == character:
                    templist = list(temp)
                    templist[num] = char
                    temp = ''.join(templist)
                    found = True
 
        if found:
            found = False
        else:
            chances -= 1
 
        if '_' not in temp:
            print(f"\nYou Won! The word was: {word}")
            print(f"You got it in {7 - chances} guess")
            break
        else:
            draw_hangman(chances)
 
        print()

Define a function to play the Hangman game. If the user inputs yes call the start_hangman_game() function otherwise quit the game with the appropriate message. In case of invalid input ask the user to enter again.

print("===== Welcome to the Hangman Game =====")
 
while True:
    choice = input("Do you wanna play hangman? (yes/no): ")
 
    if 'yes' in choice.lower():
        start_hangman_game()
    elif 'no' in choice.lower():
        print('Quitting the game...')
        break
    else:
        print("Please enter a valid choice.")
 
    print("\n")

The Output of the Hangman Game

You'll see the following output if you win the game:

You'll see the following output if you lose the game:

Use Python to Build Games

You can use Python to build command-line games as well as graphical games. Some interesting command-line games you can build using Python include the number guessing game, the Magic 8 Ball game, Mad Libs, Rock/Paper/Scissors, and a text-adventure game.

Some fun graphical games you might build with python include Tic Tac Toe, Maze, Snake, Pacman, Memory, Life. The best part about these games is that you can build them with just the Python Standard Library.

ncG1vNJzZmivp6x7rq3KnqysnZ%2Bbe6S7zGinsqyYpLtus8CmnGagkaO0rq3NZpqrnZGpsnCL1K2kmKufqr%2BksZyfo6KokqSus7CFrquml5Oku7Wxza10raegnrBmfqWam6%2BdnqnCs7HGmqSe