JSFiddle - React, Tailwind, and code Playground
by Gwyn Milcote
HTML
<canvas id='maze'></canvas>
<button id='generate-btn'>Generate</button>
JavaScript
function replaceAt(str, index, replacement) {
// Replace a character at index in a string
if (index > str.length - 1) {
return str;
}
return str.substr(0, index) + replacement + str.substr(index + 1);
}
function stringVal(str, index) {
// Get the number value at a specific index in a string (0 or 1)
return parseInt(str.charAt(index), 10);
}
function getEntryNode( entries, type, gate = false ) {
if ( !hasEntries( entries ) ) {
return false;
}
if( 'start' === type ) {
return gate ? entries.start.gate : {'x': entries.start.x, 'y': entries.start.y};
}
if( 'end' === type ) {
return gate ? entries.end.gate : {'x': entries.end.x, 'y': entries.end.y};
}
return false;
}
function hasEntries( entries ) {
if ( entries.hasOwnProperty( 'start' ) && entries.hasOwnProperty( 'end' ) ) {
return true;
}
return false;
}
function randomNumber(min, max){
return Math.floor(Math.random() * (max - min + 1) + min);
}
function randomArray(array){
return array[Math.floor(Math.random()*array.length)];
}
function Maze() {
const settings = {
width: 20,
height: 20,
wallSize: 8,
entryType: 'horizontal',
color: '#000000',
backgroundColor: '#FFFFFF',
// No restrictions
maxMaze: 0,
maxCanvas: 0,
maxCanvasDimension: 0,
}
this.matrix = [];
this.width = parseInt(settings['width'], 10);
this.height = parseInt(settings['height'], 10);
this.wallSize = parseInt(settings['wallSize'], 10);
this.entryNodes = this.getEntryNodes(settings['entryType']);
this.color = settings['color'];
this.backgroundColor = settings['backgroundColor'];
this.maxMaze = parseInt(settings['maxMaze'], 10);
this.maxCanvas = parseInt(settings['maxCanvas'], 10);
this.maxCanvasDimension = parseInt(settings['maxCanvasDimension'], 10);
}
Maze.prototype.generate = function() {
if (!this.isValidSize()) {
this.matrix = [];
alert('Please use smaller maze dimensions');
return;
}
let nodes = this.generateNodes();
nodes =...