User:Alessia/Pen plot this maze!‧

From XPUB & Lens-Based wiki

https://hub.xpub.nl/chopchop/~aleevadh/maze/


Javascript

let currentGrid;
const widthInput = document.getElementById('width');
const heightInput = document.getElementById('height');
const generateButton = document.getElementById('generate');
const canvas = document.getElementById('maze');
const ctx = canvas.getContext('2d');

html elements

const cellSize = 20;

size of each cell in the grid of the generated maze

class Cell {
   constructor(x, y) {
       this.x = x;
       this.y = y;
       this.walls = {top: true, right: true, bottom: true, left: true};
       this.visited = false;
   }
}

Cell object, x y coordinates

function createGrid(width, height) {
   const grid = [];
   for (let y = 0; y < height; y++) {
       const row = [];
       for (let x = 0; x < width; x++) {
           row.push(new Cell(x, y));
       }
       grid.push(row);
   }
   return grid;
}

with specified width and height creates a new cell object

function drawMaze(grid) {
   const width = grid[0].length;
   const height = grid.length;
   canvas.width = width * cellSize;
   canvas.height = height * cellSize;
   ctx.fillStyle = 'white';
   ctx.fillRect(0, 0, canvas.width, canvas.height);
   for (let y = 0; y < height; y++) {
       for (let x = 0; x < width; x++) {
           const cell = grid[y][x];
           ctx.strokeStyle = 'black';
           ctx.lineWidth = 2;
           if (cell.walls.top) {
               ctx.beginPath();
               ctx.moveTo(x * cellSize, y * cellSize);
               ctx.lineTo((x + 1) * cellSize, y * cellSize);
               ctx.stroke();
           }
       }
   }
}

starting ending point of the maze, drawing of walls

generateButton.addEventListener('click', () => {
   const width = parseInt(widthInput.value, 10);
   const height = parseInt(heightInput.value, 10);
   generateMaze(width, height);
});

add event listener to generate! button. It takes the chosen values of height and width, convert them into integers, creates generateMaze

generateMaze(parseInt(widthInput.value, 10), parseInt(heightInput.value, 10));
const exportButton = document.getElementById('save');


generate! Save

function printMaze() {
   window.print();
}
const printButton = document.getElementById('print');
printButton.addEventListener('click', printMaze);

printMaze event listener print button


I watched some tutorials and followed some examples to get this done:

https://medium.com/swlh/how-to-create-a-maze-with-javascript-36f3ad8eebc1
https://www.youtube.com/watch?v=RrpFqVBLlmI&ab_channel=TheB4XGuy
https://www.youtube.com/watch?v=EN733Aq4ynM&ab_channel=Devression
https://github.com/topics/maze-generator?l=javascript
https://www.youtube.com/watch?v=HyK_Q5rrcr4&ab_channel=TheCodingTrain