Here’s the Sudoku Game in Python Source Code

| |

Home » Here’s the Sudoku Game in Python Source Code
Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

This blog will look at how to create a game called sudoku in python. This post is not meant to be the be-all and end-all of sudoku games but it should be a good starting point for anyone who is looking for a new project to build and you can also use it in your resume. You can also use the Sudoku game in Python source code to update and make it for 10×10, 12×12, etc.

We are going to build a sudoku game using Python and PyGame. It will have a basic GUI that will load pre-loaded puzzles from an API then the user can fill in the rows and columns by tapping on the blocks.

What is a sudoku game?

Sudoku is a logic-based game and the goal is to fill in numbers into a 9×9 grid. Every single row must contain the numbers 1 to 9. And every column and sub-box of the grid must contain the number of times the number 1 appears equals to the number of times that 9 appears.

Things we need to do to build sudoku in Python

  1. Install pygame library.
  2. Creating a window frame for the game.
  3. Adding the 9×9 grid for numbers.
  4. Putting starting numbers of game grids using API.
  5. We will add input functionality which is used to input the digits in blank space.

Before we begin programming, let’s install a library called Pygame for Python. Using your Terminal / Command Prompt, enter the following command This will download and install the Pygame module, which we’ll be using throughout our project.

pip3 install pygame

This command will work in all operating systems (Windows, Linux & Mac)

Now let’s start programming:

# importing the pygame
import pygame
# importing request library
import requests

# setting up the width and the background color of the window
WIDTH = 550
background_color = (38, 38, 38)
original_grid_element_color = (255, 255, 255)
buffer = 5

In this section of the code, we imported the pygame library, request library (the request library used in python to get and post calls) and we also defined the background-color size of the window frame and grid colors.

#adding API in our sudoku game
response = requests.get("https://sugoku.herokuapp.com/board?difficulty=easy")
grid = response.json()['board']
grid_original = [[grid[x][y] for y in range(len(grid[0]))] for x in range(len(grid))]

Here, in this section, we are going to use an API and fetch the starting numbers in the grid and for that, we need sudoku API the reason that we cannot use any random number we need to have a proper set of numbers for the user can solve.

#adding the functionality that can add the number on user bases
def insert(win, position):
    i,j = position[1], position[0]
    #adding the font and its size
    myfont = pygame.font.SysFont('Comic Sans MS', 35)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
            if event.type == pygame.KEYDOWN:
                   
                if(grid_original[i-1][j-1] != 0):
                    return
                if(event.key == 48): #checking with 0
                    grid[i-1][j-1] = event.key - 48
                    pygame.draw.rect(win, background_color, (position[0]*50 + buffer, position[1]*50+ buffer,50 -2*buffer , 50 - 2*buffer))
                    pygame.display.update()
                    return
                if(0 < event.key - 48 <10):  #We are checking for valid input
                    pygame.draw.rect(win, background_color, (position[0]*50 + buffer, position[1]*50+ buffer,50 -2*buffer , 50 - 2*buffer))
                    value = myfont.render(str(event.key-48), True, (179, 179, 179))
                    win.blit(value, (position[0]*50 +15, position[1]*50))
                    grid[i-1][j-1] = event.key - 48
                    pygame.display.update()
                    return
                return

In this section of the code, we added the functionality of the sudoku game.

  • Adding the functionality that users can add numbers in black spaces to complete the game.
  • The user should not be able to edit the original number that is generated by API.
  • The users should be able to edit the user-added numbers because one may notice mistakes made and would want to correct that.
  • The user should be able to add any number in the blank spaces.

And we also added fonts style and fonts size for the digit

#initializing pygame
def main():   
    pygame.init()
    win = pygame.display.set_mode((WIDTH, WIDTH)) # creating the window
    pygame.display.set_caption("Sudoku")#giving caption
    win.fill(background_color) # filling the window with background color
    myfont = pygame.font.SysFont('Comic Sans MS', 35)  #adding the font and its size

In this section of the code, we initialize the pygame library and created the window frame gave it a caption and added the background color in the windows frame.

# creating grid
    for i in range(0,10):
        if(i%3 == 0):
            #drwaing the block line (vertical)
            pygame.draw.line(win, (255, 255, 255), (50 + 50*i, 50), (50 + 50*i ,500 ), 4 )
            #(Horizontal)
            pygame.draw.line(win, (255, 255, 255), (50, 50 + 50*i), (500, 50 + 50*i), 4 )

        #drwaing vertical line
        pygame.draw.line(win, (166, 166, 166), (50 + 50*i, 50), (50 + 50*i ,500 ), 2 )
        #drwaing horizental line
        pygame.draw.line(win, (166, 166, 166), (50, 50 + 50*i), (500, 50 + 50*i), 2 )
    pygame.display.update()
   
    for i in range(0, len(grid[0])):
        for j in range(0, len(grid[0])):
            if(0<grid[i][j]<10):
                value = myfont.render(str(grid[i][j]), True, original_grid_element_color)
                win.blit(value, ((j+1)*50 + 15, (i+1)*50 ))
    pygame.display.update()

In this section, we added the 9×9 grid defined the line size line thickness, and also added the bold lines for sudoku blocks.

#adding the function that if we press the quit key then the pygame window will close.   
    while True:
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
                pos = pygame.mouse.get_pos()
                insert(win, (pos[0]//50, pos[1]//50))
            if event.type == pygame.QUIT:
                pygame.quit()
                return
 
main()

And lastly, we add the function that if we press the quit key then the pygame window will close. 

Output:

After you’ve completed all of the steps required to build your Sudoku game, it will look similar to the above image and will have every feature we added during this process. Users cannot edit the digits that were originally placed into their spots users can input a new number into a blank space by clicking on the space and pressing any digit from 0 – 9 onto their keyboard. Users can only edit the digit they themselves added.

Final Words

Sudoku, a one-player game or puzzle. It starts with a 9×9 grid consisting of cells, some empty, and others that already have a number between 1 and 9. The 81 cells can be further divided into nine boxes of 3×3. When each box, column, and row contains the exact same number as before, the puzzle is complete. We shared the complete Sudoku Game in Python Source Code which you can use in your projects.

And in this article, we have explained how you can make that game. We covered everything you need to know about creating a sudoku game in python. We went over the basic logic of the game and how to get started and also went over a few different ways to get started. From installation to the actual creation. Needless to say, you now possess the skills to make your own sudoku game in Python! While there is always more to learn it’s great to have a deeper understanding of what goes into making some cool games. We hope you enjoyed this tutorial, if you have any questions or suggestions, feel free to leave a comment below. Thank you very much for reading!

Here are some useful tutorials that you can read:

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
Previous

How to create a single-page web app with Flask

Leave a Comment