Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing a checkerboard in Python

I am trying to write a Python program which uses a graphics.py file and creates a checkerboard (like a chess board) with 64 squares alternating black and white. However, I am not able to get anything printed.

Here is my code so far. Please feel free to tear down the whole code or make any changes.

from graphics import GraphicsWindow

win = GraphicsWindow(400,400)
canvas = win.canvas()

for j in range(10, 90, 10):
    for j in range(10, 90, 20):
        if j % 2 == 1:
            for i in 10, 30, 50, 70:
                canvas.setFill("black")
                canvas.drawRect(i, j, 10, 10)
    else:
        for i in 20, 40, 60, 80:
            canvas.setFill("white")
            canvas.drawRect(i, j, 10, 10)
like image 723
GopherTech Avatar asked Sep 18 '25 20:09

GopherTech


2 Answers

You should be doing % 20 because your indices are multiples of 10.

Here's a simpler approach with one pair of nested loops:

offset_x = 10      # Distance from left edge.
offset_y = 10      # Distance from top.
cell_size = 10     # Height and width of checkerboard squares.

for i in range(8):             # Note that i ranges from 0 through 7, inclusive.
    for j in range(8):           # So does j.
        if (i + j) % 2 == 0:       # The top left square is white.
            color = 'white'
        else:
            color = 'black'
        canvas.setFill(color)
        canvas.drawRect(offset_x + i * cell_size, offset_y + j * cell_size,
                        cell_size, cell_size)
like image 188
Michael Laszlo Avatar answered Sep 21 '25 10:09

Michael Laszlo


My go at it, in case may be usefull to someone:

import matplotlib.pyplot as plt
import numpy as np

def Checkerboard(N,n):
    """N: size of board; n=size of each square; N/(2*n) must be an integer """
    if (N%(2*n)):
        print('Error: N/(2*n) must be an integer')
        return False
    a = np.concatenate((np.zeros(n),np.ones(n)))
    b=np.pad(a,int((N**2)/2-n),'wrap').reshape((N,N))
    return (b+b.T==1).astype(int)

B=Checkerboard(600,30)
plt.imshow(B)
plt.show()
like image 42
celiponcio Avatar answered Sep 21 '25 09:09

celiponcio