-
Notifications
You must be signed in to change notification settings - Fork 3
/
06_01_hangman_file.py
executable file
·73 lines (59 loc) · 1.5 KB
/
06_01_hangman_file.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
#06_01_hangman_file
import random
f = open('prog_pi_ed3/hangman_words.txt')
words = f.read().splitlines()
f.close()
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():
word_position = random.randint(0, len(words) - 1)
return words[word_position]
def get_guess(word):
print_word(word)
print('Lives Remaining: ' + str(lives_remaining))
guess = input(' Guess a letter or whole word?')
return guess
def print_word(word):
display_word = ''
for letter in word:
if guessed_letters.find(letter) > -1:
display_word = display_word + letter
else:
display_word = display_word + '-'
print(display_word)
def process_guess(guess, word):
if len(guess) > 1:
return whole_word_guess(guess, word)
else:
return single_letter_guess(guess, word)
def whole_word_guess(guess, word):
global lives_remaining
if guess == word:
return True
else:
lives_remaining = lives_remaining - 1
def single_letter_guess(guess, word):
global guessed_letters
global lives_remaining
if word.find(guess) == -1:
lives_remaining = lives_remaining - 1
guessed_letters = guessed_letters + guess
if all_letters_guessed(word):
return True
def all_letters_guessed(word):
for letter in word:
if guessed_letters.find(letter) == -1:
return False
return True
play()