A* algorithm implementation
by Julien Roche
HTML
<canvas></canvas>
CSS
html, body {
border: none;
height: 100%;
margin: 0px 0px 0px 0px;
overflow: hidden;
padding: 0px 0px 0px 0px;
width: 100%;
}
JavaScript
const AVAILABLE_POSITIONS = [];
const NB_ROWS = 50;
const NB_COLUMNS = 50;
const NB_ELEMENTS = Math.round(NB_ROWS * NB_COLUMNS * 0.15);
for (let i = 0; i < NB_ROWS; ++i) {
for (let j = 0; j < NB_COLUMNS; ++j) {
AVAILABLE_POSITIONS.push({ 'x': i, 'y': j });
}
}
AVAILABLE_POSITIONS.shift(); // Remove first position
AVAILABLE_POSITIONS.pop(); // Remove last position
class Maze {
static draw(elementPositions, canvasElement) {
let context = canvasElement.getContext('2d');
let cellWidth = Math.floor(canvasElement.width / (NB_COLUMNS + 2));
let cellHeight = Math.floor(canvasElement.height / (NB_ROWS + 2));
let areaWidth = canvasElement.width - 2 * cellWidth;
let areaHeight = canvasElement.height - 2 * cellHeight;
// draw background
context.save();
context.fillStyle = 'black';
context.fillRect(0, 0, canvasElement.width, canvasElement.height);
context.restore();
context.save();
context.strokeStyle = 'white';
context.rect(cellWidth, cellHeight, areaWidth, areaHeight);
context.stroke();
context.restore();
// draw start cell and end cell
context.save();
context.fillStyle = 'red';
context.fillRect(cellWidth, cellHeight, cellWidth, cellHeight);
context.restore();
context.save();
context.fillStyle = 'green';
context.fillRect(areaWidth, areaHeight, cellWidth, cellHeight);
context.restore();
// draw block elements
context.save();
context.fillStyle = 'gray';
for (let position of elementPositions) {
context.fillRect(cellWidth * (position.x + 1), cellHeight * (position.y + 1), cellWidth, cellHeight);
}
context.restore();
}
static generateElements() {
let positions = [];
let i = NB_ELEMENTS;
while (i - 1 > 0) {
i -=...