9.1.7 Checkerboard V2 Answers -
Even with the correct code, students often hit frustrating roadblocks. Here’s a quick troubleshooting table:
| Error Message / Symptom | Likely Cause | Solution |
|-------------------------|--------------|----------|
| Square is not filled | Missing setFilled(true) | Add the line before setting the color. |
| All squares are the same color | Incorrect modulus logic | Use (row + col) % 2 == 0. Check your starting color. |
| ArrayIndexOutOfBoundsException | Using <= instead of < in loop | Ensure loops run 0 to 7 (not 0 to 8). |
| Nothing appears on screen | Forgot to call add(square) | After creating and coloring, call add(square). |
| Squares overlap or have gaps | Incorrect coordinate math | x = col * size, y = row * size. Don’t add extra offset. |
| Autograder fails on style | Missing constants or comments | Use private static final int for magic numbers (8, 50). |
Let’s outline a generic solution in pseudocode: 9.1.7 checkerboard v2 answers
function draw_checkerboard(rows, cols, colorA, colorB, top_left_is_colorA):
for r from 0 to rows-1:
for c from 0 to cols-1:
if (r + c) % 2 == 0:
color = colorA if top_left_is_colorA else colorB
else:
color = colorB if top_left_is_colorA else colorA
draw_square_at(r, c, color)
Deep point: The condition (r + c) % 2 naturally alternates. The top_left_is_colorA flag just swaps which color gets the even sum.
The checkerboard problem usually requires creating a program that can: Even with the correct code, students often hit
import java.awt.Color; import acm.graphics.*; import acm.program.*;public class CheckerboardV2 extends GraphicsProgram
private static final int ROWS = 8; private static final int COLS = 8; private static final int SQUARE_SIZE = 50; public void run() // Create a 2D array to store colors Color[][] checkerboard = new Color[ROWS][COLS]; // Fill the array with alternating colors for (int row = 0; row < ROWS; row++) for (int col = 0; col < COLS; col++) if ((row + col) % 2 == 0) checkerboard[row][col] = Color.RED; else checkerboard[row][col] = Color.BLACK; // Draw the checkerboard using the stored colors for (int row = 0; row < ROWS; row++) for (int col = 0; col < COLS; col++) int x = col * SQUARE_SIZE; int y = row * SQUARE_SIZE; GRect square = new GRect(x, y, SQUARE_SIZE, SQUARE_SIZE); square.setFilled(true); square.setFillColor(checkerboard[row][col]); add(square);
Here is a simple Python solution to generate a checkerboard pattern: Let’s outline a generic solution in pseudocode: function
def print_checkerboard():
for row in range(8):
for col in range(8):
# Use the sum of row and column indices to determine the color
if (row + col) % 2 == 0:
print('\033[40m ', end='') # Black
else:
print('\033[47m ', end='') # White
print('\033[0m') # Reset color
print_checkerboard()
This script prints a simple text-based checkerboard to the console. The colors are represented using ANSI escape codes.
To make each square stand out, add:
square.setBorderColor(Color.WHITE);