Hangman is a classic word-guessing game that’s fun and a great project for beginner programmers.
In this article, we’ll learn how to build a simple version of the Hangman game in Python.
By the end, you'll understand how to use Python’s basic control structures, functions, and lists to create this game.
What is Hangman?
The goal of Hangman is to guess a secret word by suggesting letters one at a time.
The player can make only a limited number of incorrect guesses before the game ends.
For each incorrect guess, a part of the "hangman" figure is drawn, and if the full figure is drawn before the word is guessed, the player loses.
Let’s break this down and build the game step by step.
Get the eBook
Inside, you'll discover a plethora of Python secrets that will guide you through a journey of learning how to write cleaner, faster, and more Pythonic code. Whether it's mastering data structures, understanding the nuances of object-oriented programming, or uncovering Python's hidden features, this ebook has something for everyone.
Step 1: Plan the Game
Let's plan the game and its key features:
- The game randomly selects a word.
- The player guesses one letter at a time.
- The player has a limited number of incorrect guesses.
- The game displays the word with the correctly guessed letters and blanks for the remaining letters.
The game will have the following components:
- Word selection
- Player input (guess)
- Update the display of the word
- Track the number of incorrect guesses
Step 2: Import Required Libraries
We'll use the random
module to randomly select a word from a list.
import random
Step 3: Define the Word List
Next, define a list of words that the game will randomly choose from.
You can add more words to make the game more interesting.
word_list = ['python', 'java', 'hangman', 'programming', 'computer']
Step 4: Define Functions for the Game
Function 1: Randomly Select a Word
We need a function to randomly pick a word from our word list.
def get_random_word(word_list):
return random.choice(word_list)
Function 2: Display the Current State of the Word
As the player guesses letters, we need to show the correctly guessed letters and placeholders (_
) for the unguessed letters.
def display_word(word, guessed_letters):
display = ''
for letter in word:
if letter in guessed_letters:
display += letter + ' '
else:
display += '_ '
return display.strip()
Function 3: Check if the Player Won
This function checks whether all letters of the word have been guessed.
def is_word_guessed(word, guessed_letters):
for letter in word:
if letter not in guessed_letters:
return False
return True
Function 4: Display Hangman
To display a hangman figure in a text-based game, you can use ASCII art to represent the different stages of the hangman.
This article is for paid members only
To continue reading this article, upgrade your account to get full access.
Subscribe NowAlready have an account? Sign In