Hang Man in Python

Subscribe to my newsletter and never miss my upcoming articles

Hang Man is like an interesting, fun-filled time pass game. Where a random word is taken by computer and we need to guess the word by alphabets. We have 6 lives to guess the word. If all the lives are completed then we lose the game. If we somehow manage to guess the words before the completion of our lives then we win. Though it is really difficult to guess the word, still we can give it a try as it is very very interesting. You can check the official documentation of it here wikiwand.com/en/Hangman_(game)

The flow chart for the game is as follows:

Screenshot (74).png As you can see above, Computer generates a random word and then generate as many blanks as letters in the word. Then it's our turn to guess the letter. For each guess, if it is in the blank then it replaces the blank with a letter else you will lose the life. This process continues until all blanks are filled or if you run out of lives.

Now, let's dive into code parts by parts.

  1. Computer wants to guess the word.
    chosen_word = random.choice(word_list)
    word_length = len(chosen_word)
    
  2. Creation of blanks
    display = []
    for _ in range(word_length):
     display += "_"
    
  3. Guessing the letter
    guess = input("Guess a letter: ").lower()
    
  4. Checking the guessed letter

    for position in range(word_length):
        letter = chosen_word[position]
    
        if letter == guess:
            display[position] = letter
    
    if guess not in chosen_word:
        print(f'You guesses {guess}, thats not in the list. You lost a life')
        lives -= 1
        if lives == 0:
            end_of_game = True
            print("You lose.")
    
    print(f"{' '.join(display)}")
    
    if "_" not in display:
        end_of_game = True
        print("You win.")
    
    from hangman_art import stages
    print(stages[lives])
    

    That's it. If all these four steps are successfully completed then it's the end of the game.

To get the ASCII and a number of words then I will attach my project link below. The entire code snippet lies in main.py, ASCII lies in hangman_art.py and the words lies in hangman_words.py. The main advantage of replit is we can simply fork others code and try it for ourselves. So, just fork my code and test it by yourselves.

Link to my project is here: replit.com/@BharadwajV/HangMan#main.py

No Comments Yet