forked from Rits1272/PythonPrograms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhangman.py
142 lines (70 loc) · 2.77 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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import random
from collections import Counter
somewords = '''apple banana mango strawberry
orange grape pineapple apricot lemon coconut watermelon
cherry papaya berry peach lychee muskmelon'''
somewords = somewords.split(' ')
word = random.choice(somewords)
print(word)
if __name__ == '__main__':
print('Guess the word! HINT: word is a name of a fruit.')
for i in word:
print('_', end=' ')
print()
playing = True
letterGuessed = ''
chances = len(word) + 2
correct = 0
flag = 0
try:
while(chances != 0) and flag == 0:
print()
chances -= 1
try:
guess = str(input("Enter a letter to guess : "))
except:
print('Enter only a letter')
continue
# Validation of the guess
if not guess.isalpha(): #isalpha = isalphabet
print('Enter only a LETTER')
continue
elif len(guess) > 1:
print('Only a single letter')
continue
elif guess is letterGuessed:
print("You have already guessed that letter")
continue
# If letter is guessed correctly
if guess in word:
k = word.count(guess) # k = {'a': 3}
# k stores the number of times the guess appears in the
# the secret word
for _ in range(k):
letterGuessed += guess
# Print the word
for char in word:
if char in letterGuessed and (Counter(letterGuessed)):
print(char, end=' ')
correct += 1
# if user has guessed all the letters
elif (Counter(letterGuessed) == Counter(word)):
print("The word is : ", end='')
print(word)
flag = 1
print('Congratulations you won!')
break
break
else:
print('_', end= ' ')
print()
print('You have {} chances left'.format(chances))
# If user has used all of his chances.
if chances <= 0 and (Counter(letterGuessed) != Counter(word)):
print()
print("You lost! Try again")
print('The word was {}'.format(word))
except KeyboardInterrupt:
print()
print("Bye! Try again.")
exit()