程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python prim algorithm generates maze and visualizes it through pyGame

編輯:Python

The first two articles , We use Prim The algorithm generates articles , This time, , We need to use it. Pygame Visualize the complete generation process of the maze


Import module first , Here we need to use pygame, Random library ,sys,time Used to slow down ,threading Another thread for generating the maze

import pygame
from pygame.locals import *
import random as rd
import sys
import time
import threading

We implement... In the form of classes and objects , Definition Game class , Set the window in the initialization function ,a and b Represents the size of the maze ,lineWidth It is the thickness of the labyrinth wall painted in the window , Create a thread , Point to createMaze(createMaze Will be added below the code of ), Then start the thread

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()

establish listen function , Used to listen for events

 def listen(self):
for event in pygame.event.get():
if event.type==QUIT:
sys.exit()

Next is the code to create the maze , In the last article, when traversing a wall to generate a maze , We have written the code in its entirety , Just modify a small part of the content , The changes to be made are as follows :

Add to function arguments self

def createMaze(self,a,b):

then , Put... In the function maze Change all to self.maze, Directly stored in class variables

The code is no longer shown here , If you need algorithm code, you can check my last article :

Python Prim Algorithm Create mazes _Leleprogrammer The blog of -CSDN Blog Python Prim Algorithm Generate a maze by traversing the walls , Come and see !https://blog.csdn.net/leleprogrammer/article/details/125472436?spm=1001.2014.3001.5501 Or copy it in the final code at the end of the text , To learn the principle of the algorithm , Just check out the previous article

Next ,draw function , Used to draw mazes , The code here is not too hard , Just don't explain too much

 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)

And then there was run function , Main circulation

 def run(self):
while True:
self.listen()
self.draw()
self.refreshWindow()
pygame.display.update()

Functions for displaying text , There's no use for , You can't add , It is added here to make use of this framework to write games in the future , Here is the function to display text for you

 @staticmethod
def print_text(name,size,text,color):
font=pygame.font.SysFont(name,size)
image=font.render(text,True,color)
return image

Last , Add this startup code

if __name__ == '__main__':
game=Game()
game.run()

That's good !

The final code ( For reference )

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()

This teaching is over here ! Like my article , Don't forget to give more praise and support ! thank you ~


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved