The first function that we will add is called maze_generator_kruskal.
Uses randomized Kruskal's algorithm to generate a maze.
https://en.wikipedia.org/wiki/Maze_generation_algorithm#Randomized_Kruskal.27s_algorithm
Normally this algorithm generates 'perfect' mazes, with only one route from end to beginning. For gameplay reasons multiple routes through the maze is preferred. This is achieved by randomly deleting additional walls.
class Cell {
constructor(x, y, i, j) {
this.ind_x = i;
this.ind_y = j;
this.x = x;
this.y = y;
this.right_wall = true;
this.bottom_wall = true;
}
};
We will embed a function called shuffle. Shuffles array in place. Taken from http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript
function shuffle(a) {
var j, x, i;
for (var i = a.length; i; i--) {
j = Math.floor(Math.random() * i);
x = a[i - 1];
a[i - 1] = a[j];
a[j] = x;
}
}
Our next function is called find_cell_set. Finds the set where the given cell is found.
function find_cell_set(cell, sets) {
for (set in sets) {
if (sets[set].has(cell)) return set;
}
}
Our next function is called join_cell_sets. Checks if given cells are in different sets, joins the sets and returns true. Otherwise returns false.
function join_cell_sets(cell_1, cell_2, sets) {
set_ind1 = find_cell_set(cell_1, sets);
set_ind2 = find_cell_set(cell_2, sets);
if (!(set_ind1 === set_ind2)) {
var joined_set = new Set(function*() {
yield* sets[set_ind1]; yield* sets[set_ind2]; }()
);
delete sets[set_ind1];
delete sets[set_ind2];
sets.push(joined_set);
return true;
}
return false;
}
We will create some attributes for each of our cells.
cell_size_min = 30;
cell_size_max = 100;
rand = Math.random();
CELL_SIZE = 30 + (rand * (100-30)); // A random number between min and max
CELL_SIZE = Math.floor(CELL_SIZE);
console.log(CELL_SIZE);
console.log(CELL_SIZE % 5);
CELL_SIZE -= CELL_SIZE % 5;
console.log(CELL_SIZE);
Next we will create cells to assist with maze generation.
var cells = [];
CELLS_X = Math.floor(WIDTH / CELL_SIZE);
CELLS_Y = Math.floor(HEIGHT / CELL_SIZE);
for (var i = 0; i < CELLS_X; i++) {
var x = i * CELL_SIZE + CELL_SIZE / 2;
var column = []
for (var j = 0; j < CELLS_Y; j++) {
var y = j * CELL_SIZE + CELL_SIZE / 2;
new_cell = new Cell(x, y, i, j);
column[j] = new_cell;
}
cells[i] = column;
}