-
Notifications
You must be signed in to change notification settings - Fork 3
/
04_09_hangman_full_solution.py
executable file
·74 lines (61 loc) · 1.6 KB
/
04_09_hangman_full_solution.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
#04_09_hangman_full_solution
import random
words = ['chicken', 'dog', 'cat', 'mouse', 'frog']
lives_remaining = 14
guessed_letters = ''
def play():
word = pick_a_word()
while True:
guess = get_guess(word)
if process_guess(guess, word):
print('You win! Well Done!')
break
if lives_remaining == 0:
print('You are Hung!')
print('The word was: ' + word)
break
def pick_a_word():
return random.choice(words)
def get_guess(word):
print_word_with_blanks(word)
print('Lives Remaining: ' + str(lives_remaining))
guess = input(' Guess a letter or whole word?')
return guess
def print_word_with_blanks(word):
display_word = ''
for letter in word:
if guessed_letters.find(letter) > -1:
# letter found
display_word = display_word + letter
else:
# letter not found
display_word = display_word + '-'
print(display_word)
def process_guess(guess, word):
if len(guess) > 1 and len(guess) == len(word):
return whole_word_guess(guess, word)
else:
return single_letter_guess(guess, word)
def whole_word_guess(guess, word):
global lives_remaining
if guess.lower() == word.lower():
return True
else:
lives_remaining = lives_remaining - 1
return False
def single_letter_guess(guess, word):
global guessed_letters
global lives_remaining
if word.find(guess) == -1:
# letter guess was incorrect
lives_remaining = lives_remaining - 1
guessed_letters = guessed_letters + guess.lower()
if all_letters_guessed(word):
return True
return False
def all_letters_guessed(word):
for letter in word:
if guessed_letters.find(letter.lower()) == -1:
return False
return True
play()