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]
check=[]
firstrow=rd.randrange(1,row-2,2)
firstcol=rd.randrange(1,col-2,2)
maze[firstrow][firstcol]=1
check.append([firstrow,firstcol])
while len(check):
c=rd.choice(check)
nears=[]
conditions=[]
for maybe in nearmaybe:
conditions.append([c[0]+maybe[0],c[1]+maybe[1]])
for condition in conditions:
if condition[0]>=1 and condition[0]<=row-2 \
and condition[1]>=1 and condition[1]<=col-2:
nears.append([condition[0],condition[1]])
for n in nears.copy():
if maze[n[0]][n[1]]:
nears.remove(n)
for block in nears:
if block[0]==c[0]:
if block[1]<c[1]:
maze[block[0]][c[1]-1]=1
maze[block[0]][block[1]]=1
check.append([block[0],block[1]])
else:
maze[block[0]][block[1]-1]=1
maze[block[0]][block[1]]=1
check.append([block[0],block[1]])
else:
if block[0]<c[0]:
maze[c[0]-1][block[1]]=1
maze[block[0]][block[1]]=1
check.append([block[0],block[1]])
else:
maze[block[0]-1][block[1]]=1
maze[block[0]][block[1]]=1
check.append([block[0],block[1]])
if not len(nears):
check.remove(c)
maze[1][1]="s"
while True:
c=rd.randint(1,col-2)
if maze[row-2][c]:
maze[row-2][c]="e"
break
return maze
调用该函数的方法:
maze=createMaze(27,27)
for l in maze:
for s in l:
print(s,end=" ")
print()
CreateMaze传入的两个参数必须都是单数,否则程序可能会无法运行!
下面的for循环遍历就是将生成的迷宫矩阵打印出来
S表示出发点
1表示路
0表示墙
E表示终点
生成迷宫矩阵后,就可以将其引用到游戏中去啦!
到此这篇关于Python利用Prim算法生成迷宫的文章就介绍到这了,更多相关Python Prim生成迷宫内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341