-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
146 lines (127 loc) · 3.46 KB
/
main.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
140
141
142
143
144
145
146
import random
class HangManGame:
DEFAULT_LIVES = 6
def __init__(self):
self.chosen_word: bool = False
self.guessed_letters: set = set()
self.is_completed: bool = False
self.__word: str = ""
self.lives = HangManGame.DEFAULT_LIVES
def random_word(self):
with open("wordlist.txt", "r") as fp:
words = fp.read().splitlines()
word_index = random.randint(0, len(words) - 1)
self.set_chosen_word(words[word_index])
def set_chosen_word(self, word: str):
self.__word = word.strip().lower()
self.chosen_word = True
def draw_board(self):
board = self.draw_hangman() + "\n"
for letter in self.__word:
if letter == " ":
board += " "
elif letter in self.guessed_letters:
upper_letter = letter.upper()
board += upper_letter + " "
else:
board += "_ "
board += f"\nLives remaining: {self.lives}"
print(board)
def draw_hangman(self):
stages = [
"""
-----
| |
O |
/|\\ |
/ \\ |
|
---------
""",
"""
-----
| |
O |
/|\\ |
/ |
|
---------
""",
"""
-----
| |
O |
/|\\ |
|
|
---------
""",
"""
-----
| |
O |
/| |
|
|
---------
""",
"""
-----
| |
O |
| |
|
|
---------
""",
"""
-----
| |
O |
|
|
|
---------
""",
"""
-----
| |
|
|
|
|
---------
"""
]
return stages[self.lives]
def validate_winning(self):
for letter in self.__word.replace(" ", ""):
if letter not in self.guessed_letters:
return False
return True
def make_guess(self, letter: str):
if len(letter) != 1:
print("Please enter a single letter")
return
if letter in self.guessed_letters:
print("You've already guessed this letter")
return
self.guessed_letters.add(letter)
if letter not in self.__word:
self.lives -= 1
def play(self):
while not self.is_completed:
self.draw_board()
self.make_guess(input("Enter a letter: "))
if self.lives <= 0:
self.draw_board()
print("You've lost!")
self.is_completed = True
elif self.validate_winning():
self.draw_board()
print("You've won!")
self.is_completed = True
if __name__ == "__main__":
game = HangManGame()
game.random_word()
game.play()