Hangman is a guessing game played by two players. One player thinks of a word and the other player tries to guess it by trying one alphabet at a time with a limited number of tries. It usually is played with paper and pencil but wait a minute, you already know what Hangman is and you probably have played it. So what is this article really about?
This article is a step-by-step guide to building the Hangman game with Python. We will write functions to make the code more modular and readable. We will be using loops to parse through the string and use conditional statements to accept or reject a guess. The word will initially be represented by dashes and as we provide the right guesses they will be replaced by the guess.
Rules of the Game
- If the player makes a wrong guess, the number of chances decreases by one, and the wrong guess is saved.
- If the player makes a right guess, the dashes which correspond to that guess get replaced with that guess and the guess is saved with no reduction in the number of chances.
- If the player guesses a letter that he has already guessed then no chances are detected and he is prompted with a message saying he has already guessed it.
- If the player uses all of his chances and is still unable to guess the word then it's game over.
- If the player is able to guess the word correctly then he/she wins the game.
Let's code
For playing this game we require a source for the words. You can find a file in the repository called words.txt which has a plethora of words that can be used for this purpose. So our first step would be to read the text from the words.txt file. The function loadWords() performs this action. After this step, we need to select a word at random which will serve as the secret word which needs to be guessed. The function chooseWord() performs this action. We import the module random for performing the random selection.
def loadWords():
with open("words.txt", 'r') as G:
textfile = G.read()
return textfile
def chooseWord():
textfile = loadWords()
sl = textfile.split()
return(random.choice(sl))
We call the chooseWord() function to get the secret word and pass it to the hangman() function which is the driver function for our game. After every guess, we need to make sure whether the word has been guessed correctly or not. This is performed by the isWordGuessed() function. It takes the secret word and the lettersGuessed as parameters and returns true if all the letters in the secret word are present in lettersGuessed else it returns false. If this function returns true it means that the player has guessed the word correctly and he wins the game.
The next function is getAvailableLetters() which returns the alphabets which have not yet been guessed yet. It takes the alphabets which have been guessed as the parameter. The final helper function is getGuessedWord(). This function is responsible for displaying the dashes and the alphabets which have been guessed correctly. On every successful guess, the dash is replaced with the correct guess.
def isWordGuessed(secretWord, lettersGuessed):
for i in secretWord:
if i not in lettersGuessed:
return False
return True
def getGuessedWord(secretWord, lettersGuessed):
l = len(secretWord)
s = ["_ "]*l
for i in range(l):
if secretWord[i] in lettersGuessed:
pos = i
for j in range(l):
if(pos == j):
s[pos] = secretWord[i]+" "
return("".join(s))
def getAvailableLetters(lettersGuessed):
alph = "abcdefghijklmnopqrstuvwxyz"
r = ""
for i in alph:
if i not in lettersGuessed:
r = r+i
return(r)
Finally, we are at the hangman() function. This function takes the secret word as the parameter and drives the whole game. There is a loop that keeps running till the user guesses the word correctly or the user has extinguished all his/her guesses. Conditions are in place to make sure that we don't enter anything other than alphabets and enter only one alphabet at a time. Helper functions are called after every guess and decisions are taken based on the guess.
def hangman(secretWord):
numguess = 8
lettersGuessed = []
print()
print("Welcome to the game hangman")
print(f"I am thinking of a word that is {len(secretWord)} words long")
print("------------------------")
while(True):
print("you have", numguess, " guesses left")
print("Available Letters:", getAvailableLetters(lettersGuessed))
guess = input("Please guess a letter: ")
if(len(guess) != 1):
print("Please enter only one letter")
elif(guess not in "abcdefghijklmnopqrstuvwxyz"):
print("Please Enter only lowercase Alphabets")
else:
guessInLowerCase = guess.lower()
if(guessInLowerCase in secretWord and guessInLowerCase not in lettersGuessed):
lettersGuessed.append(guessInLowerCase)
print("Good Guess:", getGuessedWord(
secretWord, lettersGuessed))
elif(guessInLowerCase in lettersGuessed):
print(f"Oops!! {guessInLowerCase} has been guessed before", getGuessedWord(
secretWord, lettersGuessed))
else:
print(f"Oops {guessInLowerCase} is not in my word",
getGuessedWord(secretWord, lettersGuessed))
lettersGuessed.append(guessInLowerCase)
numguess = numguess-1
print("_______________")
if(isWordGuessed(secretWord, lettersGuessed) == True):
print("Congratulations u have won!!")
break
if(numguess == 0):
print(f"Sorry u ran out of guesses.the word is {secretWord}")
break
Working of the game
The game begins by running the play_hangman.py file. There are totally 8 chances for guessing and if we wish to vary the toughness of the game, we can increase or decrease it.
If we guess the letter correctly it says that it was a good guess and displays the position of the guess. In this case, we have guessed ‘a' and it displays ‘a' in its apparent position. We also get available letters that can be used to guess the next letter. As ‘a' has been guessed correctly it will not be in the available letters. Since it is a correct guess the number of guesses remains the same.
If we have guessed the word wrongly. The number of guesses will decrease by one and the available letters will not include the wrong guess.
That's it. We have created our very own hangman game from scratch using Python. We can also improve the game by providing clues regarding the secret word. The code for this can be found in Prithivee7/Hangman (github.com)
Want to Connect?_
If you have enjoyed this article, please follow me here on Medium for more stories about machine learning and computer science._
Linked In — Prithivee Ramalingam