Art Maze-generator

Readme

Maze Generator

This project is powered by p5.js and originates from this Maze Generator tutorial.

Live example here

Preview of Maze Generator


Project Code

This code is written and rendered using p5.js, a quick and easy graphical sketchbook engine written in JavaScript
class Cell {
	constructor(i, j) {
		this.i = i;
		this.j = j;
		this.walls = [true, true, true, true];
		this.visited = false;
	}
	
	checkNeighbors() {
		let neighbors = [];
		
		let top    = grid[ this.index(this.i    , this.j - 1) ];
		let right  = grid[ this.index(this.i + 1, this.j    ) ];
		let bottom = grid[ this.index(this.i    , this.j + 1) ];
		let left   = grid[ this.index(this.i - 1, this.j    ) ];
		
		if(top && !top.visited) {
			neighbors.push(top);
		}
		
		if(right && !right.visited) {
			neighbors.push(right);
		}
		
		if(bottom && !bottom.visited) {
			neighbors.push(bottom);
		}
		
		if(left && !left.visited) {
			neighbors.push(left);
		}
		
		if(neighbors.length) {
			let r = floor(random(0, neighbors.length));
			
			return neighbors[ r ];
		} else {
			return undefined;
		}
	}
	
	highlight() {
		let x = (this.i * w);
		let y = (this.j * w);
		
		noStroke();
		fill(0, 0, 255, 100);
		rect(x, y, w, w);
	}
	
	show() {
		let x = (this.i * w);
		let y = (this.j * w);
		
		stroke(255);
		
		if(this.walls[0]) {
			line(x    , y    , x + w, y    );   // top
		}
		
		if(this.walls[1]) {
			line(x + w, y    , x + w, y + w);   // right
		}
		
		if(this.walls[2]) {
			line(x + w, y + w, x    , y + w);   // bottom
		}
		
		if(this.walls[3]) {
			line(x    , y + w, x    , y    );   // left
		}
		
		if(this.visited) {
			fill(255, 0, 255, 100);
			noStroke();
			rect(x, y, w, w);
		}
	}
	
	index(i, j) {
		if((i < 0) || (j < 0) || (i > (cols - 1)) || (j > (rows - 1))) {
			return -1;
		}
		
		return (i + (j * cols));
	}
}

let cols, rows;
let w = 10;
let grid = [];

let current;

let stack = [];

function setup() {
	createCanvas(800, 600);
	
	cols = floor(width / w);
	rows = floor(height / w);
	
	for(let y = 0; y < rows; y++) {
		for(let x = 0; x < cols; x++) {
			let cell = new Cell(x, y);
			grid.push(cell);
		}
	}
	
	current = grid[0];
}

function draw() {
	background(51);
	
	for(let i = 0; i < grid.length; i++) {
		grid[ i ].show();
	}
	
	// step 1
	current.visited = true;
	current.highlight();
	let next = current.checkNeighbors();
	
	if(next) {
		next.visited = true;
		
		// step 2
		stack.push(current);
		
		// step 3
		removeWalls(current, next);
		
		// step 4
		current = next;
	} else if(stack.length) {
		current = stack.pop();
	}
}

function removeWalls(a, b) {
	let x = (a.i - b.i);
	
	if(x === 1) {
		a.walls[3] = false;
		b.walls[1] = false;
	} else if(x === -1) {
		a.walls[1] = false;
		b.walls[3] = false;
	}
	
	let y = (a.j - b.j);
	
	if(y === 1) {
		a.walls[0] = false;
		b.walls[2] = false;
	} else if(y === -1) {
		a.walls[2] = false;
		b.walls[0] = false;
	}
}

please visit our Contact Us page to get in touch
pyxol © 2021