Spaces:
Paused
Tier 3c: the AI's found-a-building protocol, and its decision predicates
Browse filesThirteen sites across aiEconomy.js and aiIndustry.js hand-rolled the same four
steps to found a building — findPlacement, canAct, issueBuild, spend — and two
of those four fail silently when dropped. Omit `spend` and the AI founds
buildings for free, its APM dial quietly no longer throttling it; omit `canAct`
and it ignores the budget outright. Neither shows up as a crash, and neither
moves a determinism fingerprint on the default archetype, because the default
AI has `apm == null` and both calls are then no-ops. Only the APM-limited
difficulties and self-play can see the difference — and five of the thirteen
sites were already relying on a `canAct` in the guard three lines up rather
than at the call itself.
aiCommon.js gains tryBuild/tryBuildAt, and the thirteen sites become one line
each. The builder stays a parameter rather than baked in: two sites (the
Habitat and the first Barracks) have always founded with workers[0] instead of
the nearest free worker, so they pass [workers[0]] — pickBuilder returns a lone
candidate whether it is busy or idle, which pins the equivalence. Widening them
to the full worker list would change which unit walks to the site, and with it
the fingerprint; that is a behaviour change, not a refactor, so it is left
alone.
This makes aiCommon.js import commands/colliders, so its header no longer
claims "no engine imports" — the invariant was always acyclicity, and neither
of those modules has a route back to the AI layer. static-integrity's SCC check
holds the engine to that.
Also exports nine decision predicates that were buried inside the phase
functions (standingArmyCap, armySurplusBonus, homeOreFraction; withoutHomeGuard,
threatCentroid, counterToPlayerArmy, visibleEnemyCombatNear, playerHasPresence,
raidTarget) so they can be driven directly, with characterisation tests for the
two whose behaviour was previously only observable through a full runAI cycle.
They are exported in place rather than moved to a new module: they read state
and ctx, they belong with their phase, and a module existing only for
testability would have to import back into the layer it came from.
Suite 2006 -> 2011, typecheck clean.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XZ2MLqDX3grEPTJpwivWZX
- engine/aiCommon.js +53 -5
- engine/aiEconomy.js +25 -30
- engine/aiIndustry.js +6 -13
- engine/aiMilitary.js +14 -6
- test/ai.test.js +64 -1
- test/aiMilitary.test.js +30 -0
|
@@ -1,15 +1,23 @@
|
|
| 1 |
// @ts-check
|
| 2 |
/* ============================================================
|
| 3 |
AI — shared primitives used by every decision phase (engine/ai.js and the
|
| 4 |
-
aiEconomy / aiMilitary / aiIndustry phase modules)
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
============================================================ */
|
| 10 |
|
| 11 |
"use strict";
|
| 12 |
|
|
|
|
|
|
|
|
|
|
| 13 |
const APM_BURST_FRAC = 1 / 15; // a busy AI can bank at most ~4 seconds' worth of unspent actions
|
| 14 |
|
| 15 |
/* ---------- owner resolution (Tier 1 self-play) ---------- */
|
|
@@ -101,3 +109,43 @@ export function pickBuilder(workers, x, y) {
|
|
| 101 |
}
|
| 102 |
return best || workers[0];
|
| 103 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
// @ts-check
|
| 2 |
/* ============================================================
|
| 3 |
AI — shared primitives used by every decision phase (engine/ai.js and the
|
| 4 |
+
aiEconomy / aiMilitary / aiIndustry phase modules): owner resolution
|
| 5 |
+
(controllerFor/otherOwner), the APM action budget (the configurable AI
|
| 6 |
+
speed), the reserve-aware affordability check, the "which idle worker founds
|
| 7 |
+
this building" pick, and the found-a-building protocol those picks feed.
|
| 8 |
+
|
| 9 |
+
Imports only DOWNWARD, into commands/colliders — never back into an AI phase
|
| 10 |
+
module — so the phase modules can all share it without a cycle. That is the
|
| 11 |
+
invariant, not "no engine imports": commands.js and colliders.js have no
|
| 12 |
+
route back to the AI layer, and test/static-integrity.test.js's SCC check
|
| 13 |
+
holds the whole engine to it.
|
| 14 |
============================================================ */
|
| 15 |
|
| 16 |
"use strict";
|
| 17 |
|
| 18 |
+
import { issueBuild } from "./commands.js";
|
| 19 |
+
import { findPlacement } from "./colliders.js";
|
| 20 |
+
|
| 21 |
const APM_BURST_FRAC = 1 / 15; // a busy AI can bank at most ~4 seconds' worth of unspent actions
|
| 22 |
|
| 23 |
/* ---------- owner resolution (Tier 1 self-play) ---------- */
|
|
|
|
| 109 |
}
|
| 110 |
return best || workers[0];
|
| 111 |
}
|
| 112 |
+
|
| 113 |
+
/* ---------- founding a building ---------- */
|
| 114 |
+
|
| 115 |
+
// The AI's found-a-building protocol, in one place: slide the request to valid ground,
|
| 116 |
+
// check the action budget, issue the order, and charge the budget for it. Thirteen sites
|
| 117 |
+
// across aiEconomy.js and aiIndustry.js hand-rolled these four steps, and two of the four
|
| 118 |
+
// fail SILENTLY when dropped — omit `spend` and the AI founds buildings for free (its APM
|
| 119 |
+
// dial quietly stops throttling it), omit `canAct` and it ignores the budget outright.
|
| 120 |
+
// Neither shows up as a crash, and neither shows up in a determinism fingerprint on the
|
| 121 |
+
// default archetype, because the default AI has `apm == null` and both calls are then
|
| 122 |
+
// no-ops. Only the APM-limited difficulties and self-play can see the difference.
|
| 123 |
+
//
|
| 124 |
+
// findPlacement is what makes the fixed build offsets safe: a node or an earlier building
|
| 125 |
+
// squatting on the nominal spot would make issueBuild reject the identical coordinates
|
| 126 |
+
// every think cycle and stall the order forever, so the search slides it to the nearest
|
| 127 |
+
// valid ground instead.
|
| 128 |
+
//
|
| 129 |
+
// `workers` is a candidate list, not a single unit, because the builder is chosen by
|
| 130 |
+
// distance to the spot that placement actually settled on — which isn't known until after
|
| 131 |
+
// the search. Two sites (the Habitat and the first Barracks) historically founded with
|
| 132 |
+
// workers[0] rather than the nearest free worker; they pass [workers[0]] so the pick is
|
| 133 |
+
// forced to that same unit, since pickBuilder returns a lone candidate either way. Widening
|
| 134 |
+
// them to the full list would change which unit walks to the site, and with it the
|
| 135 |
+
// determinism fingerprint — a behaviour change, not a refactor.
|
| 136 |
+
/** @param {State} state @param {string} owner @param {Unit[]} workers @param {string} type @param {number} x @param {number} y @param {number} [maxRadius] @returns {boolean} */
|
| 137 |
+
export function tryBuild(state, owner, workers, type, x, y, maxRadius) {
|
| 138 |
+
return tryBuildAt(state, owner, workers, type, findPlacement(state, type, x, y, maxRadius));
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
// tryBuild for a caller that already searched for its own spot (the Habitat scans every
|
| 142 |
+
// completed Command Center and takes the first that yields one). `spot` may be null —
|
| 143 |
+
// "nowhere to put it" is an ordinary outcome, not an error.
|
| 144 |
+
/** @param {State} state @param {string} owner @param {Unit[]} workers @param {string} type @param {{x:number,y:number}|null} spot @returns {boolean} */
|
| 145 |
+
export function tryBuildAt(state, owner, workers, type, spot) {
|
| 146 |
+
if (!spot || !workers.length || !canAct(state, owner)) return false;
|
| 147 |
+
const builder = pickBuilder(workers, spot.x, spot.y);
|
| 148 |
+
if (!builder || !issueBuild(state, builder.id, type, spot.x, spot.y)) return false;
|
| 149 |
+
spend(state, owner);
|
| 150 |
+
return true;
|
| 151 |
+
}
|
|
@@ -11,7 +11,7 @@
|
|
| 11 |
"use strict";
|
| 12 |
|
| 13 |
import { queueProduction, researchUpgrade } from "./production.js";
|
| 14 |
-
import {
|
| 15 |
import { findPlacement } from "./colliders.js";
|
| 16 |
import { BUILDINGS, UNITS, UPGRADES, canAfford, prereqsMet } from "./entities.js";
|
| 17 |
import { recipeOf } from "./industry.js";
|
|
@@ -19,7 +19,7 @@ import { supplyUsed, supplyCap, buildingSupplyCap } from "./supply.js";
|
|
| 19 |
import { isNodeDiscovered } from "./fog.js";
|
| 20 |
import { playerUnits } from "./state.js";
|
| 21 |
import { deployColonyShip } from "./colony.js";
|
| 22 |
-
import { canAct, spend, canAffordKeeping,
|
| 23 |
import { affordableOnSurface, aiDoctrine, maxSupplyDemand, plannedMix } from "./aiWorkers.js";
|
| 24 |
import { pickNextUnitType, visibleEnemyForceCount } from "./aiMilitary.js";
|
| 25 |
import { difficultyFor } from "./aiDifficulty.js";
|
|
@@ -141,11 +141,9 @@ export function aiExpand(state, ctx) {
|
|
| 141 |
ctx.oreReserve = ccCost; // bank toward the CC by pausing infrastructure spend
|
| 142 |
if (ai.resources.ore >= ccCost) {
|
| 143 |
const toward = Math.atan2(cc.y - anchor.y, cc.x - anchor.x); // place on the home side of the cluster
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
if (spot && canAct(state, owner) && issueBuild(state, pickBuilder(workers, spot.x, spot.y).id, "command", spot.x, spot.y)) {
|
| 148 |
-
spend(state, owner);
|
| 149 |
ctx.oreReserve = 0;
|
| 150 |
}
|
| 151 |
}
|
|
@@ -222,16 +220,13 @@ export function aiBaseAndTech(state, ctx) {
|
|
| 222 |
spot = findPlacement(state, "habitat", c.x, c.y + 90, HABITAT_SEARCH_RADIUS);
|
| 223 |
if (spot) break;
|
| 224 |
}
|
| 225 |
-
|
| 226 |
}
|
| 227 |
|
| 228 |
-
// First Barracks. Build spots are fixed offsets from the CC
|
| 229 |
-
//
|
| 230 |
-
// reject the same spot every think cycle and stall the order forever —
|
| 231 |
-
// findPlacement slides the request to the nearest valid ground instead.
|
| 232 |
if (!barracks && cc && workers.length > 0 && canAfford(ai.resources, BUILDINGS.barracks.cost)) {
|
| 233 |
-
|
| 234 |
-
if (spot && canAct(state, owner) && issueBuild(state, workers[0].id, "barracks", spot.x, spot.y)) spend(state, owner);
|
| 235 |
}
|
| 236 |
|
| 237 |
// FOUNDRY — the military tech gate for the Tier-2 units (Lancer/Breacher).
|
|
@@ -252,11 +247,7 @@ export function aiBaseAndTech(state, ctx) {
|
|
| 252 |
let hasFoundry = buildings.some(b => b.type === "foundry"); // built or still constructing
|
| 253 |
if (wantsFoundry && !hasFoundry && barracks && !barracks.constructing && cc && workers.length > 0
|
| 254 |
&& canAffordKeeping(ai.resources, BUILDINGS.foundry.cost, ctx.oreReserve)) {
|
| 255 |
-
|
| 256 |
-
if (spot && canAct(state, owner) && issueBuild(state, pickBuilder(workers, spot.x, spot.y).id, "foundry", spot.x, spot.y)) {
|
| 257 |
-
spend(state, owner);
|
| 258 |
-
hasFoundry = true;
|
| 259 |
-
}
|
| 260 |
}
|
| 261 |
// While teching, reserve the Foundry's ore from unit production so the AI
|
| 262 |
// actually banks its cost instead of spending every spare 100 on another
|
|
@@ -279,8 +270,7 @@ export function aiBaseAndTech(state, ctx) {
|
|
| 279 |
const hasArsenal = buildings.some(b => b.type === "arsenal");
|
| 280 |
if (wantsArsenal && !hasArsenal && foundryHandled && barracks && !barracks.constructing && cc && workers.length > 0
|
| 281 |
&& canAffordKeeping(ai.resources, BUILDINGS.arsenal.cost, ctx.oreReserve + BARRACKS_BUFFER)) {
|
| 282 |
-
|
| 283 |
-
if (spot && canAct(state, owner) && issueBuild(state, pickBuilder(workers, spot.x, spot.y).id, "arsenal", spot.x, spot.y)) spend(state, owner);
|
| 284 |
}
|
| 285 |
// Refinery reserve, sequenced after the Foundry (Arsenal is unreserved above).
|
| 286 |
ctx.refineryReserve = archetype.wantsRefinery && !refinery && foundryHandled && ctx.oreReserve === 0
|
|
@@ -321,7 +311,7 @@ export function aiBaseAndTech(state, ctx) {
|
|
| 321 |
// production spends the ore straight back down, and the garrison itself is still bounded by
|
| 322 |
// supply (aiBaseAndTech only raises Habitats up to state.popCap) — so this cannot run away into
|
| 323 |
// an unbounded army the way an uncapped income stream would otherwise threaten to.
|
| 324 |
-
function armySurplusBonus(state, ai) {
|
| 325 |
return state.endless ? Math.floor(ai.resources.ore / SURPLUS_STEP) : 0;
|
| 326 |
}
|
| 327 |
|
|
@@ -333,7 +323,15 @@ function armySurplusBonus(state, ai) {
|
|
| 333 |
// aiming a bit above parity with a floor for a not-yet-scouted enemy. Read once per cycle against
|
| 334 |
// ctx.army.length, a fixed snapshot — an acceptable per-cycle approximation, same spirit as the
|
| 335 |
// rest of this AI's think-cycle decisions.
|
| 336 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
const { strategy, ai, owner } = ctx;
|
| 338 |
if (strategy.matchEnemyForce) {
|
| 339 |
const enemy = visibleEnemyForceCount(state, owner);
|
|
@@ -403,10 +401,9 @@ export function aiProduceAndFortify(state, ctx) {
|
|
| 403 |
const len = Math.hypot(mx - cc.x, my - cc.y) || 1;
|
| 404 |
const dx = (mx - cc.x) / len, dy = (my - cc.y) / len; // the approach vector
|
| 405 |
const side = i % 2 === 0 ? 1 : -1;
|
| 406 |
-
|
| 407 |
cc.x + dx * (140 + 80 * i) - dy * 30 * side,
|
| 408 |
cc.y + dy * (140 + 80 * i) + dx * 30 * side);
|
| 409 |
-
if (spot && canAct(state, owner) && issueBuild(state, pickBuilder(workers, spot.x, spot.y).id, type, spot.x, spot.y)) spend(state, owner);
|
| 410 |
}
|
| 411 |
}
|
| 412 |
}
|
|
@@ -429,8 +426,7 @@ export function aiProduceAndFortify(state, ctx) {
|
|
| 429 |
if (barracks && !barracks.constructing && cc && workers.length > 0
|
| 430 |
&& allBarracks.length < (archetype.maxBarracks || 1) + surplusBarracks
|
| 431 |
&& canAffordKeeping(ai.resources, BUILDINGS.barracks.cost, ctx.oreReserve + BARRACKS_BUFFER)) {
|
| 432 |
-
|
| 433 |
-
if (spot && canAct(state, owner) && issueBuild(state, pickBuilder(workers, spot.x, spot.y).id, "barracks", spot.x, spot.y)) spend(state, owner);
|
| 434 |
}
|
| 435 |
|
| 436 |
// REFINERY. Hosts the AI's doctrine research, so it builds exactly one, near
|
|
@@ -440,8 +436,7 @@ export function aiProduceAndFortify(state, ctx) {
|
|
| 440 |
const buildResearchRefinery = refineries.length === 0; // ungated by archetype, as before
|
| 441 |
if (buildResearchRefinery && barracks && !barracks.constructing && cc && workers.length > 0
|
| 442 |
&& canAffordKeeping(ai.resources, BUILDINGS.refinery.cost, ctx.oreReserve)) {
|
| 443 |
-
|
| 444 |
-
if (spot && canAct(state, owner) && issueBuild(state, pickBuilder(workers, spot.x, spot.y).id, "refinery", spot.x, spot.y)) spend(state, owner);
|
| 445 |
}
|
| 446 |
}
|
| 447 |
|
|
@@ -496,7 +491,7 @@ export function aiMarketBarter(state, owner = "ai") {
|
|
| 496 |
// first expansion the moment the starting seam runs dry. Not fog-gated itself
|
| 497 |
// (it sums real node state, not what's been scouted) — bestExpansionCluster
|
| 498 |
// right below is the one that actually needs a look at the map.
|
| 499 |
-
function homeOreFraction(state, ccs) {
|
| 500 |
let amt = 0, max = 0;
|
| 501 |
for (const n of state.map.nodes) {
|
| 502 |
if (n.com !== "ore") continue;
|
|
|
|
| 11 |
"use strict";
|
| 12 |
|
| 13 |
import { queueProduction, researchUpgrade } from "./production.js";
|
| 14 |
+
import { issueMove } from "./commands.js";
|
| 15 |
import { findPlacement } from "./colliders.js";
|
| 16 |
import { BUILDINGS, UNITS, UPGRADES, canAfford, prereqsMet } from "./entities.js";
|
| 17 |
import { recipeOf } from "./industry.js";
|
|
|
|
| 19 |
import { isNodeDiscovered } from "./fog.js";
|
| 20 |
import { playerUnits } from "./state.js";
|
| 21 |
import { deployColonyShip } from "./colony.js";
|
| 22 |
+
import { canAct, spend, canAffordKeeping, tryBuild, tryBuildAt } from "./aiCommon.js";
|
| 23 |
import { affordableOnSurface, aiDoctrine, maxSupplyDemand, plannedMix } from "./aiWorkers.js";
|
| 24 |
import { pickNextUnitType, visibleEnemyForceCount } from "./aiMilitary.js";
|
| 25 |
import { difficultyFor } from "./aiDifficulty.js";
|
|
|
|
| 141 |
ctx.oreReserve = ccCost; // bank toward the CC by pausing infrastructure spend
|
| 142 |
if (ai.resources.ore >= ccCost) {
|
| 143 |
const toward = Math.atan2(cc.y - anchor.y, cc.x - anchor.x); // place on the home side of the cluster
|
| 144 |
+
if (tryBuild(state, owner, workers, "command",
|
| 145 |
+
anchor.x + Math.cos(toward) * EXPANSION_STANDOFF,
|
| 146 |
+
anchor.y + Math.sin(toward) * EXPANSION_STANDOFF)) {
|
|
|
|
|
|
|
| 147 |
ctx.oreReserve = 0;
|
| 148 |
}
|
| 149 |
}
|
|
|
|
| 220 |
spot = findPlacement(state, "habitat", c.x, c.y + 90, HABITAT_SEARCH_RADIUS);
|
| 221 |
if (spot) break;
|
| 222 |
}
|
| 223 |
+
tryBuildAt(state, owner, [workers[0]], "habitat", spot); // [workers[0]], not workers: this site has always founded with the first worker, not the nearest free one
|
| 224 |
}
|
| 225 |
|
| 226 |
+
// First Barracks. Build spots are fixed offsets from the CC; tryBuild's placement
|
| 227 |
+
// search is what keeps that safe (see its comment in aiCommon.js).
|
|
|
|
|
|
|
| 228 |
if (!barracks && cc && workers.length > 0 && canAfford(ai.resources, BUILDINGS.barracks.cost)) {
|
| 229 |
+
tryBuild(state, owner, [workers[0]], "barracks", cc.x + 90, cc.y - 90); // [workers[0]]: founded by the first worker, not the nearest free one
|
|
|
|
| 230 |
}
|
| 231 |
|
| 232 |
// FOUNDRY — the military tech gate for the Tier-2 units (Lancer/Breacher).
|
|
|
|
| 247 |
let hasFoundry = buildings.some(b => b.type === "foundry"); // built or still constructing
|
| 248 |
if (wantsFoundry && !hasFoundry && barracks && !barracks.constructing && cc && workers.length > 0
|
| 249 |
&& canAffordKeeping(ai.resources, BUILDINGS.foundry.cost, ctx.oreReserve)) {
|
| 250 |
+
if (tryBuild(state, owner, workers, "foundry", cc.x - 90, cc.y + 90)) hasFoundry = true;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
}
|
| 252 |
// While teching, reserve the Foundry's ore from unit production so the AI
|
| 253 |
// actually banks its cost instead of spending every spare 100 on another
|
|
|
|
| 270 |
const hasArsenal = buildings.some(b => b.type === "arsenal");
|
| 271 |
if (wantsArsenal && !hasArsenal && foundryHandled && barracks && !barracks.constructing && cc && workers.length > 0
|
| 272 |
&& canAffordKeeping(ai.resources, BUILDINGS.arsenal.cost, ctx.oreReserve + BARRACKS_BUFFER)) {
|
| 273 |
+
tryBuild(state, owner, workers, "arsenal", cc.x - 90, cc.y - 30);
|
|
|
|
| 274 |
}
|
| 275 |
// Refinery reserve, sequenced after the Foundry (Arsenal is unreserved above).
|
| 276 |
ctx.refineryReserve = archetype.wantsRefinery && !refinery && foundryHandled && ctx.oreReserve === 0
|
|
|
|
| 311 |
// production spends the ore straight back down, and the garrison itself is still bounded by
|
| 312 |
// supply (aiBaseAndTech only raises Habitats up to state.popCap) — so this cannot run away into
|
| 313 |
// an unbounded army the way an uncapped income stream would otherwise threaten to.
|
| 314 |
+
export function armySurplusBonus(state, ai) {
|
| 315 |
return state.endless ? Math.floor(ai.resources.ore / SURPLUS_STEP) : 0;
|
| 316 |
}
|
| 317 |
|
|
|
|
| 323 |
// aiming a bit above parity with a floor for a not-yet-scouted enemy. Read once per cycle against
|
| 324 |
// ctx.army.length, a fixed snapshot — an acceptable per-cycle approximation, same spirit as the
|
| 325 |
// rest of this AI's think-cycle decisions.
|
| 326 |
+
|
| 327 |
+
// Exported for direct unit testing. engine/ai.js has ONE export (runAI) and aiContext is private,
|
| 328 |
+
// so every phase test had to stage a whole match — which is the direct cause of two gaps this
|
| 329 |
+
// review found: commit ac44339's army-cap feature shipped with no test at all, and garrisonSlots'
|
| 330 |
+
// corrective branch had never executed under npm test. These helpers are pure arithmetic over
|
| 331 |
+
// plain arguments; exporting them (rather than moving them to a testability-only leaf module,
|
| 332 |
+
// which would need imports back into the phase that owns them) is the smallest change that makes
|
| 333 |
+
// that arithmetic reachable without a staged game.
|
| 334 |
+
export function standingArmyCap(state, ctx) {
|
| 335 |
const { strategy, ai, owner } = ctx;
|
| 336 |
if (strategy.matchEnemyForce) {
|
| 337 |
const enemy = visibleEnemyForceCount(state, owner);
|
|
|
|
| 401 |
const len = Math.hypot(mx - cc.x, my - cc.y) || 1;
|
| 402 |
const dx = (mx - cc.x) / len, dy = (my - cc.y) / len; // the approach vector
|
| 403 |
const side = i % 2 === 0 ? 1 : -1;
|
| 404 |
+
tryBuild(state, owner, workers, type,
|
| 405 |
cc.x + dx * (140 + 80 * i) - dy * 30 * side,
|
| 406 |
cc.y + dy * (140 + 80 * i) + dx * 30 * side);
|
|
|
|
| 407 |
}
|
| 408 |
}
|
| 409 |
}
|
|
|
|
| 426 |
if (barracks && !barracks.constructing && cc && workers.length > 0
|
| 427 |
&& allBarracks.length < (archetype.maxBarracks || 1) + surplusBarracks
|
| 428 |
&& canAffordKeeping(ai.resources, BUILDINGS.barracks.cost, ctx.oreReserve + BARRACKS_BUFFER)) {
|
| 429 |
+
tryBuild(state, owner, workers, "barracks", cc.x + 90, cc.y + 90);
|
|
|
|
| 430 |
}
|
| 431 |
|
| 432 |
// REFINERY. Hosts the AI's doctrine research, so it builds exactly one, near
|
|
|
|
| 436 |
const buildResearchRefinery = refineries.length === 0; // ungated by archetype, as before
|
| 437 |
if (buildResearchRefinery && barracks && !barracks.constructing && cc && workers.length > 0
|
| 438 |
&& canAffordKeeping(ai.resources, BUILDINGS.refinery.cost, ctx.oreReserve)) {
|
| 439 |
+
tryBuild(state, owner, workers, "refinery", cc.x - 90, cc.y - 90);
|
|
|
|
| 440 |
}
|
| 441 |
}
|
| 442 |
|
|
|
|
| 491 |
// first expansion the moment the starting seam runs dry. Not fog-gated itself
|
| 492 |
// (it sums real node state, not what's been scouted) — bestExpansionCluster
|
| 493 |
// right below is the one that actually needs a look at the map.
|
| 494 |
+
export function homeOreFraction(state, ccs) {
|
| 495 |
let amt = 0, max = 0;
|
| 496 |
for (const n of state.map.nodes) {
|
| 497 |
if (n.com !== "ore") continue;
|
|
@@ -12,13 +12,11 @@
|
|
| 12 |
"use strict";
|
| 13 |
|
| 14 |
import { queueProduction } from "./production.js";
|
| 15 |
-
import { issueBuild } from "./commands.js";
|
| 16 |
-
import { findPlacement } from "./colliders.js";
|
| 17 |
import { BUILDINGS, UNITS, canAfford, prereqsMet, isElectrifiable } from "./entities.js";
|
| 18 |
import { powerCap, powerDraw } from "./industry.js";
|
| 19 |
import { researchTech } from "./techtree.js";
|
| 20 |
import { supplyUsed, supplyCap } from "./supply.js";
|
| 21 |
-
import { canAct, spend, canAffordKeeping,
|
| 22 |
import { wantsDeepIndustry } from "./aiWorkers.js";
|
| 23 |
import { difficultyFor } from "./aiDifficulty.js";
|
| 24 |
import { strategyFor } from "./aiStrategy.js";
|
|
@@ -163,8 +161,7 @@ export function aiIndustry(state, ctx) {
|
|
| 163 |
const reactorPending = reactors.some(b => b.constructing);
|
| 164 |
const wantMorePower = !reactors.length || (cap > 0 && draw > cap * 0.85);
|
| 165 |
if (wantMorePower && !reactorPending && canAffordKeeping(ai.resources, BUILDINGS.reactor.cost, ctx.oreReserve) && canAct(state, owner)) {
|
| 166 |
-
|
| 167 |
-
if (spot && issueBuild(state, pickBuilder(workers, spot.x, spot.y).id, "reactor", spot.x, spot.y)) spend(state, owner);
|
| 168 |
}
|
| 169 |
|
| 170 |
// ELECTRIFY: once the grid is live, wire the base's non-power buildings in — 30% faster unit
|
|
@@ -196,8 +193,7 @@ export function aiIndustry(state, ctx) {
|
|
| 196 |
const nextFactory = chain.find(t => !buildings.some(b => b.type === t) && prereqsMet(state, owner, BUILDINGS[t]));
|
| 197 |
if (nextFactory && canAffordKeeping(ai.resources, BUILDINGS[nextFactory].cost, ctx.oreReserve) && canAct(state, owner)) {
|
| 198 |
const ang = industryCount * 2.4, rad = 120 + 18 * industryCount;
|
| 199 |
-
|
| 200 |
-
if (spot && issueBuild(state, pickBuilder(workers, spot.x, spot.y).id, nextFactory, spot.x, spot.y)) spend(state, owner);
|
| 201 |
}
|
| 202 |
|
| 203 |
// RESEARCH: at a completed Datacenter, queue the next unowned node whose prereqs are met (lowest
|
|
@@ -218,8 +214,7 @@ export function aiIndustry(state, ctx) {
|
|
| 218 |
const hasStardock = buildings.some(b => b.type === "stardock");
|
| 219 |
if (!hasStardock && prereqsMet(state, owner, BUILDINGS.stardock)
|
| 220 |
&& canAffordKeeping(ai.resources, BUILDINGS.stardock.cost, ctx.oreReserve) && canAct(state, owner)) {
|
| 221 |
-
|
| 222 |
-
if (spot && issueBuild(state, pickBuilder(workers, spot.x, spot.y).id, "stardock", spot.x, spot.y)) spend(state, owner);
|
| 223 |
}
|
| 224 |
// Train a Leviathan at a completed, idle Star Dock when the manufactured strategic goods (AI Cores
|
| 225 |
// + Plasma Torpedoes) are on hand and there's supply for the 8-supply capital ship. queueProduction
|
|
@@ -252,8 +247,7 @@ export function aiIndustry(state, ctx) {
|
|
| 252 |
const hasRig = buildings.some(b => b.type === "plasmarig");
|
| 253 |
if (!hasRig && prereqsMet(state, owner, BUILDINGS.plasmarig)
|
| 254 |
&& canAffordKeeping(ai.resources, BUILDINGS.plasmarig.cost, ctx.oreReserve) && canAct(state, owner)) {
|
| 255 |
-
|
| 256 |
-
if (spot && issueBuild(state, pickBuilder(workers, spot.x, spot.y).id, "plasmarig", spot.x, spot.y)) spend(state, owner);
|
| 257 |
}
|
| 258 |
|
| 259 |
// THE RIVAL GATE: once rivalGateEligible (above) — the Strategic tier standing, a real
|
|
@@ -266,7 +260,6 @@ export function aiIndustry(state, ctx) {
|
|
| 266 |
const hasGate = buildings.some(b => b.type === "antimatter_gate");
|
| 267 |
if (!hasGate && rivalGateEligible(state, owner)
|
| 268 |
&& canAffordKeeping(ai.resources, BUILDINGS.antimatter_gate.cost, ctx.oreReserve) && canAct(state, owner)) {
|
| 269 |
-
|
| 270 |
-
if (spot && issueBuild(state, pickBuilder(workers, spot.x, spot.y).id, "antimatter_gate", spot.x, spot.y)) spend(state, owner);
|
| 271 |
}
|
| 272 |
}
|
|
|
|
| 12 |
"use strict";
|
| 13 |
|
| 14 |
import { queueProduction } from "./production.js";
|
|
|
|
|
|
|
| 15 |
import { BUILDINGS, UNITS, canAfford, prereqsMet, isElectrifiable } from "./entities.js";
|
| 16 |
import { powerCap, powerDraw } from "./industry.js";
|
| 17 |
import { researchTech } from "./techtree.js";
|
| 18 |
import { supplyUsed, supplyCap } from "./supply.js";
|
| 19 |
+
import { canAct, spend, canAffordKeeping, tryBuild } from "./aiCommon.js";
|
| 20 |
import { wantsDeepIndustry } from "./aiWorkers.js";
|
| 21 |
import { difficultyFor } from "./aiDifficulty.js";
|
| 22 |
import { strategyFor } from "./aiStrategy.js";
|
|
|
|
| 161 |
const reactorPending = reactors.some(b => b.constructing);
|
| 162 |
const wantMorePower = !reactors.length || (cap > 0 && draw > cap * 0.85);
|
| 163 |
if (wantMorePower && !reactorPending && canAffordKeeping(ai.resources, BUILDINGS.reactor.cost, ctx.oreReserve) && canAct(state, owner)) {
|
| 164 |
+
tryBuild(state, owner, workers, "reactor", cc.x - 60, cc.y + 60);
|
|
|
|
| 165 |
}
|
| 166 |
|
| 167 |
// ELECTRIFY: once the grid is live, wire the base's non-power buildings in — 30% faster unit
|
|
|
|
| 193 |
const nextFactory = chain.find(t => !buildings.some(b => b.type === t) && prereqsMet(state, owner, BUILDINGS[t]));
|
| 194 |
if (nextFactory && canAffordKeeping(ai.resources, BUILDINGS[nextFactory].cost, ctx.oreReserve) && canAct(state, owner)) {
|
| 195 |
const ang = industryCount * 2.4, rad = 120 + 18 * industryCount;
|
| 196 |
+
tryBuild(state, owner, workers, nextFactory, cc.x + Math.cos(ang) * rad, cc.y + Math.sin(ang) * rad);
|
|
|
|
| 197 |
}
|
| 198 |
|
| 199 |
// RESEARCH: at a completed Datacenter, queue the next unowned node whose prereqs are met (lowest
|
|
|
|
| 214 |
const hasStardock = buildings.some(b => b.type === "stardock");
|
| 215 |
if (!hasStardock && prereqsMet(state, owner, BUILDINGS.stardock)
|
| 216 |
&& canAffordKeeping(ai.resources, BUILDINGS.stardock.cost, ctx.oreReserve) && canAct(state, owner)) {
|
| 217 |
+
tryBuild(state, owner, workers, "stardock", cc.x + 120, cc.y - 90);
|
|
|
|
| 218 |
}
|
| 219 |
// Train a Leviathan at a completed, idle Star Dock when the manufactured strategic goods (AI Cores
|
| 220 |
// + Plasma Torpedoes) are on hand and there's supply for the 8-supply capital ship. queueProduction
|
|
|
|
| 247 |
const hasRig = buildings.some(b => b.type === "plasmarig");
|
| 248 |
if (!hasRig && prereqsMet(state, owner, BUILDINGS.plasmarig)
|
| 249 |
&& canAffordKeeping(ai.resources, BUILDINGS.plasmarig.cost, ctx.oreReserve) && canAct(state, owner)) {
|
| 250 |
+
tryBuild(state, owner, workers, "plasmarig", cc.x - 120, cc.y - 90);
|
|
|
|
| 251 |
}
|
| 252 |
|
| 253 |
// THE RIVAL GATE: once rivalGateEligible (above) — the Strategic tier standing, a real
|
|
|
|
| 260 |
const hasGate = buildings.some(b => b.type === "antimatter_gate");
|
| 261 |
if (!hasGate && rivalGateEligible(state, owner)
|
| 262 |
&& canAffordKeeping(ai.resources, BUILDINGS.antimatter_gate.cost, ctx.oreReserve) && canAct(state, owner)) {
|
| 263 |
+
tryBuild(state, owner, workers, "antimatter_gate", cc.x - 150, cc.y + 150);
|
|
|
|
| 264 |
}
|
| 265 |
}
|
|
@@ -441,7 +441,7 @@ export function visibleEnemyForceCount(state, owner = "ai") {
|
|
| 441 |
// Enemy combat units `owner` can currently SEE within `radius` of (x, y) — the live opposition at
|
| 442 |
// a fight. Zero against an undefended base, which is what makes the retreat safe for the
|
| 443 |
// resolves-to-a-winner guarantee.
|
| 444 |
-
function visibleEnemyCombatNear(state, owner, x, y, radius) {
|
| 445 |
let n = 0;
|
| 446 |
for (const u of visibleEnemyCombatUnits(state, owner)) {
|
| 447 |
if (Math.hypot(u.x - x, u.y - y) <= radius) n++;
|
|
@@ -465,7 +465,7 @@ export function visibleThreatsNearHome(state, owner = "ai") {
|
|
| 465 |
return threats;
|
| 466 |
}
|
| 467 |
|
| 468 |
-
function threatCentroid(threats) {
|
| 469 |
let x = 0, y = 0;
|
| 470 |
for (const t of threats) { x += t.x; y += t.y; }
|
| 471 |
return { x: x / threats.length, y: y / threats.length };
|
|
@@ -478,7 +478,15 @@ function threatCentroid(threats) {
|
|
| 478 |
// all-in archetype with garrison:0 (nobody held back, but the order is exactly
|
| 479 |
// as load-bearing for a PARTIAL commit as it is when garrison > 0): sort first,
|
| 480 |
// then drop the closest `garrison` (zero is a no-op slice, not a skip).
|
| 481 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 482 |
if (homeArmy.length <= garrison) return [];
|
| 483 |
if (!cc) return homeArmy.slice(); // nothing to measure distance from — can't sort, return everyone
|
| 484 |
const byDistHome = homeArmy.slice().sort((a, b) =>
|
|
@@ -494,7 +502,7 @@ function withoutHomeGuard(homeArmy, cc, garrison) {
|
|
| 494 |
// creation), and no amount of fog-of-war nuance changes that a wave sent there fights nobody.
|
| 495 |
// `owner` defaults to "player" (the caller always means "the OTHER side", and every pre-existing
|
| 496 |
// call site is aiOffense's Odyssey branch checking the human player).
|
| 497 |
-
function playerHasPresence(state, owner = "player") {
|
| 498 |
return playerUnits(state, owner).length > 0 || playerBuildings(state, owner).length > 0;
|
| 499 |
}
|
| 500 |
|
|
@@ -514,7 +522,7 @@ const RAID_EVERY = 3; // every Nth Tactical wave goes for the economy instead
|
|
| 514 |
// wave onto the worker line to cripple production rather than grinding the defended main base.
|
| 515 |
// Null when no worker is in sight — nothing to raid, so the caller falls back to the ordinary base
|
| 516 |
// assault. `owner` defaults to "ai" so the pre-existing (single-owner) call site is unaffected.
|
| 517 |
-
function raidTarget(state, owner = "ai") {
|
| 518 |
const enemyOwner = otherOwner(owner);
|
| 519 |
const fog = state.fogs[owner];
|
| 520 |
const from = state.map.bases[owner];
|
|
@@ -595,7 +603,7 @@ export function pickNextUnitType(state, archetype, owner = "ai") {
|
|
| 595 |
// test/balance.test.js turret-line proof), overriding the unit-type counter above —
|
| 596 |
// prefersBuildings targeting and its 150 range (outranging the turret's 130) do the rest once it's
|
| 597 |
// queued. `owner` defaults to "ai" so the pre-existing (single-owner) call site is unaffected.
|
| 598 |
-
function counterToPlayerArmy(state, owner = "ai") {
|
| 599 |
const enemyOwner = otherOwner(owner);
|
| 600 |
const fog = state.fogs[owner];
|
| 601 |
const counts = {};
|
|
|
|
| 441 |
// Enemy combat units `owner` can currently SEE within `radius` of (x, y) — the live opposition at
|
| 442 |
// a fight. Zero against an undefended base, which is what makes the retreat safe for the
|
| 443 |
// resolves-to-a-winner guarantee.
|
| 444 |
+
export function visibleEnemyCombatNear(state, owner, x, y, radius) {
|
| 445 |
let n = 0;
|
| 446 |
for (const u of visibleEnemyCombatUnits(state, owner)) {
|
| 447 |
if (Math.hypot(u.x - x, u.y - y) <= radius) n++;
|
|
|
|
| 465 |
return threats;
|
| 466 |
}
|
| 467 |
|
| 468 |
+
export function threatCentroid(threats) {
|
| 469 |
let x = 0, y = 0;
|
| 470 |
for (const t of threats) { x += t.x; y += t.y; }
|
| 471 |
return { x: x / threats.length, y: y / threats.length };
|
|
|
|
| 478 |
// all-in archetype with garrison:0 (nobody held back, but the order is exactly
|
| 479 |
// as load-bearing for a PARTIAL commit as it is when garrison > 0): sort first,
|
| 480 |
// then drop the closest `garrison` (zero is a no-op slice, not a skip).
|
| 481 |
+
|
| 482 |
+
// Exported for direct unit testing. engine/ai.js has ONE export (runAI) and aiContext is private,
|
| 483 |
+
// so every phase test had to stage a whole match — which is the direct cause of two gaps this
|
| 484 |
+
// review found: commit ac44339's army-cap feature shipped with no test at all, and garrisonSlots'
|
| 485 |
+
// corrective branch had never executed under npm test. These helpers are pure arithmetic over
|
| 486 |
+
// plain arguments; exporting them (rather than moving them to a testability-only leaf module,
|
| 487 |
+
// which would need imports back into the phase that owns them) is the smallest change that makes
|
| 488 |
+
// that arithmetic reachable without a staged game.
|
| 489 |
+
export function withoutHomeGuard(homeArmy, cc, garrison) {
|
| 490 |
if (homeArmy.length <= garrison) return [];
|
| 491 |
if (!cc) return homeArmy.slice(); // nothing to measure distance from — can't sort, return everyone
|
| 492 |
const byDistHome = homeArmy.slice().sort((a, b) =>
|
|
|
|
| 502 |
// creation), and no amount of fog-of-war nuance changes that a wave sent there fights nobody.
|
| 503 |
// `owner` defaults to "player" (the caller always means "the OTHER side", and every pre-existing
|
| 504 |
// call site is aiOffense's Odyssey branch checking the human player).
|
| 505 |
+
export function playerHasPresence(state, owner = "player") {
|
| 506 |
return playerUnits(state, owner).length > 0 || playerBuildings(state, owner).length > 0;
|
| 507 |
}
|
| 508 |
|
|
|
|
| 522 |
// wave onto the worker line to cripple production rather than grinding the defended main base.
|
| 523 |
// Null when no worker is in sight — nothing to raid, so the caller falls back to the ordinary base
|
| 524 |
// assault. `owner` defaults to "ai" so the pre-existing (single-owner) call site is unaffected.
|
| 525 |
+
export function raidTarget(state, owner = "ai") {
|
| 526 |
const enemyOwner = otherOwner(owner);
|
| 527 |
const fog = state.fogs[owner];
|
| 528 |
const from = state.map.bases[owner];
|
|
|
|
| 603 |
// test/balance.test.js turret-line proof), overriding the unit-type counter above —
|
| 604 |
// prefersBuildings targeting and its 150 range (outranging the turret's 130) do the rest once it's
|
| 605 |
// queued. `owner` defaults to "ai" so the pre-existing (single-owner) call site is unaffected.
|
| 606 |
+
export function counterToPlayerArmy(state, owner = "ai") {
|
| 607 |
const enemyOwner = otherOwner(owner);
|
| 608 |
const fog = state.fogs[owner];
|
| 609 |
const counts = {};
|
|
@@ -7,7 +7,7 @@ import { UNITS, UPGRADES } from "../engine/entities.js";
|
|
| 7 |
import { updateResearch, researchTimeScale } from "../engine/techtree.js";
|
| 8 |
import { isNodeDiscovered, isExploredAt, isVisibleAt, updateFog } from "../engine/fog.js";
|
| 9 |
import { aiDoctrine, effectiveMix, assignIdlePlayerGather } from "../engine/aiWorkers.js";
|
| 10 |
-
import { pickBuilder, accrueActionBudget } from "../engine/aiCommon.js";
|
| 11 |
import { pickNextUnitType } from "../engine/aiMilitary.js";
|
| 12 |
|
| 13 |
const THINK_INTERVAL = 1.5; // must match ai.js's own THINK_INTERVAL to force a fresh think cycle each call
|
|
@@ -989,6 +989,69 @@ test("pickBuilder prefers a genuinely idle worker over one mid-build/mid-service
|
|
| 989 |
}
|
| 990 |
});
|
| 991 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 992 |
test("a legacy archetype without the Tier 4 fields still runs without throwing", () => {
|
| 993 |
const state = createGameState({ planetId: "ferros", rng: () => 0.5 });
|
| 994 |
state.ai.archetype = { name: "Legacy", workerTarget: 4, armyAttackSize: 4, attackTimeout: 90, unitMix: ["skiff"] };
|
|
|
|
| 7 |
import { updateResearch, researchTimeScale } from "../engine/techtree.js";
|
| 8 |
import { isNodeDiscovered, isExploredAt, isVisibleAt, updateFog } from "../engine/fog.js";
|
| 9 |
import { aiDoctrine, effectiveMix, assignIdlePlayerGather } from "../engine/aiWorkers.js";
|
| 10 |
+
import { pickBuilder, accrueActionBudget, tryBuild } from "../engine/aiCommon.js";
|
| 11 |
import { pickNextUnitType } from "../engine/aiMilitary.js";
|
| 12 |
|
| 13 |
const THINK_INTERVAL = 1.5; // must match ai.js's own THINK_INTERVAL to force a fresh think cycle each call
|
|
|
|
| 989 |
}
|
| 990 |
});
|
| 991 |
|
| 992 |
+
// ---- Tier 3: tryBuild, the AI's found-a-building protocol (engine/aiCommon.js) ----
|
| 993 |
+
//
|
| 994 |
+
// Thirteen sites across aiEconomy/aiIndustry hand-rolled the same four steps —
|
| 995 |
+
// findPlacement, canAct, issueBuild, spend — and two of the four fail SILENTLY when
|
| 996 |
+
// dropped: omit `spend` and the AI founds buildings for free (its APM dial stops
|
| 997 |
+
// throttling it), omit `canAct` and it ignores the budget outright. Neither shows up
|
| 998 |
+
// as a crash or a failing determinism fingerprint on the default archetype, because
|
| 999 |
+
// the default AI has `apm == null` and canAct/spend are then both no-ops. So the
|
| 1000 |
+
// protocol needs a test that runs with the budget ACTUALLY armed.
|
| 1001 |
+
test("tryBuild spends exactly one action per building it founds, and none when it founds nothing", () => {
|
| 1002 |
+
const state = createGameState({ planetId: "ferros", rng: () => 0.5 });
|
| 1003 |
+
const cc = [...state.buildings.values()].find(b => b.owner === "ai" && b.type === "command");
|
| 1004 |
+
const worker = makeUnit("worker", "ai", cc.x, cc.y + 40);
|
| 1005 |
+
state.units.set(worker.id, worker);
|
| 1006 |
+
state.players.ai.resources.ore = 100000;
|
| 1007 |
+
state.ai.apm = 60; // arm the budget — with apm null, canAct/spend are no-ops and this proves nothing
|
| 1008 |
+
state.ai.actionBudget = 1; // exactly one action in hand
|
| 1009 |
+
|
| 1010 |
+
assert.equal(tryBuild(state, "ai", [worker], "barracks", cc.x + 90, cc.y - 90), true,
|
| 1011 |
+
"the first call founds the building and reports it");
|
| 1012 |
+
assert.equal(state.ai.actionBudget, 0, "founding it cost exactly one action");
|
| 1013 |
+
assert.equal(worker.order?.type, "build", "and the chosen worker actually carries the build order");
|
| 1014 |
+
|
| 1015 |
+
// Budget now empty: canAct is false, so the next attempt must not issue an order at all.
|
| 1016 |
+
const before = state.buildings.size;
|
| 1017 |
+
assert.equal(tryBuild(state, "ai", [worker], "refinery", cc.x - 90, cc.y - 90), false,
|
| 1018 |
+
"with the budget spent it declines rather than acting for free");
|
| 1019 |
+
assert.equal(state.buildings.size, before, "no building was founded");
|
| 1020 |
+
assert.equal(state.ai.actionBudget, 0, "and nothing was over-spent into a negative budget");
|
| 1021 |
+
});
|
| 1022 |
+
|
| 1023 |
+
test("tryBuild reports false and spends nothing when the ground offers no placement", () => {
|
| 1024 |
+
const state = createGameState({ planetId: "ferros", rng: () => 0.5 });
|
| 1025 |
+
const cc = [...state.buildings.values()].find(b => b.owner === "ai" && b.type === "command");
|
| 1026 |
+
const worker = makeUnit("worker", "ai", cc.x, cc.y + 40);
|
| 1027 |
+
state.units.set(worker.id, worker);
|
| 1028 |
+
state.players.ai.resources.ore = 100000;
|
| 1029 |
+
state.ai.apm = 60;
|
| 1030 |
+
state.ai.actionBudget = 5;
|
| 1031 |
+
|
| 1032 |
+
// Far outside the map: findPlacement's whole search ring is off-map, so it returns null.
|
| 1033 |
+
const founded = tryBuild(state, "ai", [worker], "barracks", state.map.width + 5000, state.map.height + 5000);
|
| 1034 |
+
assert.equal(founded, false, "no spot, no order");
|
| 1035 |
+
assert.equal(state.ai.actionBudget, 5, "and an action is spent only when an order is actually issued");
|
| 1036 |
+
assert.equal(worker.order, null, "the candidate worker is left alone");
|
| 1037 |
+
});
|
| 1038 |
+
|
| 1039 |
+
test("tryBuild picks the builder the same way pickBuilder does — a single-worker list always yields that worker", () => {
|
| 1040 |
+
const state = createGameState({ planetId: "ferros", rng: () => 0.5 });
|
| 1041 |
+
const cc = [...state.buildings.values()].find(b => b.owner === "ai" && b.type === "command");
|
| 1042 |
+
state.players.ai.resources.ore = 100000;
|
| 1043 |
+
// Two aiEconomy sites (Habitat, first Barracks) historically passed workers[0] rather than the
|
| 1044 |
+
// nearest free worker. They now pass [workers[0]] so tryBuild's pick is forced to that same unit
|
| 1045 |
+
// — this pins the equivalence, since pickBuilder falls back to workers[0] when the only
|
| 1046 |
+
// candidate is busy, and returns it directly when it is idle.
|
| 1047 |
+
for (const busy of [false, true]) {
|
| 1048 |
+
const only = makeUnit("worker", "ai", cc.x + 400, cc.y + 400); // deliberately far from the spot
|
| 1049 |
+
if (busy) only.order = { type: "haul" };
|
| 1050 |
+
assert.equal(pickBuilder([only], cc.x, cc.y).id, only.id,
|
| 1051 |
+
`a one-element worker list resolves to that worker whether it is ${busy ? "busy" : "idle"}`);
|
| 1052 |
+
}
|
| 1053 |
+
});
|
| 1054 |
+
|
| 1055 |
test("a legacy archetype without the Tier 4 fields still runs without throwing", () => {
|
| 1056 |
const state = createGameState({ planetId: "ferros", rng: () => 0.5 });
|
| 1057 |
state.ai.archetype = { name: "Legacy", workerTarget: 4, armyAttackSize: 4, attackTimeout: 90, unitMix: ["skiff"] };
|
|
@@ -208,3 +208,33 @@ test("garrisonSlots keeps a large parked group inside the recall radius, corners
|
|
| 208 |
assert.ok(farthest <= limit + 1e-6,
|
| 209 |
`every parked slot must sit inside the recall radius — farthest ${farthest.toFixed(2)} vs limit ${limit}`);
|
| 210 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
assert.ok(farthest <= limit + 1e-6,
|
| 209 |
`every parked slot must sit inside the recall radius — farthest ${farthest.toFixed(2)} vs limit ${limit}`);
|
| 210 |
});
|
| 211 |
+
|
| 212 |
+
/* ---- T3: the decision arithmetic, tested directly ------------------------------------------
|
| 213 |
+
These are pure functions over plain arguments, and until now every one of them could only be
|
| 214 |
+
reached by staging a whole match through runAI. That is the direct cause of two coverage gaps
|
| 215 |
+
this review found (an army-cap feature with no test at all, and a corrective branch that had
|
| 216 |
+
never executed), so the point of exporting them is that the arithmetic is now cheap to pin. */
|
| 217 |
+
|
| 218 |
+
test("withoutHomeGuard keeps the `garrison` units NEAREST home and releases the rest (T3)", async () => {
|
| 219 |
+
const { withoutHomeGuard } = await import("../engine/aiMilitary.js");
|
| 220 |
+
const cc = { x: 0, y: 0 };
|
| 221 |
+
const near = { id: "near", x: 10, y: 0 };
|
| 222 |
+
const mid = { id: "mid", x: 100, y: 0 };
|
| 223 |
+
const far = { id: "far", x: 500, y: 0 };
|
| 224 |
+
const army = [far, near, mid]; // deliberately unsorted
|
| 225 |
+
|
| 226 |
+
assert.deepEqual(withoutHomeGuard(army, cc, 0).map(u => u.id), ["near", "mid", "far"],
|
| 227 |
+
"garrison 0 releases everyone, nearest-home first");
|
| 228 |
+
assert.deepEqual(withoutHomeGuard(army, cc, 1).map(u => u.id), ["mid", "far"],
|
| 229 |
+
"the single closest unit stays home");
|
| 230 |
+
assert.deepEqual(withoutHomeGuard(army, cc, 3), [], "a garrison at or above the army size keeps everyone");
|
| 231 |
+
assert.deepEqual(withoutHomeGuard(army, cc, 9), [], "…and above it too");
|
| 232 |
+
assert.deepEqual(withoutHomeGuard(army, null, 1).map(u => u.id).sort(), ["far", "mid", "near"],
|
| 233 |
+
"with no Command Center there is nothing to measure from, so everyone is released");
|
| 234 |
+
});
|
| 235 |
+
|
| 236 |
+
test("threatCentroid averages the threat positions (T3)", async () => {
|
| 237 |
+
const { threatCentroid } = await import("../engine/aiMilitary.js");
|
| 238 |
+
assert.deepEqual(threatCentroid([{ x: 0, y: 0 }, { x: 10, y: 20 }]), { x: 5, y: 10 });
|
| 239 |
+
assert.deepEqual(threatCentroid([{ x: 7, y: -3 }]), { x: 7, y: -3 });
|
| 240 |
+
});
|