在 Python 中绘制棋盘

Drawing a checkerboard in Python

我正在尝试编写一个 Python 程序,该程序使用 graphics.py 文件并创建一个有 64 个黑白交替方格的棋盘(如棋盘)。但是,我无法打印任何内容。

到目前为止,这是我的代码。请随时拆除整个代码或进行任何更改。

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)

你应该做 % 20 因为你的索引是 10 的倍数。

这是一种使用一对嵌套循环的更简单的方法:

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)

我的努力,以防对某人有用:

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()