Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for [old] Find Enemy by Moff
const createHexagon = (key) => new Hexagon(key.charCodeAt(0), parseInt(key[1]));
const directions = ['N', 'S', 'NW', 'SW', 'NE', 'SE'];
class Hexagon {
constructor(x, y) {
this.x = x;
this.y = y;
}
get key() {
return `${String.fromCharCode(this.x)}${this.y}`;
}
getMove(dir, steps) {
let coords = {
'N': [this.x, this.y - steps],
'NE': [this.x + steps, this.y - Math.floor((steps + this.x % 2) / 2)],
'SE': [this.x + steps, this.y + Math.floor((steps + 1 - this.x % 2) / 2)],
'S': [this.x, this.y + steps],
'SW': [this.x - steps, this.y + Math.floor((steps + 1 - this.x % 2) / 2)],
'NW': [this.x - steps, this.y - Math.floor((steps + this.x % 2) / 2)]
}[dir];
return new Hexagon(coords[0], coords[1]);
}
neighbours() {
return directions.map(d => this.getMove(d, 1));
}
distTo(target) {
let pathTo = {};
let queue = [createHexagon(this.key)];
while (queue.length) {
let x = queue.pop();
for (let v of x.neighbours()) {
if (pathTo[v.key] === undefined) {
pathTo[v.key] = pathTo[x.key] + 1 || 1;
queue.unshift(v);
if (v.key === target.key)
return pathTo[target.key];
}
}
}
return pathTo;
}
relativeDirectionTo(direction, target) {
let dx = target.x - this.x;
let dy = target.y - this.y;
let tmp = ['NW', 'SW', 'NE', 'SE'].map(d => this.getMove(d, Math.abs(dx)));
let nw = tmp[0],
sw = tmp[1],
ne = tmp[2],
se = tmp[3];
if (direction == 'N') {
if (dx < 0 && nw.y <= target.y && target.y <= sw.y) {
return 'L';
} else if (dx > 0 && ne.y <= target.y && target.y <= se.y) {
return 'R';
} else if (dy > 0) {
return 'B';
} else {
return 'F';
}
} else if (direction == 'NE') {
if (dx <= 0 && target.y <= nw.y) {
return 'L';
} else if (dx < 0 && target.y > nw.y) {
return 'B';
} else if (dx >= 0 && target.y >= se.y) {
return 'R';
} else {
return 'F';
}
} else if (direction == 'SE') {
if (dx < 0 && target.y < sw.y) {
return 'B';
} else if (dx <= 0 && target.y >= sw.y) {
return 'R';
} else if (dx >= 0 && target.y <= nw.y) {
return 'L';
} else {
return 'F';
}
} else if (direction == 'S') {
if (dx < 0 && nw.y <= target.y && target.y <= sw.y) {
return 'R';
} else if (dx > 0 && ne.y <= target.y && target.y <= se.y) {
return 'L';
} else if (dy > 0) {
return 'F';
} else {
return 'B';
}
} else if (direction == 'SW') {
if (dx <= 0 && target.y <= nw.y) {
return 'R';
} else if (dx < 0 && target.y > nw.y) {
return 'F';
} else if (dx >= 0 && target.y >= se.y) {
return 'L';
} else {
return 'B';
}
} else if (direction == 'NW') {
if (dx < 0 && target.y < sw.y) {
return 'F';
} else if (dx <= 0 && target.y >= sw.y) {
return 'L';
} else if (dx >= 0 && target.y <= nw.y) {
return 'R';
} else {
return 'B';
}
}
}
}
function findEnemy(you, dir, enemy) {
let source = createHexagon(you);
let target = createHexagon(enemy);
return [source.relativeDirectionTo(dir, target), source.distTo(target)];
}
Aug. 3, 2017
Comments: