Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
wb_sunny

Hangman Game in Python – A Step-By-Step Walkthrough

Hangman Game Featured Image

In this tutorial, we will learn the steps of creating our own hangman game in Python Language.

About Hangman

Hangman is a guessing game in which the objective of the player is to find out the hidden word. Every incorrect guess leads to the decrement of the chances left for the player.

The chances left are represented in the form of a hanging man. And the job of every hero is to save lives.


Demo Gameplay of Hangman Game in Python

Hangman Game in Python – Demo Gameplay

Designing Hangman

Before we move on to the section of creating the game logic, we first need to figure out how the game will look for any player. There are two particular design components in this game:

  • The Hangman – We need to provide a visual aid to the player in the context of the hanging man.
  • Word Display – At the start of the game, the word must be displayed as blanks, instead of letters.

Hangman design

As we know, after every incorrect move, a new part of the hanging man’s body is displayed. To implement this, we store the body parts in a list.

# Stores the hangman's body values
hangman_values = ['O','/','|','\\','|','/','\\']

# Stores the hangman's body values to be shown to the player
show_hangman_values = [' ', ' ', ' ', ' ', ' ', ' ', ' ']

The function that handles these hangman values is presented below:

# Functuion to print the hangman
def print_hangman(values):
	print()
	print("\t +--------+")
	print("\t |       | |")
	print("\t {}       | |".format(values[0]))
	print("\t{}{}{}      | |".format(values[1], values[2], values[3]))
	print("\t {}       | |".format(values[4]))
	print("\t{} {}      | |".format(values[5],values[6]))
	print("\t         | |")
	print("  _______________|_|___")
	print("  `````````````````````")
	print()

The video below displays all the hangman states possible in the game. Each incorrect mistake adds a body part until the body is complete and the player loses.

All hangman states

The final state displayed in the video represents the hangman escaping the gallows after the player guesses the complete word.

# Function to print the hangman after winning
def print_hangman_win():
	print()
	print("\t +--------+")
	print("\t         | |")

	print("\t         | |")
	print("\t O       | |")
	print("\t/|\\      | |")
	print("\t |       | |")
	print("  ______/_\\______|_|___")
	print("  `````````````````````")
	print()

The above function, 'print_hangman_win()' takes care of printing the escaped hangman when the player wins.

Word display

At the start of the game, only the blanks must be visible. After each player input, we must manipulate what needs to be displayed.

# Stores the letters to be displayed
word_display = []

Initially, the list 'word_display' contains underscores for every alphabet in the hidden word. The following function is used to display this list.

# Function to print the word to be guessed
def print_word(values):
	print()
	print("\t", end="")
	for x in values:
		print(x, end="")
	print()

Data-set for words

In this part of creating the game, we can let our imagination run wild. There can be multiple ways to access the list words like importing from a .csv file, extracting from a database, etc.

To keep this tutorial simple, we will be hard-coding some categories and words.

# Types of categories
topics = {1: "DC characters", 2:"Marvel characters", 3:"Anime characters"}

# Words in each category
dataset = {"DC characters":["SUPERMAN", "JOKER", "HARLEY QUINN", "GREEN LANTERN", "FLASH", "WONDER WOMAN", "AQUAMAN", "MARTIAN MANHUNTER", "BATMAN"],\
			 "Marvel characters":["CAPTAIN AMERICA", "IRON MAN", "THANOS", "HAWKEYE", "BLACK PANTHER", "BLACK WIDOW"],
			 "Anime characters":["MONKEY D. LUFFY", "RORONOA ZORO", "LIGHT YAGAMI", "MIDORIYA IZUKU"]
			 }

Let us understand the data-structures used here:

  • 'topics'– This Python dictionary provides, each category with a numeric value. This will further be used to implement a category-based menu.
  • 'dataset' – This Python dictionary contains a list of words in each category. After the player chooses a category, we are supposed to pick words from here itself.

Game Loop

Every game which depends upon a series of moves from the player requires a game loop. This loop is responsible for managing the player input, displaying game design, and other essential parts of game-logic.

# The GAME LOOP
while True:

Inside this game loop, we will take care of the following things:


Game Menu

The game menu is responsible for providing the notion of game-control to the player. The player decides the category on the basis of his/her interests.

# Printing the game menu
print()
print("-----------------------------------------")
print("\t\tGAME MENU")
print("-----------------------------------------")
for key in topics:
	print("Press", key, "to select", topics[key])
print("Press", len(topics)+1, "to quit")	
print()

It is advisable to always provide an option of quitting the game, whenever a game menu is created.


Handling the player’s category choice

A game developer no matter what level of skill, must always handle player input with great attention. The game must not crash on some erroneous player input.

# Handling the player category choice
try:
	choice = int(input("Enter your choice = "))
except ValueError:
	clear()
	print("Wrong choice!!! Try again")
	continue

# Sanity checks for input
if choice > len(topics)+1:
	clear()
	print("No such topic!!! Try again.")
	continue	

# The EXIT choice	
elif choice == len(topics)+1:
	print()
	print("Thank you for playing!")
	break

After doing some sanity checks, we are ready to pick the word for the game-play.

Note: The 'clear()' function is responsible for clearing the terminal. It makes use of inbuilt 'os' library of Python.


Pick the game-play word

We use the inbuilt Python library, 'random' for picking a random word from the specific category list.

# The topic chosen
chosen_topic = topics[choice]

# The word randomly selected
ran = random.choice(dataset[chosen_topic])

# The overall game function
hangman_game(ran)

After picking the word, comes the game-logic section.


Game-Logic for Hangman

The function 'hangman()' contains the entire game functioning. It includes storing incorrect guesses, reducing the number of chances left, and printing the specific state of hangman.

# Function for each hangman game
def hangman_game(word):

	clear()

	# Stores the letters to be displayed
	word_display = []

	# Stores the correct letters in the word
	correct_letters = []

	# Stores the incorrect guesses made by the player
	incorrect = []

	# Number of chances (incorrect guesses)
	chances = 0

	# Stores the hangman's body values
	hangman_values = ['O','/','|','\\','|','/','\\']

	# Stores the hangman's body values to be shown to the player
	show_hangman_values = [' ', ' ', ' ', ' ', ' ', ' ', ' ']

The above code snippet contains all the elementary data structures and variables required for smooth functioning of our hangman game.


Initialize necessary components

One of the most important aspects of creating a game is the initial state of the game components.

# Loop for creating the display word
for char in word:
	if char.isalpha():
		word_display.append('_')
		correct_letters.append(char.upper())
	else:
		word_display.append(char)

We are required to initialize the structure of word display as it will vary for every other word for the game. For our convenience, we initialize the container for storing the correct letters, in the same loop.

Note: Our version of the hangman game only supports the guessing of the alphabets. If the reader wants to add the functionality of guessing other elements like numbers or special characters, the changes have to be made here.


Inner game loop

This inner game loop is responsible for controlling the flow of single gameplay of the hangman game. It includes showing proper display, handling character input, updating the necessary data structures, and other key aspects of the game.

# Inner Game Loop			
while True:

	# Printing necessary values
	print_hangman(show_hangman_values)
	print_word(word_display)			
	print()
	print("Incorrect characters : ", incorrect)
	print()

Player’s move input

This part of our game deals with the player’s interaction with our game. The input must be checking for few scenarios before implementing it in the game logic:

  • Valid length – Since we are accepting a single character, we need to check in case the player mischievously enters multiple characters.
  • An alphabet? – As told before, our version of the hangman game only supports guessing of alphabets.
  • Already tried – Being a considerate programmer, we have to notify if the player enters an incorrect and already tried alphabet.
# Accepting player input
inp = input("Enter a character = ")
if len(inp) != 1:
	clear()
	print("Wrong choice!! Try Again")
	continue

# Checking whether it is a alphabet
if not inp[0].isalpha():
	clear()
	print("Wrong choice!! Try Again")
	continue

# Checking if it already tried before	
if inp.upper() in incorrect:
	clear()
	print("Already tried!!")
	continue 	

Manage the player’s move

It is quite obvious that we will come across only two situations while managing the player’s move.

  • Incorrect Alphabet – For an incorrect move, we update the list of incorrect letters and the hangman display (adding body-parts).
# Incorrect character input	
if inp.upper() not in correct_letters:
	
	# Adding in the incorrect list
	incorrect.append(inp.upper())
	
	# Updating the hangman display
	show_hangman_values[chances] = hangman_values[chances]
	chances = chances + 1
	
	# Checking if the player lost
	if chances == len(hangman_values):
		print()
		clear()
		print("\tGAME OVER!!!")
		print_hangman(hangman_values)
		print("The word is :", word.upper())
		break
  • Correct Alphabet – In case, a capable player enters a correct alphabet, we update our word display.
# Correct character input
else:

	# Updating the word display
	for i in range(len(word)):
		if word[i].upper() == inp.upper():
			word_display[i] = inp.upper()

	# Checking if the player won		
	if check_win(word_display):
		clear()
		print("\tCongratulations! ")
		print_hangman_win()
		print("The word is :", word.upper())
		break

It is in the best interest of the game developer to check for a win each time a correct alphabet is entered. This is not a hard and fast rule, the reader can implement their own version of checking for the end game.


The Complete Code

Below is the complete and running code of the hangman game discussed above:

import random
import os

# Funtion to clear te terminal
def clear():
	os.system("clear")

# Functuion to print the hangman
def print_hangman(values):
	print()
	print("\t +--------+")
	print("\t |       | |")
	print("\t {}       | |".format(values[0]))
	print("\t{}{}{}      | |".format(values[1], values[2], values[3]))
	print("\t {}       | |".format(values[4]))
	print("\t{} {}      | |".format(values[5],values[6]))
	print("\t         | |")
	print("  _______________|_|___")
	print("  `````````````````````")
	print()

# Function to print the hangman after winning
def print_hangman_win():
	print()
	print("\t +--------+")
	print("\t         | |")

	print("\t         | |")
	print("\t O       | |")
	print("\t/|\\      | |")
	print("\t |       | |")
	print("  ______/_\\______|_|___")
	print("  `````````````````````")
	print()

# Function to print the word to be guessed
def print_word(values):
	print()
	print("\t", end="")
	for x in values:
		print(x, end="")
	print()	

# Function to check for win
def check_win(values):
	for char in values:
		if char == '_':
			return False
	return True		

# Function for each hangman game
def hangman_game(word):

	clear()

	# Stores the letters to be displayed
	word_display = []

	# Stores the correct letters in the word
	correct_letters = []

	# Stores the incorrect guesses made by the player
	incorrect = []

	# Number of chances (incorrect guesses)
	chances = 0

	# Stores the hangman's body values
	hangman_values = ['O','/','|','\\','|','/','\\']

	# Stores the hangman's body values to be shown to the player
	show_hangman_values = [' ', ' ', ' ', ' ', ' ', ' ', ' ']

	# Loop for creating the display word
	for char in word:
		if char.isalpha():
			word_display.append('_')
			correct_letters.append(char.upper())
		else:
			word_display.append(char)

	# Game Loop			
	while True:

		# Printing necessary values
		print_hangman(show_hangman_values)
		print_word(word_display)			
		print()
		print("Incorrect characters : ", incorrect)
		print()


		# Accepting player input
		inp = input("Enter a character = ")
		if len(inp) != 1:
			clear()
			print("Wrong choice!! Try Again")
			continue

		# Checking whether it is a alphabet
		if not inp[0].isalpha():
			clear()
			print("Wrong choice!! Try Again")
			continue

		# Checking if it already tried before	
		if inp.upper() in incorrect:
			clear()
			print("Already tried!!")
			continue 	

		# Incorrect character input	
		if inp.upper() not in correct_letters:
			
			# Adding in the incorrect list
			incorrect.append(inp.upper())
			
			# Updating the hangman display
			show_hangman_values[chances] = hangman_values[chances]
			chances = chances + 1
			
			# Checking if the player lost
			if chances == len(hangman_values):
				print()
				clear()
				print("\tGAME OVER!!!")
				print_hangman(hangman_values)
				print("The word is :", word.upper())
				break

		# Correct character input
		else:

			# Updating the word display
			for i in range(len(word)):
				if word[i].upper() == inp.upper():
					word_display[i] = inp.upper()

			# Checking if the player won		
			if check_win(word_display):
				clear()
				print("\tCongratulations! ")
				print_hangman_win()
				print("The word is :", word.upper())
				break
		clear()	
	

if __name__ == "__main__":

	clear()

	# Types of categories
	topics = {1: "DC characters", 2:"Marvel characters", 3:"Anime characters"}

	# Words in each category
	dataset = {"DC characters":["SUPERMAN", "JOKER", "HARLEY QUINN", "GREEN LANTERN", "FLASH", "WONDER WOMAN", "AQUAMAN", "MARTIAN MANHUNTER", "BATMAN"],\
				 "Marvel characters":["CAPTAIN AMERICA", "IRON MAN", "THANOS", "HAWKEYE", "BLACK PANTHER", "BLACK WIDOW"],
				 "Anime characters":["MONKEY D. LUFFY", "RORONOA ZORO", "LIGHT YAGAMI", "MIDORIYA IZUKU"]
				 }
	
	# The GAME LOOP
	while True:

		# Printing the game menu
		print()
		print("-----------------------------------------")
		print("\t\tGAME MENU")
		print("-----------------------------------------")
		for key in topics:
			print("Press", key, "to select", topics[key])
		print("Press", len(topics)+1, "to quit")	
		print()
		
		# Handling the player category choice
		try:
			choice = int(input("Enter your choice = "))
		except ValueError:
			clear()
			print("Wrong choice!!! Try again")
			continue

		# Sanity checks for input
		if choice > len(topics)+1:
			clear()
			print("No such topic!!! Try again.")
			continue	

		# The EXIT choice	
		elif choice == len(topics)+1:
			print()
			print("Thank you for playing!")
			break

		# The topic chosen
		chosen_topic = topics[choice]

		# The word randomly selected
		ran = random.choice(dataset[chosen_topic])

		# The overall game function
		hangman_game(ran)

Conclusion

At first, creating the hangman game may seem a daunting task but we hope that this tutorial might clear the reader’s misconceptions. For any queries or criticisms, feel free to comment below.

If you wish to learn more about developing terminal-based games in Python, you can check out other games like Minesweeper or Tic-tac-toe.

Leave a Reply

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