For our purposes, a "board" is a 2-dimensional array of
Color objects. Our goal here is to allocate the board in a
constructor, and then to paint the board in our paint methods.
To help us test our code, we will add a few lines in the
constructor 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 constructor:
We'll have the constructor take the rows and columns ("cols") as parameters.
There are several tasks we need to do here. First, we simply need to
store the rows and cols in instance variables.
Next, we need to allocate our board as a 2-dimensional array of Color
objects, and fill it with our emptyColor, as all cells are empty to start
the game.
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[0][0] = Color.red; // top-left is red
board[0][cols-1] = Color.white; // top-right is white
board[rows-1][0] = Color.green; // bottom-left is green
board[rows-1][cols-1] = Color.gray; // bottom-right is gray
}
As an extra step, we add a second constructor, which provides default
values for the rows and cols:
public Tetris() { this(Tetris.DEFAULT_ROWS,Tetris.DEFAULT_COLS); }
By convention, the default values are 15 rows and 10 columns.
Writing the paint methods:
Our main paint method will paint the background of the entire component
(orange in the picture above), then it will use top-down design and call a
new method, paintBoard, to paint the board.
To paint the board in the paintBoard method, we simply iterate over every cell (with two
variables running over every row and column), and paint that cell using the
color stored in the board array corresponding to that cell (that is, in this.board[row][col]).
And, finally, to paint a cell a given color, we will paint an outer rectangle in the grid color followed by an
inner rectangle in the cell's color (other reasonable approaches exist, but
we'll go with this one).
David Kosbie |