const { parentPort } = require("worker_threads"); const PriorityQueue = require("../Utility/PriorityQueue"); const grids = require("../Game/Grids"); const COUNT_NEIGHBOURS = 4; parentPort.on("message", d => { const { destination, position, id, mapId, wasMoving, movementRequestTracker } = d; const grid = grids[mapId - 1]; const start = grid.getCell(position.x, position.y); const open = new PriorityQueue(); const openRead = {}; const close = {}; open.enqueue({ xw: start.xw, xh: start.xh, gCost: 0, hCost: 0, fCost: 0 }, 0); while (open.items.length > 0) { const current = open.dequeue(); if (current.xw === destination.xw && current.xh === destination.xh) { const path = backtrace(current, grid); const startingPosition = path.shift(); return parentPort.postMessage({ startingPosition, path, id, mapId, wasMoving, movementRequestTracker }); }; close[`${current.xw}-${current.xh}`] = current; const neighbours = grid.getNodeNeighbours(current); for (let i = 0; i < COUNT_NEIGHBOURS; i++) { const n = neighbours[i]; if (!grid.isValidNode(n)) continue; let closed = close[`${n.xw}-${n.xh}`]; if (closed) continue; let alreadyIn = openRead[`${n.xw}-${n.xh}`]; if (alreadyIn) continue; n.hCost = Math.abs(n.xw - destination.xw) + Math.abs(n.xh - destination.xh); n.gCost = current.gCost + 1; n.fCost = n.gCost + n.hCost; n.parent = current; open.enqueue(n, n.hCost); openRead[`${n.xw}-${n.xh}`] = n; }; }; }); 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(); };