Skip to content

Commit 9c0a8cd

Browse files
committed
Added Hangman game algorithm in Python
1 parent e2a78d4 commit 9c0a8cd

File tree

1 file changed

+162
-0
lines changed

1 file changed

+162
-0
lines changed

other/hangman_game.py

Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
"""
2+
hangman.py
3+
A simple command-line Hangman game implemented in Python.
4+
5+
This program randomly selects a word from a given list and allows the user
6+
to guess it letter by letter. The game ends when the user either correctly
7+
guesses all the letters or exceeds the maximum allowed wrong attempts.
8+
9+
Usage:
10+
python hangman.py
11+
12+
Example:
13+
$ python hangman.py
14+
Welcome to Hangman!
15+
_ _ _ _ _
16+
Enter a letter: a
17+
Correct!
18+
a _ _ _ _
19+
...
20+
"""
21+
import random
22+
23+
24+
# ----------------------------- #
25+
# HANGMAN STAGES (ASCII ART)
26+
# ----------------------------- #
27+
28+
words = (
29+
# Fruits
30+
'apple', 'orange', 'banana', 'coconut', 'pineapple', 'mango', 'papaya',
31+
'strawberry', 'blueberry', 'raspberry', 'grape', 'watermelon', 'peach',
32+
'pear', 'cherry', 'plum', 'kiwi', 'apricot', 'lemon', 'lime',
33+
34+
# Animals
35+
'elephant', 'tiger', 'lion', 'giraffe', 'zebra', 'monkey', 'kangaroo',
36+
'dolphin', 'rabbit', 'panda', 'koala', 'wolf', 'bear', 'fox', 'camel',
37+
'penguin', 'snake', 'turtle', 'deer', 'leopard',
38+
39+
# Countries
40+
'pakistan', 'india', 'china', 'japan', 'brazil', 'canada', 'france',
41+
'germany', 'australia', 'italy', 'spain', 'egypt', 'turkey', 'russia',
42+
'mexico', 'norway', 'sweden', 'argentina', 'indonesia', 'nigeria',
43+
44+
# Colors
45+
'red', 'blue', 'green', 'yellow', 'purple', 'orange', 'black', 'white',
46+
'pink', 'brown', 'gray', 'violet', 'indigo', 'silver', 'gold',
47+
48+
# Computer / Tech
49+
'python', 'javascript', 'variable', 'function', 'developer', 'keyboard',
50+
'internet', 'website', 'database', 'algorithm', 'software', 'hardware',
51+
'network', 'browser', 'program', 'compiler', 'laptop', 'machine', 'coding',
52+
53+
# Random everyday words
54+
'school', 'teacher', 'window', 'garden', 'flower', 'butterfly', 'dream',
55+
'sunshine', 'moonlight', 'family', 'holiday', 'mountain', 'river',
56+
'forest', 'island', 'cloud', 'ocean', 'rainbow', 'friend', 'love'
57+
)
58+
59+
60+
hangman_art: dict[int, tuple[str, str, str]] = {
61+
0: (" ", " ", " "),
62+
1: (" o ", " ", " "),
63+
2: (" o ", " | ", " "),
64+
3: (" o ", "/| ", " "),
65+
4: (" o ", "/|\\ ", " "),
66+
5: (" o ", "/|\\ ", "/ "),
67+
6: (" o ", "/|\\ ", "/ \\ "),
68+
}
69+
70+
71+
def display_man(wrong_guesses: int) -> None:
72+
"""
73+
Display the current hangman stage according to the number of wrong guesses.
74+
75+
Args:
76+
wrong_guesses (int): Number of incorrect guesses made so far.
77+
"""
78+
print("*****************")
79+
for line in hangman_art[wrong_guesses]:
80+
print(line)
81+
print("*****************")
82+
83+
84+
def display_hint(hint: list[str]) -> None:
85+
"""
86+
Display the current state of the guessed word as underscores and letters.
87+
88+
Args:
89+
hint (list[str]): List containing correctly guessed letters or underscores.
90+
"""
91+
print(" ".join(hint))
92+
93+
94+
def display_answer(answer: str) -> None:
95+
"""
96+
Display the correct word at the end of the game.
97+
98+
Args:
99+
answer (str): The correct word that was to be guessed.
100+
"""
101+
print(f"The correct word was: {answer}")
102+
103+
104+
def main() -> None:
105+
"""
106+
Main function to run the Hangman game.
107+
108+
The player has up to 6 incorrect guesses to complete the word.
109+
The game ends when the player wins or loses.
110+
"""
111+
answer: str = random.choice(words)
112+
hint: list[str] = ["_"] * len(answer)
113+
wrong_guesses: int = 0
114+
guessed_letters: set[str] = set()
115+
is_running: bool = True
116+
117+
print("\n Welcome to Hangman!")
118+
print("Guess the word, one letter at a time.\n")
119+
120+
while is_running:
121+
display_man(wrong_guesses)
122+
display_hint(hint)
123+
guess = input("Enter a letter: ").lower().strip()
124+
125+
# Input validation
126+
if len(guess) != 1 or not guess.isalpha():
127+
print("Invalid input. Please enter a single alphabetic character.\n")
128+
continue
129+
130+
if guess in guessed_letters:
131+
print(f"'{guess}' has already been guessed.\n")
132+
continue
133+
134+
guessed_letters.add(guess)
135+
136+
# Check if the guessed letter is in the word
137+
if guess in answer:
138+
for i, letter in enumerate(answer):
139+
if letter == guess:
140+
hint[i] = guess
141+
print("Correct!\n")
142+
else:
143+
wrong_guesses += 1
144+
print("Wrong guess!\n")
145+
146+
# Win condition
147+
if "_" not in hint:
148+
display_man(wrong_guesses)
149+
display_answer(answer)
150+
print("YOU WIN!\n")
151+
is_running = False
152+
153+
# Lose condition
154+
elif wrong_guesses >= len(hangman_art) - 1:
155+
display_man(wrong_guesses)
156+
display_answer(answer)
157+
print("YOU LOSE!\n")
158+
is_running = False
159+
160+
161+
if __name__ == "__main__":
162+
main()

0 commit comments

Comments
 (0)