Python Number Guessing Game Project with Source Code

FREE Online Courses: Enroll Now, Thank us Later!

Everybody loves playing games. Number games are so much fun and also so good for brain activities. In this project, we are going to create a fun Number Guessing game using python. Let us start making the project.

About Number Guessing Game Project

Today we are going to create a Number Guessing Game. This game is about creating an interactive game that will display scores and a person has to guess the number. There will be hints displayed every time the user guesses a wrong number. The objective of creating this project is to challenge our brains and add some fun while learning python.

Python Number Guessing Game Project Details

During the creation of the project, we are going to use two libraries-

1. Tkinter – Tkinter Module will help us create an easy GUI in python with lots of inbuilt functions that we will learn.

2. Random – We will use the Random Module to generate a random number that the user will be guessing. This number will only be known to the computer.

Project Prerequisites

To create this project we need to install the two libraries that we will be using for creation of the project. The commands are given below.

1. Tkinter –

pip install tk

2. Random –

pip install random

Download the Source Code for Number Guessing Game using Python

Before proceeding with the project, please download the source code of python number guessing game project: Python Number Guessing Game Code

Steps To Create Python Number Guessing Game Project

Below given are the steps to create the python Number Guessing Game:

  1. Import the required libraries
  2. Creating the GUI window
  3. Creating the Labels, Entry boxes and Buttons
  4. Create the Main Function – Execution of the game.

1. Importing the Required Libraries for Python Number Guessing Game

import tkinter as tk
from tkinter import *
import random
  • Tkinter Module – Tkinter Module will provide us with a lot of inbuilt functions that will help us with the creation of a GUI window.
  • Random Module – We will be using this module to generate a random number that the user will be guessing. Generating a random number will make the game very interesting and exciting.

2. Creating the GUI Window:

win = tk.Tk()
win.geometry("750x750")
win.title("PythonGeeks")
  • Using the TK() we make a window named win.
  • We specify the size of the window using the geometry() function and give a title to it using the title() function. Both these functions are a part of the Tkinter Module.

3. Creating the Labels, Entry Boxes and Button:

 
Entry(win, textvariable=guess, width=3,font=('Ubuntu', 50), relief=GROOVE).place(relx=0.5, rely=0.3, anchor=CENTER)
 
Entry(win, textvariable=hint, width=50,font=('Courier', 15), relief=GROOVE,bg='orange').place(relx=0.5, rely=0.7, anchor=CENTER)
 
Entry(win, text=final_score, width=2,font=('Ubuntu', 24), relief=GROOVE).place(relx=0.61, rely=0.85, anchor=CENTER)
 
Label(win, text='I challenge you to guess the number ',font=("Courier", 25)).place(relx=0.5, rely=0.09, anchor=CENTER)
 
Label(win, text='Score out of 5',font=("Courier", 25)).place(relx=0.3, rely=0.85, anchor=CENTER)
 
Button(win, width=8, text='CHECK', font=('Courier', 25), command=fun, relief=GROOVE,bg='light blue').place(relx=0.5, rely=0.5, anchor=CENTER)
  • As visible in the output, we have created an entry field using the Entry() function where we specify the width of the entry field, font, size of the text etc. To place this entry field, we make use of the place() function. In the place() function, we specify the x-y coordinates and also the anchor as center. There are a total of 3 Entry fields that we have created. They are-
    1. Entry area to enter a number.
    2. Displaying the current score.
    3. Displaying the hints.
  • We have created labels using the Label() function. These labels are primarily to display a text.To place this label, we make use of the place() function. In the place() function, we specify the x-y coordinates and also the anchor as center.
  • We create a Check Button which will check if the user’s number is equal to the number generated through the random module. command=fun will initiate the fun function which will generate hints and perform the comparison between the generated number and the number entered by the user.

4. Create The Main Function – Execution of the game:

num=random.randint(1,50)
  • Randint() – this function is to randomly generate a number in the specified range(here the range is 1-50). We have created a num variable and store the randomly generated number in this variable.
hint = StringVar()
score = IntVar()
final_score= IntVar()
guess= IntVar()
  • Hint- For displaying the hints. Using the StringVar() method we have specified that it is of string type.
  • Score – For displaying the score initially. Using the IntVar() method we have specified that it is of integer type.
  • Final_score – For displaying the updated score after every round or every guess. Using the IntVar() method we have specified that it is of integer type.
  • Guess – This stores the number that the user has entered.
hint.set("Guess a number between 1 to 50 ")
score.set(5)
final_score.set(score.get())

Using the set() method we set what will be the value of these variables when they are displayed on the window.

def fun():
    x=guess.get()
    final_score.set(score.get())
    if score.get()>0:
 
        if x > 20 or x<0:
            hint.set("You just lost 1 Chance")
            score.set(score.get()-1)
            final_score.set(score.get())
   
        elif num==x:
            hint.set("Congratulation YOU WON!!!")
            score.set(score.get()-1)
            final_score.set(score.get())
     
        elif num > x:
            hint.set("Your guess was too low: Guess a number higher ")
            score.set(score.get()-1)
            final_score.set(score.get())
        elif num < x:
            hint.set("Your guess was too High: Guess a number Lower ")
            score.set(score.get()-1)
            final_score.set(score.get())
    else:
         hint.set("Game Over You Lost")
  • We have created a function fun() to compare the number entered to the generated number and then after comparing make the necessary changes on the display window.
  • We have extracted the entered number using the get() method and saved its value in a variable x.
  • Using the if-else loops in python, we check if the number is equal to the generated number, less than, greater than or not in the range. According to these conditions we update the score and hints. Everytime a guess goes wrong the final score becomes one less so there are a total of 5 chances.
  • If the user guesses the right number, a congratulatory message is displayed. If a user loses all chances then a sorry message is displayed. We set the value of these variables as given in the conditions using the set() method.

Hurray! We have created the game successfully. Now let us play the games and have a look.

Python Number Guessing Game Output

This is how the window looks when opened. Let’s guess a random number.

Oh! we lost a chance. Look at the hint and repeat the process till you win or lose.

Oh no! We lost the game. Now you make the game and try if you can challenge your brain with this fun game.

python number guessing game output

Summary

We have successfully created the Number Guessing Game with the help of Tkinter Module and Random Module of Python. We learned about these modules and their inbuilt functions during the project.

Your opinion matters
Please write your valuable feedback about PythonGeeks on Google | Facebook


1 Response

  1. Dennis says:

    Thnx for helping me

Leave a Reply

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