Build a Hangman Game for the Command Line in Python

Build a Hangman Game for the Command Line in Python

by Jon Fincher Nov 01, 2023 basics gamedev projects python

Many people learn basic language and word skills by playing the game of hangman. First mentioned in print in the late nineteenth century and popularized in international media as the game show Wheel of Fortune, hangman appeals to many people. For beginning programmers who want a challenge or for more experienced coders looking for a bit of fun, writing hangman in Python is a rewarding endeavor.

Throughout this tutorial, you’ll build the hangman game in Python in a series of steps. The game will work as a command-line application. Throughout the process, you’ll also learn the basics of building computer games.

In this tutorial, you’ll:

  • Learn the common elements of a computer game
  • Track the state of a computer game
  • Get and validate the user’s input
  • Create a text-based user interface (TUI) for your game
  • Figure out when the game is over and who the winner is

To get the most from this tutorial, you should be comfortable working with Python sets and lists. You don’t need to have any previous knowledge about game writing.

All the code that you’ll write in this tutorial is available for download at the link below:

Demo: Command-Line Hangman Game in Python

In this tutorial, you’ll write a hangman game for your command line using Python. Once you’ve run all the steps to build the game, then you’ll end up with a text-based user interface (TUI) that will work something like the following:

Throughout this tutorial, you’ll run through several challenges designed to help you solve specific game-related problems. At the end, you’ll have a hangman game that works like the demo above.

Project Overview

The first step to building a good computer game is to come up with a good design. So, the design for your hangman game should begin with a good description of the game itself. You also need to have a general understanding of the common elements that make up a computer game. These two points are crucial for you to come up with a good design.

Description of the Hangman Game

While many people know the game well, it’s helpful to have a formal description of the game. You can use this description to resolve programming issues later during development. As with many things in life, the exact description of a hangman game could vary from person to person. Here’s a possible description of the game:

  • Game setup: The game of hangman is for two or more players, comprising a selecting player and one or more guessing players.
  • Word selection: The selecting player selects a word that the guessing players will try to guess.
    • The selected word is traditionally represented as a series of underscores for each letter in the word.
    • The selecting player also draws a scaffold to hold the hangman illustration.
  • Guessing: The guessing players attempt to guess the word by selecting letters one at a time.
  • Feedback: The selecting player indicates whether each guessed letter appears in the word.
    • If the letter appears, then the selecting player replaces each underscore with the letter as it appears in the word.
    • If the letter doesn’t appear, then the selecting player writes the letter in a list of guessed letters. Then, they draw the next piece of the hanged man. To draw the hanged man, they begin with the head, then the torso, the arms, and the legs for a total of six parts.
  • Winning conditions: The selecting player wins if the hanged man drawing is complete after six incorrect guesses, in which case the game is over. The guessing players win if they guess the word.
    • If the guess is right, the game is over, and the guessing players win.
    • If the guess is wrong, the game continues.

A game in progress is shown below. In this game, the word to be guessed is hangman:

A game of hangman in progress

In this tutorial, to write the hangman game in Python, you’ll make a few additional design decisions:

  • The game will be between the computer and one human player.
  • The computer will act as the selecting player and will select the word to guess, process human input, and handle all output.
  • The human player is the guessing player, hereafter simply referred to as the player. When the player knows the word, they continue to guess correct letters until the word is complete.

With this basic understanding of the game and some design decisions for the computer version, you can begin creating the game. First, however, you need to know the common elements of computer games and understand how they interact to produce the desired result.

Common Elements of a Computer Game

Every game, whether it’s a computer game or not, has a set of elements that make it a game. Without these elements, there’s no game:

  • Initial setup: You get the game ready to play. This might mean setting the pieces on a chess board, dealing out cards, or rolling dice to see who goes first.
  • Gameplay: When people think of the game, this is what they normally think of. The flow of gameplay is controlled by a game loop, which keeps the game moving and doesn’t end until the game is over. The game loop ensures the following happens:
    • The user input is gathered and processed.
    • The game state is updated based on reactions to the user input. This may include checking for end-of-game conditions.
    • Any required output changes are made to reflect the new game state.
    • The game loop repeats.
  • Game ending: How the game ends depends on the game itself. Whether capturing the enemy king in checkmate, achieving a certain score in a card game, or having your piece cross the line in a board game, certain conditions determine the end of the game and the winner.

All games have a game loop. For example, in a chess game, you first set the pieces on the board and declare the current player. Then the game loop begins:

  • The current player moves a piece, updating the game state.
  • The checkmate condition is checked to determine whether the game is over.
  • The current player is updated, and the loop starts again.

Real-world games blur the lines between the individual elements of a game. For example, moves in chess update both the game state and the game output. Despite this, the key elements of the game are always present. With them in mind, you can begin writing your first version of hangman in Python.

Prerequisites

The project that you’ll build in this tutorial will require familiarity with general Python programming. You should have basic knowledge of the following topics:

However, if you don’t have all this knowledge yet, then that’s okay! You might learn more by going ahead and giving the project a shot. You can always stop and review the resources linked here if you get stuck.

With this short overview of your hangman project and the prerequisites, you’re all set up to start Pythoning and having fun while coding.

Step 1: Set Up the Hangman Project

Your hangman game will select a word, handle user input, and display all output using a text-based user interface. You need code to handle each of these tasks. However, you’ll do everything using built-in and standard-library tools. You don’t need to install anything else.

For writing the game, you’ll use a single file called hangman.py. This file will contain all the required code to handle the game’s operations. So, go ahead and create the file in your favorite code editor or IDE.

Next, go ahead and create a words.txt file. This file will contain a list of words from which the game will select the target word. Click the collapsible section below to get the content of this file:

Text
prettiest
close
dog
massive
hollow
cultured
seashore
explode
dizzy
minister
competent
thoughtful
harbor
tidy
dance
children
zesty
clean
ball
nostalgic
plan
week
strap
board
slope
bat
steep
mourn
cat
girl
ancient
street
mice
dare
wasteful
tub
limping
whimsical
eager
eggs
detail
experience
beds
train
place
cows
admit
rare
respect
loose
group
enjoy
internal
macabre
imported
superb
crooked
confused
hug
feigned
unkempt
coal
meddle
hapless
country
zealous
sick
pray
lake
tiny
key
empty
labored
delirious
ants
need
omniscient
onerous
damp
subtract
sack
connection
toad
gather
record
new
trashy
flow
river
sparkling
kneel
daughter
glue
allow
raspy
eminent
weak
wrong
pretend
receipt
celery
plain
fire
heal
damaging
honorable
foot
ignorant
substance
box
crime
giant
learned
itchy
smoke
likable
station
jaded
innocent
dead
straw
tray
chin
pack
geese
guess
wealthy
slippery
book
curly
swing
cure
flowers
rate
ignore
insidious
necessary
snakes
entertaining
rich
comb
lamentable
fuel
camera
multiply
army
exist
sulky
brief
worried
third
magical
wary
laborer
end
somber
authority
rainstorm
anxious
purpose
agreeable
spiky
toe
mixed
waiting
hungry
lopsided
flagrant
windy
ground
slap
please
white
hurry
governor
abandoned
reject
spiritual
abrasive
hunt
weather
endurable
hobbies
occur
bake
print
tire
juicy
blush
listen
trousers
daffy
scarecrow
rude
stem
bustling
nail
sneeze
bellicose
love

You can also download the complete source of your hangman game, including the words.txt file, by clicking the link below:

With this initial setup, you’re ready to start writing the code. Your first step will be to code a function for selecting the word to guess in your hangman game.

Step 2: Select a Word to Guess

The first step in playing hangman is to select the target word. When a human player selects a word for hangman, they pick one word from their own vocabulary. For the computer to select a word, it needs to have a vocabulary from which to select. Of course, its vocabulary doesn’t need to be as large as a human’s.

So, how would you select one word from your word list? Here’s a possible solution:

Python
# hangman.py

from random import choice

def select_word():
    with open("words.txt", mode="r") as words:
        word_list = words.readlines()
    return choice(word_list).strip()

In this code snippet, you create the select_word() function to select the word to guess from the words.txt file. You use a with statement to open the file and the .readlines() method to create a list of words.

Then, you use the random.choice() function to choose a random word from the list. Notice that all the words in the file are written in lowercase letters. This detail will be important later when you need to compare the letters in the target words with the player’s input.

Here’s how your select_word() works:

Python
>>> from hangman import select_word

>>> select_word()
'toad'
>>> select_word()
'daffy'
>>> select_word()
'insidious'

Every time you call the function, you get a random word from your list of words. That’s the first step in playing the hangman game.

Creating a separate function to handle the vocabulary and word selection makes it easier to modify or expand the vocabulary later. It also makes your code more readable for others, or for yourself in a few months.

Step 3: Get and Validate the Player’s Input

Now, you need a way to get the player’s guesses at the command line. After all, a game isn’t much of a game if there isn’t some way for the player to influence the outcome.

In your hangman game, you have to get the player’s input and make sure that it’s valid. Remember when you created your list of words? All the words were in lowercase, so you should turn the player’s guesses into lowercase letters as well.

Additionally, the player shouldn’t be able to guess the same letter twice. It’d also be good to avoid numbers, special characters, and complete words as well.

So you need a two-part solution. The first part will gather the player’s input, and the second part will validate it. You can get the player’s input for the command line using the built-in input() function:

Python
# hangman.py
# ...

def get_player_input(guessed_letters):
    while True:
        player_input = input("Guess a letter: ").lower()
        if _validate_input(player_input, guessed_letters):
            return player_input

This is an example of an input validation loop, which you can use to restrict the user’s input. The loop iterates until the player provides valid data. In this case, that means a single letter that the player hasn’t already guessed.

You first set player_input to the player’s input in lowercase. Then, you pass the guess to _validate_input() along with the guessed_letters set. Here’s the code for the _validate_input() helper function:

Python
# hangman.py

import string
# ...

def _validate_input(player_input, guessed_letters):
    return (
        len(player_input) == 1
        and player_input in string.ascii_lowercase
        and player_input not in guessed_letters
    )

The _validate_input() function performs three independent checks. It makes sure that:

  1. Exactly one character is entered.
  2. The input is a lowercase letter between a and z, inclusive.
  3. The input isn’t a letter that the player has already guessed.

All of these conditions must be true for the function to return True. If any of those checks is false, then the function returns False, and the input loop restarts. Here’s how this new code works:

Python
>>> from hangman import get_player_input

>>> get_player_input({"a", "b"})
Guess a letter: 3
Guess a letter: e
'e'

>>> get_player_input({"a", "b"})
Guess a letter: a
Guess a letter: f
'f'

When you call get_player_input() with a set containing previously guessed letters, you get a prompt that asks you to enter a letter. If you enter a non-letter character or a previous guess, then the function dismisses it because it’s not valid. Then, you get the prompt again. When you enter a valid letter, you get the letter back.

Now, you have a way to get and validate the player’s input. It’s time to decide when to end the game!

Step 4: Display the Guessed Letters and Word

Once you’ve selected the target word in a real-life game of hangman, you need to write an underscore, or blank, for each letter in the word. These blanks tell the players how many letters are in the target word. As players make guesses, you fill in the blanks with the correct letters. You should also keep track of incorrect letters, which you write to the side.

So, you now have two tasks:

  1. Display the letters that the player has guessed.
  2. Display the correct letters in their respective places in the word.

To track the letters that the player has guessed, you’ll use a Python set. Using a set allows you to efficiently check if the player has already guessed a given letter by using membership tests with the in operator.

Showing the guessed letters takes advantage of the .join() method of strings:

Python
# hangman.py
# ...

def join_guessed_letters(guessed_letters):
    return " ".join(sorted(guessed_letters))

The .join() method builds a single string consisting of the members of the guessed_letters set, separated by a whitespace character. The built-in sorted() function allows you to sort the guessed letters alphabetically.

You use another function to build the word to show to the player:

Python
# hangman.py
# ...

def build_guessed_word(target_word, guessed_letters):
    current_letters = []
    for letter in target_word:
        if letter in guessed_letters:
            current_letters.append(letter)
        else:
            current_letters.append("_")
    return " ".join(current_letters)

This function uses a