After messing around with a maze in another discussion, I thought I would see what was involved in writing a maze generating program. This code is set up to make mazes from 10 x 10 to 25 x 25. It could be changed to make even larger mazes if I wanted to remove the animation, but I liked watching what was happening as the maze was created.
supportedOrientations(LANDSCAPE_ANY)
function setup()
parameter.integer("dim",10,25,12,setup1)
end
function setup1()
tab={vec2(0,1),vec2(1,0),vec2(0,-1),vec2(-1,0)}
tab1={3,4,1,2}
dots={}
locations={}
square={}
size=HEIGHT/(dim+5)
s2=size/2
s4=size/4
for z=1,dim*dim do
square[z]=vec4(1,1,1,1)
end
curr=vec2(math.random(dim),math.random(dim))
table.insert(locations,curr)
table.insert(dots,vec3(curr.x,curr.y,2))
prevCurr=vec2(0,0)
end
function draw()
background(40, 40, 50)
stroke(255)
strokeWidth(2)
if #locations>0 then
nextSquare()
if prev then
curr=locations[#locations]
table.insert(dots,vec3(curr.x,curr.y,1))
table.remove(locations,#locations)
prevCurr=curr
else
if prevCurr.x>0 then
table.insert(locations,prevCurr)
prevCurr=vec2(0,0)
end
table.insert(locations,curr)
table.insert(dots,vec3(curr.x,curr.y,2))
end
for a,b in pairs(dots) do
noStroke()
if b.z==1 then
fill(0, 45, 255, 255)
elseif b.z==2 then
fill(255, 0, 46, 255)
end
ellipse(b.x*size+s2,b.y*size+s2,s4)
end
fill(255, 255, 0)
ellipse(curr.x*size+s2,curr.y*size+s2,size-5)
else
square[1][4]=0
square[dim*dim][2]=0
text("Tap screen for another "..dim.." x "..dim.." maze",WIDTH/2,HEIGHT-100)
end
stroke(255)
strokeWidth(2)
local v=0
for a=1,dim do
for b=1,dim do
v=v+1
if square[v].x==1 then -- top line
line(a*size,(b+1)*size,(a+1)*size,(b+1)*size)
end
if square[v].y==1 then -- right line
line((a+1)*size,b*size,(a+1)*size,(b+1)*size)
end
if square[v].z==1 then -- bottom line
line(a*size,b*size,(a+1)*size,b*size)
end
if square[v].w==1 then -- left line
line(a*size,b*size,a*size,(b+1)*size)
end
end
end
end
function nextSquare()
local done=false
prev=false
local side={0,0,0,0}
while not done do
local r=math.random(4)
side[r]=1
nxt=curr+tab[r]
if nxt.x>=1 and nxt.x<=dim and nxt.y>=1 and nxt.y<=dim then
local c=curr.x*dim+curr.y-dim
local n=nxt.x*dim+nxt.y-dim
local tn=square[n][1]+square[n][2]+square[n][3]+square[n][4]
if tn>3 then
square[c][r]=0
square[n][tab1[r]]=0
curr=nxt
done=true
return
end
end
local ts=side[1]+side[2]+side[3]+side[4]
if ts==4 then
prev=true
done=true
end
end
end
function touched(t)
if t.state==BEGAN then
setup1()
end
end