-
Notifications
You must be signed in to change notification settings - Fork 0
/
hangman.py
95 lines (76 loc) · 2.46 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
import random
import time
# let user input theme for game
def select_theme(words : dict) -> str:
'''
print theme options & prompt user to select a theme
input : dictionary
output : string containing name of theme
'''
# get themes from dict
themes = words.keys()
# print options
print('Select a theme :')
i = 1
for theme in themes :
print(i, '.', theme)
i += 1
choice = int(input('Enter a number to proceed : '))
# return chosen theme (i started from 1)
return list(themes)[choice - 1]
# choose random word from given theme
def random_word(words : dict, theme : str) -> str :
'''
choose a random word from a given theme
input : dictionary, string containing name of theme
output : string containing game word
'''
# shuffle list
random.shuffle(list(words[theme]))
# return random word
return random.choice(list(words[theme]))
# get all indices of string that match the character
def indices_of(word : str, ch : str) -> list:
'''
get all indices of character in string
input : string containing word, character to search in string
output : list of indices
'''
lst_of_indices = []
i = 0
for letter in word:
if letter == ch :
lst_of_indices.append(i)
i+=1
return lst_of_indices
# game logic
def play_game(words : dict, theme : str) :
'''
function containing game logic
input : dictionary, string containing theme
'''
game_word = random_word(words, theme)
word_to_solve = '_' * len(game_word)
# write function - print rules
print("LET THE GAME BEGIN...")
time.sleep(1)
total_num_guesses = len(game_word) * 2
for guess_num in range(total_num_guesses) :
if word_to_solve == game_word:
print(word_to_solve)
print('You are a winner!!')
return
print(word_to_solve)
guess = input("Guess a character : ")
if guess in game_word:
# get occurences of guess in string
indices = indices_of(game_word, guess)
# replace character in word to solve
# strings are immutable
# convert to list, modify char at index & convert back to string
lst = list(word_to_solve)
for index in indices :
lst[index] = guess
word_to_solve = "".join(lst)
print('You could have won :(')
print('The word was ', game_word)