GITHUB REPO | FOLLOW ME ON -> TWITTER | LINKEDIN

Hangman Game in Python — A Beginners Guide

In this article, we will use Python to create a Hangman game. Hangman is a popular word-guessing game in which you try to guess a word by suggesting letters until you either solve the word or run out of life. This game will be built making use of Python concepts such as loops, conditionals, and functions.

Al-Junaed Islam

--

Hangman

Step-by-Step Code Explanation

The first thing we need to do is set up our Python Hangman Game. Open up your preferred code editor, create a new file, and save it with a descriptive name such as “hangman.py.”. Also create another two files which will be used as modules hangman_art and hangman_words.

hangman_art.py

In this file there are two variables name stages and logo. Stages represents the stage of Hangman. And the logo will be shown on the first time when user run the game.

stages = ['''
+---+
| |
O |
/|\ |
/ \ |
|
========= ''', '''
+---+
| |
O |
/|\ |
/ |
|
========= ''', '''
+---+
| |
O |
/|\ |
|
|
========= ''', '''
+---+
| |
O |
/| |
|
|
========= ''', '''
+---+
| |
O |
| |
|
|
========= ''', '''
+---+
| |
O |
|
|
|
========= ''', '''
+---+
| |
|
|
|
|
========= ''']

logo = '''
_
| |
| |__ __ _ _ __ __ _ _ __ ___ __ _ _ __
| '_ \ / _` | '_ \ / _` | '_ ` _ \ / _` | '_ \
| | | | (_| | | | | (_| | | | | | | (_| | | | |
|_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_|
__/ |
|___/ '''

hangman_words.py

word_list is the list of words that will be use for the game.

word_list = ['abruptly', 'absurd', 'abyss', 'affix', 'askew', 'avenue', 
'awkward', 'axiom', 'azure', 'bagpipes', 'bandwagon', 'banjo', 'bayou',
'beekeeper', 'bikini', 'blitz', 'blizzard', 'boggle', 'bookworm', 'boxcar',
'boxful', 'buckaroo', 'buffalo', 'buffoon', 'buxom', 'buzzard', 'buzzing',
'buzzwords', 'caliph', 'cobweb', 'cockiness', 'croquet', 'crypt', 'curacao',
'cycle', 'daiquiri', 'dirndl', 'disavow', 'dizzying', 'duplex', 'dwarves',
'embezzle', 'equip', 'espionage', 'euouae', 'exodus', 'faking', 'fishhook',
'fixable', 'fjord', 'flapjack', 'flopping', 'fluffiness', 'flyby', 'foxglove',
'frazzled', 'frizzled', 'fuchsia', 'funny', 'gabby', 'galaxy', 'galvanize',
'gazebo', 'giaour', 'gizmo', 'glowworm', 'glyph', 'gnarly', 'gnostic',
'gossip', 'grogginess', 'haiku', 'haphazard', 'hyphen', 'iatrogenic', 'icebox',
'injury', 'ivory', 'ivy', 'jackpot', 'jaundice', 'jawbreaker', 'jaywalk',
'jazziest', 'jazzy', 'jelly', 'jigsaw', 'jinx', 'jiujitsu', 'jockey',
'jogging', 'joking', 'jovial', 'joyful', 'juicy', 'jukebox', 'jumbo', 'kayak',
'kazoo', 'keyhole', 'khaki', 'kilobyte', 'kiosk', 'kitsch', 'kiwifruit',
'klutz', 'knapsack', 'larynx', 'lengths', 'lucky', 'luxury', 'lymph',
'marquis', 'matrix', 'megahertz', 'microwave', 'mnemonic', 'mystify',
'naphtha', 'nightclub', 'nowadays', 'numbskull', 'nymph', 'onyx', 'ovary',
'oxidize', 'oxygen', 'pajama', 'peekaboo', 'phlegm', 'pixel', 'pizazz',
'pneumonia', 'polka', 'pshaw', 'psyche', 'puppy', 'puzzling', 'quartz',
'queue', 'quips', 'quixotic', 'quiz', 'quizzes', 'quorum', 'razzmatazz',
'rhubarb', 'rhythm', 'rickshaw', 'schnapps', 'scratch', 'shiv', 'snazzy',
'sphinx', 'spritz', 'squawk', 'staff', 'strength', 'strengths', 'stretch',
'stronghold', 'stymied', 'subway', 'swivel', 'syndrome', 'thriftless',
'thumbscrew', 'topaz', 'transcript', 'transgress', 'transplant',
'triphthong', 'twelfth', 'twelfths', 'unknown', 'unworthy', 'unzip', 'uptown',
'vaporize', 'vixen', 'vodka', 'voodoo', 'vortex', 'voyeurism', 'walkway',
'waltz', 'wave', 'wavy', 'waxy', 'wellspring', 'wheezy', 'whiskey', 'whizzing',
'whomever', 'wimpy', 'witchcraft', 'wizard', 'woozy', 'wristwatch', 'wyvern',
'xylophone', 'yachtsman', 'yippee', 'yoked', 'youthful', 'yummy', 'zephyr',
'zigzag', 'zigzagging', 'zilch', 'zipper', 'zodiac', 'zombie', ]

hangman.py

First, we import the required modules, such as random, which selects random words from the word list, os, which clears the terminal for cleaner output, and our own modules hangman_art and hangman_words, which show ASCII art and provide a list of words, respectively. We then define a clear function using a lambda function that clears the terminal.

import random
from hangman_art import stages,logo
from hangman_words import word_list
import os

clear = lambda: os.system('cls')

Next, we select a random word from the word list and get its length. We set end_of_game to False and lives to 6, as the player has 6 lives before they lose the game.

chosen_word = random.choice(word_list)
word_length = len(chosen_word)

end_of_game = False
lives = 6

We display the ASCII art using logo and initialize the display list with underscores for each letter in the chosen word.

print(logo)

display = []
for _ in range(word_length):
display += "_"

We then enter a loop that continues until the end_of_game variable is set to True. In each iteration, we ask the player for a letter guess, clear the terminal, and check if the letter has already been guessed. If so, we print a message informing the player.

while not end_of_game:
guess = input("Guess a letter: ").lower()

clear()

if guess in display:
print(f"You already guessed the letter {guess}.")

Then we loop over each letter in the chosen word, checking to see whether the guess fits any of them. If this occurs, we update the display list to include the proper letter in the appropriate position.

We decrement lives if the guess is not in the chosen term. We set end_of_game to True and display a loss message with the right answer if the player has no more lives. Otherwise, we warn the player that they have lost a life and display the number of lives left.

    for position in range(word_length):
letter = chosen_word[position]
if letter == guess:
display[position] = letter
if guess not in chosen_word:
lives -= 1
if lives == 0:
end_of_game = True
print(f"{guess} is not in the word. You lost all of your lives.\nYou lose.\nCorrect answer was: {chosen_word}")
else:
print(f"{guess} is not in the word. You lost a life.\nRemaining Life: {lives}")
print(f"{' '.join(display)}")

We then show the current state of the word with underscores alongside the correctly guessed letters and see if the player has won by looking for any underscores in the display list. If there are no more underscores, the player has won, and we show a congratulations message.

Finally, we display the appropriate ASCII art for the current number of lives remaining using the stages list.

        if "_" not in display:
end_of_game = True
print("Congratulation! You guessed all the letters correctly.\nYou win.")
print(stages[lives])

Here is the full code altogether.

Test Output

Hangman Game Test Run
Test Output of Hangman Game

Features

Program’s Feature

  • Words are chosen at random.
  • ASCII art for visual appeal.
  • Capability to deal with repeated guesses.
  • The game loops until the game are won or lost.
  • Throughout the game, the player receives informative messages.

Python Concepts and Techniques Used

  • Importing modules
  • for and while loops
  • if-else conditions
  • The random() method was used to select a random word from the set word list.
  • On each round, we used the clear() function to clean the terminal.
  • To connect strings, we used the join() method.
  • Lists and list operations

Importance of the feature in the project

Each of these elements is required for the development of the Hangman game. Without the random word selection, the game would constantly utilize the same word, which would rapidly become boring. ASCII arts enhance the game’s visual attractiveness, making it more entertaining to play. By clearing the terminal, the player may concentrate on the present condition of the game. The capacity to deal with frequent guesses is required for accurate gameplay. The game loop is what allows the game to function, and helpful messages keep the player informed throughout.

In the end, the Hangman game demonstrates how Python may be used to develop entertaining and interactive applications. This game is a wonderful tool for developers of all levels to practice and improve their programming abilities, thanks to its simple code and robust features. So why not give it a shot and see what you can come up with?

This article is a part of my Python Project Journal. To learn more about my journey in learning Python and to see my other projects, check out this project journal. Thank you!

--

--