Last active
May 21, 2017 18:26
-
-
Save morkin1792/336ddc411bfb50580693c9b250f34f12 to your computer and use it in GitHub Desktop.
Algoritmo Gerador de Mazes com base no Algoritmo de divisão recursiva.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Fonte algorítmo: https://en.wikipedia.org/wiki/Maze_generation_algorithm#Recursive_division_method | |
math.randomseed(os.time()) | |
function generate(x, y) --gera uma table de table com # e ' ' no centro representando uma maze | |
local r = {} | |
for i=1,y do | |
local ry = {} | |
for j=1, x do | |
if i ~= 1 and i~=y and j~=1 and j~=x then -- se não for das bordas | |
table.insert(ry, ' ') | |
else | |
table.insert(ry, '#') | |
end | |
end | |
table.insert(r, ry) | |
end | |
return r | |
end | |
function mazing(maze, p1, p2, c, cmax) | |
-- m = uma table de table representando a maze, | |
-- p1, p2 = dois pontos representando os cantos supeior esquerdo e inferior direito | |
-- c = contador da complexidade da maze | |
-- cmax = limite de complexidade da maze | |
if math.min(p2.x - p1.x, p2.y - p1.y) <= 3 or c >= cmax then return end -- se não tem mais espaço ou a complexidade chegou no limite | |
-- dividindo a maze em outras 4 com 1 ponto | |
local p = {} | |
p.x,p.y = math.random(p1.x+2, p2.x-2), math.random(p1.y+2, p2.y-2) -- ponto aleatorio para dividir maze | |
mazing(maze, p1, p, c+1, cmax) -- as 4 mazes geradas com a divisão da original com o ponto | |
mazing(maze, p, p2, c+1, cmax) | |
mazing(maze, {x=p.x, y=p1.y}, {x=p2.x, y=p.y}, c+1, cmax) | |
mazing(maze, {x=p1.x, y=p.y}, {x=p.x, y=p2.y}, c+1, cmax) | |
for i=p1.x, p2.x do -- marcando parede referente ao ponto horizontalmente | |
maze[p.y][i] = '#' | |
end | |
for i=p1.y, p2.y do -- marcando parede verticalmente | |
maze[i][p.x] = '#' | |
end | |
-- furando as paredes geradas | |
local wx = math.random(p1.x, p.x-1) -- furo na horizontal | |
local w2x = math.random(p.x+1, p2.x) -- outro furo na horizontal | |
local twy = {math.random(p1.y, p.y-1), math.random(p.y+1, p2.y)} -- opcoes para furo na vertical, eliminando p.y | |
local wy = twy[math.random(#twy)] --escolhendo entre opcoes | |
maze[p.y][wx] = ' ' --marcando | |
maze[p.y][w2x] = ' ' | |
maze[wy][p.x] = ' ' | |
end | |
function mprint(maze, x, y) -- print maze | |
for i=1, y do | |
local s = "" | |
for j=1, x do | |
s = s .. maze[i][j] | |
end | |
print(s) | |
end | |
end | |
x, y = 75, 27 | |
complex = 1 | |
maze = generate(x,y) | |
mazing(maze, {x=2, y=2}, {x=x-1, y=y-1}, 0, complex) | |
mprint(maze, x, y) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment