【教学类-09-02】20240331细线迷宫图01(A4横版一页1份横版)

作品展示

背景需求:

从以下代码获取一个迷宫图片

Python生成迷宫_如何生成一个迷宫python-CSDN博客文章浏览阅读3k次。算法简介:生成一张网格,把网格里面的所有边都存进一个列表edgeList里面.从(0, 0)开始,做DFS。每次DFS的时候,随机地选择四周一个没有走过的格子,凿墙过去,把道路打通。凿墙的时候,把edgeList列表中相对应的那堵墙删除掉。将剩下的没有凿开过的墙画出来,就是一个完整的迷宫了。import sysimport matplotlib.pyplot as pltfrom random import randintWIDTH = 60HEIGHT = 40sys_如何生成一个迷宫pythonhttps://blog.csdn.net/u014297502/article/details/124839912

2022年9月30日:我不要坐标,可是我看不懂代码,不知道怎么修改

2024年3月31日,用Ai对话大师修改代码

对比显示后,我获得了想要的单张细线迷宫图

1、有坐标和没有坐标的图片的长宽一样。

2、有坐标和没有坐标豆有一圈白边。

设计过程

一、通过修改原始代码,实现批量下载多张细线迷宫图的需求

1、修改原代码的基本参数——长宽格子的数量+一共多少张

2、图片长宽大小、图片清晰度,

3、代码展示


num=int(input('几张(30份)\n'))

print('-----------1、 生成细线迷宫-----------')
import sys
import matplotlib.pyplot as plt
from random import randint
import os

# 保存多少张图?
for i in range(num):
	WIDTH  = 30
	HEIGHT = 21
	sys.setrecursionlimit(WIDTH * HEIGHT)

	def initVisitedList():
		visited = []
		for y in range(HEIGHT):
			line = []
			for x in range(WIDTH):
				line.append(False)
			visited.append(line)
		return visited

	def drawLine(x1, y1, x2, y2):
		plt.plot([x1, x2], [y1, y2], color="black")

	def removeLine(x1, y1, x2, y2):
		plt.plot([x1, x2], [y1, y2], color="white")

	def get_edges(x, y):
		result = []
		result.append((x, y, x, y+1))
		result.append((x+1, y, x+1, y+1))
		result.append((x, y, x+1, y))
		result.append((x, y+1, x+1, y+1))

		return result

	def drawCell(x, y):
		edges = get_edges(x, y)
		for item in edges:
			drawLine(item[0], item[1], item[2], item[3])

	def getCommonEdge(cell1_x, cell1_y, cell2_x, cell2_y):
		edges1 = get_edges(cell1_x, cell1_y)
		edges2 = set(get_edges(cell2_x, cell2_y))
		for edge in edges1:
			if edge in edges2:
				return edge
		return None

	def initEdgeList():
		edges = set()
		for x in range(WIDTH):
			for y in range(HEIGHT):
				cellEdges = get_edges(x, y)
				for edge in cellEdges:
					edges.add(edge)
		return edges

	def isValidPosition(x, y):
		if x < 0 or x >= WIDTH:
			return False
		elif y < 0 or y >= HEIGHT:
			return False
		else:
			return True

	def shuffle(dX, dY):
		for t in range(4):
			i = randint(0, 3)
			j = randint(0, 3)
			dX[i], dX[j] = dX[j], dX[i]
			dY[i], dY[j] = dY[j], dY[i]

	def DFS(X, Y, edgeList, visited):
		dX = [0,  0, -1, 1]
		dY = [-1, 1, 0,  0]
		shuffle(dX, dY)
		for i in range(len(dX)):
			nextX = X + dX[i]
			nextY = Y + dY[i]
			if isValidPosition(nextX, nextY):
				if not visited[nextY][nextX]:
					visited[nextY][nextX] = True
					commonEdge = getCommonEdge(X, Y, nextX, nextY)
					if commonEdge in edgeList:
						edgeList.remove(commonEdge)
					DFS(nextX, nextY, edgeList, visited)

	edgeList = initEdgeList()
	visited  = initVisitedList()
	DFS(0, 0, edgeList, visited)
	edgeList.remove((0, 0, 0, 1))
	edgeList.remove((WIDTH, HEIGHT-1, WIDTH, HEIGHT))

	figure = plt.figure(figsize=(29.7,21))  # 创建一个指定大小的图像窗口
	ax = plt.Axes(figure, [0., 0., 1., 1.], frame_on=False)  # 创建一个坐标轴,覆盖整个图像窗口
	figure.add_axes(ax)
	ax.axis('off')  # 关闭坐标轴显示

	for edge in edgeList:
		drawLine(edge[0], edge[1], edge[2], edge[3])

	# 新建图片文件夹,保存所有生成的迷宫图
	path=r'C:\Users\jg2yXRZ\OneDrive\桌面\细线迷宫图图片'
	folder_path = path+r'\01迷宫图'
	os.makedirs(folder_path, exist_ok=True)

	
	plt.savefig(folder_path+r'\{}.png'.format('%02d'%i), dpi=600)  # 保存迷宫图像为maze.png,设置dpi参数调整图像质量
	
	plt.close()  # 超过20张图片会提

4、效果展示

每张迷宫图图片线路都不同

因为是600分辨率,且图片A4大小,所以生成时间很长

二、docx模板准备

三、把“01迷宫图”里面png写入docx模板,导成PDF,合并PDF

1、代码展示

print('-----------2、 导入word,合并png----------')

import os,time
from docx import Document
from docx.shared import Cm, RGBColor
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.oxml.ns import qn
from docx2pdf import convert
from PyPDF2 import PdfMerger

# 设置路径和文件夹名称

folder_path ='迷宫图所有图片文件夹路径'
path=r'C:\Users\jg2yXRZ\OneDrive\桌面\细线迷宫图图片'
folder_path = path+r'\01迷宫图'
template_path = path+r"\01迷宫图细线(A4横版1张图).docx"# 模板文件路径
output_path =path+r'\零时Word'# 生成docx和PDF的文件夹,最后要删除

# 创建输出文件夹
if not os.path.exists(output_path):
    os.makedirs(output_path)

n = 1
# 遍历图片文件夹
for filename in os.listdir(folder_path):
    if filename.endswith('.png'):
        # 打开模板文档
        doc = Document(template_path)
        
        # 获取第一个表格
        table = doc.tables[0]
        
        # 在表格中插入图片
        table.cell(0, 0).paragraphs[0].add_run().add_picture(os.path.join(folder_path, filename), width=Cm(29.7), height=Cm(20.93))
        
        # 保存为Word文档
        doc.save(os.path.join(output_path, '{:02d}.docx'.format(n)))
        
        # 转换为PDF
        convert(os.path.join(output_path, '{:02d}.docx'.format(n)), os.path.join(output_path, '{:02d}.pdf'.format(n)))
        n += 1
	
# 合并PDF
pdf_lst = [os.path.join(output_path, filename) for filename in os.listdir(output_path) if filename.endswith('.pdf')]
pdf_lst.sort()

file_merger = PdfMerger()
for pdf in pdf_lst:
    file_merger.append(pdf)

file_merger.write(path+fr'\(打印合集)迷宫图(A4横版整页1份)({num}份).pdf')
time.sleep(5)

# file_merger.write(os.path.join(output_path, '合并后的PDF.pdf'))
file_merger.close()

# 删除临时文件夹
import shutil
shutil.rmtree(output_path)

2、把png插入word横版一页内的单元格里。

PDF效果,都是A4横版 整页1张

3、合并PDF,便于打印

单张

两张对比

四张对比

全部代码

'''
批量制作细线条的迷宫图(A4横板一面一份横版)
作者:
1、落难Coder https://blog.csdn.net/u014297502/article/details/124839912
2、AI对话大师、
3、阿夏
作者:2024年3月31日
'''


num=int(input('几张(30份)\n'))

print('-----------1、 生成细线迷宫-----------')
import sys
import matplotlib.pyplot as plt
from random import randint
import os

# 保存多少张图?
for i in range(num):
	WIDTH  = 30
	HEIGHT = 21
	sys.setrecursionlimit(WIDTH * HEIGHT)

	def initVisitedList():
		visited = []
		for y in range(HEIGHT):
			line = []
			for x in range(WIDTH):
				line.append(False)
			visited.append(line)
		return visited

	def drawLine(x1, y1, x2, y2):
		plt.plot([x1, x2], [y1, y2], color="black")

	def removeLine(x1, y1, x2, y2):
		plt.plot([x1, x2], [y1, y2], color="white")

	def get_edges(x, y):
		result = []
		result.append((x, y, x, y+1))
		result.append((x+1, y, x+1, y+1))
		result.append((x, y, x+1, y))
		result.append((x, y+1, x+1, y+1))

		return result

	def drawCell(x, y):
		edges = get_edges(x, y)
		for item in edges:
			drawLine(item[0], item[1], item[2], item[3])

	def getCommonEdge(cell1_x, cell1_y, cell2_x, cell2_y):
		edges1 = get_edges(cell1_x, cell1_y)
		edges2 = set(get_edges(cell2_x, cell2_y))
		for edge in edges1:
			if edge in edges2:
				return edge
		return None

	def initEdgeList():
		edges = set()
		for x in range(WIDTH):
			for y in range(HEIGHT):
				cellEdges = get_edges(x, y)
				for edge in cellEdges:
					edges.add(edge)
		return edges

	def isValidPosition(x, y):
		if x < 0 or x >= WIDTH:
			return False
		elif y < 0 or y >= HEIGHT:
			return False
		else:
			return True

	def shuffle(dX, dY):
		for t in range(4):
			i = randint(0, 3)
			j = randint(0, 3)
			dX[i], dX[j] = dX[j], dX[i]
			dY[i], dY[j] = dY[j], dY[i]

	def DFS(X, Y, edgeList, visited):
		dX = [0,  0, -1, 1]
		dY = [-1, 1, 0,  0]
		shuffle(dX, dY)
		for i in range(len(dX)):
			nextX = X + dX[i]
			nextY = Y + dY[i]
			if isValidPosition(nextX, nextY):
				if not visited[nextY][nextX]:
					visited[nextY][nextX] = True
					commonEdge = getCommonEdge(X, Y, nextX, nextY)
					if commonEdge in edgeList:
						edgeList.remove(commonEdge)
					DFS(nextX, nextY, edgeList, visited)

	edgeList = initEdgeList()
	visited  = initVisitedList()
	DFS(0, 0, edgeList, visited)
	edgeList.remove((0, 0, 0, 1))
	edgeList.remove((WIDTH, HEIGHT-1, WIDTH, HEIGHT))

	figure = plt.figure(figsize=(29.7,21))  # 创建一个指定大小的图像窗口
	ax = plt.Axes(figure, [0., 0., 1., 1.], frame_on=False)  # 创建一个坐标轴,覆盖整个图像窗口
	figure.add_axes(ax)
	ax.axis('off')  # 关闭坐标轴显示

	for edge in edgeList:
		drawLine(edge[0], edge[1], edge[2], edge[3])

	# 新建图片文件夹,保存所有生成的迷宫图
	path=r'C:\Users\jg2yXRZ\OneDrive\桌面\细线迷宫图图片'
	folder_path = path+r'\01迷宫图'
	os.makedirs(folder_path, exist_ok=True)

	
	plt.savefig(folder_path+r'\{}.png'.format('%02d'%i), dpi=600)  # 保存迷宫图像为maze.png,设置dpi参数调整图像质量
	
	plt.close()  # 超过20张图片会提示占内存,所以关闭图像窗口释放内存
# plt.show()



print('-----------2、 导入word,合并png----------')

import os,time
from docx import Document
from docx.shared import Cm, RGBColor
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.oxml.ns import qn
from docx2pdf import convert
from PyPDF2 import PdfMerger

# 设置路径和文件夹名称

folder_path ='迷宫图所有图片文件夹路径'
path=r'C:\Users\jg2yXRZ\OneDrive\桌面\细线迷宫图图片'
folder_path = path+r'\01迷宫图'
template_path = path+r"\01迷宫图细线(A4横版1张图).docx"# 模板文件路径
output_path =path+r'\零时Word'# 生成docx和PDF的文件夹,最后要删除

# 创建输出文件夹
if not os.path.exists(output_path):
    os.makedirs(output_path)

n = 1
# 遍历图片文件夹
for filename in os.listdir(folder_path):
    if filename.endswith('.png'):
        # 打开模板文档
        doc = Document(template_path)
        
        # 获取第一个表格
        table = doc.tables[0]
        
        # 在表格中插入图片
        table.cell(0, 0).paragraphs[0].add_run().add_picture(os.path.join(folder_path, filename), width=Cm(29.7), height=Cm(20.93))
        
        # 保存为Word文档
        doc.save(os.path.join(output_path, '{:02d}.docx'.format(n)))
        
        # 转换为PDF
        convert(os.path.join(output_path, '{:02d}.docx'.format(n)), os.path.join(output_path, '{:02d}.pdf'.format(n)))
        n += 1
	
# 合并PDF
pdf_lst = [os.path.join(output_path, filename) for filename in os.listdir(output_path) if filename.endswith('.pdf')]
pdf_lst.sort()

file_merger = PdfMerger()
for pdf in pdf_lst:
    file_merger.append(pdf)

file_merger.write(path+fr'\(打印合集)迷宫图(A4横版整页1份)({num}份).pdf')
time.sleep(5)

# file_merger.write(os.path.join(output_path, '合并后的PDF.pdf'))
file_merger.close()

# 删除临时文件夹
import shutil
shutil.rmtree(output_path)


完成了,这款细线的迷宫图因为是21*30格的,有难度,但是如果太简单,孩子们一会儿就打通了路线,

1、先打印10份备用

2、后续再做一些长宽格子少的,一张A4放2张图,或4张图,让幼儿走迷宫。

2024年4月1日

考虑到以前有孩子问我“哪里是起点”,于是有改了以下word模板

1、模板文件名修改

2、分辨率从600改500、900Kb变成420KB

3、删除“零食文件夹”和01”迷宫图“

代码展示:

'''
批量制作细线条的迷宫图(A4横板一面一份横版)
作者:
1、落难Coder https://blog.csdn.net/u014297502/article/details/124839912
2、AI对话大师、
3、阿夏
作者:2024年3月31日
'''


num=int(input('几张(30份)\n'))

print('-----------1、 生成细线迷宫-----------')
import sys
import matplotlib.pyplot as plt
from random import randint
import os

# 保存多少张图?
for i in range(num):
	WIDTH  = 30
	HEIGHT = 21
	sys.setrecursionlimit(WIDTH * HEIGHT)

	def initVisitedList():
		visited = []
		for y in range(HEIGHT):
			line = []
			for x in range(WIDTH):
				line.append(False)
			visited.append(line)
		return visited

	def drawLine(x1, y1, x2, y2):
		plt.plot([x1, x2], [y1, y2], color="black")

	def removeLine(x1, y1, x2, y2):
		plt.plot([x1, x2], [y1, y2], color="white")

	def get_edges(x, y):
		result = []
		result.append((x, y, x, y+1))
		result.append((x+1, y, x+1, y+1))
		result.append((x, y, x+1, y))
		result.append((x, y+1, x+1, y+1))

		return result

	def drawCell(x, y):
		edges = get_edges(x, y)
		for item in edges:
			drawLine(item[0], item[1], item[2], item[3])

	def getCommonEdge(cell1_x, cell1_y, cell2_x, cell2_y):
		edges1 = get_edges(cell1_x, cell1_y)
		edges2 = set(get_edges(cell2_x, cell2_y))
		for edge in edges1:
			if edge in edges2:
				return edge
		return None

	def initEdgeList():
		edges = set()
		for x in range(WIDTH):
			for y in range(HEIGHT):
				cellEdges = get_edges(x, y)
				for edge in cellEdges:
					edges.add(edge)
		return edges

	def isValidPosition(x, y):
		if x < 0 or x >= WIDTH:
			return False
		elif y < 0 or y >= HEIGHT:
			return False
		else:
			return True

	def shuffle(dX, dY):
		for t in range(4):
			i = randint(0, 3)
			j = randint(0, 3)
			dX[i], dX[j] = dX[j], dX[i]
			dY[i], dY[j] = dY[j], dY[i]

	def DFS(X, Y, edgeList, visited):
		dX = [0,  0, -1, 1]
		dY = [-1, 1, 0,  0]
		shuffle(dX, dY)
		for i in range(len(dX)):
			nextX = X + dX[i]
			nextY = Y + dY[i]
			if isValidPosition(nextX, nextY):
				if not visited[nextY][nextX]:
					visited[nextY][nextX] = True
					commonEdge = getCommonEdge(X, Y, nextX, nextY)
					if commonEdge in edgeList:
						edgeList.remove(commonEdge)
					DFS(nextX, nextY, edgeList, visited)

	edgeList = initEdgeList()
	visited  = initVisitedList()
	DFS(0, 0, edgeList, visited)
	edgeList.remove((0, 0, 0, 1))
	edgeList.remove((WIDTH, HEIGHT-1, WIDTH, HEIGHT))

	figure = plt.figure(figsize=(29.7,21))  # 创建一个指定大小的图像窗口
	ax = plt.Axes(figure, [0., 0., 1., 1.], frame_on=False)  # 创建一个坐标轴,覆盖整个图像窗口
	figure.add_axes(ax)
	ax.axis('off')  # 关闭坐标轴显示

	for edge in edgeList:
		drawLine(edge[0], edge[1], edge[2], edge[3])

	# 新建图片文件夹,保存所有生成的迷宫图
	path=r'C:\Users\jg2yXRZ\OneDrive\桌面\细线迷宫图图片'
	folder_path = path+r'\01迷宫图'
	os.makedirs(folder_path, exist_ok=True)

	
	plt.savefig(folder_path+r'\{}.png'.format('%02d'%i), dpi=400)  # 保存迷宫图像为maze.png,设置dpi参数调整图像质量
	
	plt.close()  # 超过20张图片会提示占内存,所以关闭图像窗口释放内存
# plt.show()



print('-----------2、 导入word,合并png----------')

import os,time
from docx import Document
from docx.shared import Cm, RGBColor
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.oxml.ns import qn
from docx2pdf import convert
from PyPDF2 import PdfMerger

# 设置路径和文件夹名称

folder_path ='迷宫图所有图片文件夹路径'
path=r'C:\Users\jg2yXRZ\OneDrive\桌面\细线迷宫图图片'
folder_path = path+r'\01迷宫图'
template_path = path+r"\01迷宫图细线(A4横版1张横图).docx"# 模板文件路径
output_path =path+r'\零时Word'# 生成docx和PDF的文件夹,最后要删除

# 创建输出文件夹
if not os.path.exists(output_path):
    os.makedirs(output_path)

n = 1
# 遍历图片文件夹
for filename in os.listdir(folder_path):
    if filename.endswith('.png'):
        # 打开模板文档
        doc = Document(template_path)
        
        # 获取第一个表格
        table = doc.tables[0]
        
        # 在表格中插入图片
        table.cell(0, 0).paragraphs[0].add_run().add_picture(os.path.join(folder_path, filename), width=Cm(29.7), height=Cm(20.93))
        
        # 保存为Word文档
        doc.save(os.path.join(output_path, '{:02d}.docx'.format(n)))
        time.sleep(3)
        # 转换为PDF
        convert(os.path.join(output_path, '{:02d}.docx'.format(n)), os.path.join(output_path, '{:02d}.pdf'.format(n)))
        n += 1
	
# 合并PDF
pdf_lst = [os.path.join(output_path, filename) for filename in os.listdir(output_path) if filename.endswith('.pdf')]
pdf_lst.sort()

file_merger = PdfMerger()
for pdf in pdf_lst:
    file_merger.append(pdf)

file_merger.write(path+fr'\01(打印合集)迷宫图(A4横版整页1份横图)({num}份).pdf')
time.sleep(5)

# file_merger.write(os.path.join(output_path, '合并后的PDF.pdf'))
file_merger.close()

# 删除临时文件夹
import shutil
shutil.rmtree(output_path)
shutil.rmtree(folder_path)


最后只有一个PDF,迷宫图都删除了

把这份打印几张,找几个孩子测试完成时间吧,估计有的孩子慧做的很快,所以还可以想象更多的玩法

1、平面:在路径上画陷阱、人物等

2、立体,将大树、房屋、人物纸片垂直贴在迷宫图上,做立体展示

  • 42
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

阿夏reasonsummer

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

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

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

打赏作者

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

抵扣说明:

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

余额充值