-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmilestone_5.py
53 lines (47 loc) · 1.9 KB
/
milestone_5.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
import random
class Hangman:
def __init__(self, word_list, num_lives):
self.word_list = word_list
self.num_lives = num_lives
self.word = random.choice(word_list)
self.word_guessed = ['_' for letter in self.word]
self.list_of_guesses = []
self.num_letters = len(set(self.word))
def check_guess(self, guess):
guess = guess.lower()
if guess in self.word:
print(f"Good guess! {guess} is in the word.")
for word_id in range(len(self.word)):
if guess == self.word[word_id]:
self.word_guessed[word_id] = guess
print(self.word_guessed)
self.num_letters -= 1
else:
self.num_lives -=1
print(f"Sorry, {guess} is not in the word.")
print(f"You have {self.num_lives} lives left.")
self.list_of_guesses.append(guess)
def ask_for_input(self):
while True:
guess = input("Please choose a single alphabetical character:")
if not (len(guess) == 1 and guess.isalpha()):
print("Invalid letter. Please, enter a single alphabetical character.")
elif guess in self.list_of_guesses:
print("You already tried that letter!")
else:
self.check_guess(guess)
break
def play_game(word_list):
game = Hangman(word_list , num_lives = 5)
print(game.word_guessed)
while True:
if game.num_lives == 0:
print("You lost!")
break
elif game.num_letters > 0:
game.ask_for_input()
elif game.num_lives > 0 and game.num_letters == 0:
print("Congratulations. You won the game!")
break
word_list = ['apple' , 'banana' , 'orange' , 'kiwi' , 'grapefruit' , 'pear' , 'strawberry' , 'pineapple' , 'mango' , 'pomegranate' , 'rasberry']
play_game(word_list)