For our purposes, a "board" is a
2-dimensional list of color names (strings like "red"). Our goal
here is to allocate the board in the init() function, and then to draw
the board in our draw functions (which will be called by the redrawAll
To help us
test our code, we will add a few lines in the init function to pre-load
a few cells in the board with some colors. This code will be
removed after this step. In particular, we will paint the
top-left cell red, the top-right cell white, the bottom-left cell
green, and bottom-right cell gray.
Here is how our code should paint the board at this point:
Writing the init function:
We'll have the run function take the rows and columns ("cols") as parameters, and use these values to create a properly sized window. To keep things simple, we'll also have the run function make the window non-resizable by adding the following line (right after canvas.pack()):
Next, the run function will store the rows and columns values in the canvas's data prior to calling the init function. Then, there are several tasks we need to do in the init function.
First, we need to allocate our board as a 2-dimensional list of names of colors, and fill it with our emptyColor ("blue"), as all cells are empty to start the game. We also need to store this board, and the emptyColor, in the canvas's data.
Finally, we add the temporary code to pre-load the 4 corner cells with colors for testing purposes:
# pre-load a few cells with known colors for testing purposes
board = "red" # top-left is red
board[cols-1] = "white" # top-right is white
board[rows-1] = "green" # bottom-left is green
board[rows-1][cols-1] = "gray" # bottom-right is gray
By convention, when we call run, we will use the default values of 15 rows and 10 columns: run(15, 10)
Writing the draw functions:
Our main draw function, drawGame, will be called by redrawAll. It will draw the background of the entire game (orange in the picture above), then it will use top-down design and call a new function, drawBoard, to draw the board.
To draw the board in the drawBoard function, we simply iterate over every cell (with two variables running over every row and column), and repeatedely call the drawCell function, which takes 4 parameters: the canvas, the row of the cell, the col of the cell, and the color of the cell (which for now is just the value in board[row][col]).
Finally, the drawCell function must draw the given cell using the color stored in the board list corresponding to that cell (that is, in board[row][col]). To draw a cell a given color, we will create two rectangles: an outer rectangle in the grid color (black) followed by an inner rectangle in the cell's color (other reasonable approaches exist, but we'll go with this one).