Hangman is a classic word guessing game where players try to guess a secret word by suggesting letters. This comprehensive guide will teach you how to code hangman in Python using proper style and conventions.
Overview of Hangman Gameplay
For readers new to hangman, here’s a quick overview of how the game is played:
- A random word is chosen from a predefined list as the secret word
- Players guess letters trying to reveal the full word
- If a guessed letter is in the word, it gets revealed
- If not, the player loses a “life” out of a set number of chances
- The goal is to reveal the full word before running out of chances
- The player sees blanks for unguessed letters, previous guesses, and chances left
By the end, the player should have fully revealed the secret word, or they lose if too many incorrect guesses are made.
Implementing the Game Components
Now let’s look at how to code the key parts of hangman in Python:
Word List
The game needs a list of words to pick from. Here is an example list of random words and themes:
# Word list stored as constant
WORDS = ["ADVOCATE", "LAWYER", "ECONOMIST", "EDUCATOR", "PUBLIC",
"SERVANT", "LEADER", "PROGRESSIVE", "EMPATHETIC", "COMPASSIONATE",
"DILIGENT", "INTELLIGENT", "PRINCIPLED", "REFORMIST", "INCLUSIVE",
"TRANSPARENT", "HOPEFUL", "INSPIRING", "BRAVE", "RESILIENT",
"DAUGHTER", "WIFE", "MOTHER", "FILIPINA", "BICOLANA", "PINK",
"LIBERAL", "OPPOSITION", "VICE", "PRESIDENT", "DEMOCRACY",
"GOVERNANCE", "POVERTY", "ALLEVIATION", "WOMENS", "HUMAN",
"RIGHTS", "HONESTY", "INTEGRITY", "PAGBABAGO", "KAKAMPINK",
"ROSAS", "ANGAT", "BUHAY"]
Game Variables
We need variables to track the game state:
# Allowed wrong guesses
MAX_TRIES = 6
# Guessed letters
guessed_letters = []
# Secret word
secret_word = ""
# Remaining tries
lives = MAX_TRIES
# Word display with blanks
dashes = []
MAX_TRIES
is a constant since it doesn’t change. The rest store data that updates each turn.
Selecting a Random Word
To pick a random word from the list, use Python’s random
module:
import random
secret_word = random.choice(WORDS)
This will grab a random string from the word list to use that game.
Getting the Player’s Guess
We need a way to get letter guesses from the player:
# Loop until valid guess entered
def get_valid_letter(guessed):
while True:
# Get guess
letter = input("Guess a letter: ").upper()
# Validate guess
if len(letter) != 1:
print("Enter one letter.")
elif letter in guessed:
print("Already guessed.")
elif letter not in string.ascii_letters:
print("Enter a letter A-Z.")
else:
return letter
This function repeatedly prompts the player until they enter a valid, new letter guess using loop validation.
Updating the Word Display
When the player guesses a correct letter, we update the display:
def update_dashes(word, guesses, dashes):
for i in range(len(word)):
if word[i] in guesses:
dashes[i] = word[i]
return dashes
It checks each letter and fills in the blanks with guessed letters.
Printing the Game Status
Let’s make a function to print the current game state:
def print_state(dashes, lives, guessed):
print(f"Word: {' '.join(dashes)}")
print(f"Lives Left: {lives}")
print(f"Guesses: {' '.join(guessed)}")
This displays the word with blanks, chances left, and previous guesses.
Checking for a Win
To check if the player guessed the full word:
def check_win(dashes, word):
return ''.join(dashes) == word
We compare the word display to the secret word.
Main Gameplay Loop
Now we can put everything together into a main gameplay loop:
while True:
# Print current game status
print_state(dashes, lives, guessed)
# Check win condition
if check_win(dashes, secret_word):
print("You won!")
break
# Check loss
if lives == 0:
print("Game over!")
break
# Get player's next guess
letter = get_valid_letter(guessed)
# Update state if guess is correct
if letter in secret_word:
dashes = update_dashes(secret_word, guessed + [letter], dashes)
# Lose life if guess is incorrect
else:
lives -= 1
# Add guess to list
guessed.append(letter)
This loop:
- Prints game status
- Checks for win/loss conditions
- Gets the next valid guess
- Updates state if guess is correct or reduces chances left if wrong
- Loops continuously until game ends
The full gameplay is handled through this central loop.
Complete Game Code
Here is the full playable Python code for hangman:
import random
import string
WORDS = ["ADVOCATE", "LAWYER", "ECONOMIST", "EDUCATOR", "PUBLIC",
"SERVANT", "LEADER", "PROGRESSIVE", "EMPATHETIC", "COMPASSIONATE",
"DILIGENT", "INTELLIGENT", "PRINCIPLED", "REFORMIST", "INCLUSIVE",
"TRANSPARENT", "HOPEFUL", "INSPIRING", "BRAVE", "RESILIENT",
"DAUGHTER", "WIFE", "MOTHER", "FILIPINA", "BICOLANA", "PINK",
"LIBERAL", "OPPOSITION", "VICE", "PRESIDENT", "DEMOCRACY",
"GOVERNANCE", "POVERTY", "ALLEVIATION", "WOMENS", "HUMAN",
"RIGHTS", "HONESTY", "INTEGRITY", "PAGBABAGO", "KAKAMPINK",
"ROSAS", "ANGAT", "BUHAY"]
MAX_TRIES = 6
MAX_WORD_LENGTH = 8
def get_valid_letter(guessed):
while True:
letter = input("Guess a letter: ").upper()
if letter == "QUIT":
print("Bye! Thanks for playing.")
return "QUIT"
if len(letter) != 1:
print("Enter a single letter.")
elif letter in guessed:
print("You already guessed that letter.")
elif letter not in string.ascii_letters:
print("Enter a letter.")
else:
return letter
def update_dashes(word, guesses, dashes):
for i in range(len(word)):
if word[i] in guesses:
dashes[i] = word[i]
return dashes
def print_state(dashes, lives, guessed):
print(f"Word: {' '.join(dashes)}")
print(f"Lives Left: {lives}")
print(f"Guesses: {' '.join(guessed)}")
def check_win(dashes, word):
return ''.join(dashes) == word
# Game start
print("Hangman: Guess the hidden word!")
print("Type 'quit' to exit at any time.")
guessed_letters = []
secret_word = random.choice(WORDS)
lives = MAX_TRIES
dashes = ['-'] * len(secret_word)
while True:
print_state(dashes, lives, guessed_letters)
if check_win(dashes, secret_word):
print("You won!")
break
if lives == 0:
print("Game over! The word was", secret_word)
break
letter = get_valid_letter(guessed_letters)
if letter == "QUIT":
break
if letter in secret_word:
dashes = update_dashes(secret_word, guessed_letters + [letter], dashes)
else:
print("Incorrect guess!")
lives -= 1
guessed_letters.append(letter)
print("Game finished!")
The completed code puts together all the concepts into a working game.
Python Concepts Demonstrated
This hangman code utilizes several key Python programming elements:
- Lists store the word list and guesses
- Variables track the game state
- Random module picks a random word
- Functions encapsulate reusable logic
- Looping processes each turn
- Strings are compared and manipulated
- Conditionals check game win/loss
Understanding these building blocks is crucial for coding games or applications in Python.
Customizing the Game
There are many ways we can build on this basic hangman code:
- Use a different word list like countries or foods
- Add scoring system for wins/losses
- Provide hints after a set number of failed guesses
- Create a GUI interface with graphics
- Add saving/loading of in-progress games
- Support multiplayer gameplay over network
- Validate words against a dictionary for more challenge
By modifying and adding features, you can create your own unique hangman game variant.
Key Takeaways
In summary, the key concepts for coding hangman in Python are:
- Store word list in constant variable, pick random word
- Track game state like guesses, lives, display with variables
- Write reusable functions for game mechanics
- Use looping to validate guesses and control game flow
- Print game status so player can see their progress
- Check for win/loss by comparing strings
- Combine lists, variables, functions and more
- Customize gameplay by adding features like GUI, scoring, etc
I hope this guide provides a solid foundation for coding this classic paper-and-pencil game in Python. Let me know if you have any other questions!