One line will output a value of 10, while the next will print one less:
console.log("ds length: " + ds.length); // Outputs 10
console.log(ds); // Displays all elements except the last and reports the length as one less.
All relevant sections of my code are contained within the singleton AS object:
FindPath: function(oX, oY, dX, dY) { // origin, destination
var heap = AS.Heap();
var g = AS.Grid; // Declared in AS as: Grid: new Array(),
var node;
var cn = g[oX][oY]; // current node
var dn = g[dX][dY]; // destination node
heap.push(cn);
cn.CoorType = AS.CoorType.VISITED;
while (heap.length > 0) {
cn = heap.pop();
if (cn === dn) {
var ds = new Array(); // direction set (instructions)
var pn;// parent node;
do {
pn = cn.Parent;
ds.push({
Dir: cn.Y - pn.Y !== 0 ? cn.Y - pn.Y < 0 ? AS.Direction.UP : AS.Direction.DOWN : cn.X - pn.X > 0 ? AS.Direction.RIGHT : AS.Direction.LEFT,
Node: cn});
cn = pn;
} while (pn.Parent);
console.log("length of ds: " + ds.length);
console.log(ds);
AS.CleanUp();
return ds;
}
// The following code eliminates the use of functions to improve performance, due to lag issues when calling FindPath() multiple times quickly in a large area.
node = g[cn.X+1][cn.Y];
if (node.CoorType === AS.CoorType.NOTHING) {
node.CoorType = AS.CoorType.VISITED;
node.Parent = cn;
node.Score = ((Math.abs(node.X - oX) + Math.abs(node.Y - oY)) * AS.SMALL_ADVANTAGE + Math.abs(node.X - dX) + Math.abs(node.Y - dY)) +
Math.abs((node.X - dX) * (oY - dY) - (node.Y - dY) * (oX - dX)) * 0.0001;
heap.Sink(node);
}
// Repeat similar block for other directions...
}
AS.CleanUp();
return heap;
},
Heap: function() {
var heap = new Array();
heap.Sink = function(node) {
var i = this.length-1;
while (i > 0 && this[i].Score < node.Score) i--;
this.splice(i, 0, node);
};
return heap;
},
CleanUp: function() {
var x, y, g = AS.Grid;
var limX = g.length - 3;
var limY = g[0].length - 3;
for (x = 2; x < limX; x++) {
for (y = 2; y < limY; y++) {
if (g[x][y].CoorType === AS.CoorType.VISITED) {
g[x][y].CoorType = AS.CoorType.NOTHING;
delete g[x][y].Parent;
}
}
}
}
I discovered that at times, the objects moving based on the path returned by FindPath miss a step. Upon further investigation, I found the pattern described above.