local MazeGen = require("maze")
local Maze = MazeGen.New(20, 10)
MazeGen.Print(Maze)
local Walls = MazeGen.GetWalls(Maze)
for i, v in ipairs(Walls) do
print("X: "..v.PositionX)
print("Y: "..v.PositionY)
print("Width: "..v.Width)
end
local MazeGen = {}
local Dirs = {
{-1, 0, 3, 4},
{0, -1, 1, 2},
{1, 0, 4, 3},
{0, 1, 2, 1}
}
local function Visit(Maze, X, Y, MoveID)
local Dx, Dy, WallExit, WallEnter = unpack(Dirs[MoveID])
local Current = Maze[X + Dx] and Maze[X + Dx][Y + Dy]
if not Current or Current.Visited then
return
end
Current.Visited = true
Current.Walls[WallEnter] = false
Maze[X][Y].Walls[WallExit] = false
local Options = {1, 2, 3, 4}
for i = 1, 4 do
local Id = table.remove(Options, math.random(#Options))
if Visit(Maze, X + Dx, Y + Dy, Id) then
return
end
end
end
function MazeGen.New(X, Y)
math.randomseed(os.time())
local Maze = {}
for i = 1, X do
Maze[i] = {}
for j = 1, Y do
Maze[i][j] = {
Walls = {true, true, true, true}, -- up, down, left, right
Visited = false
}
end
end
Visit(Maze, math.random(#Maze - 2) + 1, math.random(#Maze[1] - 2) + 1, math.random(4))
return Maze
end
local Display = {
-- 0 0 0 0
"╹", -- 1 0 0 0
"╻", -- 0 1 0 0
"┃", -- 1 1 0 0
"╸", -- 0 0 1 0
"┛", -- 1 0 1 0
"┓", -- 0 1 1 0
"┫", -- 1 1 1 0
"╺", -- 0 0 0 1
"┗", -- 1 0 0 1
"┏", -- 0 1 0 1
"┣", -- 1 1 0 1
"━", -- 0 0 1 1
"┻", -- 1 0 1 1
"┯", -- 0 1 1 1
"╋" -- 1 1 1 1
}
function MazeGen.Print(Maze)
local Output = ""
for y = 1, #Maze[1] do
for x = 1, #Maze do
local Id = 0
for i, v in ipairs(Maze[x][y].Walls) do
if not v then
Id = Id + 2 ^ (i - 1)
end
end
Output = Output..Display[Id]
end
Output = Output.."\n"
end
print(Output)
end
function MazeGen.GetWalls(Maze)
local Walls = {}
for X = 1, #Maze do
local Length = 0
local Start = 0
for Y = 1, #Maze[X] do
if Maze[X][Y].Walls[3] then
if Length == 0 then
Start = Y
end
Length = Length + 1
elseif Length ~= 0 then
table.insert(Walls, {
PositionX = X,
PositionY = Start + (Length - 1) * .5,
Width = Length
})
Length = 0
end
end
table.insert(Walls, {
PositionX = X,
PositionY = Start + #Maze[X] * .5 - 1,
Width = Length
})
end
return Walls
end
return MazeGen