Create Hangman game in python with random popular English word

Hi, today we are going to learn a very interesting and popular game in the Python programming language. Name of the game is Hangman game. I think at a time almost everyone played this game.

 

What is a Hangman game – Word Guessing Game

Hangman game is a very popular game. We can guess the game from the game name, something is related to a man who is hanging.

This game is based on your guessing power. Any random English word will be selected. Maybe month name, animal name, etc but no slang language or any bad language, any sort form is not allowed in this game. The empty slots( ‘_ _ _ _’ )  will be given to you. You need to fill up the given empty places with the help of your guessing skill. If any correct letter you guess then the letter will be placed in the correct position on the empty slot. Then you can guess the word easily. The main twist in this game is you have limited chances of guessing the correct letters. For every wrong guess, the man will slowly be going to hang.  When you reach the limit the man will completely hang and you will lose the game. If you guess all the correct letters of the word the man will not be hanged and you will win the game.



So let’s start creating hangman game in Python.

 

hangman game in Python

hangman game in Python

In this image, we can easily remember the game.

Create a Hangman Game in Python

This game is actually a word guessing game. So who are not familiar with the game name ( Hangman) now they can easily understand.

Here an example of the game:

Your Wrong Guesses left : 8
_ _ _ _ _ _ Please enter a letter : t

Your Wrong Guesses left : 8
T _ _ _ _ _ Please enter a letter : a

Wrong ! Try again

Your Wrong Guesses left : 7
T _ _ _ _ _ Please enter a letter : b

Wrong ! Try again

Your Wrong Guesses left : 6
T _ _ _ _ _ Please enter a letter : c

Wrong ! Try again

Your Wrong Guesses left : 5
T _ _ _ _ _ Please enter a letter : d

Wrong ! Try again

Your Wrong Guesses left : 4
T _ _ _ _ _ Please enter a letter : e

Wrong ! Try again

Your Wrong Guesses left : 3
T _ _ _ _ _ Please enter a letter : f

Wrong ! Try again

Your Wrong Guesses left : 2
T _ _ _ _ _ Please enter a letter : e

Wrong ! Try again

Your Wrong Guesses left : 1
T _ _ _ _ _ Please enter a letter : q

Wrong ! Try again


Your Maximum Wrong Guesses Is Exceed !
You Lose !

Word is : THOUGH

Let’s see the code:

Requirements:

Step by step code to create this Python game

Here we have created a list and added the words from the text file one by one so that we can generate a random word later from this list of words.

You may check this tutorial: How to add items to a list from a text file in Python

import random

my_words =[]#created an empty list
f = open("google-10000-english-usa-no-swears.txt", "rt") # Importing the word collection text file
for x in f:
    word = str(x)
    word = word.rstrip("\n") # Removine'\n' character from the word
    if(len(word)>2): # We take the word which have more than 2 characters
        my_words.append(word)
f.close()

Explanation:

  • At first, we have imported the random library.
  • We have created an empty list (my_words ).
  • We used python file handling part for reading the text file.
  • Took the words which have more than 2 characters.

 

def pick(my_words): # This function will pick random one word
    rand_word = random.sample(my_words,1)
    rand_word = str(rand_word[0]).upper() # creating the word into uppercase
    return(rand_word)

Explanation:

  • Here we have created a ‘pick’ function for taking a random word from the ‘my_words’ list.
  • This function will return the random word.

 

def initial(rand_word): # This function will return '_' characters according to the selected word length
    sent = ''
    for i in range(len(rand_word)):
        sent+='_'
    return(sent)

Explanation:

  • Here we have created another function named ‘initial’.
  • This function will return the empty slots with ‘_’ character according to the selected random word length.

 

def usr_inp(get,word): # This function for taking the user input letter
    for i in get:
        print(i,end=' ')
    inp = input('Please Enter a Letter : ')
    inp = str(inp).upper()
    if (len(inp)>1 or inp==''):
        return(get)
    else:
        res = match(inp,get,word) # Calling the match function for checking the user input
        return(res)

Explanation:

  • This function ‘usr_inp’, the main task is to print the current empty slots. And take the user input letter and pass the user input to another function to check.

 

def match(inp,get,word): # This is the original function which will check if the user input right or wrong
    getl = list(get)
    for i in range (len(word)):
        if inp == word[i]:
            getl[i] = inp
    gts=''
    for x in getl:
        gts+=x
    return(gts)

Explanation:

  • Actually, this ‘match’ function is the main algorithm of the whole game.
  • This function will check if the user input is present in the selected random word. if found then place the letter into the empty slot.
  • Then return the empty slot with values.

 

def play(get,word): # This function is the main game Function
    var = 0
    max_limit = 8
    while True:
        
        
            
        if(var>=max_limit): # Checking the wrong chances reach the max limit
            print('')
            print('Your Maximum Wrong Guesses Is Exceed !')
            print('You Lose !')
            print('')
            print('Word is : ',word)
            break
            
        
        print("Your Wrong Guesses left :",(max_limit-var))
        ans = usr_inp(get,word)

        if(ans == get):
            print('')
            var+=1
            print('Wrong ! Try again')
            print('')
            
        else:
            get = ans
            print('')
            
        if(ans.count('_')== 0): # Checking if any '_' left or not
            print('')
            print('Yahoo ! You Win')
            print('')
            print('The Word Is : ',ans)
            break

Explanation:

  • This function ‘play’ is the main game function. Here is the main control of the game is present. For every wrong input guessing value will increase and the remaining chance will be decreased.
  • We checked if the ‘var’ reached with the maximum limit then you will Lose the game.
  • And we check here if no empty ‘_’ symbol is present in the string then you will Win the game.

 

word = pick(my_words) # Picking a randomword
get = initial(word) # Getting the empty structure
play(get,word) # Call the Game function

Explanation:

  • This is the game starting part.
  • Here we have selected any random word. Then we get the empty slot. Then we proceed to play the game.

An example:

Your Wrong Guesses left : 8
_ _ _ _ _ _ _ Please Enter a Letter : p

Your Wrong Guesses left : 8
P _ _ _ _ _ _ Please Enter a Letter : o

Your Wrong Guesses left : 8
P O _ _ _ _ _ Please Enter a Letter : r

Your Wrong Guesses left : 8
P O R _ _ _ _ Please Enter a Letter : s

Your Wrong Guesses left : 8
P O R S _ _ _ Please Enter a Letter : c

Your Wrong Guesses left : 8
P O R S C _ _ Please Enter a Letter : h

Your Wrong Guesses left : 8
P O R S C H _ Please Enter a Letter : e


Yahoo ! You Win

The Word Is :  PORSCHE

Whole code:

Text file link: https://github.com/first20hours/google-10000-english/blob/master/google-10000-english-no-swears.txt

The final code to create guess the word game in Python

import random

my_words =[]
f = open("google-10000-english-usa-no-swears.txt", "rt") # Importing the word collection text file
for x in f:
    word = str(x)
    word = word.rstrip("\n") # Removine'\n' character from the word
    if(len(word)>2): # We take the word which have more than 2 characters
        my_words.append(word)
f.close()

def pick(my_words): # This function will pick random one word
    rand_word = random.sample(my_words,1)
    rand_word = str(rand_word[0]).upper() # creating the word into uppercase
    return(rand_word)

def initial(rand_word): # This function will return '_' characters according to the selected word length
    sent = ''
    for i in range(len(rand_word)):
        sent+='_'
    return(sent)


def usr_inp(get,word): # This function for taking the user input letter
    for i in get:
        print(i,end=' ')
    inp = input('Please Enter a Letter : ')
    inp = str(inp).upper()
    if (len(inp)>1 or inp==''):
        return(get)
    else:
        res = match(inp,get,word) # Calling the match function for checking the user input
        return(res)

def match(inp,get,word): # This is the original function which will check if the user input right or wrong
    getl = list(get)
    for i in range (len(word)):
        if inp == word[i]:
            getl[i] = inp
    gts=''
    for x in getl:
        gts+=x
    return(gts)

def play(get,word): # This function is the main game Function
    var = 0
    max_limit = 8
    while True:
        
        
            
        if(var>=max_limit): # Checking the wrong chances reach the max limit
            print('')
            print('Your Maximum Wrong Guesses Is Exceed !')
            print('You Lose !')
            print('')
            print('Word is : ',word)
            break
            
        
        print("Your Wrong Guesses left :",(max_limit-var))
        ans = usr_inp(get,word)

        if(ans == get):
            print('')
            var+=1
            print('Wrong ! Try again')
            print('')
            
        else:
            get = ans
            print('')
            
        if(ans.count('_')== 0): # Checking if any '_' left or not
            print('')
            print('Yahoo ! You Win')
            print('')
            print('The Word Is : ',ans)
            break

word = pick(my_words) # Picking a randomword
get = initial(word) # Getting the empty structure
play(get,word) # Call the Game function

 

You may like to read:

 

Leave a Reply

Your email address will not be published. Required fields are marked *