-
Notifications
You must be signed in to change notification settings - Fork 1
/
hangmanen.py
380 lines (242 loc) · 9.54 KB
/
hangmanen.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
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
"""
Modified hangman with multiple songs as entries. Originaly designed for
use on DTForums' roulette games.
"""
from Entry import *
SPECIAL_CHARS = " -(),.:;?!'&"
def askForName():
"""A simple user prompt."""
print("Name of the text file to load (without the extension): ", end="")
LIST_NAME = input()
return LIST_NAME
def loadSongs(LIST_NAME, entries_list):
"""Loads the list of names from a text file, one per line."""
with open(LIST_NAME + ".txt", "r", encoding='utf-8') as file:
for line in file:
entry = Entry()
# line = "Player: Artist - Song\n"
line = line.strip()
# temp = ["Player", "Artist - Song"]
temp = line.split(": ", maxsplit = 1)
entry.player = temp[0]
# temp2 = ["Artist", "Song"]
temp2 = temp[1].split(" - ", maxsplit = 1)
entry.artist = temp2[0]
entry.song = temp2[1]
entries_list.append(entry)
return entries_list
def createBlankName(name):
"""
Based on the names loaded, creates the blanks for the player to
guess. They're saved in a text file.
"""
new_name = ""
for letter in name:
index = SPECIAL_CHARS.find(letter)
# The letter is no special character
if index == -1:
new_name = new_name + "_"
else:
new_name = new_name + SPECIAL_CHARS[index]
return new_name
def saveBlankNames(entries_list):
"""
Since both artist and song have to be 'blanked', making a separate
function is easier than copypasting the same code for each.
"""
for entry in entries_list:
entry.blank_artist = createBlankName(entry.artist)
entry.blank_song = createBlankName(entry.song)
def isLetter(words):
"""
This looks nicer and more understandable instead of just
using a '==' comparison.
"""
return len(words) == 1
def invalidLetter(entries_list, guess):
"""
Only replaces the letter if it exists on the entry,
otherwise prepare for hangman.
"""
hangman = True
guess_lower = guess.lower()
guess_upper = guess.upper()
for entry in entries_list:
# The letter has to be checked in both the artist and song names,
# in lower and uppercase.
if guess_lower in entry.artist:
entry.blank_artist = entry.replaceLetter(entry.artist, guess_lower,
entry.blank_artist)
hangman = False
if guess_lower in entry.song:
entry.blank_song = entry.replaceLetter(entry.song, guess_lower,
entry.blank_song)
hangman = False
if guess_upper in entry.artist:
entry.blank_artist = entry.replaceLetter(entry.artist, guess_upper,
entry.blank_artist)
hangman = False
if guess_upper in entry.song:
entry.blank_song = entry.replaceLetter(entry.song, guess_upper,
entry.blank_song)
hangman = False
return hangman
def invalidWords(entries_list, guess):
"""
This assumes you're writing the words exactly as they written in
the entries. No spellchecking, this is case-sensitive. Enter either
artist or song name (or part of either) here, but not both.
"""
for entry in entries_list:
index = entry.artist.find(guess)
if index != -1:
entry.blank_artist = entry.replaceWords(entry.blank_artist,
guess, index)
return False
else:
index = entry.song.find(guess)
if index != -1:
entry.blank_song = entry.replaceWords(entry.blank_song,
guess, index)
return False
else:
return True
def checkGuess(entries_list, guess, guessed_letters, guessed_words):
"""
It is important to separate what kind of guess the player is
giving and save the correct ones.
"""
while guess in guessed_letters or guess in guessed_words:
print("\nGuess is already existing. Try another one.")
guess = input("New guess: ")
else:
if isLetter(guess):
if invalidLetter(entries_list, guess):
print("ohnoes, a hangman!")
else:
# make a for loop and call the replace method?
guessed_letters.append(guess)
else:
if invalidWords(entries_list, guess):
print(guess)
print("hangman D:")
else:
guessed_words.append(guess)
return (guessed_letters, guessed_words)
def loadGuessesFile(LIST_NAME, entries_list, guessed_letters, guessed_words):
"""LIST_NAME must not end in '.txt'."""
try:
file = open(LIST_NAME + ' guesses.txt', 'r', encoding='utf-8')
except FileNotFoundError:
file = open(LIST_NAME + ' guesses.txt', 'w', encoding='utf-8')
finally:
for line in file:
line = line.strip()
if "\ufeff" in line:
line = line.replace("\ufeff", "")
guessed_entries = checkGuess(entries_list, line,
guessed_letters, guessed_words)
guessed_letters = guessed_entries[0]
guessed_words = guessed_entries[1]
file.close()
return guessed_letters
def askGuess():
guess = input("Enter a word or letter to guess: ")
return guess
def checkComplete(entries_list):
"""If all entries have been guessed, game is over."""
for entry in entries_list:
if (entry.artist != entry.blank_artist
or entry.song != entry.blank_song):
if not entry.guessed_player:
return False
else:
return True
def promptUser():
"""Main game options."""
while True:
print("\n\n",
"1. Guess a word or a letter. \n",
"2. A player has been guessed. \n",
"3. Exit. \n")
choice = input("Choose one: ")
if choice != "1" and choice != "2" and choice != "3":
print("Error, insert a valid number.")
else:
break
return choice
def saveGuess(LIST_NAME, guess):
"""Puts them in a text file to be loaded later."""
with open(LIST_NAME + ' guesses.txt', 'a', encoding='utf-8') as file:
file.write(guess + '\n')
def saveGuessedPlayer(LIST_NAME, player):
"""Same as above, but separate from it."""
with open(LIST_NAME + " guessed players.txt",
"a", encoding="utf-8") as file:
file.write(player + '\n')
def loadGuessedPlayers(LIST_NAME, entries_list):
"""Reads from a file then modifies the entry objects if it exists."""
try:
with open(LIST_NAME + ' guessed players.txt',
'r', encoding='utf-8') as file:
for line in file:
line = line.strip()
guessedPlayer(entries_list, line)
except FileNotFoundError:
file = open(LIST_NAME + ' guessed players.txt', 'w', encoding='utf-8')
file.close()
def guessedPlayer(entries_list, player):
"""
Looks for the the player and makes it printable once it's
been guessed.
"""
for entry in entries_list:
if entry.player == player:
entry.guessed_player = True
return entry.guessed_player
def printBlankList(entries_list):
"""
Prints it using the folloowing format:
Player: Artist - Song
"""
for entry in entries_list:
if entry.guessed_player:
print(entry.player, end=": ")
else:
print("?:", end=" ")
print(entry.blank_artist, "-", entry.blank_song)
def printGuessedLetters(guessed_letters):
"""Helps to keep track of what's been guessed."""
print("\nGuessed letters: ", end="")
for letter in guessed_letters:
print(letter.upper(), end=" ")
def main():
LIST_NAME = askForName()
entries_list = []
entries_list = loadSongs(LIST_NAME, entries_list)
guessed_letters = []
guessed_words = []
saveBlankNames(entries_list)
loadGuessesFile(LIST_NAME, entries_list, guessed_letters, guessed_words)
loadGuessedPlayers(LIST_NAME, entries_list)
printBlankList(entries_list)
printGuessedLetters(guessed_letters)
while not checkComplete(entries_list):
choice = promptUser()
if choice == "1":
guess = askGuess()
guessed_entries = checkGuess(entries_list, guess,
guessed_letters, guessed_words)
guessed_letters = guessed_entries[0]
guessed_words = guessed_entries[1]
if guess in guessed_letters or guess in guessed_words:
saveGuess(LIST_NAME, guess)
elif choice == "2":
player = input("Write the name of the guessed player: ")
guessedPlayer(entries_list, player)
saveGuessedPlayer(LIST_NAME, player)
elif choice == "3":
break
printBlankList(entries_list)
printGuessedLetters(guessed_letters)
main()