用Python绘制棋盘

2024-06-25 22:58:36 发布

您现在位置: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)

Tags: 文件inpy程序for棋盘rangewin
2条回答

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

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

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

相关问题 更多 >