Python Hangman – Word Guessing Game Program

FREE Online Courses: Transform Your Career – Enroll for Free!

In this project, we will develop Hangman Word Guessing Game using Python. Let’s start!!!

What is the Hangman Game?

Hangman is a school favorite game, a word game where the intention is surely to find the missing word or phrases. You will be supplied with a number of blank areas representing the missing letters you need to discover. In this project, there’s a list of words out of which the player will select 1 random word. The player is first asked to input any alphabet. If the secret word consists of that letter, then it will be shown because of the output; else the program will ask you to input every other alphabet. The user will be given 6 turns to bet the complete word.

Python Hangman Project Details

This is a simple Hangman game in python programming. Here we use the tkinter python library for creating a graphical user interface that is a GUI. Also, the random python module which selects any secret random word from the words list.

The word to guess is represented by dashes on the gaming screen. If the player guesses a letter that exists in the secret word then it will appear at the correct position in the secret word. The Player has 6 turns to guess the correct word. If we use all 6 turns then the game ends, you will get hang. And if the player guesses the word correctly, matching the length of spacing in display, then the player wins the game.

We are passing the message box that you have won or the game is over and do you want to play again? Yes or no. We can press the exit button if we want to quit the game.

Project Prerequisite

The hangman project requires good knowledge of python programming. And here we are creating the gui of the game so it also requires a good knowledge of the tkinter library.

Download Hangman Python Code

Please download the source code of python hangman from the following link: Python Hangman Project

Steps to Build a Python Hangman Game

Below are the steps to develop python word guessing hangman game:

1. Importing Modules random and tkinter
2. Creating main loop
3. Creating the dashes of secret word
4. Creating letters icon images and Hangman images.
5. Placing letters icon and hangman image on the gaming screen
6. Creating Exit function
7. Creating check word function

Step 1- Importing Modules random and tkinter

#PythonGeeks- import modules in python word guessing hangman game
import random
from tkinter import *
from tkinter import messagebox

Code Explanation-

  • Random module – Random module is an in-built module of Python useful to generate random words from list[].
  • Tkinter module – Tkinter is the standard interface in python for creating a GUI that is Graphical User Interface.
  • tkinter import * – import everything from the module.
  • from tkinter import messagebox – Import message box separately for showing messages on the screen.

Step 2 – Creating main loop in python word guessing game

#PythonGeeks- main loop
while run:
    root = Tk()
    root.geometry('905x700')
    root.title('HANGMAN BY PYTHONGEEKS')
    root.config(bg = '#ffffe7')
    count = 0
    win_count = 0
 
    words = ['programming', 'data', 'python', 'code', 'geeks', 'computer',  'engineer', 'word', 'science', 'machine', 'java', 'college', 'player', 'mobile', 'image']
    word = random.choice(words)

Code Explanation-

  • Here we have created a while loop in which we created a root variable.
  • root = Root is the variable under which all the variables like geometry, title, and config are called.
  • root.geometry- used to provide dimension of screen.
  • root.tite- Setting the title of the gaming screen that is ‘HANGMAN BY PYTHON GEEKS’
  • root.config – For setting background color.
  • count – Count is initialized to zero. If a guessed letter is not in the word then the count goes down and the maximum count is 6. If the count reaches 6 then the game is over.
  • win_count – If win_count is equal to the length of the word then this is a win case and the player wins the game.
  • words – It contains all the hangman words that we have to guess in the game.
  • word – we use the random module in this variable to randomly choose the word from words in the game.
  • random.choice – which selects any random word from the words.

Step 3 – Creating the dashes of secret word

#PythonGeeks- creation of word dashes variables
    x = 250
    for i in range(0,len(word)):
        x += 60
exec('d{}=Label(root,text="_",bg="#ffffe7",font=("arial",40))'.format(i))
exec('d{}.place(x={},y={})'.format(i,x,450))

Code Explanation-

  • x = 250 – length towards the starting point of dashes.
  • We don’t know what is the length of the word that is going to be selected because we are selecting a word using a random module so we keep the first dash at 250 and move each dash to +60 using a for loop.
  • exec – use this function for dynamic execution.
  • Label.format(i) – Use for creating a number of dashes using a for loop. Using parameters such as root, text, background color, font and font size.
  • .place – Use for placing dashes on the screen.

Step 4 – Creating letters icon images and Hangman images.

#PythonGeeks- Creating letters icon and Hangman images.
# letters icon
icon=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    for let in icon:
        exec('{}=PhotoImage(file="{}.png")'.format(let,let))

#hangman images
hangman_img = ['h1','h2','h3','h4','h5','h6','h7']
for hangman in hangman_img:
    exec('{}=PhotoImage(file="{}.png")'.format(hangman,hangman))

Code Explanation-

  • I have created png files of all the alphabets from A to Z that we are going to place on our gaming screen.
  • Icon – In this variable we have created a list of all the alphabets and then we iterate it using the for loop and exec function. Using this selector we can place all the image icons on the screen.
  • hangman_img – List which store the hangman images.
  • I have created all these images in paint and renamed them as h1,h2,h3, h4…h7 .
  • photoimage().format() – This widget supports the png file format as of tkinter.

Step 5 – Placing letters icon and hangman image on the screen

#PythonGeeks- Placing letters icon and hangman image on the screen
#Buttons placement
Button = [['btn1','a',0,595],['btn2','b',70,595],['btn3','c',140,595],['btn4','d',210,595],['btn5','e',280,595],['btn6','f',350,595],['btn7','g',420,595],['btn8','h',490,595],['btn9','i',560,595],['btn10','j',630,595],['btn11','k',700,595],['btn12','l',770,595],['btn13','m',840,595],['btn14','n',0,645],['btn15','o',70,645],['btn16','p',140,645],['btn17','q',210,645],['btn18','r',280,645],['b19','s',350,645],['btn20','t',420,645],['btn21','u',490,645],['btn22','v',560,645],['btn23','w',630,645],['btn24','x',700,645],['b25','y',770,645],['b26','z',840,645]]
 
    for p1 in Button:
        exec('{}=Button(root,bd=0,command=lambda:check("{}","{}"),bg="#ffffe7",activebackground="#ffffe7",font=10,image={})'.format(p1[0],p1[1],p1[0],p1[1]))
        exec('{}.place(x={},y={})'.format(p1[0],p1[2],p1[3]))
       
    #hangman placement
    hang = [['c1','h1'],['c2','h2'],['c3','h3'],['c4','h4'],['c5','h5'],['c6','h6'],['c7','h7']]
    for p1 in hang:
        exec('{}=Label(root,bg="#ffffe7",image={})'.format(p1[0],p1[1]))
 
    # placement of first hangman image
    c1.place(x = 300,y =- 50)

Code Explanation-

  • We have generated Letter buttons and hangman images and now place them on the gaming screen.
  • buttons – Here we have created a nested list button. Having 4 parameters in each inner list.
  • b1, b2,…b26 – Variables used for creating buttons
  • a, b,…z – Letters icon photo images.
  • 0, 70, 140, 210, … 840 – x coordinates. x coordinate will change by 70+ each time.
  • 595 and 645 are the y coordinates and y coordinate has two values 595 and 645.
  • Here we use the for loop to iterate all the buttons one by one using function check inside the exec function.
  • Button().format() – this function checks if the button is pressed using command check. Also using parameters root, border width, font and font size, bg means the screen when we didn’t click the button and active background means the screen when we click the button.
  • hang – Nested list of hangman images for placing hangman on the screen. Here c1 equals to label and h1 equals to image.
  • We use a for loop for iterating all img and in the exec function we use the label of formation (p1[0],p1[1])
  • c1.place – Used to place the first hangman image on the screen.

Step 6 – Creating exit function

#PythonGeeks- exit button
    def exit():
        global run
        answer = messagebox.askyesno('ALERT','DO YOU WANT TO EXIT THE GAME?')
        if answer == True:
            run = False
            root.destroy()
           
    E1 = PhotoImage(file = 'exit.png')
    Ex = Button(root,bd = 0,command = exit,bg="#ffffe7",activebackground = "#ffffe7",font = 10,image = E1)
    Ex.place(x=770,y=10)
    s2 = 'SCORE:'+str(score)
    s1 = Label(root,text = s2,bg = "#ffffe7",font = ("arial",25))
    s1.place(x = 10,y = 10)

Code Explanation-

  • close() – Function for quitting the game.
  • run – globaling the variable run.
  • message box – We are passing the message box to the player. Do you want to exit the game ? yes or no. If the player press yes the answer gets true and if the player presses no it gets false and it will be destroyed.
  • e1 – creating exit button image.
  • ex – using the button image gives the root, border width, active background and font command.
  • s2 – Storing the scored value.
  • s1.place – placing scored value on the gaming screen.

Step 7 – Creating check word function

#PythonGeeks- check function
    def check_word(letter,button):
        global count
        global win_count
        global run
        global score
        exec('{}.destroy()'.format(button))
        if letter in word:
            for i in range(0,len(word)):
                if word[i] == letter:
                    win_count += 1
                    exec('d{}.config(text="{}")'.format(i,letter.upper()))
            if win_count == len(word):
                score += 1
                answer = messagebox.askyesno('GAME OVER','YOU WON!\nDO WANT TO PLAY AGAIN?')
                if answer == True:
                    run = True
                    root.destroy()  
                else:
                    run = False
                    root.destroy()
        else:
            count += 1
            exec('c{}.destroy()'.format(count))
            exec('c{}.place(x={},y={})'.format(count+1,300,-50))
            if count == 6:
                answer = messagebox.askyesno('GAME OVER','YOU LOST!\nDO WANT TO PLAY AGAIN?')
                if answer == True:
                    run = True
                    score = 0
                    root.destroy()
                else:
                    run = False
                    root.destroy()        
    root.mainloop()

Code Explanation-

  • check_word(letter,button) – Check function gets executed if letters and buttons are pressed.
  • globling the count variable, win_count variable, run variable, score variable.
  • .destroy() – destroying the button using exec func.
  • If a guessed letter is present in the word then first it will check how many times this letter is present and then if all letters match with the words you will win.
  • .config(text) – Used to change dash into letters in the upper case as we mention in the exec function.
  • If win_count equals the length of the word then we pass the message box to the player that Game Over, you Won! Want to play again? yes or no.
  • else condition is executed when the letter is not there in the selected word. then increase the count to +1.
  • .destroy() – destroying the hangman 1st image
  • .place() – placing new hangman image
  • If the count is equal to 6. It means the player has input the wrong letters for the 6 times. So the max limit has been reached so the game is over and we pass the message box to the player that Game is over, you lost! Want to play again? yes or no. And the score will be 0.
  • root.mainloop() – this is where the program ends.

Python Hangman Game Output

You played well. You won the hangman game

python hangmangame output

Learning from Python Hangman project

What do you learn from Playing Hangman?

The Hangman game supports students/ kids to be interested in English spelling, vocabulary. It is also able to spell English words fluently and also identify the meaning of words.

Summary

Hangman has been our most advanced game yet, and we have learned several new concepts while making it.

In the conclusion of this project, Hangman is typically played with words. It’s possible, however, to play the category Hangman rather than guessing words; the participant may guess names of towns, or athletes, or fictional characters, or anything else; the listing is limitless. You’ll be writing software to play a “guess a secret word letter – by – letter” model of hangman as proven above. You’ll additionally be doing a little statistical analysis of the phrases used inside the Hangman game.

Did we exceed your expectations?
If Yes, share your valuable feedback on Google | Facebook


Leave a Reply

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