Hangman Game

Photo by Ben Hershey on Unsplash

Hangman Game

Table of contents

No heading

No headings in the article.

Let's code the hangman game step by step.

  1. Now we need a list of words to play right! we can add any number of words and any words.

    List in Python
    A list in Python is an ordered and mutable collection of items enclosed within square brackets.

    Example : Numbers = [1, 2, 3, 4, 5]

  2. Next, we have to select a word from the list, which happens randomly.

    Import Random Module
    The random module in Python is a built-in library that provides functions for generating random numbers and performing random operations. It's commonly used in applications where randomness or unpredictability is needed, such as games, simulations, and data shuffling.
    1. Initialize variables to be used in the game throughout the code.

      Initializing variables means assigning an initial value to a variable before you use it in your code. This is an essential step in programming, as it allows you to store and manipulate data.

      Example : my_variable = 42

      In this example, we've created a variable called my_variable and assigned it the value 42. Python will automatically determine the data type based on the assigned value.

       display = []
       for _ in range(word_length):
           display += "_"
      
    2. Visually (Manually) designing the hangman

       # Hangman stages
       stages = [
           """
            -----
           |     |
                 |
                 |
                 |
                 |
           """,
           """
            -----
           |     |
           O     |
                 |
                 |
                 |
           """,
           """
            -----
           |     |
           O     |
           |     |
                 |
                 |
           """,
           """
            -----
           |     |
           O     |
          /|     |
                 |
                 |
           """,
           """
            -----
           |     |
           O     |
          /|\\    |
                 |
                 |
           """,
           """
            -----
           |     |
           O     |
          /|\\    |
          /      |
                 |
           """,
           """
            -----
           |     |
           O     |
          /|\\    |
          / \\    |
                 |
           GAME OVER!
           """
       ]
      

5.We have to loop through and check if the user entered input is eqaul to the randomaly generated word.

# Game loop
game_over = False
attempts = len(stages) - 1

while not game_over:
    # Display the current state of the word
    print(" ".join(display))

    # Get a guess from the player
    guess = input("Guess a letter: ").lower()

    if guess in guessed_letters:
        print(f"You've already guessed '{guess}'. Try again.")
        continue

    if guess in chosen_word:
        for i in range(word_length):
            if chosen_word[i] == guess:
                display[i] = guess
    else:
        print(f"'{guess}' is not in the word.")
        guessed_letters.append(guess)
        attempts -= 1
        print(stages[attempts])

    if "_" not in display:
        print("Congratulations! You guessed the word.")
        game_over = True
    elif attempts == 0:
        print(f"Out of attempts. The word was '{chosen_word}'.")
        game_over = True
  1. Let's Complete the code.

     import random
    
     # List of words to choose from
     word_list = ["paris", "spain", "seoul", "india", "busan", "america", "poland", "london"]
    
     # Select a random word from the list
     chosen_word = random.choice(word_list)
     word_length = len(chosen_word)
    
     # Initialize game variables
     display = []
     for _ in range(word_length):
         display += "_"
    
     # Hangman stages
     stages = [
         """
          -----
         |     |
               |
               |
               |
               |
         """,
         """
          -----
         |     |
         O     |
               |
               |
               |
         """,
         """
          -----
         |     |
         O     |
         |     |
               |
               |
         """,
         """
          -----
         |     |
         O     |
        /|     |
               |
               |
         """,
         """
          -----
         |     |
         O     |
        /|\\    |
               |
               |
         """,
         """
          -----
         |     |
         O     |
        /|\\    |
        /      |
               |
         """,
         """
          -----
         |     |
         O     |
        /|\\    |
        / \\    |
               |
         GAME OVER!
         """
     ]
    
     # Track guessed letters
     guessed_letters = []
    
     # Game loop
     game_over = False
     attempts = len(stages) - 1
    
     while not game_over:
         # Display the current state of the word
         print(" ".join(display))
    
         # Get a guess from the player
         guess = input("Guess a letter: ").lower()
    
         if guess in guessed_letters:
             print(f"You've already guessed '{guess}'. Try again.")
             continue
    
         if guess in chosen_word:
             for i in range(word_length):
                 if chosen_word[i] == guess:
                     display[i] = guess
         else:
             print(f"'{guess}' is not in the word.")
             guessed_letters.append(guess)
             attempts -= 1
             print(stages[attempts])
    
         if "_" not in display:
             print("Congratulations! You guessed the word.")
             game_over = True
         elif attempts == 0:
             print(f"Out of attempts. The word was '{chosen_word}'.")
             game_over = True
    
    1. Output time