-
Notifications
You must be signed in to change notification settings - Fork 458
/
Hangman.py
129 lines (110 loc) · 2.7 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
import random
HANGMAN_PICS = [
"""
------
| |
|
|
|
|
--------
""",
"""
------
| |
| O
|
|
|
--------
""",
"""
------
| |
| O
| |
|
|
--------
""",
"""
------
| |
| O
| /|
|
|
--------
""",
"""
------
| |
| O
| /|\\
|
|
--------
""",
"""
------
| |
| O
| /|\\
| /
|
--------
""",
"""
------
| |
| O
| /|\\
| / \\
|
--------
""",
]
WORDS = ['python', 'javascript', 'hangman', 'development', 'terminal', 'project']
def get_random_word(word_list):
return random.choice(word_list).lower()
def display_board(missed_letters, correct_letters, secret_word):
print(HANGMAN_PICS[len(missed_letters)])
print("\nMissed letters:", ' '.join(missed_letters))
blanks = ['_' if letter not in correct_letters else letter for letter in secret_word]
print(" ".join(blanks))
def is_valid_guess(guess, missed_letters, correct_letters):
# Check if the input is a single alphabetic character
if len(guess) != 1 or not guess.isalpha():
print("Invalid input! Please enter a single letter.")
return False
# Check if the letter has already been guessed
if guess in missed_letters or guess in correct_letters:
print("You've already guessed that letter! Try again.")
return False
return True
def play_hangman():
secret_word = get_random_word(WORDS)
missed_letters = []
correct_letters = []
while len(missed_letters) < len(HANGMAN_PICS) - 1:
display_board(missed_letters, correct_letters, secret_word)
guess = input("Guess a letter: ").lower()
if is_valid_guess(guess, missed_letters, correct_letters):
if guess in secret_word:
correct_letters.append(guess)
if all(letter in correct_letters for letter in secret_word):
print(f"Congratulations! You've guessed the word '{secret_word}'.")
break
else:
missed_letters.append(guess)
if len(missed_letters) == len(HANGMAN_PICS) - 1:
display_board(missed_letters, correct_letters, secret_word)
print(f"Sorry, you've been hanged! The word was '{secret_word}'.")
break
if __name__ == "__main__":
while True:
play_hangman()
play_again = input("Do you want to play again? (yes/no): ").lower()
if play_again != 'yes':
print("Thanks for playing!")
break