Recursive Division Maze

Algorithm to create a maze through recursively dividing rooms

by Mohammed Affan

HTML

<div id ="grid"></div>

CSS

body {
  display:flex;
  height:100vh;
  align-items: center;
  justify-content:center;
}

#grid {
  display:grid;
  grid-template-columns: repeat(30, 15px);
  
}

.node {
  width: 15px;
  height: 15px;
  border: 1px solid black;
}

.wall {
  background:black;
}

JavaScript

const nodes = [];
const width = 30;
const height = 30;


// Helper functions
const pointToString = (point) => {
  return `${point.x}, ${point.y}`
}

const stringToPoint = (pointString) => {
  return pointString.split(", ").map((coord) => parseInt(coord));
};

function randomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}


// Initializing the grid of nodes
for (let y = 0; y < height; y++) {
  const row = []
  for (let x = 0; x < width; x++) {
    row.push({
      x: x,
      y: y
    })
  }
  nodes.push(row)
}


// Adding the nodes to the UI
$.each(nodes.flat(), function(index, value) {
  $('<div />', {
    'text': '',
    'class': 'node',
    'data-pos': pointToString(value)
  }).appendTo('#grid');
});

// Function to add walls, to be run at the end of maze creation
const addWallsToUI = (walls) => {
  for (const wall of walls) {
    $(`div[data-pos="${wall}"]`).addClass('wall')
  }
}


// Function to add borders
const addBorders = (width, height) => {
  const borders = [];
  for (let i = 0; i < width; i++) {
    borders.push(pointToString({
      x: i,
      y: 0
    }));
  }
  for (let i = 0; i < height; i++) {
    borders.push(pointToString({
      x: width - 1,
      y: i
    }));
  }
  for (let i = width - 1; i >= 0; i--) {
    borders.push(pointToString({
      x: i,
      y: height - 1
    }));
  }
  for (let i = height - 1; i >= 0; i--) {
    borders.push(pointToString({
      x: 0,
      y: i
    }));
  }

  return borders;
};

const walls = [];

function generate(width, height, numDoors) {

  addInnerWalls(true, 1, width - 2, 1, height - 2);
}



function addInnerWalls(h, minX, maxX, minY, maxY) {
  if (h) {

    if (maxX - minX < 2) {
      return;
    }

    var y = Math.floor(randomNumber(minY, maxY) / 2) * 2;
    addHWall(minX, maxX, y);

    addInnerWalls(!h, minX, maxX, minY, y - 1);
    addInnerWalls(!h, minX, maxX, y + 1, maxY);
  } else {
    if (maxY - minY < 2) {
      return;
    }

    var x =...