-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathutils.js
65 lines (58 loc) · 1.51 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const _ = require('lodash');
function euclideanDist(x, y) {
return Math.sqrt(x * x + y * y);
}
function turnDist(p1, p2) {
return Math.ceil(euclideanDist(p1.x - p2.x, p1.y - p2.y));
}
function getShips(thing) {
return thing.ships;
}
function countShips(planets, fleets) {
// TODO: Don't assume two players.
let shipCounts = [0, 0, 0];
for (let planet of planets) {
if (!shipCounts[planet.owner]) {
shipCounts[planet.owner] = planet.ships;
} else {
shipCounts[planet.owner] += planet.ships;
}
}
for (let fleet of fleets) {
if (!shipCounts[fleet.owner]) {
shipCounts[fleet.owner] = fleet.ships;
} else {
shipCounts[fleet.owner] += fleet.ships;
}
}
let countPairs = shipCounts.map((c, i) => [i, c]).filter(([, c]) => c > 0);
return _.sortBy(countPairs, ([, c]) => -c);
}
function battle(planet, fleets) {
let forces = countShips([planet], fleets);
if (forces.length === 1) {
return forces[0];
}
let ships = forces[0][1] - forces[1][1];
let owner = planet.owner;
if (ships > 0) {
owner = forces[0][0];
}
return [owner, ships];
}
function aggroPartition(player, planets) {
let mine = [];
let theirs = [];
let neutral = [];
for (let planet of planets) {
if (planet.owner === player) {
mine.push(planet);
} else if (planet.owner === 0) {
neutral.push(planet);
} else {
theirs.push(planet);
}
}
return [mine, theirs, neutral];
}
module.exports = { aggroPartition, battle, countShips, getShips, turnDist };