Initialize the Sudoku Board and Set its Properties
Create the utility functions to initialize the Sudoku board.
We'll cover the following
Introduction
Let's start by developing the building blocks of our Sudoku game. We'll be using a third-party API that will provide us with a matrix prefilled with the numbers. We will then need to fill the empty cells of the matrix using recursion and backtracking. But before that, we will be performing the following steps to render the Sudoku board on the web page:
Create the HTML
div
elements for each cell of the Sudoku board.Write a utility function to load all the
div
elements for each cell and store them in a 2D array, so that eachdiv
element in the2D array corresponds to a cell of the Sudoku board on the HTML page. For example, a div
element at position (0, 3) indicates the fourth element in the first row of the Sudoku board. Recall that the indexing of arrays starts from 0.Write a utility function to initialize a
2D array with a boolean flag to determine whether each cell in the Sudoku board is filled or not. Initially, all the values will be false
because the board is empty.Write a utility function to initialize the color for the numbers displayed in each cell. Since each cell is created using a
div
element, we can set thecolor
property for eachdiv
element. We will use the colorgreen
to initialize all the cells.Write a utility function to set a different color for the filled cells. This is to differentiate between the filled cells and empty cells.
Now let's start the implementation.
Create the HTML div
elements for each cell
First we'll create the HTML web page and apply styling to its elements. Since there are 81 cells in a div
elements, each of which will denote one cell of the Sudoku board. We'll also add an id
attribute to each div
element, corresponding to the cell number of the Sudoku board. Now let's see the code:
Get hands-on with 1400+ tech skills courses.