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strow=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生成迷宫内容请搜索编程宝库以前的文章,希望以后支持编程宝库!
Terminal终端命令行Shell设置解决方案File --> Settings --> Tools --> Terminal --> She ...