Creating a Simple Hangman Game with Python

Hello aspiring programmers and game enthusiasts! Have you ever wanted to build your own game? Python is a fantastic language to start with because it’s easy to read and very versatile. Today, we’re going to create a classic word-guessing game: Hangman!

Hangman is a game where one player thinks of a word, and the other player tries to guess it by suggesting letters. If the guessing player suggests a letter that is in the word, all instances of that letter are revealed. If the suggested letter is not in the word, the guessing player loses a “life” or an attempt. The game ends when the word is guessed, or all attempts are used up.

This project is perfect for beginners because it covers several fundamental programming concepts like variables, lists, loops, and conditional statements in a fun and interactive way. Let’s get started!

What You’ll Learn

By building this simple Hangman game, you’ll get hands-on experience with:

  • Importing Modules: How to use existing Python tools.
  • Variables: Storing information like the secret word and player’s lives.
  • Lists: Managing collections of items, such as the letters already guessed.
  • Loops: Repeating actions until a condition is met (the game continues!).
  • Conditional Statements: Making decisions in your code (e.g., “Is the guess correct?”).
  • User Input: How to let the player type things into your game.
  • String Manipulation: Working with text, like displaying the word.

Step 1: Setting Up Our Game

First, we need to prepare some basic ingredients for our game.

Importing the random Module

We need a way to pick a secret word for our game. Python has a helpful tool called the random module that can do just that.

  • Module: Think of a module as a toolbox full of pre-written functions and tools that you can use in your own programs. The random module provides tools for generating random numbers or making random choices.
import random

This line tells Python, “Hey, I want to use the tools from the random toolbox.”

Choosing a Word List

Next, we need a list of words for our game to choose from. For a simple game, we’ll create a small list of words right in our code.

  • List: A list is an ordered collection of items. In Python, you write lists using square brackets [], with items separated by commas. It’s like a shopping list where each item has a specific order.
word_list = ["apple", "banana", "orange", "strawberry", "grape"]

Picking a Random Word

Now, let’s use the random module to pick one word from our word_list.

chosen_word = random.choice(word_list)
  • random.choice(): This is a function from the random module that picks a random item from a list.
  • Variable: A variable is like a container or a box with a label. You can store information inside it, and you can change what’s inside later. Here, chosen_word is a variable that will hold the secret word for the current game.

Step 2: Initializing Game Variables

We need to keep track of a few things as the game progresses:

  • How many lives the player has left.
  • What letters the player has already guessed.
  • How to display the word, showing underscores for unguessed letters.
game_lives = 6 # The number of incorrect guesses allowed
guessed_letters = [] # A list to store letters the player has already guessed
display = [] # A list to show the current state of the word (e.g., '_ a _ _ e')

for _ in chosen_word:
    display.append("_")

print("Let's play Hangman!")
print(f"The word has {len(chosen_word)} letters.")
print(" ".join(display)) # The .join() method puts a space between each item in the list
  • game_lives: An integer variable holding the player’s remaining attempts. We start with 6.
  • guessed_letters: An empty list. We’ll add each letter the player guesses to this list to prevent them from guessing the same letter twice.
  • display: This list will hold underscores initially, one for each letter in chosen_word. As the player guesses correct letters, we’ll replace the underscores with those letters.
  • len(chosen_word): This function tells us how many characters (letters) are in the chosen_word.
  • f-string: The f before the opening quote of f"The word has {len(chosen_word)} letters." means it’s a “formatted string literal.” It allows you to embed expressions (like len(chosen_word)) directly inside string literals by putting them in curly braces {}. It’s a neat way to build strings easily.

Step 3: The Game Loop

The heart of our game is a while loop that will keep running as long as the player has lives left and hasn’t guessed the word yet.

  • Loop (while): A loop is a way to repeat a block of code multiple times. A while loop continues to execute its code block as long as a certain condition is true.
while game_lives > 0 and "_" in display:
    print("\n---") # Separator for better readability

    # 1. Get player's guess
    guess = input("Guess a letter: ").lower()
    # The .lower() method converts the input to lowercase, so 'A' becomes 'a'.
    # This makes our letter checking easier.

    # 2. Check if the letter was already guessed
    if guess in guessed_letters:
        print(f"You already guessed '{guess}'. Try a different letter.")
        continue # Skip the rest of this loop iteration and go to the next one

    # Add the current guess to the list of guessed letters
    guessed_letters.append(guess)

    # 3. Check if the guess is in the word
    if guess in chosen_word:
        print(f"Good guess! '{guess}' is in the word.")
        # Update the display with the correctly guessed letter
        for position in range(len(chosen_word)):
            letter = chosen_word[position]
            if letter == guess:
                display[position] = letter
    else:
        print(f"Sorry, '{guess}' is not in the word.")
        game_lives -= 1 # Lose a life
        print(f"You have {game_lives} lives left.")

    # Show the current state of the word
    print(" ".join(display))
    print(f"Guessed letters: {', '.join(guessed_letters)}")

Explaining the Loop Details:

  • while game_lives > 0 and "_" in display:: This is our game’s main condition. The loop will keep running as long as game_lives is greater than 0 (player still has attempts) AND there’s at least one underscore _ left in the display list (meaning the word hasn’t been fully guessed).
  • input("Guess a letter: ").lower():
    • input(): This function pauses your program and waits for the user to type something and press Enter. Whatever they type becomes the return value of input().
    • .lower(): This is a string method that converts all uppercase letters in a string to lowercase. This is important so that if the word is “apple” and the user guesses ‘A’, it matches ‘a’.
  • if guess in guessed_letters::
    • Conditional Statement (if, else): These allow your program to make decisions. An if statement checks if a condition is true. If it is, the code inside the if block runs. If not, it might check an elif (else if) condition or run the code in an else block.
    • Here, we check if the guess (the letter the user just typed) is already present in our guessed_letters list.
  • continue: If the letter was already guessed, continue tells the loop to immediately jump back to the beginning of the while loop and check its condition again, skipping the rest of the code in the current iteration.
  • guessed_letters.append(guess): If the letter is new, we add it to our list of guessed_letters.
  • if guess in chosen_word:: We check if the guessed letter is actually present in the chosen_word.
    • for position in range(len(chosen_word)):: If the guess is correct, we need to go through each letter of the chosen_word. range(len(chosen_word)) gives us numbers from 0 up to (but not including) the length of the word, which are the indices (positions) of letters.
    • letter = chosen_word[position]: We get the letter at the current position in the chosen_word.
    • if letter == guess:: If this letter matches the player’s guess, we update our display list at that position.
    • display[position] = letter: We replace the underscore with the correctly guessed letter.
  • else: (for if guess in chosen_word:): If the guess is not in chosen_word, the player loses a life. game_lives -= 1 is a shorthand for game_lives = game_lives - 1.

Step 4: Checking Win/Loss Conditions

After the while loop finishes (meaning game_lives is 0 or _ is no longer in display), we need to tell the player if they won or lost.

if "_" not in display:
    print("\n🎉 Congratulations! You guessed the word!")
    print(f"The word was: {chosen_word.upper()}")
else:
    print("\nGame Over! You ran out of lives.")
    print(f"The word was: {chosen_word.upper()}")
  • if "_" not in display:: This condition checks if there are no underscores left in the display list. If there aren’t, it means the player has guessed all the letters and won!
  • else:: If there are still underscores (and the loop ended because game_lives reached 0), it means the player lost.
  • .upper(): Another string method that converts all letters in a string to uppercase. It’s nice to show the final word prominently.

Putting It All Together: The Complete Code

Here’s the full code for your simple Hangman game! Copy and paste this into a Python file (e.g., hangman.py) and run it from your terminal using python hangman.py.

import random

word_list = ["apple", "banana", "orange", "strawberry", "grape", "kiwi", "pineapple", "mango"]
chosen_word = random.choice(word_list)

game_lives = 6
guessed_letters = []
display = []

for _ in chosen_word:
    display.append("_")

print("Welcome to Simple Hangman!")
print(f"The word has {len(chosen_word)} letters.")
print(" ".join(display))
print(f"You have {game_lives} lives.")

while game_lives > 0 and "_" in display:
    print("\n--------------------") # Separator for better readability

    # Get player's guess
    guess = input("Guess a letter: ").lower()

    # Input validation (simple check)
    if not guess.isalpha() or len(guess) != 1:
        print("Invalid input. Please guess a single letter.")
        continue # Skip the rest of this loop iteration

    # Check if the letter was already guessed
    if guess in guessed_letters:
        print(f"You already guessed '{guess}'. Try a different letter.")
        continue

    # Add the current guess to the list of guessed letters
    guessed_letters.append(guess)

    # Check if the guess is in the word
    if guess in chosen_word:
        print(f"Good guess! '{guess}' is in the word.")
        # Update the display with the correctly guessed letter
        for position in range(len(chosen_word)):
            letter = chosen_word[position]
            if letter == guess:
                display[position] = letter
    else:
        print(f"Sorry, '{guess}' is not in the word.")
        game_lives -= 1 # Lose a life
        print(f"You have {game_lives} lives left.")

    # Show the current state of the word and guessed letters
    print(" ".join(display))
    print(f"Guessed letters: {', '.join(sorted(guessed_letters))}") # Sorted for neatness

print("\n--------------------")
if "_" not in display:
    print("🎉 Congratulations! You guessed the word!")
    print(f"The word was: {chosen_word.upper()}")
else:
    print("😭 Game Over! You ran out of lives.")
    print(f"The word was: {chosen_word.upper()}")
print("Thanks for playing!")

Next Steps and Improvements

You’ve built a functional Hangman game! But this is just the beginning. Here are some ideas to make your game even better:

  • More Robust Input Validation: What if the user types numbers or multiple letters? You could add more checks using if not guess.isalpha() (checks if all characters in the string are alphabetic) and if len(guess) != 1. (I added a basic one in the final code!)
  • Difficulty Levels: Create different word lists for easy, medium, and hard difficulties.
  • Visual Hangman: Draw a simple ASCII art representation of the hangman figure that updates with each incorrect guess.
  • Player Names: Ask for the player’s name at the beginning.
  • Play Again Option: Ask the player if they want to play another round without restarting the script.
  • Score Tracking: Keep a score if the player wins multiple rounds.

Conclusion

Congratulations! You’ve successfully created a simple Hangman game using Python. This project is a fantastic way to solidify your understanding of basic programming concepts. Remember, the best way to learn programming is by doing, experimenting, and building things. Keep coding, keep exploring, and have fun!


Comments

Leave a Reply