81 lines
2.3 KiB
JavaScript
81 lines
2.3 KiB
JavaScript
const { parentPort } = require("worker_threads");
|
|
|
|
const grids = require("../Game/Grids");
|
|
|
|
parentPort.on("message", data => {
|
|
const { position, mapID, id, preSelectedDestinationNode, predefinedArea } = data;
|
|
const grid = grids[mapID - 1];
|
|
const obj = grid.getCell(position.x, position.y);
|
|
const open = [];
|
|
const close = {};
|
|
|
|
let desinationNode = preSelectedDestinationNode ? preSelectedDestinationNode : grid.randomNode(10);
|
|
|
|
while (desinationNode.x === position.x && desinationNode.y === position.y)
|
|
desinationNode = predefinedArea ? grid.randomNodeInArea(predefinedArea) : grid.randomNode(10);
|
|
|
|
const destination = grid.getCell(desinationNode.x, desinationNode.y);
|
|
|
|
open.push({
|
|
xw: obj.xw,
|
|
xh: obj.xh,
|
|
gCost: 0,
|
|
hCost: 0,
|
|
fCost: 0
|
|
});
|
|
|
|
while (open.length > 0) {
|
|
let current = open.reduce((prev, curr) => prev.hCost < curr.hCost ? prev : curr); // uhhhh
|
|
open.splice(open.findIndex(s => s === current), 1); // uhh
|
|
|
|
close[`${current.xw}-${current.xh}`] = true;
|
|
|
|
if (current.xw === destination.xw && current.xh === destination.xh) {
|
|
const path = backtrace(current, grid);
|
|
path.shift();
|
|
|
|
return parentPort.postMessage({
|
|
path,
|
|
id,
|
|
mapID,
|
|
messageId: 1
|
|
});
|
|
};
|
|
|
|
const neighbours = grid.getNodeNeighbours(current);
|
|
for (let i = 0; i < neighbours.length; i++) {
|
|
const n = neighbours[i];
|
|
if (!grid.isValidNode(n)) continue;
|
|
|
|
let closed = close[`${n.xw}-${n.xh}`];
|
|
if (closed) continue;
|
|
|
|
let alreadyIn = open.find(c => c.xw === n.xw && c.xh === n.xh);
|
|
if (alreadyIn) continue;
|
|
|
|
n.gCost = current.gCost + 1.4;
|
|
n.hCost = Math.abs(n.xw - destination.xw) + Math.abs(n.xh - destination.xh);
|
|
n.fCost = n.gCost + n.hCost;
|
|
n.parent = current;
|
|
|
|
open.push(n);
|
|
};
|
|
};
|
|
|
|
return false;
|
|
});
|
|
|
|
function backtrace(node, map) {
|
|
let coords = map.getCoords(node.xw, node.xh);
|
|
let path = [[coords.x, coords.y]];
|
|
|
|
while (node.parent) {
|
|
node = node.parent;
|
|
coords = map.getCoords(node.xw, node.xh);
|
|
path.push([coords.x, coords.y]);
|
|
};
|
|
|
|
return path.reverse();
|
|
};
|
|
|