I am trying to make a randomized maze generator, but for some reason the recursion doesn't work and only one path is made.
local maze = workspace:WaitForChild("Model2")
local grid = table.create(#maze:GetChildren(),table.create(#maze:FindFirstChild("1"):GetChildren(),0))
local directionsX = {
N = 0;
E = 1;
S = 0;
W = -1;
}
local directionsY = {
N = 1;
E = 0;
S = -1;
W = 0;
}
local opposites = {
N = "S";
E = "W";
S = "N";
W = "E";
}
local function destroywall(x,y,d,tx,ty,td)
maze:FindFirstChild(tostring(y)):FindFirstChild(tostring(x)):FindFirstChild(d):Destroy()
maze:FindFirstChild(tostring(ty)):FindFirstChild(tostring(tx)):FindFirstChild(td):Destroy()
end
local function checkifvalid(x,y,grid)
if grid[y] then
if grid[y][x] then
return true
end
end
end
local function colour(x,y,types)
if types == 1 then
maze:FindFirstChild(tostring(y)):FindFirstChild(tostring(x)):FindFirstChild("Part").BrickColor = BrickColor.Green()
else
maze:FindFirstChild(tostring(y)):FindFirstChild(tostring(x)):FindFirstChild("Part").BrickColor = BrickColor.White()
end
end
local function shuffle(array)
local buffer = {}
for i = 1, #array do
buffer[i] = array[i]
end
local newArray = {}
while (#buffer > 0) do
newArray[#newArray+1] = table.remove(buffer, math.random(#buffer))
end
return newArray
end
local function recursivebacktracking(cx,cy,grid)
local newdirections = shuffle({"N","S","E","W"})
for i,direction in pairs(newdirections) do
if checkifvalid(cx + directionsX[direction], cy + directionsY[direction],grid) then
if grid[cy + directionsY[direction]][cx + directionsX[direction]] == 0 then
local nx, ny = cx + directionsX[direction], cy + directionsY[direction]
print(nx..ny.."works")
grid[cy][cx] = 1
destroywall(cx,cy,direction,nx,ny,opposites[direction])
colour(cx,cy,1)
recursivebacktracking(nx, ny, grid)
end
end
end
end
recursivebacktracking(1, 1, grid)
