How to Create a Sudoku Game in Python

Python course with 57 real-time projects - Learn Python

It is one of the most popular puzzle games that we have been playing since our childhood. It’s a great brain game as it helps the player to improve their brain capacity. Let’s start developing the popular sudoku game and learn some amazing concepts while developing the project.

About Sudoku Game

In this puzzle game, the user has to fill a 9×9 grid with digits such that each row, each column and each of the 3×3 subgrids that form the grid contains the digit from 1 to 9.

Python Sudoku Game project

The main objective of the project is to develop a sudoku game. You need to install pygame in order to start the project. You need to import the pygame module for this project.

Project Prerequisites

This project requires good knowledge of python and pygame.

Download Python Sudoku Game

Please download source code of python sudoku game: Sudoku Game in Python

Project File Structure

Let’s start developing python sudoku game:

1. Installation of Pygame module
2. Initializing sudoku game window and variables
3. Function for highlighting selected cell
4. Function to draw lines for making sudoku grid
5. Function to fill value in the cell
6. Function for raising error when wrong value is entered
7. Function to check if the entered value is valid
8. Function to solve sudoku game
9. Function to show result
10. Rest code

1. Installation of Pygame module

Pygame is a cross-platform set of python modules that are specially designed for writing video games. It is necessary to install pygame before starting the project. To install pygame on your system, write the following command on your terminal window or cmd.

pip install pygame

2. Initializing sudoku game window and variables

import pygame
pygame.font.init()
Window = pygame.display.set_mode((500, 500))
pygame.display.set_caption("SUDOKU GAME by DataFlair")
x = 0
z = 0
diff = 500 / 9
value= 0
defaultgrid =[
        [0, 0, 4, 0, 6, 0, 0, 0, 5],
        [7, 8, 0, 4, 0, 0, 0, 2, 0],
        [0, 0, 2, 6, 0, 1, 0, 7, 8],
        [6, 1, 0, 0, 7, 5, 0, 0, 9],
        [0, 0, 7, 5, 4, 0, 0, 6, 1],
        [0, 0, 1, 7, 5, 0, 9, 3, 0],
        [0, 7, 0, 3, 0, 0, 0, 1, 0],
        [0, 4, 0, 2, 0, 6, 0, 0, 7],
        [0, 2, 0, 0, 0, 7, 4, 0, 0],
    ]
 
 
font = pygame.font.SysFont("comicsans", 40)
font1 = pygame.font.SysFont("comicsans", 20)

Code Explanation:

a. Pygame.display.set_mode: set_mode is a function inside the display module. It initializes the window and sets the size of the pygame window.
b. pygame.display.set_caption: It displays the title mentioned in the parenthesis on the top of the window.
c. defaultgrid: It is a nested list that will display a default 9×9 grid on the screen.
d. font.SysFont: It creates a font object from the system fonts.
e. diff : It is the size of a block.

3. Function for highlighting selected cell

def cord(pos):
    global x
    x = pos[0]//diff
    global z
    z = pos[1]//diff
 
def highlightbox():
    for k in range(2):
        pygame.draw.line(Window, (0, 0, 0), (x * diff-3, (z + k)*diff), (x * diff + diff + 3, (z + k)*diff), 7)
        pygame.draw.line(Window, (0, 0, 0), ( (x + k)* diff, z * diff ), ((x + k) * diff, z * diff + diff), 7) 

Code Explanation:

a. highlightbox: This function highlights the cell selected by the user.
b. pygame.draw.line(): It is a function that draws a straight line.

4. Function to draw lines for making sudoku grid

def drawlines():
    for i in range (9):
        for j in range (9):
            if defaultgrid[i][j]!= 0:
                pygame.draw.rect(Window, (255, 255, 0), (i * diff, j * diff, diff + 1, diff + 1))
                text1 = font.render(str(defaultgrid[i][j]), 1, (0, 0, 0))
                Window.blit(text1, (i * diff + 15, j * diff + 15))         
    for l in range(10):
        if l % 3 == 0 :
            thick = 7
        else:
            thick = 1
        pygame.draw.line(Window, (0, 0, 0), (0, l * diff), (500, l * diff), thick)
        pygame.draw.line(Window, (0, 0, 0), (l * diff, 0), (l * diff, 500), thick)

Code Explanation:

a. pygame.draw.rect(): It is a function that draws a rectangle.
b. font.render(): It renders the font.
c. Window.blit(): It copies the content of one surface onto another surface.

5. Function to fill value in the cell

def fillvalue(value):
    text1 = font.render(str(value), 1, (0, 0, 0))
    Window.blit(text1, (x * diff + 15, z * diff + 15))   

Code Explanation:

a. fillvalue(): This function fills the value entered by the user in the cell.
b. text1: It stores the digit entered by the user.

6. Function for raising error when wrong value is entered

def raiseerror():
    text1 = font.render("wrong!", 1, (0, 0, 0))
    Window.blit(text1, (20, 570)) 
def raiseerror1():
    text1 = font.render("wrong ! enter a valid key for the game", 1, (0, 0, 0))
    Window.blit(text1, (20, 570)) 

Code Explanation:

a. raiseerror() and raiseerror1(): These functions will generate error if the wrong value is entered.

7. Function to check if the entered value is valid

def validvalue(m, k, l, value):
    for it in range(9):
        if m[k][it]== value:
            return False
        if m[it][l]== value:
            return False
    it = k//3
    jt = l//3
    for k in range(it * 3, it * 3 + 3):
        for l in range (jt * 3, jt * 3 + 3):
            if m[k][l]== value:
                return False
    return True

Code Explanation:

a. validvalue(): This function checks whether the value entered by the user is valid or not.
b. range(): The sequence of numbers starting from 0 is returned by range() and increments the number every time by 1 and stops before the given number.

8. Function to solve sudoku game

def solvegame(defaultgrid, i, j):
     
    while defaultgrid[i][j]!= 0:
        if i<8:
            i+= 1
        elif i == 8 and j<8:
            i = 0
            j+= 1
        elif i == 8 and j == 8:
            return True
    pygame.event.pump()   
    for it in range(1, 10):
        if validvalue(defaultgrid, i, j, it)== True:
            defaultgrid[i][j]= it
            global x, z
            x = i
            z = j
            Window.fill((255, 255, 255))
            drawlines()
            highlightbox()
            pygame.display.update()
            pygame.time.delay(20)
            if solvegame(defaultgrid, i, j)== 1:
                return True
            else:
                defaultgrid[i][j]= 0
            Window.fill((0,0,0))
         
            drawlines()
            highlightbox()
            pygame.display.update()
            pygame.time.delay(50)   
    return False 

Code Explanation:

a. solvegame(): This function helps in solving the sudoku game.
b. pygame.event.pump(): This function puts every event in an event queue.
c. pygame.display.update(): This function helps to update a portion of the screen.
d. pygame.time.delay(): This function will pause for a given number of milliseconds on the basis of CPU clock.

9. Function to show result

def gameresult():
    text1 = font.render("game finished”, 1, (0, 0, 0))
    Window.blit(text1, (20, 570)) 
flag=True  
flag1 = 0
flag2 = 0
rs = 0
error = 0

Code Explanation:

a. gameresult(): This function displays the result after completing the game.
b. flag: It is used for running the window.

10. Rest Code

while flag:
    Window.fill((255,182,193))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            flag = False   
        if event.type == pygame.MOUSEBUTTONDOWN:
            flag1 = 1
            pos = pygame.mouse.get_pos()
            cord(pos)
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x-= 1
                flag1 = 1
            if event.key == pygame.K_RIGHT:
                x+= 1
                flag1 = 1
            if event.key == pygame.K_UP:
                y-= 1
                flag1 = 1
            if event.key == pygame.K_DOWN:
                y+= 1
                flag1 = 1   
            if event.key == pygame.K_1:
                value = 1
            if event.key == pygame.K_2:
                value = 2   
            if event.key == pygame.K_3:
                value = 3
            if event.key == pygame.K_4:
                value = 4
            if event.key == pygame.K_5:
                value = 5
            if event.key == pygame.K_6:
                value = 6
            if event.key == pygame.K_7:
                value = 7
            if event.key == pygame.K_8:
                value = 8
            if event.key == pygame.K_9:
                value = 9 
            if event.key == pygame.K_RETURN:
                flag2 = 1  
            if event.key == pygame.K_r:
                rs = 0
                error = 0
                flag2 = 0
                defaultgrid=[
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0]
                ]
            if event.key == pygame.K_d:
                rs = 0
                error = 0
                flag2 = 0
                defaultgrid  =[
                    [0, 0, 4, 0, 6, 0, 0, 0, 5],
                    [7, 8, 0, 4, 0, 0, 0, 2, 0],
                    [0, 0, 2, 6, 0, 1, 0, 7, 8],
                    [6, 1, 0, 0, 7, 5, 0, 0, 9],
                    [0, 0, 7, 5, 4, 0, 0, 6, 1],
                    [0, 0, 1, 7, 5, 0, 9, 3, 0],
                    [0, 7, 0, 3, 0, 0, 0, 1, 0],
                    [0, 4, 0, 2, 0, 6, 0, 0, 7],
                    [0, 2, 0, 0, 0, 7, 4, 0, 0],
                ]
    if flag2 == 1:
        if solvegame(defaultgrid , 0, 0)== False:
            error = 1
        else:
            rs = 1
        flag2 = 0   
    if value != 0:           
        fillvalue(value)
        if validvalue(defaultgrid , int(x), int(z), value)== True:
            defaultgrid[int(x)][int(z)]= value
            flag1 = 0
        else:
            defaultgrid[int(x)][int(z)]= 0
            raiseerror1()  
        value = 0   
       
    if error == 1:
        raiseerror() 
    if rs == 1:
        gameresult()       
    drawlines() 
    if flag1 == 1:
        highlightbox()      
    pygame.display.update() 
   
pygame.quit()    

Code Explanation:

a. pygame.QUIT: This function will quit the pygame window.
b. pygame.mouse.get_pos():It gets the position of the mouse so that the number can be entered.
c. pygame.KEYDOWN: It gets the number to be inserted if the keys are pressed.
d. pygame.K_LEFT: If the left arrow key is pressed, the position of the highlighted box will move towards left.
e. pygame.K_RIGHT: If the right arrow key is pressed, the position of the highlighted box will move towards right.
f. pygame.K_UP: If the up arrow key is pressed, the position of the highlighted box will move upwards.
g. pygame.K_DOWN: If the down arrow key is pressed, the position of the highlighted box will move downwards.

Python Sudoku Game Output

python sudoku game output

Summary:

We have successfully completed the development of Sudoku Game in Python. We learned the implementation of pygame while developing the project.

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google

follow dataflair on YouTube

6 Responses

  1. Venkat says:

    Can i play that puzzle..?

  2. Dickbutt says:

    this isn’t an explanation, you just commented your code

  3. karina says:

    how to play this game, after getting output, exactly shown in output section?

  4. whoknew says:

    There are errors with the default grid with numbers being repeated in columns, rows or sub-grid. Each sub-grid in the middle vertical column has repeated numbers. For example – The centre sub-grid contains the number “5” three times and the number “7” twice.

Leave a Reply

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