-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathmain.py
More file actions
303 lines (242 loc) · 8.53 KB
/
main.py
File metadata and controls
303 lines (242 loc) · 8.53 KB
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
"""Hangman CLI game
Author: Jose Noriega
"""
import os
import random
import unicodedata
def clear():
os.system('clear')
class GameManager:
"""Holds all the business layer to make de game."""
def __init__(self):
self.strikes = 0
self.words = []
self.word_indexes_used = []
self.word = None
self.guessed_letters = None
self._load_words()
self._set_game_level()
self._render_frame()
def _render_frame(self):
"""Renders and refresh the main scene."""
while True:
clear()
self._render_level()
self._render_gallow()
self._render_word_indicator()
if self.strikes >= 6:
print('=========== GAME OVER ===========')
print(f'WORD: {self.word}')
input('<press enter to restart the game or ctrl + c to exit>')
self.strikes = 0
self.word_indexes_used = []
self._set_game_level()
continue
if len([letter for letter in self.word if letter not in self.guessed_letters]) == 0:
self._set_game_level()
input('<press enter to continue>')
continue
letter = self._ask_for_letter()
if letter:
is_valid = self._validate_letter(letter)
if not is_valid:
self.strikes += 1
def _render_level(self):
"""Shows the current level on the scene."""
print('=' * 15 + f' LEVEL {len(self.word_indexes_used)} ' + '=' * 15)
def _set_game_level(self):
"""Sets the word to start the game."""
self.guessed_letters = set()
idx = None
while idx is None:
random_index = random.randint(0, len(self.words) - 1)
if random_index not in self.word_indexes_used:
idx = random_index
self.word = self.words[idx]
self.word_indexes_used.append(idx)
@staticmethod
def _normalize_string(string):
"""Removes the accents from the provided string.
Args:
string: String to be normalized
Returns:
str: normalized string
"""
assert isinstance(string, str), 'The parameter should be a string.'
return unicodedata.normalize('NFKD', string).encode('ASCII', 'ignore').decode()
def _validate_letter(self, letter):
"""Checks if the provided letter is part of the current word.
Args:
letter: Letter typed by the user
Returns:
Bool: Validation result
"""
assert isinstance(letter, str) and len(letter), 'letter should be a string'
is_valid = False
special_letters = ['Á', 'É', 'Í', 'Ó', 'Ú', 'Ü']
for char in self.word:
_char = char
_letter = letter
if char in special_letters:
_char = self._normalize_string(char)
if letter in special_letters:
_char = self._normalize_string(letter)
if _char == _letter:
self.guessed_letters.add(char)
is_valid = True
return is_valid
def _load_words(self):
"""Loads the words from a text file."""
base_dir = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(base_dir, 'data.txt'), 'r', encoding='UTF-8') as file:
for line in file:
normalized_word = line.strip().upper()
self.words.append(normalized_word)
assert len(self.words) > 0, 'There are not words in the data file'
def _render_word_indicator(self):
"""Renders the word fields in the scene."""
# normalized_word = unicodedata.normalize('NFKD', normalized_word).encode('ASCII', 'ignore')
template = ''
for letter in self.word:
if letter in list(self.guessed_letters):
template += f' {letter} '
else:
template += f' __ '
print('Word: ', template)
def _render_gallow(self):
"""Renders the gallow scene based on the strikes.
Strike description:
- For 0 it will render just the gallow
- For 1 it will render the head
- For 2 it will render the torso
- For 3 it will render the left arm
- For 4 it will render the right arm
- For 5 it will render the left leg
- For 6 it will render the right leg
"""
template = """
** ** *** ** ** ******* ** ** *** ** **
** ** ** ** *** ** ** *** *** ** ** *** **
****** ***** **** ** ** *** **** **** ***** **** **
** ** ** ** ** **** ** ** ** **** ** ** ** ** ****
** ** ** ** ** *** ******* ** ** ** ** ** ** ***
||===================
||
||
||
||
||
||
||
||
||
||
||
==========@ ========
|| ||
|| ||
|| ||
"""
head = (
(8, 23, '|',),
(9, 23, '|',),
(10, 22, '_',),
(10, 23, '_',),
(10, 24, '_',),
(11, 20, '|',),
(11, 22, '.',),
(11, 24, '.',),
(11, 26, '|',),
(12, 21, '\\',),
(12, 23, '_',),
(12, 25, '/',),
)
torso = (
(13, 23, '|',),
(13, 24, '|',),
(14, 23, '|',),
(14, 24, '|',),
(15, 23, '|',),
(15, 24, '|',),
(16, 23, '|',),
(16, 24, '|',),
)
left_arm = (
(14, 20, '=',),
(14, 21, '=',),
(14, 22, '=',),
)
right_arm = (
(14, 25, '=',),
(14, 26, '=',),
(14, 27, '=',),
)
left_leg = (
(17, 22, '/',),
(17, 23, '/',),
(18, 21, '/',),
(18, 22, '/',),
)
right_leg = (
(17, 24, '\\',),
(17, 25, '\\',),
(18, 25, '\\',),
(18, 26, '\\',),
)
tramp_closed = (
(19, 19, '=',),
(19, 20, '=',),
(19, 21, '=',),
(19, 22, '=',),
(19, 23, '=',),
(19, 24, '=',),
(19, 25, '=',),
(19, 26, '=',),
(19, 27, '=',),
)
tramp_opened = (
(19, 19, '\\',),
(19, 20, '\\',),
(20, 20, '\\',),
(20, 21, '\\',),
(21, 21, '\\',),
(21, 22, '\\',),
(22, 22, '\\',),
(22, 23, '\\',),
)
scene_descriptors = []
if self.strikes >= 1:
scene_descriptors += head
if self.strikes >= 2:
scene_descriptors += torso
if self.strikes >= 3:
scene_descriptors += left_arm
if self.strikes >= 4:
scene_descriptors += right_arm
if self.strikes >= 5:
scene_descriptors += left_leg
if self.strikes == 6:
scene_descriptors += right_leg
if self.strikes < 6:
scene_descriptors += tramp_closed
else:
scene_descriptors += tramp_opened
lines = [list(line) for line in template.splitlines()]
for descriptor in scene_descriptors:
lines[descriptor[0]][descriptor[1]] = descriptor[2]
scene = '\n'.join([''.join(l) for l in lines])
print(scene)
def _ask_for_letter(self):
"""Shows a form to enter the letter.
Returns:
str: returns the letter enterd by the user if is valid, otherwise, it will return None.
"""
print('Instructions: Type a letter and press enter.')
input_letter = input(': ')
if len(input_letter) != 1:
print('Input error: Please type a letter.')
input('<press enter to continue>')
return None
return input_letter.upper()
if __name__ == '__main__':
game = GameManager()