9.1.7 Checkerboard V2 Codehs [top]
Let's break down the solution for a basic 8x8 board.
# This is the logic for the checkerboard pattern: # If the sum of the row and column indices is even, make it red. # Otherwise, make it black. if (row + col) % 2 == 0: pen.color("red") else: pen.color("black")
If you want to write this more concisely (though CodeHS might prefer the loop method for grading), you can use a : board = [[(i + j + 1) % 2 for j in range(8)] for i in range(8)] If you'd like, I can help you: Debug your specific error message Explain how to change the grid size dynamically
This public link is valid for 7 days and shares a thread, including any personal information you added. This link or copies made by others cannot be deleted. If you share with third parties, their policies apply. Can’t copy the link right now. Try again later. 9.1.7 Checkerboard V2 Codehs
Depending on your specific language track in CodeHS (typically Java or JavaScript), you will implement nested for loops to traverse the matrix. 1. Initialize the Loops
function setup() createCanvas(400, 400); background(255);
// Set the size of the checkerboard var squareSize = 50; var rows = 8; var cols = 8; Let's break down the solution for a basic 8x8 board
s where the numbers alternate in a checkerboard pattern. The key is to use nested loops modulus operator ) to determine if a specific cell should be a based on its row and column indices. The Core Logic
def print_board(board): for i in range(len(board)): print(" ".join([str(x) for x in board[i]]))
Create a checkerboard pattern of squares in a graphics window using nested loops. Each square is the same size; squares alternate color (e.g., black and white). The pattern should form an N-by-N grid (commonly 8×8), and the top-left square’s color should follow the specification (typically black). if (row + col) % 2 == 0: pen
Translate the logic into Python code. Use a for loop to iterate through each row's index. Inside, for each row, convert each number to a string and join them with spaces before printing.
: Each square's x position is col * SQUARE_SIZE and its y position is row * SQUARE_SIZE . The Code Solution (JavaScript/karel) javascript
This approach is fine for an 8x8 board, but what if you needed a 12x12 board? That's a lot of repetitive code. A better, more professional approach is to write a function that can build a checkerboard of any size.
In CodeHS graphics (using the GraphicsProgram or Turtle ), you will use add(new Rectangle(x, y, width, height)) or similar methods.
// Move to next line after each row System.out.println();