Skip to content

Instantly share code, notes, and snippets.

@RichardMarks
Created April 16, 2017 22:27
Show Gist options
  • Save RichardMarks/2e81c2bbbb410f493f40d3a9b7a5d2de to your computer and use it in GitHub Desktop.
Save RichardMarks/2e81c2bbbb410f493f40d3a9b7a5d2de to your computer and use it in GitHub Desktop.
Simple 2D Maze Generator
// Maze Generator
// (c) 2017, Bang Bang Attack Studios
// http://www.bangbangattackstudios.com
const random = options => {
const index = Math.random() * options.length
return options[~~index]
}
const maze = (width, height, factory) => {
const stack = [
[1, 1, width - 2, height - 2]
]
const map = []
for (let column = 0; column < width; column += 1) {
map.push([])
for (let row = 0; row < height; row += 1) {
const edge = (column === 0 || row === 0 || column + 1 === width || row + 1 === height)
map[column].push(edge ? 1 : 0)
}
}
const partitionRoom = room => {
const ax = []
const ay = []
for (let i = room[0] + 1; i < room[2]; i += 1) {
const top = map[i][room[1] - 1]
const bottom = map[i][room[3] + 1]
if (i % 2 === 0 && top && bottom) {
ax.push(i)
}
}
for (let i = room[1] + 1; i < room[3]; i += 1) {
const left = map[room[0] - 1][i]
const right = map[room[2] + 1][i]
if (i % 2 === 0 && left && right) {
ay.push(i)
}
}
if (!ax.length || !ay.length) {
return
}
const x = random(ax)
const y = random(ay)
map[x][y] = 1
const walls = []
const left = []
const right = []
const top = []
const bottom = []
walls.push(left)
walls.push(right)
walls.push(top)
walls.push(bottom)
for (let i = room[0]; i < x; i += 1) {
map[i][y] = 1
left.push([i, y])
}
for (let i = x + 1; i <= room[2]; i += 1) {
map[i][y] = 1
right.push([i, y])
}
for (let i = room[1]; i < y; i += 1) {
map[x][i] = 1
top.push([x, i])
}
for (let i = y + 1; i <= room[3]; i += 1) {
map[x][i] = 1
bottom.push([x, i])
}
const solid = random(walls)
walls.forEach(wall => {
if (wall !== solid) {
const hole = random(wall)
map[hole[0]][hole[1]] = 0
}
})
stack.push([room[0], room[1], x - 1, y - 1])
stack.push([x + 1, room[1], room[2], y - 1])
stack.push([room[0], y + 1, x - 1, room[3]])
stack.push([x + 1, y + 1, room[2], room[3]])
}
while (stack.length) {
partitionRoom(stack.shift())
}
for (let column = 0; column < width; column += 1) {
for (let row = 0; row < height; row += 1) {
factory && factory(column, row, map[column][row])
}
}
return map
}
module.exports = maze
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment