Hangman is a guessing game for two or more players. One player thinks of a word and the other(s) tries to guess it by suggesting letters within a certain number of guesses.
We will be making a similar Hangman Game using Python. We will be using fruits' names for words to guess.
The word to guess will be chosen from the list of words at random using 'random.choice()' method.
Save the below code in a file named 'hangman.py'.
import random
hang = ["""
H A N G M A N - Fruit Edition
+---+
| |
|
|
|
|
=========""", """
H A N G M A N - Fruits Edition
+---+
| |
O |
|
|
|
=========""", """
H A N G M A N - Fruits Edition
+---+
| |
O |
| |
|
|
=========""", """
H A N G M A N - Fruits Edition
+---+
| |
O |
/| |
|
|
=========""", """
H A N G M A N - Fruits Edition
+---+
| |
O |
/|\ |
|
|
=========""", """
H A N G M A N - Fruits Edition
+---+
| |
O |
/|\ |
/ |
|
=========""", """
H A N G M A N - Fruits Edition
+---+
| |
O |
/|\ |
/ \ |
|
========="""]
def getRandomWord():
words = ['apple', 'banana', 'mango', 'strawberry', 'orange', 'grape', 'pineapple', 'apricot',
'lemon', 'coconut', 'watermelon', 'cherry', 'papaya', 'berry', 'peach', 'lychee', 'muskmelon']
word = random.choice(words)
return word
def displayBoard(hang, missedLetters, correctLetters, secretWord):
print(hang[len(missedLetters)])
print()
print('Missed Letters:', end=' ')
for letter in missedLetters:
print(letter, end=' ')
print("\n")
blanks = '_' * len(secretWord)
for i in range(len(secretWord)): # replace blanks with correctly guessed letters
if secretWord[i] in correctLetters:
blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
for letter in blanks: # show the secret word with spaces in between each letter
print(letter, end=' ')
print("\n")
def getGuess(alreadyGuessed):
while True:
guess = input('Guess a letter: ')
guess = guess.lower()
if len(guess) != 1:
print('Please enter a single letter.')
elif guess in alreadyGuessed:
print('You have already guessed that letter. Choose again.')
elif guess not in 'abcdefghijklmnopqrstuvwxyz':
print('Please enter a LETTER.')
else:
return guess
def playAgain():
return input("\nDo you want to play again? ").lower().startswith('y')
missedLetters = ''
correctLetters = ''
secretWord = getRandomWord()
gameIsDone = False
while True:
displayBoard(hang, missedLetters, correctLetters, secretWord)
guess = getGuess(missedLetters + correctLetters)
if guess in secretWord:
correctLetters = correctLetters + guess
foundAllLetters = True
for i in range(len(secretWord)):
if secretWord[i] not in correctLetters:
foundAllLetters = False
break
if foundAllLetters:
print('\nYes! The secret word is "' +
secretWord + '"! You have won!')
gameIsDone = True
else:
missedLetters = missedLetters + guess
if len(missedLetters) == len(hang) - 1:
displayBoard(hang, missedLetters,
correctLetters, secretWord)
print('You have run out of guesses!\nAfter ' + str(len(missedLetters)) + ' missed guesses and ' +
str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"')
gameIsDone = True
if gameIsDone:
if playAgain():
missedLetters = ''
correctLetters = ''
gameIsDone = False
secretWord = getRandomWord()
else:
break
To run the game, enter the below command in a Terminal/Command Line:
python3 hangman.py
A sample output will look like this
H A N G M A N - Fruit Edition
+---+
| |
|
|
|
|
=========
Missed Letters:
_ _ _ _ _ _
Guess a letter: a
H A N G M A N - Fruits Edition
+---+
| |
O |
|
|
|
=========
Missed Letters: a
_ _ _ _ _ _
Guess a letter: b
H A N G M A N - Fruits Edition
+---+
| |
O |
| |
|
|
=========
Missed Letters: a b
_ _ _ _ _ _
Guess a letter: c
H A N G M A N - Fruits Edition
+---+
| |
O |
| |
|
|
=========
Missed Letters: a b
c _ _ _ _ _
Guess a letter: h
H A N G M A N - Fruits Edition
+---+
| |
O |
| |
|
|
=========
Missed Letters: a b
c h _ _ _ _
Guess a letter: e
H A N G M A N - Fruits Edition
+---+
| |
O |
| |
|
|
=========
Missed Letters: a b
c h e _ _ _
Guess a letter: r
H A N G M A N - Fruits Edition
+---+
| |
O |
| |
|
|
=========
Missed Letters: a b
c h e r r _
Guess a letter: y
Yes! The secret word is "cherry"! You have won!
Do you want to play again? no
Comments
Dejaswarooba
30-Jan-2023 10:35:25 PM