Code

Stripes and Checkers

To paint every pixel, put one loop inside another. The outer loop picks a row, the inner loop visits each pixel in that row.

for y in range(canvas.height):
    for x in range(canvas.width):
        canvas.set(x, y, "sky")

canvas.width and canvas.height tell you the canvas size, so the same code works for any size.

Patterns with %

% gives the remainder after dividing. x % 2 is 0 for even numbers and 1 for odd ones. That makes repeating patterns:

if x % 2 == 0:
    color = "gold"
else:
    color = "navy"

For a checkerboard, add the two coordinates. When x + y is even you are on one colour; when it is odd, on the other. Moving one step in any direction flips it.

Pip tip: Want bigger squares? Try (x // 2 + y // 2) % 2.

Assignment

  1. stripes(canvas, a, b): paint every pixel. Column x gets colour a when x is even and colour b when it is odd.
  2. checkers(canvas, a, b): paint every pixel. Pixel (x, y) gets a when x + y is even, otherwise b.
  3. Both must work for any canvas size (use canvas.width and canvas.height). The program already draws an 8 × 8 board.