I made this maze generation program following this post
The top answer has some algorithm-style code which I tried to implement in python using this code, but for some reason it creates "loops" around 1 wide tiles, which I don't want to happen
My code:
import numpy as np
import random
from gridmaker import Grid # my custom class
xlim = 50
ylim = 50
image = Grid(xlim, ylim)
fronts = []
def test_if_wall(x, y):
global image
def scan(x, y):
'''scanning'''
global image
coords = []
if x == 1:
x == 3
elif y == 1:
y == 3
elif x == 49:
x == 47
elif y == 49:
y == 47
if image.test_colour(x + 2, y) == False:
coords.append([x + 2, y])
if image.test_colour(x - 2, y) == False:
coords.append([x - 2, y])
if image.test_colour(x, y + 2) == False:
coords.append([x, y + 2])
if image.test_colour(x, y - 2) == False:
coords.append([x, y - 2])
return coords
def check_neighbours(x, y):
global image
coords = []
if x == 1:
x == 3
elif y == 1:
y == 3
elif x == 49:
x == 47
elif y == 49:
y == 47
if image.test_colour(x + 2, y) == True:
coords.append([x + 2, y])
if image.test_colour(x - 2, y) == True:
coords.append([x - 2, y])
if image.test_colour(x, y + 2) == True:
coords.append([x, y + 2])
if image.test_colour(x, y - 2) == True:
coords.append([x, y - 2])
return coords
def join_to_rneighbour(x, y):
global image
nb = check_neighbours(x,y)
#print(nb)
rand = random.choice(nb)
if rand == [x + 2, y]:
image.set_white(x + 1, y)
image.set_white(x, y)
elif rand == [x - 2, y]:
image.set_white(x - 1, y)
image.set_white(x, y)
elif rand == [x, y + 2]:
image.set_white(x, y + 1)
image.set_white(x, y)
elif rand == [x, y - 2]:
image.set_white(x, y - 1)
image.set_white(x, y)
fronts = []
def logic(x, y):
global image, fronts
_fronts = scan(x, y)
for item in _fronts:
fronts.append(item)
image.set_white(x, y)
while fronts != []:
rand = random.choice(fronts)
xp = rand[0]
yp = rand[1]
join_to_rneighbour(xp, yp)
fronts.remove([xp, yp])
logic(xp, yp)
logic(3, 3)
print(image.test_colour(0,0))
image.refresh()
(I'm writing this in an IPython notebook)
class Grid()
makes a matplotlib graph like the one in the image and it can:
- Set a block to white or black:
image.set_white(x, y)
sets cell to 1,image.set_black(x, y)
sets cell to 0 - Test colour:
image.test_colour(x, y)
returns True if there is a passage there and False if there is a wall there - Refresh graph:
image.refresh()
Grid.grid
is anumpy.zeros
array of specified size50, 50
I've also tried switching the function in join_to_rneighbour()
to scan()
instead of check_neighbours()
but it then creates "loops" where there are walls on all four sides of a cell.