Skip to content

Commit 63db2eb

Browse files
committed
Python Hangman Game
1 parent b43a60e commit 63db2eb

File tree

1 file changed

+36
-3
lines changed

1 file changed

+36
-3
lines changed

Programs/P37_HangmanGame.py

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
# This is just an example of how we can use Python for some gaming problems.
33

44
import random
5+
from collections import Counter
56

67
someWords = '''apple banana mango strawberry orange grape pineapple apricot lemon coconut watermelon
78
cherry papaya berry peach lychee muskmelon'''
@@ -16,13 +17,32 @@
1617
print()
1718

1819
playing = True
19-
2020
letterGuessed = ''
21+
chances = len(word) + 2
22+
correct = 0
2123

2224
try:
23-
while playing == True:
25+
while (chances != 0):
2426
print()
25-
guess = str(input('Enter a letter to guess: '))
27+
chances -= 1
28+
29+
try:
30+
guess = str(input('Enter a letter to guess: '))
31+
except:
32+
print('Enter only a letter!')
33+
continue
34+
35+
# Validation of the guess
36+
if not guess.isalpha():
37+
print('Enter only a LETTER')
38+
continue
39+
elif len(guess) > 1:
40+
print('Enter only a SINGLE letter')
41+
continue
42+
elif guess in letterGuessed:
43+
print('You have already guessed that letter')
44+
continue
45+
2646

2747
# If letter is guessed correcly
2848
if guess in word:
@@ -32,9 +52,22 @@
3252
for char in word:
3353
if char in letterGuessed:
3454
print(char, end = ' ')
55+
correct += 1
3556
else:
3657
print('_', end = ' ')
3758

59+
# If user has guessed all the letters
60+
if (Counter(letterGuessed) == Counter(word)):
61+
print()
62+
print('Congratulations, You won!')
63+
break
64+
65+
# If user has used all of his chances
66+
if chances == 0:
67+
print()
68+
print('You lost! Try again..')
69+
print('The word was {}'.format(word))
70+
3871
except KeyboardInterrupt:
3972
print()
4073
print('Bye! Try again.')

0 commit comments

Comments
 (0)