-
Notifications
You must be signed in to change notification settings - Fork 0
/
Hangman.py
139 lines (122 loc) · 3.21 KB
/
Hangman.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
import random
WORDS = ["lion", "elephant", "kangaroo", "dolphin", "panda", "giraffe", "penguin", "tiger", "owl", "cheetah"]
# Draw a gallows and person
def draw_hangman(life):
drawing = [
'''
-----
| |
O |
/|\\ |
/ \\ |
|
---------
''',
'''
-----
| |
O |
/|\\ |
/ |
|
---------
''',
'''
-----
| |
O |
/|\\ |
|
|
---------
''',
'''
-----
| |
O |
/| |
|
|
---------
''',
'''
-----
| |
O |
| |
|
|
---------
''',
'''
-----
| |
O |
|
|
|
---------
''',
'''
-----
| |
|
|
|
|
---------
'''
]
return drawing[life]
# Select a word from WORDS
def select_word():
return random.choice(WORDS)
# User input a guess
def make_guess():
guess = input("Guess a letter: ").upper()
return guess
def hangman_game():
word = select_word().upper()
letters_to_guess = set(word)
correct_guesses = set()
wrong_guesses = set()
life = 6
guesses = 0
# Greet the player
print("\n\033[1;32mWelcome to Hangman game!","\033[0m")
print(f"The word has \033[1;32m{len(word)}\033[0m letters")
while len(letters_to_guess) > 0 and life > 0:
# Diplay the current guessed word
display_word = [ltr if ltr in correct_guesses else "_" for ltr in word]
print(draw_hangman(life))
print("\033[1;32mCurrent word: ", " ".join(display_word), "\033[0m")
print(f"{guesses} guessess have been made (correct : {len(correct_guesses)} wrong : {guesses - len(correct_guesses)})")
print(f"wrong_guesses : \033[1;31m{', '.join(wrong_guesses)}\033[0m")
guess = make_guess()
guesses += 1
# Check if the guess is correct
if guess in letters_to_guess:
correct_guesses.add(guess)
letters_to_guess.remove(guess)
print(f"\n\033[1;32mCongrats, you guessed the letter {guess} right!\033[0m")
else:
wrong_guesses.add(guess)
life -=1
print(f"\n\033[1;32mWrong guess! You have \033[1;31m{life}\033[0m \033[1;32mlives left\033[0m")
print(life)
# Tell the result
if life == 0:
print(draw_hangman(life))
print(f"\033[1;31mHangman died! The word was '{word}'\033[0m")
else:
print(f"\033[1;32mCongratulations, you guessed the word {word} right!\033[0m")
# Ask if the player wants to retry
retry = input("Retry? (Y/N):").upper()
if retry == "Y":
hangman_game()
else:
print("Thanks for playing!")
def main():
hangman_game()
if __name__=="__main__":
main()