JSFiddle - React, Tailwind, and code Playground
by amatiasq
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/2.6.1/phaser.min.js"></script>
JavaScript
/* eslint-env es6 */
const PAUSE = 500;
const COLUMNS = 16;
const ROWS = COLUMNS;
const CELL_SIZE = 50;
const WORLD_WIDTH = CELL_SIZE * COLUMNS;
const WORLD_HEIGHT = CELL_SIZE * ROWS;
class Pathfinding {
constructor(grid, startPoint, endPoint) {
this.grid = grid;
this.start = grid.getNodeFromPoint(startPoint);
this.end = grid.getNodeFromPoint(endPoint);
this.open = [];
this.closed = [];
this.setOpen(this.start);
}
next() {
if (this.neighbours)
this.processNeighbour();
else if (this.open.length)
return this.processOpen();
else
throw new Error('Path not found');
}
processOpen() {
let best = 0;
for (let i = 1; i < this.open.length; i++) {
const bestNode = this.open[best];
const entry = this.open[i];
if (entry.fCost < bestNode.fCost || (entry.fCost === bestNode.fCost && entry.hCost < bestNode.hCost))
best = i;
}
if (this.current)
this.current.tint = 0x888888;
this.current = this.open[best];
this.setClosed(this.current, best);
this.current.tint = 0x00FFFF;
if (this.current === this.end)
return Pathfinding.retrace(this.start, this.end);
this.neighbours = this.grid.getNeighbours(this.current);
console.log(`current ${this.current} neighbors:${this.neighbours.length}`);
this.neighbourIndex = 0;
while (this.neighbours)
this.processNeighbour();
}
processNeighbour() {
const neighbour = this.neighbours[ this.neighbourIndex++ ];
console.log(`processsing ${neighbour}`);
if (this.neighbourIndex >= this.neighbours.length)
this.neighbours = null;
if (this.closed.indexOf(neighbour) !== -1)
return;
const movement = this.current.gCost + Pathfinding.getDistance(this.current, neighbour);
if (movement < neighbour.gCost || this.open.indexOf(neighbour) === -1) {
neighbour.gCost = movement;
neighbour.hCost = Pathfinding.getDistance(neighbour, this.end);
...