Building a Hangman game Using Python
Being a game enthusiast, part of my career goal is to develop and code my own game be it actions, arcades, adventures or a simple logic game. As a lover of games, I spent a lot of time brainstorming on how to code a game.
Have you ever tried to try to build your own game but it seems almost impossible? Today in this article, We will be building together a Hangman game using Python which will be pretty fun and simple to understand.
Introduction
The way the game works is that you will have to guess a word and for every wrong word you guessed Hangman will lose a life. This simply means that the longer you tried to guess the right word the more you put the little man in danger.
So you need to think and guess the right word to save his life as soon as possible. Isn't that fascinating? You can as well check the game demo ahead at the Hangman game
Pre-requisites
A. Some Fundamental Knowledge of Python:
For and While Loops
IF/ELSE Statement
Lists
Strings
Range Functions
Modules
B. We are going to be using Replit to test our code.
I hope you are much more excited to start building this game with me. If so, Let's get started.
Picking a Random word and checking the User's answer
We are going to create a variable called word_list
which will contain some items in a List
like ["Monkey", "Cheetah", "Cat"]
.
#Creating a variable called word_list
word_list = ["Monkey", "Cheetah", "cat"]
We will create another variable called choosen_word
which will allow us to randomly pick a word from the word_list
using the function random.choice()
. We should know that before we can be able to pick a word randomly we need to introduce import random
import random
#Creating a variable called word_list
word_list = ["Monkey", "Cheetah", "cat"]
#Picking a random word from wrod_list
chosen_word = random.choice(word_list)
The next step is for us to create a variable called guess
which will be used to ask the user to guess a certain letter. In case the user guessed a letter in Upper case, we will be using lower()
to automatically convert all inputs to the lowercase letter.
import random
#Creating a variable called word_list
word_list = ["Monkey", "Cheetah", "cat"]
#Picking a random word from wrod_list
chosen_word = random.choice(word_list)
# Asking the user to guess a number
guess = input("Guess a letter: ").lower()
Now, you can test the code we wrote above by copying it into Replit to see the amazing work we have done so far.
Replacing Blanks with Guesses
In addition to our above procedure, We will print out the variable chosen_word
using fstring
to call out the exact word.
import random
#Creating a variable called word_list
word_list = ["Monkey", "Cheetah", "cat"]
#Picking a random word from wrod_list
chosen_word = random.choice(word_list)
print(f'Pssst, the solution is {chosen_word}.')
Then, we will create an empty list called display
, For each letter in the chosen_word
we will add a "_"
to display
.
print(f'Pssst, the solution is {chosen_word}.')
# Setting an empty list
display = []
This implies that if the chosen_word
is "Rabbit"
, display
should be equal to ["_", "_", "_", "_", "_", "_"]
with 6 "_"
represents each letter the user is going to guess.
To Know the length of any chosen word, we will use len(chosen_word)
which will be assigned to a variable called word_length
.
A for loop
will be used to add "_"
to display
by the total length of the chosen_word
using the increment function. Now the user will be asked to guess a number.
We will be giving high priority to our indentations as they matter very much when coding in Python
print(f'Pssst, the solution is {chosen_word}.')
#Knowing the length of the randomly chosen_word
word_length = len(chosen_word)
# Setting an empty list
display = []
# Adding "_" to display
for _ in range(word_length):
display += "_"
guess = input("Guess a letter: ").lower()
For us to Replace "_"
with the correctly guessed letter, We will loop through each position in the chosen word
using a for loop
. If the letter at that position matches the letter the user guessed then it will be revealed in the display at that exact position.
For example, If the user guesses the letter "p"
and the chosen word
was "apple"
, then display
should be equal to ["_", "p", "p", "_", "_"].
To achieve this, we will be nesting an if Statement
under the for loop
to check if the letter guessed is correct and falls in the same position in the chosen_word
.
import random
#Creating a variable called word_list
word_list = ["Monkey", "Cheetah", "cat"]
#Picking a random word from word_list
chosen_word = random.choice(word_list)
#Knowing the length of the randomly chosen_word
word_length = len(chosen_word)
print(f'Pssst, the solution is {chosen_word}.')
# Setting an empty list
display = []
# Adding "_" to display
for _ in range(word_length):
display += "_"
guess = input("Guess a letter: ").lower()
#Replacing "_" with the correct guessed letter
for position in range(word_length):
letter = chosen_word[position]
if letter == guess:
display[position] = letter
Then, we will Print (display)
to check if the guessed letter is in the correct position and every other letter replace with "_"
.
#Replacing "_" with the coreect guessed letter
for position in range(word_length):
letter = chosen_word[position]
if letter == guess:
display[position] = letter
#Printing display
print(display)
Now let's test our code using replit
Guessing again and Checking if the User has won
To allow the User to guess another letter, We need to reconstruct our code a little bit. We are going to use a while loop
whereby the loop will only stop once the user has guessed all the letters in the chosen_word
.
We will then use if Statement
to check if there are no more "_"
in display
, which means all the letters have been guessed and the user has won the game.
import random
#Creating a variable called word_list
word_list = ["Monkey", "Cheetah", "cat"]
#Picking a random word from word_list
chosen_word = random.choice(word_list)
#Knowing the length of the randomly chosen_word
word_length = len(chosen_word)
#Printing out the chosen_word
print(f'Pssst, the solution is {chosen_word}.')
# Setting an empty list
display = []
# Adding "_" to display
for _ in range(word_length):
display += "_"
# Guessing again and Checking if the User has won
# Using While loop to stop the user if all letter has been guessed
while not end_of_game:
guess = input("Guess a letter: ").lower()
#Check guessed letter
for position in range(word_length):
letter = chosen_word[position]
if letter == guess:
display[position] = letter
print(display)
# checking if there are no more "_" in display
if "_" not in display:
end_of_game = True
print("You win.")
Now, we are going to run our code again using Replit.
ASCII art showing different stages of life remaining
Here, We are going to create a variable called stages
which will have a list containing ASCII art
depicts a pictorial view of lives remaining. Each String of art will be representing [0, 1, 2, 3, 4, 5, 6]
of Hangman lives remaining.
Inside the project folder which you will also have access to on my Replit account, We will be importing the logo from hangman_art.py and printing it at the start of the game.
import Random
#importing hangman logo
from hangman_art import logo
print(logo)
stages = ['''
+---+
| |
O |
/|\ |
/ \ |
|
=========
''', '''
+---+
| |
O |
/|\ |
/ |
|
=========
''', '''
+---+
| |
O |
/|\ |
|
|
=========
''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========
''', '''
+---+
| |
O |
|
|
|
=========
''', '''
+---+
| |
|
|
|
|
=========
''']
#Creating a variable called word_list
word_list = ["Monkey", "Cheetah", "cat"]
#Picking a random word from word_list
chosen_word = random.choice(word_list)
#Knowing the length of the randomly chosen_word
word_length = len(chosen_word)
Printing out the Hangman logo using Replit will be displayed as shown below
Keeping track of the user's Lives
Now, We are going re-adjust our code by creating another variable called end_of_game
which we are going to set to False
Then, We will create a variable called lives
and set it to equal 6
to keep track of the number of lives left.
end_of_game = False
#Set live to 6
lives = 6
display = []
for _ in range(word_length):
display += "_"
# Using While loop stop the user if all letter has been guessed
while not end_of_game:
guess = input("Guess a letter: ").lower()
#Check guessed letter
for position in range(word_length):
letter = chosen_word[position]
if letter == guess:
display[position] = letter
Now, we will use if statement
to check If the guess is not a letter in the chosen_word
, and then inform the user by printing out that your guess is not in the chosen_word, You lose a life.
Then reduce lives
by 1
, If lives go down to 0
then the game should stop and it should print "You lose."
Finally, we will print the ASCII art from stages
that correspond to the current number of 'lives' the user has remaining.
#checking if the guess is not in choosen word
if guess not in chosen_word:
print(f"You guessed {guess}, that's not in the word. You lose a life.")
lives -= 1
if lives == 0:
end_of_game = True
print("You lose.")
# checking if there are no more "_" in display
if "_" not in display:
end_of_game = True
print("You win.")
#print the ASCII art from 'stages'that corresponds to the current number of 'lives' the user has remaining
print(stages[lives])
Now let us test our code again using Replit
Source - You can have access to the source code on my Replit account.
Note - You will need to create an account on Replit and fork the source code. It's free.
Conclusion
As you have seen above, We have successfully built a Hangman game using Core Python. You can play the game alone or with a friend to catch some fun and showcase your coding skill.
Getting started with Python can seem quite easy because coding in Python does take a little line of code compared to other programming languages, but building a personal project like a game or de-bugging errors can go a long way in deepening your root while learning any tech Stack.
Well done! I believe you found this article worthwhile and interesting.
Subscribe to my newsletter
Read articles from Taofeek Raheem directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Taofeek Raheem
Taofeek Raheem
I am a well-oriented Frontend developer with a great zeal towards the transformation of innovative ideas into effective technological solutions. I am also a technical writer who loves to simplify complex concepts into digestible bit for developers and non-expert