The objective is to create a checkerboard pattern using a 2D array logic concept. You are usually provided with a Rectangle class and a Checkerboard class (which uses Grid).
In "Checkerboard v1", the standard logic is to determine the color of a square based on the sum of its row and column indices.
The Checkerboard v1 problem teaches:
The solution demonstrates how to create an alternating pattern without knowing the grid size in advance, an essential concept in robotics and grid-based programming. 9.1.6 checkerboard v1 codehs
Nested Loops:
for(int row = 0; row < size; row++): This loop runs for every row.for(int col = 0; col < size; col++): Inside every row, this loop runs for every column. This allows us to access every single cell in the grid.The Modulo Operator (%):
(row + col) % 2 == 0.% operator returns the remainder of division.Setting the Color:
Color.BLACK.Color.WHITE.Grid Integration:
grid.add(rect, row, col);: This line is crucial. It places the colored rectangle we just created onto the visual Grid window at the specific coordinates so the user can see the checkerboard pattern.Color.gray) and black (Color.black), or sometimes red and black.In this specific CodeHS exercise, you typically edit the file named Checkerboard.java. You are expected to fill in the logic inside the nested for loops to set the color of the Rectangle objects stored in a 2D array.
Here is the completed code for the relevant section: The Goal The objective is to create a
/* * This class represents a checkerboard. * It creates a grid of Rectangle objects. */ public class Checkerboard private Rectangle[][] board; private int size;public Checkerboard(int size) this.size = size; board = new Rectangle[size][size]; // Create the Grid to display the board Grid grid = new Grid(size, size, 50); // Nested loops to iterate through the 2D array for(int row = 0; row < size; row++) for(int col = 0; col < size; col++) // 1. Create a new Rectangle object Rectangle rect = new Rectangle(); // 2. Determine color based on row + col sum if((row + col) % 2 == 0) rect.setColor(Color.BLACK); else rect.setColor(Color.WHITE); // 3. Add the rectangle to the array board[row][col] = rect; // 4. Add the rectangle to the Grid to visualize it grid.add(rect, row, col);