CodeNewbie Community 🌱

Vishnubhotla Bharadwaj
Vishnubhotla Bharadwaj

Posted on • Originally published at bharadwaj.hashnode.dev on

Hang Man in Python

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 https://www.wikiwand.com/en/Hangman\_(game)

The flow chart for the game is as follows:

Screenshot (74).pngAs 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)

Enter fullscreen mode Exit fullscreen mode
  1. Creation of blanks
display = []
for _ in range(word_length):
 display += "_"

Enter fullscreen mode Exit fullscreen mode
  1. Guessing the letter
guess = input("Guess a letter: ").lower()

Enter fullscreen mode Exit fullscreen mode

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])

Enter fullscreen mode Exit fullscreen mode

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: https://replit.com/@BharadwajV/HangMan#main.py

Top comments (0)