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;
  justify-content: center;
  align-items: center;
}
#grid {
  display:grid;
  grid-template-columns: repeat(50, 15px);
  
}

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

.wall {
  background:black;
}

JavaScript

const nodes = [];
const width = 50;
const height = 20;


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

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

const getRandomInt = (max) => {
  return Math.floor(Math.random() * (max - 2)) + 1;
};

const getRandomPoint = (x, y) => {
  return {
    x: getRandomInt(x),
    y: getRandomInt(y)
  };
};


// 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 borders = addBorders(width, height)

const generateRecursiveDivisionMaze = (startPos, endPos, width, height) => {
  const walls = [];
  const counter = 0;
  const doors = [];

  divide(
    startPos,
    endPos,
    walls,
    doors, {
      x: 1,
      y: 1
    },
    width - 1,
    height - 1,
    counter
  );

  return walls;
};


// Helper function to decide whether to cut horizontally or...