Building a Hangman Game in Python

Share your love

Step 1: Pick a Random Word

First, we need to select a random word for the player to guess. We’ll create a list of words and choose one randomly each time the game starts. Here’s how you can do it:

Python

import random

def select_word():
    words = ["tiger", "tree", "underground", "giraffe", "chair"]
    return random.choice(words)

# Test the function
print(select_word())

Step 2: Initialize Variables

We’ll need a few variables to keep track of the game state:

  • remaining_attempts: Represents the number of remaining attempts (initially set to 6).
  • guessed_letters: A string containing all the letters guessed by the user.

Python

remaining_attempts = 6
guessed_letters = ""

Step 3: Ask the User to Guess a Letter

Use the input() function to prompt the user to guess a letter. Update the guessed_letters accordingly.

Step 4: Show the Hangman State

Create a list of strings representing different stages of the hangman. Use multiline strings (delimited by triple quotes) to draw the hangman based on the value of remaining_attempts.

Step 5: Check Correct or Incorrect Guess

Compare the guessed letter with the secret word. If correct, update the display; if incorrect, decrement remaining_attempts.

Step 6: Repeat with a While Loop

Wrap the guessing process in a while loop until the user either guesses the word or runs out of attempts.

Final Code

Here’s a simplified version of the Hangman game:

import random

def select_word():
    words = ["tiger", "tree", "underground", "giraffe", "chair"]
    return random.choice(words)

def main():
    secret_word = select_word()
    print("Welcome to Hangman!")
    
    while remaining_attempts > 0:
        # Ask the user to guess a letter
        guess = input("Guess a letter: ").lower()
        guessed_letters += guess
        
        # Check if the guess is correct
        if guess in secret_word:
            print("Correct guess!")
        else:
            print("Incorrect guess!")
            remaining_attempts -= 1
        
        # Display the hangman state
        # (Implement this part using multiline strings)
        
        # Check if the word has been completely guessed
        if all(letter in guessed_letters for letter in secret_word):
            print(f"Congratulations! You've guessed the word: {secret_word}")
            break
    
    if remaining_attempts == 0:
        print(f"Sorry, you're out of attempts. The word was: {secret_word}")

if __name__ == "__main__":
    main()

Written by: Piyush Patil

Feel free to enhance the game by adding more features or improving the hangman display. Happy coding! 😊


Share your love