"Mastering the Classic Hangman Game: A Python Implementation.
What is Hangman game🤔 ?:
In the Hangman game, the computer selects a secret word, which is not revealed to the player. Instead, blank spaces are displayed, each representing a letter in the word. The player guesses one letter at a time. If the guessed letter is in the word, all instances of that letter are revealed in their correct positions. If the letter is not in the word, a part of a hangman (a stick figure) is drawn, indicating a wrong guess. The player has a limited number of incorrect guesses before losing the game. Each wrong guess brings the drawing of the hangman closer to completion. In this version, the player has only 5 attempts.
The player wins if they guess the entire word before the hangman drawing is completed.
The player loses if they run out of guesses and the hangman is fully drawn.
stages = [r'''
+---+
| |
0 |
/|\ |
/ \ |
|
''',r'''
+---+
| |
0 |
/|\ |
/ |
|
''',r'''
+---+
| |
0 |
/|\ |
|
|
''',r'''
+---+
| |
0 |
/| |
|
|
''',r'''
+---+
| |
0 |
| |
|
|
''',r'''
+---+
| |
0 |
|
|
|
''',r'''
+---+
| |
|
|
|
|
''']
The random.choice(words) function picks a word from the predefined list of words.
Initially, the word is hidden, and only underscores '_' are shown, representing each letters.
The player inputs a letter, which is checked against the letters in the chosen word.
If the guessed letter is in the word, the display is updated with that letter in the correct positions.
The player starts with 6 lives. Every incorrect guess reduces the lives by 1, bring the player closer to losing.
The game ends either when the player correctly guesses all the letters or when they lose all their lives.
A visual representation of the hangman is shown after each wrong guess, indicating how many incorrect guesses the player has left from stage file.
import random
import hangman_images
words=["database","compiler","algorithm","cache","memory","internet","virtual","desktop","protocol",'website',"cookies","artificial","debugging"]
lives=6
chosen_word=random.choice(words)
# print(chosen_word)
display=[]
for i in chosen_word:
display+='_'
print(display)
game_over=False
while not game_over:
guessed_letter = input("Guess a letter (Computer Science and Technology concepts): ").lower()
for position in range(len(chosen_word)):
letter=chosen_word[position]
if letter == guessed_letter:
display[position]=guessed_letter
print(display)
if guessed_letter not in chosen_word:
lives-=1
if lives>0:
print(f"You only have {lives} lives.")
else:
game_over=True
print("You lose.")
if '_' not in display:
game_over=True
print("You won.")
print(hangman_images.stages[lives])
You can modify the list of words, adjust the number of lives, or change the hangman drawing to fit your own version🤞
Subscribe to my newsletter
Read articles from Arunmathavan K directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by