Site icon TechVidvan

Number Guessing Game in Python with Source Code

number guessing game python

Guessing a number is a fun game that involves us to relate the clues the system gives us. This fun, yet provoking game is a simple way to keep our mind stimulated.

Python Number Guessing Game Project:

We will create a simple number guessing game using python and display the scores the player gets if he/she wins. This project will serve as an introduction to functions and creating GUI using Tkinter.

Project Prerequisites:

The project makes use of Tkinter for GUI, random module for generating random targets and clues. Since we use Tkinter which is a built-in GUI library in python, we check it by importing it

python
import tkinter

If the library is installed, it will not show an error. If you face any error whilst importing Tkinter, refer Tkinter Installation

Download Number Guessing Game Code:

You can download the source code for the Number Guessing Game from the following link: Number Guessing Game

Project File Structure:

There are many GUI libraries supported by python such as PyQT5, Kivy, Pyside2 etc. Tkinter is widely used by many developers and is easy for beginners to practise.

Let’s have a look at the steps to build the project:

  1. Importing modules: tkinter, random and declaring variables
  2. Declaring clue functions
  3. Declaring and defining guess and target number functions
  4. Creating the user input interface

Feel free to play with the values and change your input methods. 

1. Importing necessary modules for Python Number Guessing Game:

#TechVidvan's Number Guessing Game
#Import modules
import random
from tkinter import *
from tkinter import messagebox
 
#Declare and initialise variables
target = 0
score = 10
guess=0

Code Explanation:

2. Declaring clue functions:

#Define the clue functions
def add():
   return "The sum of target and guess is " + str(guess+target)
 
def sub():
   return "The difference of target and guess is " + str(target-guess)
 
def multiplication():
   return "The product of target and guess is " + str(guess*target)
 
def division():
   return "The division of target by guess is " + str(target/guess)
 
def greater_lesser():
   if target < guess:
       return 'Target is less than the guess'
   elif target > guess:
       return 'Target is greater than the guess'

Code explanation: 

3. Declaring and defining guess and target number functions:

#Create the random clue generator
def clues():
   switcher = {
       0: add(),
       1: sub(),
       2: multiplication(),
       3: division(),
       4: greater_lesser()
       }
   return switcher.get(random.randint(0,4))

Code explanation: 

#Generate the target value
def generate_target_number():  
   global target
   target = random.randint(1,10)
   messagebox.showinfo(message="Random Number Generated; Start Guessing!! STARTING SCORE=10")
   #Disable the random number button until game ends   
   random_number_button['state'] = DISABLED 
   #Activate the guessing button
   guess_button['state'] = NORMAL

Code explanation: 

#Guess and score by reading user input
def guess_and_score():
   #Make variables global for access across functions
   global score
   global guess
   try:
       guess =0
       #Read if user submitted an input
       guess = int(guess_entry.get())
   except:
       messagebox.showerror(message="Enter a number to guess and play")
       return
   #If target and guess are the same, print score and prompt to user
   if guess == target:
       messagebox.showinfo(message="Congratulations!!! You guessed the number correct. Your score is "+str(score))
       #Enable random number button to play a new game and disable guessing button
       random_number_button['state'] = NORMAL
       guess_button['state'] = DISABLED 
       return
   #If the user runs out of guesses
   elif score == 0:
       messagebox.showwarning(message="Out of Guesses Buddy! Better luck next time );")
       return
   #Call the guessing functions to give the clues
   else:
       score -= 1
       message=clues()
       messagebox.showinfo(message=message)

Code explanation:

4. Creating  the user input interface:

 

#Create the user interface, specify the dimensions of the application window for Python Number Guessing project
window  = Tk()
window.geometry("350x200")
window.title("TechVidvan's Number Guessing Game")
 
#Mention the title of the app
title_label = Label(window, text="TechVidvan's Number Guessing Game\nGuess a number between 1 to 50", font=('Ubuntu Mono',12))
title_label.pack()
 
#Generate random number
random_number_button = Button(window, text="Generate Random Number", command=generate_target_number)
random_number_button.pack()
#Read User input
guess_label = Label(window, text="Enter your guess: ")
guess_label.pack()
guess_entry = Entry(window, width=3)
guess_entry.pack()
#Start guessing
guess_button = Button(window, text="Guess Me", command=guess_and_score, state=DISABLED)
guess_button.pack()
#Exit and close the app
window.mainloop()

Code explanation:

Python Number Guessing Output

Play the number guessing game by starting the random number generator and get the following output:

Summary

Thus, we created a simple project to understand and create our functions to provide clues and calculate the scores of the games. We also created a GUI using tkinter to provide an interface 

Exit mobile version