-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhangman.py
62 lines (50 loc) · 1.99 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
import os
import random
import sys
class Hangman:
def __init__(self, guess_count=10):
self.words = ['pizza', 'word', 'python', 'test', 'yellow', 'down',
'chair', 'kitties']
self.secret_word = random.choice(self.words)
self.blanks = ('_' * len(self.secret_word))
self.guess_count = guess_count
self.guesses = []
def print_blanks(self):
if self.guesses:
print('Previous guesses: ', end='')
print(', '.join(self.guesses))
print('You have {} guesses remaining!'.format(self.guess_count))
print()
print(self.blanks)
print()
def play(self):
os.system('clear')
self.print_blanks()
secret_letters = list(self.secret_word)
while self.guess_count > 0:
self.blanks = list(self.blanks)
guess = input('Guess a letter: ').lower()
# make sure the user input is valid (a single letter)
while not guess.isalpha() or len(guess) > 1:
print('Please input a single letter!')
guess = input('Guess a letter: ')
os.system('clear')
while (guess in secret_letters) and (guess not in self.guesses):
# get the index of the guessed letter
guess_index = secret_letters.index(guess)
# replace the first instance of guessed letter in the secret
# word with a dash, so the second instance etc. can be found
secret_letters[guess_index] = '-'
# add the guessed letter to the row of blanks at the same index
self.blanks[guess_index] = guess
self.guesses += guess
self.guess_count -= 1
self.blanks = ''.join(self.blanks)
self.print_blanks()
if '_' not in self.blanks:
print('You win!')
sys.exit(0)
print('You lose!')
if __name__ == '__main__':
game = Hangman()
game.play()