-
Notifications
You must be signed in to change notification settings - Fork 0
/
hangman.py
125 lines (114 loc) · 2.95 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import random
def get_word():
words = ['python', 'programme', 'computer', 'artificial', 'dataset', 'network', 'software']
return random.choice(words).upper()
def display_hangman(tries):
stages = [ # Final state: head, torso, both arms, both legs
"""
--------
| |
| O
| \\|/
| |
| / \\
-
""",
# Head, torso, both arms, one leg
"""
--------
| |
| O
| \\|/
| |
| /
-
""",
# Head, torso, both arms
"""
--------
| |
| O
| \\|/
| |
|
-
""",
# Head, torso, one arm
"""
--------
| |
| O
| \\|
| |
|
-
""",
# Head and torso
"""
--------
| |
| O
| |
| |
|
-
""",
# Head
"""
--------
| |
| O
|
|
|
-
""",
# Initial empty state
"""
--------
| |
|
|
|
|
-
"""
]
return stages[tries]
def play_hangman():
word = get_word()
word_letters = set(word) # Letters in the word
alphabet = set('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
used_letters = set() # Letters guessed by the user
tries = 6 # Number of tries before game over
# Game loop
while len(word_letters) > 0 and tries > 0:
print('\nYou have', tries, 'tries left.')
print('Used letters:', ' '.join(used_letters))
# What current word is (with underscores)
word_list = [letter if letter in used_letters else '_' for letter in word]
print(display_hangman(tries))
print('Current word:', ' '.join(word_list))
# Get user input
guess = input('Guess a letter: ').upper()
if guess in alphabet - used_letters:
used_letters.add(guess)
if guess in word_letters:
word_letters.remove(guess)
print('Good guess!')
else:
tries -= 1
print('Wrong guess.')
elif guess in used_letters:
print('You already used that letter. Please try again.')
else:
print('Invalid character. Please try again.')
# Game ended
if tries == 0:
print(display_hangman(0))
print('Sorry, you died. The word was', word)
else:
print('Congratulations! You guessed the word', word, '!!')
if __name__ == '__main__':
print("Welcome to Hangman!")
play_hangman()