Sunday, December 14, 2008

Example -- drawing the tic-tac-toe board

It's often easiest to use two-dimensional arrays with nested for loops. For example, the following code draws the tic-tac-toe board in a paint method. It assumes that a cell is 10 pixels on a side, and that a positive number represents an X and a negative number represents a O.
for (int row=0; row<3; row++) {
for (int col=0; col<3; col++) {
if (board[row][col] > 0) { // draw X
g.drawLine(col*10, row*10 , col*10+8, row*10+8);
g.drawLine(col*10, row*10+8, col*10+8, row*10 );
} else if (board[row][col] < 0) { // draw O
g.drawOval(col*10, row*10, 8, 8);
}
}
}

No comments: