前兩篇文章,我們使用Prim算法生成了文章,這一次,我們要用Pygame將迷宮的完整生成過程可視化
首先導入模塊,這裡我們要用到pygame,隨機庫,sys,time用於減緩速度,threading用於生成迷宮的另一個線程
import pygame
from pygame.locals import *
import random as rd
import sys
import time
import threading
我們用類和對象的形式實現,定義Game類,初始化函數中設置窗口,a和b表示迷宮大小,lineWidth是迷宮牆壁畫在窗口中的粗細,創建一個線程,指向createMaze(createMaze的代碼下方會補充),然後啟動線程
class Game:
def __init__(self):
pygame.init()
self.W,self.H=900,900
self.screen=pygame.display.set_mode((self.W,self.H))
self.a,self.b=28,39
self.lineWidth=5
thread=threading.Thread(target=self.createMaze,args=(self.a,self.b))
thread.start()
創建listen函數,用於監聽事件
def listen(self):
for event in pygame.event.get():
if event.type==QUIT:
sys.exit()
接下來是創建迷宮的代碼,在上一篇遍歷牆生成迷宮的時候,我們已經將代碼完整寫出來了,只要修改一小部分內容即可,要修改的地方如下:
在函數參數中添加self
def createMaze(self,a,b):
然後,把函數中的maze全部改為self.maze,直接存入類變量中
這裡不再展示代碼,需要算法代碼的可以查看我的上一篇文章:
Python Prim 算法 生成迷宮_Leleprogrammer的博客-CSDN博客Python Prim算法 通過遍歷牆來生成迷宮,快來看看吧!https://blog.csdn.net/leleprogrammer/article/details/125472436?spm=1001.2014.3001.5501或者是在文末的最終代碼中復制,要學習算法原理的,查看上一篇文章即可
接下來,draw函數,用於繪制迷宮,這裡代碼不會太難,就不做太多講解
def draw(self):
self.screen.fill((255,255,255))
for (n,face),is_wall in self.maze.items():
if is_wall:
y=n//self.a
x=n%self.a
absX=x*self.width
absY=y*self.height
if face=="u":
pygame.draw.line(self.screen,(0,0,0),(absX,absY),(absX+self.width,absY),self.lineWidth)
if face=="d":
pygame.draw.line(self.screen,(0,0,0),(absX,absY+self.height),(absX+self.width,absY+self.height),self.lineWidth)
if face=="l":
pygame.draw.line(self.screen,(0,0,0),(absX,absY),(absX,absY+self.height),self.lineWidth)
if face=="r":
pygame.draw.line(self.screen,(0,0,0),(absX+self.width,absY),(absX+self.width,absY+self.height),self.lineWidth)
然後是run函數,主循環
def run(self):
while True:
self.listen()
self.draw()
self.refreshWindow()
pygame.display.update()
用於顯示文字的函數,這裡沒有用到,可以不加上,這裡加上去是為了後續利用此框架編寫游戲,這裡還是把這個顯示文字的函數給大家
@staticmethod
def print_text(name,size,text,color):
font=pygame.font.SysFont(name,size)
image=font.render(text,True,color)
return image
最後,添加這段啟動的代碼
if __name__ == '__main__':
game=Game()
game.run()
這樣就好啦!
最終代碼(可供參考)
import pygame
from pygame.locals import *
import random as rd
import sys
import time
import threading
class Game:
def __init__(self):
pygame.init()
self.W,self.H=900,900
self.screen=pygame.display.set_mode((self.W,self.H))
pygame.display.set_caption("Find the Way")
self.a,self.b=28,39
self.lineWidth=5
thread=threading.Thread(target=self.createMaze,args=(self.a,self.b))
thread.start()
def listen(self):
for event in pygame.event.get():
if event.type==QUIT:
sys.exit()
def createMaze(self,a,b):
self.maze={}
for n in range(a*b):
for face in ["u","d","l","r"]:
self.maze[(n,face)]=1
history=[]
walls=[]
block=rd.choice(list(self.maze.keys()))[0]
history.append(block)
for face in ["u","d","l","r"]:
walls.append((block,face))
while len(walls)!=0:
time.sleep(0.001)
wall=rd.choice(walls)
twoBlocks=[wall[0]]
faces=[wall[1]]
if wall[1]=="u":
if wall[0]-a<0:
twoBlocks.append(None)
else:
twoBlocks.append(wall[0]-a)
faces.append("d")
elif wall[1]=="r":
if (wall[0]+1)%a!=0:
twoBlocks.append(wall[0]+1)
faces.append("l")
else:
twoBlocks.append(None)
elif wall[1]=="l":
if wall[0]%a!=0:
twoBlocks.append(wall[0]-1)
faces.append("r")
else:
twoBlocks.append(None)
elif wall[1]=="d":
if wall[0]+a>len(self.maze)/4-1:
twoBlocks.append(None)
else:
twoBlocks.append(wall[0]+a)
faces.append("u")
ins=[]
infaces=[]
for i,oneBlock in enumerate(twoBlocks):
if oneBlock in history:
ins.append(oneBlock)
infaces.append(faces[i])
if len(ins)==1:
mirrorFace=None
if infaces[0]=="u":
mirrorFace="d"
elif infaces[0]=="d":
mirrorFace="u"
elif infaces[0]=="r":
mirrorFace="l"
elif infaces[0]=="l":
mirrorFace="r"
if not (None in twoBlocks):
self.maze[(ins[0],infaces[0])]=0
other=None
if ins[0]==twoBlocks[0]:
other=twoBlocks[1]
else:
other=twoBlocks[0]
self.maze[(other,mirrorFace)]=0
walls.remove(wall)
history.append(other)
for face in ["u","l","r","d"]:
if self.maze.get((other,face))==1 and not ((other,face) in walls):
walls.append((other,face))
else:
walls.remove(wall)
continue
elif len(ins)==2:
walls.remove(wall)
def draw(self):
self.screen.fill((255,255,255))
for (n,face),is_wall in self.maze.items():
if is_wall:
y=n//self.a
x=n%self.a
absX=x*self.width
absY=y*self.height
if face=="u":
pygame.draw.line(self.screen,(0,0,0),(absX,absY),(absX+self.width,absY),self.lineWidth)
if face=="d":
pygame.draw.line(self.screen,(0,0,0),(absX,absY+self.height),(absX+self.width,absY+self.height),self.lineWidth)
if face=="l":
pygame.draw.line(self.screen,(0,0,0),(absX,absY),(absX,absY+self.height),self.lineWidth)
if face=="r":
pygame.draw.line(self.screen,(0,0,0),(absX+self.width,absY),(absX+self.width,absY+self.height),self.lineWidth)
def run(self):
while True:
self.listen()
self.draw()
self.refreshWindow()
pygame.display.update()
if __name__ == '__main__':
game=Game()
game.run()
本次的教學到這裡也就結束啦!喜歡我的文章的,別忘了多多點贊關注支持哦!謝謝~