在PIL中创建棋盘 [英] Creating a chessboard in PIL
问题描述
我一直试图在PIL模块中创建一个棋盘,我已经获得了前两行的常规模式,但是无法弄清楚如何将其应用于整个棋盘.如您所见,我创建了一个图像:
I have been trying to create a chessboard in the PIL module and I have got the general pattern for the first two rows, but can't figure out how to apply this to the entire board. As you can see, I have created an image:
from PIL import Image
img = Image.new("RGB", (15,15), "white") # create a new 15x15 image
pixels = img.load() # create the pixel map
我对前两行的解决方案
注意-我仍在学习Python,因此此代码似乎效率很低,但可以随时提出改进建议.
My solution for the first two rows
Note - I am still learning Python so this code may seem very inefficient, but feel free to suggest improvements.
代码:
black_2 = []
for i in range(img.size[0]):
if i % 2 == 0:
black_2.append(i)
这给了我所有放置黑色像素的水平索引位置.因此,对于我创建的15x15电路板,它返回[0, 2, 4, 6, 8, 10, 12, 14]
This gives me all the horizontal index positions on where to put a black pixel. Therefore, for the 15x15 board I created, it returns [0, 2, 4, 6, 8, 10, 12, 14]
代码:
然后我使用第二行计算出第一行的水平索引位置
I then use the second row to work out the horizontal index positions for the first row
black_1 = [i-1 for i in black_2 if i > 0]
if img.size[0] % 2 == 0: # 'that' if statement
black_1.append(img.size[0]-1)
对于我创建的15x15像素板,它返回[1, 3, 5, 7, 9, 11, 13]
.我创建了if语句,因为我意识到如果木板长度均匀,最后一个黑色像素不会显示出来,那似乎可以解决这个问题.
For the 15x15 pixel board I created, it returns [1, 3, 5, 7, 9, 11, 13]
. I created that if statement because I realised that the last black pixel was not showing if the board had an even length, and that seemed to fix it.
# hardcoded to check patterns
for i in black_1:
pixels[i,0] = (0,0,0)
for k in black_2:
pixels[k,1] = (0,0,0)
img.show()
无论大小如何如何将这两种图案都应用到电路板的其余部分?
How can I apply both patterns to the rest of the board, regardless of its size?
我怀疑需要一个for var in range()
循环,但是我不确定它会如何变化,具体取决于板的高度(img.size[1]
)是奇数还是偶数.
I would suspect a for var in range()
loop is needed, but I am not sure how it would change depending on if the height(img.size[1]
) of the board is odd or even.
black_1
适用于第一行
black_2
适用于第二行
推荐答案
一个国际象棋棋盘有64个正方形而不是256个正方形.首先需要(8,8)
,然后可以使用double for循环将颜色分配给所有8行.
A chess board has 64 squares instead of 256. Firstly you need (8,8)
and then you can use double for loops to assign the color to all the 8 rows.
任何大小的常规示例
from PIL import Image
size = 16
img = Image.new("RGB", (size,size), "white") # create a new 15x15 image
pixels = img.load() # create the pixel map
black_2 = []
for i in range(img.size[0]):
if i % 2 == 0:
black_2.append(i)
black_1 = [i-1 for i in black_2 if i > 0]
if img.size[0] % 2 == 0: # 'that' if statement
black_1.append(img.size[0]-1)
for i in black_1:
for j in range(0, size, 2):
pixels[i,j] = (0,0,0)
for k in black_2:
for l in range(1, size+1, 2):
pixels[k,l] = (0,0,0)
img.show()
这篇关于在PIL中创建棋盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!