【教学类-58-01】黑白三角拼图01(2*2宫格)固定256种+随机抽取10张

背景需求:

中班益智区素材:三角形变魔术 - 小红书自制益智区教玩具:三角形变魔术,共24题 玩法一:根据图示在空白格子里摆放。 玩法二:根据图示在空白格子里用黑笔涂。##自制玩具益智区 #幼儿园益智区 #中班益智区 #区域素材 #幼儿园益智区可打印素材icon-default.png?t=N7T8https://www.xiaohongshu.com/discovery/item/642edea90000000012032c3d?app_platform=android&ignoreEngage=true&app_version=8.36.0&share_from_user_hidden=true&type=normal&author_share=1&xhsshare=WeixinSession&shareRedId=ODszMTs4Nk82NzUyOTgwNjg3OTlHS0xC&apptime=1716531629

小红书上看到一个三角黑块拼图,我去年带的班级里也有这样的积木块。

我想用编程来做一下9块积木块共有多少种不同的排列方式。

样式是3*3的,感觉数量会很多,先做一个2*2的拼图。

代码展示:

1、800*800画布上制作2*2单元格

2、读取四个单元格的每个单元格的的四个坐标,都随机抽取3个

3、梳理出不重复的样式坐标

4、根据三点坐标制作黑色直角三角形

'''
黑白三角(2*2), 4个单元格每个有四个坐标,四个坐标随机抽取3个,进行组合,共有256种不重复排序
AI对话大师,阿夏
2024年5月24日
'''

print('---1、制作2*2格子-------')
from PIL import Image, ImageDraw
path=r'C:\Users\jg2yXRZ\OneDrive\桌面\黑白三角'
# 创建800x800的画布
canvas = Image.new('RGB', (800, 800), (255, 255, 255))
draw = ImageDraw.Draw(canvas)

# 定义表格的行数和列数
rows = 2
cols = 2

# 计算单元格的宽度和高度
cell_width = 800 // cols
cell_height = 800 // rows

# 绘制表格的竖直线
for i in range(1, cols):
    x = i * cell_width
    draw.line([(x, 0), (x, 800)], fill=(0, 0, 0), width=2)

# 绘制表格的水平线
for i in range(1, rows):
    y = i * cell_height
    draw.line([(0, y), (800, y)], fill=(0, 0, 0), width=2)
mb='2格模板.png'
# 保存画布
canvas.save(path+fr'\{mb}')


print('---2、计算三个坐标点的黑色三角形不重复图案有几个-------')

# 创建一个空列表用于存储单元格的坐标
cell_coordinates = []

# 计算每个单元格的四个顶点坐标
for row in range(rows):
    for col in range(cols):
        top_left = (col * cell_width, row * cell_height)
        top_right = ((col + 1) * cell_width, row * cell_height)
        bottom_left = (col * cell_width, (row + 1) * cell_height)
        bottom_right = ((col + 1) * cell_width, (row + 1) * cell_height)
        
        # 将四个顶点坐标添加到列表中
        cell_coordinates.append([top_left, top_right, bottom_left, bottom_right])
# print(cell_coordinates)
# [[(0, 0), (400, 0), (0, 400), (400, 400)], [(400, 0), (800, 0), (400, 400), (800, 400)], [(0, 400), (400, 400), (0, 800), (400, 800)], [(400, 400), (800, 400), (400, 800), (800, 800)]]

import itertools,os

# 生成所有组合方式
combinations = list(itertools.product(*[itertools.combinations(sublist, 3) for sublist in cell_coordinates]))
# print(combinations)
print(len(combinations))
# 256


print('---3、制作三个坐标点的黑色三角形(4个)-------')
from PIL import Image, ImageDraw

new=path+r'\二宫格组合图片'
os.makedirs(new,exist_ok=True)

m=1
# 定义要绘制的坐标点组合
for point_combination in combinations:
        # 读取图像文件
    image = Image.open(path+fr'\{mb}')

    # 创建绘图对象
    draw = ImageDraw.Draw(image)

    # 遍历每个坐标点组合
    for combination in point_combination:
        # 绘制填充为黑色的多边形
        draw.polygon(combination, fill="black")

    # 保存结果图像
    image.save(new+fr"\{m:03d}.png")
    m+=1


print('---4合并打印-------')


# 第3步,读取图片写入docx,合并PDF

import os,time
from docx import Document
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from PyPDF2 import PdfMerger
from docx.shared import Cm

# 读取123文件夹中的所有图片地址
image_folder = new
new_folder = path+r'\零时文件夹'
os.makedirs(new_folder, exist_ok=True)
image_files = [os.path.join(image_folder, file) for file in os.listdir(image_folder) if file.endswith('.png')]

# 每8个图片一组进行处理
grouped_files = [image_files[i:i+6] for i in range(0, len(image_files), 6)]
print(grouped_files)

# 处理每一组图片
for group_index, group in enumerate(grouped_files):
    # 创建新的Word文档
    doc = Document(path+r'\模板6格.docx')
    print(group)
    
    # 遍历每个单元格,并插入图片
    for cell_index, image_file in enumerate(group):
        # 计算图片长宽(单位:厘米)
     
        
        # 插入图片到单元格
        table = doc.tables[0]
        cell = table.cell(int(cell_index / 2), cell_index % 2)
        # 6列两个都是6
        cell_paragraph = cell.paragraphs[0]
        cell_paragraph.clear()
        run = cell_paragraph.add_run()
        run.add_picture(image_file, width=Cm(9.4), height=Cm(9.4))
        
    # 保存Word文档
    doc.save(os.path.join(new_folder, f'{group_index + 1}.docx'))
    
  
# 所有docx合并成PDF

# 将10个docx转为PDF
import os
from docx2pdf import convert
from PyPDF2 import PdfFileMerger
# from PyPDF4 import PdfMerger

# output_folder = output_folder
pdf_output_path = path+fr'\黑白三角256关(6张一页).pdf'

# 将所有DOCX文件转换为PDF
for docx_file in os.listdir(new_folder):
    if docx_file.endswith('.docx'):
        docx_path = os.path.join(new_folder, docx_file)
        convert(docx_path, docx_path.replace('.docx', '.pdf'))


# 合并零时文件里所有PDF文件
merger = PdfFileMerger()
for pdf_file in os.listdir(new_folder):
    if pdf_file.endswith('.pdf'):
        pdf_path = os.path.join(new_folder, pdf_file)
        merger.append(pdf_path)
time.sleep(2)

# 保存合并后的PDF文件
merger.write(pdf_output_path)
merger.close()

import shutil
# 删除输出文件夹

shutil.rmtree(new_folder)

2宫格的黑白三角拼图有256种不重复的排列方式

但是吧图片插入6格模版里,发现图片都黏连在一起了。

第二次修改

加了一个上下左右边距

代码展示:

生成的基础模版(有上下左右白色边距)

'''
黑白三角(2*2), 4个单元格每个有四个坐标,四个坐标随机抽取3个,进行组合,共有256种不重复排序,带边距
AI对话大师,阿夏
2024年5月24日
'''

from PIL import Image, ImageDraw

path = r'C:\Users\jg2yXRZ\OneDrive\桌面\黑白三角'

# 创建800x800的画布
canvas = Image.new('RGB', (800, 800), (255, 255, 255))
draw = ImageDraw.Draw(canvas)

# 定义表格的行数和列数
rows = 2
cols = 2
margin = 50

# 计算单元格的宽度和高度
cell_width = (800 - 2 * margin) // cols
cell_height = (800 - 2 * margin) // rows

# 绘制表格的竖直线
for i in range(cols + 1):
    x = margin + i * cell_width
    draw.line([(x, margin), (x, 800 - margin)], fill=(0, 0, 0), width=2)

# 绘制表格的水平线
for i in range(rows + 1):
    y = margin + i * cell_height
    draw.line([(margin, y), (800 - margin, y)], fill=(0, 0, 0), width=2)

# 保存画布
mb = '2格模板.png'
canvas.save(path + fr'\{mb}')


print('---2、计算三个坐标点的黑色三角形不重复图案有几个-------')

# 创建一个空列表用于存储单元格的坐标
cell_coordinates = []

# 计算每个单元格的四个顶点坐标
for row in range(rows):
    for col in range(cols):
        top_left = (margin + col * cell_width, margin + row * cell_height)
        top_right = (margin + (col + 1) * cell_width, margin + row * cell_height)
        bottom_left = (margin + col * cell_width, margin + (row + 1) * cell_height)
        bottom_right = (margin + (col + 1) * cell_width, margin + (row + 1) * cell_height)

        
        # 将四个顶点坐标添加到列表中
        cell_coordinates.append([top_left, top_right, bottom_left, bottom_right])
# print(cell_coordinates)
# [[(0, 0), (400, 0), (0, 400), (400, 400)], [(400, 0), (800, 0), (400, 400), (800, 400)], [(0, 400), (400, 400), (0, 800), (400, 800)], [(400, 400), (800, 400), (400, 800), (800, 800)]]

import itertools,os

# 生成所有组合方式
combinations = list(itertools.product(*[itertools.combinations(sublist, 3) for sublist in cell_coordinates]))
# print(combinations)
print(len(combinations))
# 256


print('---3、制作三个坐标点的黑色三角形(4个)-------')
from PIL import Image, ImageDraw

new=path+r'\二宫格组合图片'
os.makedirs(new,exist_ok=True)

m=1
# 定义要绘制的坐标点组合
for point_combination in combinations:
        # 读取图像文件
    image = Image.open(path+fr'\{mb}')

    # 创建绘图对象
    draw = ImageDraw.Draw(image)

    # 遍历每个坐标点组合
    for combination in point_combination:
        # 绘制填充为黑色的多边形
        draw.polygon(combination, fill="black")

    # 保存结果图像
    image.save(new+fr"\{m:03d}.png")
    m+=1


print('---4合并打印-------')


# 第3步,读取图片写入docx,合并PDF

import os,time
from docx import Document
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from PyPDF2 import PdfMerger
from docx.shared import Cm

# 读取123文件夹中的所有图片地址
image_folder = new
new_folder = path+r'\零时文件夹'
os.makedirs(new_folder, exist_ok=True)
image_files = [os.path.join(image_folder, file) for file in os.listdir(image_folder) if file.endswith('.png')]

# 每8个图片一组进行处理
grouped_files = [image_files[i:i+6] for i in range(0, len(image_files), 6)]
print(grouped_files)

# 处理每一组图片
for group_index, group in enumerate(grouped_files):
    # 创建新的Word文档
    doc = Document(path+r'\模板6格.docx')
    print(group)
    
    # 遍历每个单元格,并插入图片
    for cell_index, image_file in enumerate(group):
        # 计算图片长宽(单位:厘米)
     
        
        # 插入图片到单元格
        table = doc.tables[0]
        cell = table.cell(int(cell_index / 2), cell_index % 2)
        # 6列两个都是6
        cell_paragraph = cell.paragraphs[0]
        cell_paragraph.clear()
        run = cell_paragraph.add_run()
        run.add_picture(image_file, width=Cm(9.4), height=Cm(9.4))
        
    # 保存Word文档
    doc.save(os.path.join(new_folder, f'{group_index + 1}.docx'))
    
  
# 所有docx合并成PDF

# 将10个docx转为PDF
import os
from docx2pdf import convert
from PyPDF2 import PdfFileMerger
# from PyPDF4 import PdfMerger

# output_folder = output_folder
pdf_output_path = path+fr'\黑白三角256关(6张一页).pdf'

# 将所有DOCX文件转换为PDF
for docx_file in os.listdir(new_folder):
    if docx_file.endswith('.docx'):
        docx_path = os.path.join(new_folder, docx_file)
        convert(docx_path, docx_path.replace('.docx', '.pdf'))


# 合并零时文件里所有PDF文件
merger = PdfFileMerger()
for pdf_file in os.listdir(new_folder):
    if pdf_file.endswith('.pdf'):
        pdf_path = os.path.join(new_folder, pdf_file)
        merger.append(pdf_path)
time.sleep(2)

# 保存合并后的PDF文件
merger.write(pdf_output_path)
merger.close()

import shutil
# 删除输出文件夹

shutil.rmtree(new_folder)

有白色边距

第三种:256还是很多的,平时小孩玩的时候样板图最多20张

所以我还是随机抽取不重复的图案,

代码优化过了,参数都在最前面订好

'''
黑白三角(2*2), 4个单元格每个有4个坐标,四个坐标随机抽取3个,进行组合,自动抽取10张,带边距
随机图片
AI对话大师,阿夏
2024年5月24日

'''


from PIL import Image, ImageDraw
f=10 # 需要10份
b=800 # 画布大小
g=2 # 宫格数
by=50 # 边距

path = r'C:\Users\jg2yXRZ\OneDrive\桌面\黑白三角'

# 创建bxb的画布
canvas = Image.new('RGB', (b,b), (255, 255, 255))
draw = ImageDraw.Draw(canvas)

# 定义表格的行数和列数、边距
rows = g
cols = g
margin = by

# 计算单元格的宽度和高度
cell_width = (b - 2 * margin) // cols
cell_height = (b - 2 * margin) // rows

# 绘制表格的竖直线
for i in range(cols + 1):
    x = margin + i * cell_width
    draw.line([(x, margin), (x, b - margin)], fill=(0, 0, 0), width=2)

# 绘制表格的水平线
for i in range(rows + 1):
    y = margin + i * cell_height
    draw.line([(margin, y), (b - margin, y)], fill=(0, 0, 0), width=2)

# 保存画布
mb =f'{g}格模板.png'
canvas.save(path + fr'\{mb}')


print('---2、计算三个坐标点的黑色三角形不重复图案有几个-------')

# 创建一个空列表用于存储单元格的坐标
cell_coordinates = []

# 计算每个单元格的四个顶点坐标
for row in range(rows):
    for col in range(cols):
        top_left = (margin + col * cell_width, margin + row * cell_height)
        top_right = (margin + (col + 1) * cell_width, margin + row * cell_height)
        bottom_left = (margin + col * cell_width, margin + (row + 1) * cell_height)
        bottom_right = (margin + (col + 1) * cell_width, margin + (row + 1) * cell_height)

        
        # 将四个顶点坐标添加到列表中
        cell_coordinates.append([top_left, top_right, bottom_left, bottom_right])
# print(cell_coordinates)
# print(len(cell_coordinates))
# 16
# [[(0, 0), (400, 0), (0, 400), (400, 400)], [(400, 0), (b, 0), (400, 400), (b, 400)], [(0, 400), (400, 400), (0, b), (400, b)], [(400, 400), (b, 400), (400, b), (b, b)]]

import random
import os

combinations=[]
# 存储选取的点,随机生成坐标(样式)排除重复,生成10份样式不同的模版
while len(combinations) < f:
    selected_points = []
    for points in cell_coordinates:
        selected_points.append(tuple(random.sample(points, 3)))
    combinations.append(tuple(selected_points))

print(combinations)
print(len(combinations))
#  10


# # 生成所有组合方式,太多了,生成不出来
# combinations = lisitertools.product(*[itertools.combinations(sublist, 3) for sublist in cell_coordinates]))
# # print(combinations)
# print(len(combinations))
# # 262144


print('---3、制作三个坐标点的黑色三角形(4个)-------')
from PIL import Image, ImageDraw

new = path + fr'\{g}宫格组合图片'
os.makedirs(new, exist_ok=True)

m = 1
# 定义要绘制的坐标点组合
for point_combination in combinations:
    print(point_combination)
    # 清空selected_points列表
    selected_points = []
    
    # 遍历每个坐标点组合
    for combination in point_combination:
        # 从每个列表中随机选取三个点,并加入到selected_points中
        selected_points.append(tuple(random.sample(combination, 3)))

    # 读取图像文件
    image = Image.open(path + fr'\{mb}')

    # 创建绘图对象
    draw = ImageDraw.Draw(image)

    # 遍历每个坐标点组合
    for combination in selected_points:
        # 绘制填充为黑色的多边形
        draw.polygon(combination, fill="black")

    # 保存结果图像
    image.save(new + fr"\{m:03d}.png")
    image.close()  # 关闭图像文件
    m += 1



print('---4合并打印------')


# 第3步,读取图片写入docx,合并PDF

import os,time
from docx import Document
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from PyPDF2 import PdfMerger
from docx.shared import Cm

# 读取123文件夹中的所有图片地址
image_folder = new
new_folder = path+r'\零时文件夹'
os.makedirs(new_folder, exist_ok=True)
image_files = [os.path.join(image_folder, file) for file in os.listdir(image_folder) if file.endswith('.png')]

# 每8个图片一组进行处理
grouped_files = [image_files[i:i+6] for i in range(0, len(image_files), 6)]
print(grouped_files)

# 处理每一组图片
for group_index, group in enumerate(grouped_files):
    # 创建新的Word文档
    doc = Document(path+r'\模板6格.docx')
    print(group)
    
    # 遍历每个单元格,并插入图片
    for cell_index, image_file in enumerate(group):
        # 计算图片长宽(单位:厘米)
     
        
        # 插入图片到单元格
        table = doc.tables[0]
        cell = table.cell(int(cell_index / 2), cell_index % 2)
        # 6列两个都是6
        cell_paragraph = cell.paragraphs[0]
        cell_paragraph.clear()
        run = cell_paragraph.add_run()
        run.add_picture(image_file, width=Cm(9.4), height=Cm(9.4))
        
    # 保存Word文档
    doc.save(os.path.join(new_folder, f'{group_index + 1}.docx'))
    
  
# 所有docx合并成PDF

# 将10个docx转为PDF
import os
from docx2pdf import convert
from PyPDF2 import PdfFileMerger
# from PyPDF4 import PdfMerger

# output_folder = output_folder
pdf_output_path = path+fr'\黑白三角{g}宫格随机{f}张(6张一页).pdf'

# 将所有DOCX文件转换为PDF
for docx_file in os.listdir(new_folder):
    if docx_file.endswith('.docx'):
        docx_path = os.path.join(new_folder, docx_file)
        convert(docx_path, docx_path.replace('.docx', '.pdf'))


# 合并零时文件里所有PDF文件
merger = PdfFileMerger()
for pdf_file in os.listdir(new_folder):
    if pdf_file.endswith('.pdf'):
        pdf_path = os.path.join(new_folder, pdf_file)
        merger.append(pdf_path)
time.sleep(2)

# 保存合并后的PDF文件
merger.write(pdf_output_path)
merger.close()

import shutil
# 删除输出文件夹

shutil.rmtree(new_folder)

图片不一样

  • 15
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿夏reasonsummer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值