Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Implemented Features
3.
Installation of PyGame Module
4.
Initializing the Sudoku Game Window and Variables
5.
Function for Highlighting a Selected Cell
6.
Function in order to Draw Lines for Making Sudoku Grid
7.
Function to fill a Value in the Cell
8.
Function for Raising an Error 
9.
Function to Check if the value Entered is Valid or Not
10.
Function to Solve Sudoku Game
11.
Function to Show the Result
12.
Rest Code
13.
Frequently Asked Questions
13.1.
What is pygame used for?
13.2.
Is Sudoku NP-complete?
13.3.
What is backtracking?
14.
Conclusion
Last Updated: Mar 27, 2024
Medium

Building and Visualizing Sudoku Game Using Pygame

Introduction

Sudoku is a number-placement puzzle with a logic component. The goal is to fill a 9x9 grid with digits so that each column, row, and each of the grid's nine 3x3 subgrids contain all of the digits from 1 to 9.
 

Here, we will create the Sudoku Game in Python using the pygame library and automate it with the backtracking algorithm.

Implemented Features

In order to start our journey in building and visualizing sudoku game using pygame, we will need to know about some implemented features, 

These implemented features include:

  • Playing Autosolving Game Interface
  • Backtracking Algorithm visualization, i.e., auto-solving visualization.
  • Options: Clear game, Reset

Requirements:

  • Pygame library must be installed beforehand.
  • Understanding of the Backtracking Algorithm.
     

In order to create a sudoku game using pygame, we will follow the following steps one by one:

 

Installation of PyGame Module

We all are interested in playing games, what about building games using pygame? Interesting!? Isn’t it?? Pygame is a cross-platform collection of Python modules designed specifically for creating video games. Before beginning the project, a pygame must be installed. To install pygame on your system, type the following command into your terminal or cmd window.

pip install pygame

Initializing the Sudoku Game Window and Variables

# import pygame library
import pygame
# initialise the pygame font
pygame.font.init()

# Total window
screen = pygame.display.set_mode((500, 600))
x = 0
y = 0
dif = 500 / 9
val = 0

# Default Sudoku Board.
grid =[
        [7, 8, 0, 4, 0, 0, 1, 2, 0],
        [6, 0, 0, 0, 7, 5, 0, 0, 9],
        [0, 0, 0, 6, 0, 1, 0, 7, 8],
        [0, 0, 7, 0, 4, 0, 2, 6, 0],
        [0, 0, 1, 0, 5, 0, 9, 3, 0],
        [9, 0, 4, 0, 6, 0, 0, 0, 5],
        [0, 7, 0, 3, 0, 0, 0, 1, 2],
        [1, 2, 0, 0, 0, 7, 4, 0, 0],
        [0, 4, 9, 2, 0, 6, 0, 0, 7]
]


# Load test fonts for future use
font1 = pygame.font.SysFont("comicsans", 40)
font2 = pygame.font.SysFont("comicsans", 20)

 

Explanation:

  1. Pygame.display.set_mode: The set mode is a display module function. It sets the size of the pygame window and initializes it.
  2. pygame.display.set_caption: This command displays the title specified in the parenthesis at the top of the window.
  3. defaultgrid: This is a nested list that displays a 9-by-9 grid on the screen.
  4. font.SysFont: This function generates a font object from the system fonts.
  5. diff: It specifies the size of a block.

Function for Highlighting a Selected Cell

def get_cord(pos):
       global x
       x = pos[0]//dif
       global y
       y = pos[1]//dif

# Highlight the cell selected
def draw_box():
       for i in range(2):
                pygame.draw.line(screen, (255, 0, 0), (x * dif-3, (y + i)*dif), (x * dif + dif + 3, (y + i)*dif), 7)
                pygame.draw.line(screen, (255, 0, 0), ( (x + i)* dif, y * dif ), ((x + i) * dif, y * dif + dif), 7)

 

Explanation:

  1. highlightbox: This function highlights the cell that the user has selected.
  2. pygame.draw.line(): This is a straight line drawing function.
     

Read Fibonacci Series in Python in detail.

Function in order to Draw Lines for Making Sudoku Grid

# Function to draw required lines for making Sudoku grid 
def draw():
       # Draw the lines

         for i in range (9):
                  for j in range (9):
                           if grid[i][j]!= 0:


                            # Fill blue color in already numbered grid
                            pygame.draw.rect(screen, (152,245,255), (i * dif, j * dif, dif + 1, dif + 1))


                                    # Fill grid with default numbers specified
                                    text1 = font1.render(str(grid[i][j]), 1, (0, 0, 0))
                                    screen.blit(text1, (i * dif + 15, j * dif + 15))
                                    
       # Draw lines horizontally and verticallyto form grid 
       for i in range(10):
                if i % 3 == 0 :
                         thick = 7
                else:
                         thick = 1
                         
                pygame.draw.line(screen, (0, 0, 0), (0, i * dif), (500, i * dif), thick)
                pygame.draw.line(screen, (0, 0, 0), (i * dif, 0), (i * dif, 500), thick)

 

Explanation:

  1. pygame.draw.rect(): This is a rectangle-drawing function.
  2. font.render(): This function renders the font.
  3. Window.blit(): This function copies the content of one surface to another.

Function to fill a Value in the Cell

# Fill value entered in cell
def draw_val(val):
       text1 = font1.render(str(val), 1, (0, 0, 0))
       screen.blit(text1, (x * dif + 15, y * dif + 15))

 

Explanation:

  1. fillvalue(): This function fills the cell with the value entered by the user.
  2. text1: It saves the user's entered digit.

Function for Raising an Error 

When the entered value is wrong, an error is raised.

# Raise error when wrong value entered
def raise_error1():
        text1 = font1.render("WRONG !!!", 1, (0, 0, 0))
        screen.blit(text1, (20, 570))
        
def raise_error2():
        text1 = font1.render("Wrong !!! Not a valid Key", 1, (0, 0, 0))
        screen.blit(text1, (20, 570))

 

Explanation:

  1. raise_error() and raise_error1(): If an incorrect value is entered, these functions will generate an error.

Function to Check if the value Entered is Valid or Not

# Check if the value entered in board is valid
def valid(m, i, j, val):
       for it in range(9):
                 if m[i][it]== val:
                            return False
                 if m[it][j]== val:
                            return False
                            
       it = i//3
       jt = j//3
       for i in range(it * 3, it * 3 + 3):
                for j in range (jt * 3, jt * 3 + 3):
                         if m[i][j]== val:
                                   return False
       return True

 

Explanation:

  1. validvalue(): This function determines whether or not the value entered by the user is valid.
  2. range(): range() returns a sequence of numbers beginning with 0 that increments the number by one every time and ends before the given number.

Function to Solve Sudoku Game

# Solves the sudoku board using the Backtracking Algorithm
def solve(grid, i, j):

    while grid[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 valid(grid, i, j, it)== True:
                   grid[i][j]= it
                   global x, y
                   x = i
                   y = j
                   # white color background
                   screen.fill((255, 255, 255))
                   draw()
                   draw_box()
                   pygame.display.update()
                   pygame.time.delay(20)
                   if solve(grid, i, j)== 1:
                              return True
                   else:
                              grid[i][j]= 0
                   # white color background\
                   screen.fill((255, 255, 255))

                  draw()
                  draw_box()
                  pygame.display.update()
                  pygame.time.delay(50)
     return False

 

Explanation:

  1. solvegame(): This function aids in the completion of the sudoku puzzle.
  2. pygame.event.pump(): This function places all events in a queue.
  3. pygame.display.update(): This function aids in the updating of a portion of the screen.
  4. pygame.time.delay(): This function will pause for a predetermined number of milliseconds based on the CPU clock.

Function to Show the Result

# Display instruction for the game
def instruction():
       text1 = font2.render("PRESS D TO RESET TO DEFAULT / R TO EMPTY", 1, (0, 0, 0))
       text2 = font2.render("ENTER VALUES AND PRESS ENTER TO VISUALIZE", 1, (0, 0, 0))
       screen.blit(text1, (20, 520))
       screen.blit(text2, (20, 540))


# Display options when solved
def result():
      text1 = font1.render("FINISHED PRESS R or D", 1, (0, 0, 0))
      screen.blit(text1, (20, 570))
run = True
flag1 = 0
flag2 = 0
rs = 0
error = 0

 

Explanation:

  1. gameresult(): This function displays the game's outcome after it has been completed.
  2. flag: It is used to start the window.

Rest Code

# The loop thats keep the window running
while run:

      # White color background
        screen.fill((255, 255, 255))
      # Loop through the events stored in event.get()
        for event in pygame.event.get():
            # Quit the game window
             if event.type == pygame.QUIT:
                  run = False
           # Get the mouse position to insert number
             if event.type == pygame.MOUSEBUTTONDOWN:
                 flag1 = 1
                 pos = pygame.mouse.get_pos()
                 get_cord(pos)
                 
           # Get the number to be inserted if key pressed
              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:
                            val = 1
                    if event.key == pygame.K_2:
                             val = 2
                    if event.key == pygame.K_3:
                             val = 3
                    if event.key == pygame.K_4:
                             val = 4
                    if event.key == pygame.K_5:
                             val = 5
                    if event.key == pygame.K_6:
                             val = 6
                    if event.key == pygame.K_7:
                             val = 7
                    if event.key == pygame.K_8:
                             val = 8
                    if event.key == pygame.K_9:
                             val = 9
                    if event.key == pygame.K_RETURN:
                             flag2 = 1
                    # If R pressed clear the sudoku board
                    if event.key == pygame.K_r:
                             rs = 0
                            error = 0
                            flag2 = 0
                            grid =[
                            [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 D is pressed reset the board to default
                   if event.key == pygame.K_d:
                            rs = 0
                            error = 0
                            flag2 = 0
                            grid =[
                            [7, 8, 0, 4, 0, 0, 1, 2, 0],
                            [6, 0, 0, 0, 7, 5, 0, 0, 9],
                            [0, 0, 0, 6, 0, 1, 0, 7, 8],
                            [0, 0, 7, 0, 4, 0, 2, 6, 0],
                            [0, 0, 1, 0, 5, 0, 9, 3, 0],
                            [9, 0, 4, 0, 6, 0, 0, 0, 5],
                            [0, 7, 0, 3, 0, 0, 0, 1, 2],
                            [1, 2, 0, 0, 0, 7, 4, 0, 0],
                            [0, 4, 9, 2, 0, 6, 0, 0, 7]
                            ]
             if flag2 == 1:
                  if solve(grid, 0, 0)== False:
                           error = 1
                  else:
                           rs = 1
                           flag2 = 0
             if val != 0: 
                  draw_val(val)
                  # print(x)
                  # print(y)
                  if valid(grid, int(x), int(y), val)== True:
                           grid[int(x)][int(y)]= val
                           flag1 = 0
                  else:
                           grid[int(x)][int(y)]= 0
                           raise_error2()
                  val = 0

            if error == 1:
                    raise_error1()
            if rs == 1:
                    result()
            draw()
            if flag1 == 1:
                    draw_box()
            instruction()


            # Update window
            pygame.display.update()


# Quit pygame window
pygame.quit()

 

Explanation:

  1. pygame.QUIT: Use this function to close the pygame window.
  2. pygame.mouse.get pos(): Gets the mouse position so that the number can be entered.
  3. pygame.KEYDOWN: If the keys are pressed, it returns the number to be inserted.
  4. pygame.K_LEFT: When the left arrow key is pressed, the highlighted box moves to the left.
  5. pygame.K_RIGHT: When the right arrow key is pressed, the highlighted box will move to the right.
  6. pygame.K_UP: When the up arrow key is pressed, the highlighted box moves upwards.
  7. pygame.K_DOWN: When the down arrow key is pressed, the highlighted box moves downwards.
     

Output:

 

Check out this problem - Optimal Strategy For A Game

Frequently Asked Questions

What is pygame used for?

The pygame library is an open-source module for the Python programming language that is designed to assist you in the creation of games and other multimedia applications. Pygame, which is based on the SDL (Simple DirectMedia Layer) development library, can run on a variety of platforms and operating systems.

Is Sudoku NP-complete?

When generalized to an nxn grid, Sudoku is NP-complete; however, a conventional 9x9 Sudoku is not.

What is backtracking?

Backtracking is an algorithmic technique used for recursively solving problems by attempting to build a solution one piece at a time, incrementally, removing those solutions that fail to satisfy the problem's constraints at any point in time (by time, here, is referred to as the time elapsed till reaching any level of the search tree).

Conclusion

In this article, we have extensively discussed the way of Building and Visualizing Sudoku games using Pygame.

We hope that this blog has helped you enhance your knowledge regarding Building and Visualizing Sudoku games using Pygame. Do upvote our blog to help other ninjas grow.

After reading about the Building and Visualizing Sudoku Game using Pygame, are you not feeling excited to read/explore more articles on the topic of Pygame? Don't worry; Coding Ninjas has you covered. To learn, see Operating SystemUnix File SystemFile System Routing, and File Input/Output.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! 

But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass