Skip to content

Instantly share code, notes, and snippets.

@zaus
Created December 18, 2013 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zaus/8023434 to your computer and use it in GitHub Desktop.
Save zaus/8023434 to your computer and use it in GitHub Desktop.
A Pen by Gabriel Valfridsson.
<canvas></canvas>

Random Maze Generator

Generating a maze with a simple algorithm

  1. Find available directions
  2. pick one at random
  3. if no available directions, backtrack to last position loop step 1 to 3 until back at start location

A Pen by Gabriel Valfridsson on CodePen.

License.

//Configurable Parameters
var pathWidth = 10, //Width of the Maze Path
wall = 2, //Width of the Walls between Paths
outerWall = 2, //Width of the Outer most wall
width = 25, //Number paths fitted horisontally
height = 25, //Number paths fitted vertically
delay = 1, //Delay between algorithm cycles in ms
x = width/2|0, //Horisontal starting position
y = height/2|0 //Vertical starting position
var offset = pathWidth/2+outerWall,
map = []
canvas = document.querySelector('canvas')
ctx = canvas.getContext('2d')
canvas.width = outerWall*2+width*(pathWidth+wall)-wall
canvas.height = outerWall*2+height*(pathWidth+wall)-wall
ctx.strokeStyle = '#222a33'
ctx.lineCap = 'square'
ctx.lineWidth = pathWidth
ctx.beginPath()
for(var i=0;i<height;i++){
map[i] = []
for(var j=0;j<width;j++){
map[i][j] = false
}
}
console.log(x,y,map)
map[y][x] = true
route = [[x,y]]
ctx.moveTo(x*(pathWidth+wall)+offset,y*(pathWidth+wall)+offset)
loop = function(){
x = route[route.length-1][0]
y = route[route.length-1][1]
var directions = [[x+1,y],[x-1,y],[x,y+1],[x,y-1]],
alternatives = []
for(var i=0;i<directions.length;i++){
if(directions[i][0]>=0&&
directions[i][1]>=0&&
directions[i][0]<width&&
directions[i][1]<height&&
map[directions[i][1]][directions[i][0]]===false){
alternatives.push(directions[i])
}
}
if(alternatives.length===0){
route.pop()
if(route.length>0){
ctx.moveTo(route[route.length-1][0]*(pathWidth+wall)+offset,route[route.length-1][1]*(pathWidth+wall)+offset)
setTimeout(loop,delay)
}
return;
}
direction = alternatives[Math.random()*alternatives.length|0]
route.push([direction[0],direction[1]])
ctx.lineTo(direction[0]*(pathWidth+wall)+offset,direction[1]*(pathWidth+wall)+offset)
map[direction[1]][direction[0]] = true
ctx.stroke()
setTimeout(loop,delay)
}
loop()
body{
margin: 0;
background: #222a33;
}
canvas{
display: block;
margin: 20px auto 0 auto;
background: #d24;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment