9.1.7 Checkerboard V2 Codehs
The goal is typically to draw an 8x8 checkerboard with alternating black and red squares (or another color pair).
You need to draw an 8x8 grid. The squares must alternate colors:
The "V2" autograder on CodeHS is stricter. It may check for:
Pro Tip: Run your code with a board size of 4x4 first to verify the pattern before scaling to 8x8. 9.1.7 Checkerboard V2 Codehs
Expected 4x4 pattern:
R B R B
B R B R
R B R B
B R B R
// Constants for easy modification (Always use constants in V2!) const BOARD_SIZE = 400; const SQUARE_SIZE = BOARD_SIZE / 8; // 50px const COLOR_A = "red"; const COLOR_B = "black";function start() // Set up the canvas var board = new Rectangle(BOARD_SIZE, BOARD_SIZE); board.setPosition(0, 0); board.setColor("white"); add(board);
// Draw the checkerboard for (var row = 0; row < 8; row++) for (var col = 0; col < 8; col++) // Calculate the top-left corner of this square var x = col * SQUARE_SIZE; var y = row * SQUARE_SIZE; // Create the square var square = new Rectangle(SQUARE_SIZE, SQUARE_SIZE); square.setPosition(x, y); // Determine color using the alternating pattern if ((row + col) % 2 === 0) square.setColor(COLOR_A); else square.setColor(COLOR_B); // Add square to the canvas add(square);
Before jumping to the code, review these topics:
function start() var boardSize = 8; var squareSize = 50; var colors = ["red", "black"];for(var i = 0; i < boardSize; i++) for(var j = 0; j < boardSize; j++) var square = new Rectangle(squareSize, squareSize); square.setPosition(j * squareSize, i * squareSize); square.setColor(colors[(i + j) % 2]); add(square);
Bad Code:
if (row === 0 && col === 0) square.setColor("red");
if (row === 0 && col === 1) square.setColor("black");
// ... 62 more horrendous lines
Fix: Use the (row + col) % 2 formula. Never hardcode each tile.
If you are navigating the CodeHS Java (or JavaScript) curriculum, particularly in the "Advanced Arrays" or "Graphics" sections, you have likely encountered Exercise 9.1.7: Checkerboard V2. The goal is typically to draw an 8x8
At first glance, it seems simple: draw a checkerboard. However, this problem is a classic exercise in nested loops, conditional logic, coordinate math, and efficient rendering. It strips away the fluff of game logic and focuses on the core visual structure of an 8x8 grid.
This article will break down the problem, explore the common pitfalls, provide step-by-step solutions in both Java (Console/Graphics) and JavaScript (Web Graphics), and explain the underlying principles so you can truly master the concept.
