User:Alessia/Pen plot this maze!‧: Difference between revisions
(maze js) |
|||
Line 80: | Line 80: | ||
generateMaze(parseInt(widthInput.value, 10), parseInt(heightInput.value, 10)); | generateMaze(parseInt(widthInput.value, 10), parseInt(heightInput.value, 10)); | ||
const exportButton = document.getElementById('save'); | |||
generate! | |||
generate! Save | |||
function printMaze() { | |||
window.print(); | |||
} | |||
const printButton = document.getElementById('print'); | |||
printButton.addEventListener('click', printMaze); | |||
printMaze event listener print button |
Revision as of 10:14, 2 May 2024
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