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in range(col)] for i in range(row)]
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調(diào)用該函數(shù)的方法:
maze=createMaze(27,27)
for l in maze:
for s in l:
print(s,end=" ")
print()
CreateMaze傳入的兩個參數(shù)必須都是單數(shù),否則程序可能會無法運行!
下面的for循環(huán)遍歷就是將生成的迷宮矩陣打印出來
S表示出發(fā)點
1表示路
0表示墻
E表示終點
生成迷宮矩陣后,就可以將其引用到游戲中去啦!
到此這篇關(guān)于Python利用Prim算法生成迷宮的文章就介紹到這了,更多相關(guān)Python Prim生成迷宮內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python3環(huán)境搭建過程(利用Anaconda+pycharm)完整版
這篇文章主要介紹了python3環(huán)境搭建過程(利用Anaconda+pycharm)完整版,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-08-08
Pycharm正版2022.2.2?官方翻譯插件更新tkk失敗不能用問題及解決方案
這篇文章主要介紹了Pycharm正版2022.2.2?|?官方翻譯插件更新tkk失敗解決,?出現(xiàn)tkk問題的是這個翻譯插件,本教程只解決該翻譯插件不能用的問題,需要的朋友可以參考下2022-11-11
在 Django/Flask 開發(fā)服務(wù)器上使用 HTTPS
使用 Django 或 Flask 這種框架開發(fā) web app 的時候一般都會用內(nèi)建服務(wù)器開發(fā)和調(diào)試程序,等程序完成后再移交到生產(chǎn)環(huán)境部署。問題是這些內(nèi)建服務(wù)器通常都不支持 HTTPS,那么我們來探討下開啟https吧2014-07-07

