用Python绘制棋盘格

问题描述 投票:3回答:2

我正在尝试编写一个使用graphics.py文件的Python程序,并创建一个棋盘(如棋盘),其中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)
python python-3.x graphics ipython
2个回答
2
投票

你应该做% 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)

0
投票

我去吧,万一可能对某人有用:

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()
© www.soinside.com 2019 - 2024. All rights reserved.