@chrischall/warapp-mcp 0.0.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +4 -4
- package/.claude-plugin/plugin.json +2 -2
- package/README.md +211 -9
- package/dist/analysis/accept-surrender.js +56 -0
- package/dist/analysis/award.js +159 -0
- package/dist/analysis/bonuses.js +98 -0
- package/dist/analysis/breach.js +62 -0
- package/dist/analysis/calibrate.js +239 -0
- package/dist/analysis/card-support.js +329 -0
- package/dist/analysis/card-threats.js +234 -0
- package/dist/analysis/cards-in-effect.js +130 -0
- package/dist/analysis/chains.js +59 -0
- package/dist/analysis/chokepoints.js +140 -0
- package/dist/analysis/combat.js +231 -0
- package/dist/analysis/commander-safety.js +149 -0
- package/dist/analysis/commitments.js +338 -0
- package/dist/analysis/exchange.js +155 -0
- package/dist/analysis/finished-game.js +136 -0
- package/dist/analysis/game-lessons.js +217 -0
- package/dist/analysis/graph.js +82 -0
- package/dist/analysis/guard-off.js +54 -0
- package/dist/analysis/guess.js +351 -0
- package/dist/analysis/headroom.js +241 -0
- package/dist/analysis/hold-diff.js +64 -0
- package/dist/analysis/how-lost.js +130 -0
- package/dist/analysis/index.js +14 -0
- package/dist/analysis/local-deploy.js +179 -0
- package/dist/analysis/lookahead.js +108 -0
- package/dist/analysis/opponent-profile.js +552 -0
- package/dist/analysis/opponents.js +1253 -0
- package/dist/analysis/outlook.js +695 -0
- package/dist/analysis/overrides.js +60 -0
- package/dist/analysis/picks.js +1879 -0
- package/dist/analysis/plan/after-leftover.js +140 -0
- package/dist/analysis/plan/cap-spend.js +242 -0
- package/dist/analysis/plan/captures.js +1195 -0
- package/dist/analysis/plan/commander.js +236 -0
- package/dist/analysis/plan/completed.js +29 -0
- package/dist/analysis/plan/conceded-out.js +131 -0
- package/dist/analysis/plan/estimates.js +715 -0
- package/dist/analysis/plan/guard-off.js +232 -0
- package/dist/analysis/plan/holds.js +1631 -0
- package/dist/analysis/plan/leftover.js +760 -0
- package/dist/analysis/plan/move-order.js +319 -0
- package/dist/analysis/plan/orders.js +317 -0
- package/dist/analysis/plan/relations.js +702 -0
- package/dist/analysis/plan/report.js +672 -0
- package/dist/analysis/plan/shared.js +1405 -0
- package/dist/analysis/plan/stand-still.js +823 -0
- package/dist/analysis/plan/state.js +44 -0
- package/dist/analysis/plan/strike.js +1416 -0
- package/dist/analysis/plan/targets.js +651 -0
- package/dist/analysis/plan/team.js +299 -0
- package/dist/analysis/plan/threats.js +1001 -0
- package/dist/analysis/plan/transfers.js +328 -0
- package/dist/analysis/plan/util.js +5 -0
- package/dist/analysis/plan/vacated.js +285 -0
- package/dist/analysis/planner.js +2927 -0
- package/dist/analysis/player-record.js +144 -0
- package/dist/analysis/player.js +268 -0
- package/dist/analysis/profile.js +347 -0
- package/dist/analysis/relations.js +1030 -0
- package/dist/analysis/schedule.js +88 -0
- package/dist/analysis/since-last.js +50 -0
- package/dist/analysis/static-seats.js +71 -0
- package/dist/analysis/stress.js +584 -0
- package/dist/analysis/team-brief.js +151 -0
- package/dist/analysis/tripwire.js +644 -0
- package/dist/analysis/turn-sim.js +259 -0
- package/dist/analysis/whereabouts.js +1112 -0
- package/dist/board.js +105 -0
- package/dist/bundle.js +121082 -36148
- package/dist/calibration-source.js +75 -0
- package/dist/cards.js +435 -0
- package/dist/chat-cursor.js +135 -0
- package/dist/chat.js +265 -0
- package/dist/client.js +439 -0
- package/dist/config.js +62 -0
- package/dist/direct/link.js +102 -0
- package/dist/direct/session.js +267 -0
- package/dist/direct/transport.js +424 -0
- package/dist/finished-store.js +357 -0
- package/dist/guess-salt.js +65 -0
- package/dist/hosted.js +24 -0
- package/dist/index.js +33 -0
- package/dist/join-color.js +140 -0
- package/dist/lessons-store.js +356 -0
- package/dist/live.js +287 -0
- package/dist/map-details.js +127 -0
- package/dist/map-stats.js +160 -0
- package/dist/map-store.js +242 -0
- package/dist/move-order.js +141 -0
- package/dist/my-games.js +218 -0
- package/dist/normalize.js +443 -0
- package/dist/notifications.js +143 -0
- package/dist/open-games.js +537 -0
- package/dist/outlook-log.js +165 -0
- package/dist/path-lock.js +22 -0
- package/dist/pick-list.js +193 -0
- package/dist/player-record-store.js +231 -0
- package/dist/player-states.js +31 -0
- package/dist/profile-store.js +727 -0
- package/dist/protocol/bundle.js +375 -0
- package/dist/protocol/codec.js +556 -0
- package/dist/protocol/decoded.js +12 -0
- package/dist/protocol/interp.js +1904 -0
- package/dist/protocol/methods.js +615 -0
- package/dist/protocol/rpc.js +202 -0
- package/dist/push/listener.js +393 -0
- package/dist/push/packets.js +66 -0
- package/dist/push/socketio.js +333 -0
- package/dist/push/websocket.js +179 -0
- package/dist/redact.js +62 -0
- package/dist/relations-store.js +242 -0
- package/dist/replay.js +227 -0
- package/dist/scalars.js +28 -0
- package/dist/scout.js +346 -0
- package/dist/stats.js +291 -0
- package/dist/strategy/card-clock.js +185 -0
- package/dist/strategy/map-notes.js +128 -0
- package/dist/strategy/notes.js +2223 -0
- package/dist/surrender-pending.js +126 -0
- package/dist/team-cards.js +84 -0
- package/dist/team-orders.js +150 -0
- package/dist/teams.js +19 -0
- package/dist/tools/accept-surrender.js +311 -0
- package/dist/tools/award.js +206 -0
- package/dist/tools/begin-turn.js +162 -0
- package/dist/tools/board.js +77 -0
- package/dist/tools/card-advice.js +256 -0
- package/dist/tools/card-effects.js +49 -0
- package/dist/tools/card-plays.js +434 -0
- package/dist/tools/card-support-advice.js +140 -0
- package/dist/tools/chat-inbox.js +158 -0
- package/dist/tools/chat-read-mark.js +179 -0
- package/dist/tools/chat.js +525 -0
- package/dist/tools/check-plan.js +689 -0
- package/dist/tools/commander-check.js +103 -0
- package/dist/tools/commitments.js +216 -0
- package/dist/tools/common.js +143 -0
- package/dist/tools/diplomacy.js +342 -0
- package/dist/tools/end-of-game.js +384 -0
- package/dist/tools/game.js +151 -0
- package/dist/tools/guess-view.js +56 -0
- package/dist/tools/healthcheck.js +90 -0
- package/dist/tools/hints.js +34 -0
- package/dist/tools/how-lost.js +154 -0
- package/dist/tools/index.js +152 -0
- package/dist/tools/join-game.js +327 -0
- package/dist/tools/leave-game.js +181 -0
- package/dist/tools/live-context.js +339 -0
- package/dist/tools/live.js +404 -0
- package/dist/tools/map-details.js +88 -0
- package/dist/tools/map-stats.js +130 -0
- package/dist/tools/map.js +141 -0
- package/dist/tools/my-games.js +193 -0
- package/dist/tools/notifications.js +484 -0
- package/dist/tools/open-games.js +104 -0
- package/dist/tools/opponents.js +163 -0
- package/dist/tools/order-options.js +135 -0
- package/dist/tools/past-games.js +94 -0
- package/dist/tools/picks.js +305 -0
- package/dist/tools/profile-hook.js +156 -0
- package/dist/tools/profile-opponents.js +121 -0
- package/dist/tools/profile-reads.js +99 -0
- package/dist/tools/push.js +445 -0
- package/dist/tools/relations.js +611 -0
- package/dist/tools/resolve.js +45 -0
- package/dist/tools/route.js +36 -0
- package/dist/tools/scout.js +87 -0
- package/dist/tools/session.js +163 -0
- package/dist/tools/strategy.js +257 -0
- package/dist/tools/stress-opponents.js +83 -0
- package/dist/tools/surrender-pending.js +74 -0
- package/dist/tools/surrender.js +247 -0
- package/dist/tools/survival.js +189 -0
- package/dist/tools/team-brief.js +266 -0
- package/dist/tools/team-source.js +222 -0
- package/dist/tools/team.js +178 -0
- package/dist/tools/turn.js +2825 -0
- package/dist/tools/uncommit.js +160 -0
- package/dist/tools/where.js +300 -0
- package/dist/tools/write-kit.js +164 -0
- package/dist/transport-bridge.js +33 -0
- package/dist/trend.js +577 -0
- package/dist/version.js +4 -0
- package/manifest.json +194 -4
- package/mint.yaml +106 -14
- package/package.json +11 -6
- package/server.json +40 -3
- package/skills/warapp-api/SKILL.md +95 -4
- package/skills/warapp-api/references/scout.mjs +348 -0
- package/skills/warapp-api/scripts/warapp.sh +69 -8
- package/skills/warapp-mcp/SKILL.md +1096 -21
|
@@ -0,0 +1,1001 @@
|
|
|
1
|
+
// The threats of a planning pass (#133): what each opponent can bring against each territory of
|
|
2
|
+
// mine this turn — the trend of its stacks since the previous board (rule 1t, #69, #123), Local
|
|
3
|
+
// Deployment's enemy pools (#128), the fog's hidden stacks and the large stacks that left view
|
|
4
|
+
// (#164), Multi-Attack chains (#199), Bomb-sized threats (#163) — and the borders they make (rule
|
|
5
|
+
// 1), stated in the rationale and warnings. Run once, right after the deploy book (it reads no deploy).
|
|
6
|
+
import { carriesTeam } from '../../teams.js';
|
|
7
|
+
import { searchChains } from '../chains.js';
|
|
8
|
+
import { guaranteedKills } from '../combat.js';
|
|
9
|
+
import { bfsDistances, neighborsOf } from '../graph.js';
|
|
10
|
+
import { couldHoldBonusPools, enemyDeployReaching, freeIncome } from '../local-deploy.js';
|
|
11
|
+
import { incomeBasis, LOST_STACK_TURNS } from '../opponents.js';
|
|
12
|
+
import { HIDDEN_POOL_INCOMES, MAX_NAMED_REVEALS, coverageText, LOW_COVERAGE, MIN_ENEMY_DEPLOY, openingArmies, ownerShown, visibleState, } from './shared.js';
|
|
13
|
+
import { territoryIncome } from '../player.js';
|
|
14
|
+
import { simTerritories } from '../turn-sim.js';
|
|
15
|
+
import { byNum } from './util.js';
|
|
16
|
+
/** Read the threats against my territories, and state them. */
|
|
17
|
+
export function threatsPhase(pc, ps, input) {
|
|
18
|
+
const src = threatSources(pc, ps, input);
|
|
19
|
+
const forces = threatForces(pc, ps, src);
|
|
20
|
+
const { borders, facing, borderAt, safeAtStart } = borderThreats(pc, ps, input, src, forces);
|
|
21
|
+
const { growthOf, deployReaching, reinforcementAt, holdArmies, bombSized, hiddenFoe, hiddenMovable, hiddenPool, } = src;
|
|
22
|
+
const { chainAt, stacksAt, forceAt, threatAt, nextTurnAt, expectedAt, exposure } = forces;
|
|
23
|
+
const seen = visibleOpponents(pc, input);
|
|
24
|
+
// #275 (b): say which held bonus's borders an untrusted estimate sized.
|
|
25
|
+
if (!pc.custom)
|
|
26
|
+
for (const u of [...(input.untrusted ?? [])].sort((a, b) => a.player - b.player)) {
|
|
27
|
+
const sized = [...borders.values()].filter((b) => b.player === u.player && pc.untrustedAt(u.player, b.id) > 0).map((b) => b.id).sort(byNum);
|
|
28
|
+
ps.rationale.push(`Player ${u.player}'s estimate is untrusted (#275: an observation broke it): ${sized.length
|
|
29
|
+
? `the border${sized.length === 1 ? '' : 's'} of my held bonuses facing it (${sized.map(pc.label).join(', ')}) ${sized.length === 1 ? 'is' : 'are'} sized for a deploy of ${Math.floor(u.deploy)}, not its estimate of ${pc.deployOf(u.player)}`
|
|
30
|
+
: `no border of a bonus I hold faces it, so nothing is sized for its ${Math.floor(u.deploy)}`}.`);
|
|
31
|
+
}
|
|
32
|
+
return {
|
|
33
|
+
...seen,
|
|
34
|
+
growthOf,
|
|
35
|
+
deployReaching,
|
|
36
|
+
reinforcementAt,
|
|
37
|
+
holdArmies,
|
|
38
|
+
bombSized,
|
|
39
|
+
hiddenFoe,
|
|
40
|
+
hiddenMovable,
|
|
41
|
+
hiddenPool,
|
|
42
|
+
chainAt,
|
|
43
|
+
stacksAt,
|
|
44
|
+
forceAt,
|
|
45
|
+
threatAt,
|
|
46
|
+
nextTurnAt,
|
|
47
|
+
expectedAt,
|
|
48
|
+
exposure,
|
|
49
|
+
borders,
|
|
50
|
+
facing,
|
|
51
|
+
borderAt,
|
|
52
|
+
safeAtStart,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/** Rule 1t's trend, the enemy deploys that reach a territory, the fog's hidden stacks and the lost stacks (#164). */
|
|
56
|
+
export function threatSources(pc, ps, input) {
|
|
57
|
+
const { g, s, game: ctx, foe, custom, estimates, deployOf, territories: state, label, mine, mineSet, unitsAt, guard, bombOn, rates, toTake, turnNow, } = pc;
|
|
58
|
+
const { warnings, rationale } = ps;
|
|
59
|
+
// ---- 1t. threat trend ----
|
|
60
|
+
// Growth of each visible enemy territory next to me since the previous board
|
|
61
|
+
// (visible both times, same owner, grown): its armies per turn of build-up.
|
|
62
|
+
const growthOf = new Map();
|
|
63
|
+
if (input.previousBoard) {
|
|
64
|
+
const before = new Map(input.previousBoard.territories.map((t) => [t.territoryId, t]));
|
|
65
|
+
/** Same owner, shown with armies on both boards. */
|
|
66
|
+
const heldBoth = (id, player) => {
|
|
67
|
+
const a = visibleState(state.get(id));
|
|
68
|
+
const b = visibleState(before.get(id));
|
|
69
|
+
return a?.owner.kind === 'player' && a.owner.playerId === player && b?.owner.kind === 'player' && b.owner.playerId === player;
|
|
70
|
+
};
|
|
71
|
+
// #123: what each enemy territory visibly sent away (its shrink), claimed once (ascending ids)
|
|
72
|
+
// by a growing neighbour of the same owner: that growth was a transfer, a one-off, not a trend.
|
|
73
|
+
// The board cannot tell a fight from a transfer: a shrink beside another player's shrinking
|
|
74
|
+
// stack is read as a fight and explains nothing.
|
|
75
|
+
const shrinkLeft = new Map();
|
|
76
|
+
// A neighbour that shrank beside a shrinking stack of another player (me included) may have
|
|
77
|
+
// lost a fight rather than sent armies (as `combatLosses` in the tracker reads it): it explains
|
|
78
|
+
// no growth, so a deploy on the border beside it is still projected.
|
|
79
|
+
const shrankBy = (id) => {
|
|
80
|
+
const a = visibleState(state.get(id));
|
|
81
|
+
const b = visibleState(before.get(id));
|
|
82
|
+
if (a?.owner.kind !== 'player' || b?.owner.kind !== 'player' || a.owner.playerId !== b.owner.playerId)
|
|
83
|
+
return null;
|
|
84
|
+
return { player: a.owner.playerId, shrink: b.armies - a.armies };
|
|
85
|
+
};
|
|
86
|
+
const fought = (id, player) => neighborsOf(g, id).some((n) => {
|
|
87
|
+
const o = shrankBy(n);
|
|
88
|
+
return o !== null && o.player !== player && o.shrink > 0;
|
|
89
|
+
});
|
|
90
|
+
for (const [id, st] of state)
|
|
91
|
+
if (st.owner.kind === 'player' && foe(st.owner.playerId) && heldBoth(id, st.owner.playerId) && !fought(id, st.owner.playerId))
|
|
92
|
+
shrinkLeft.set(id, Math.max(0, visibleState(before.get(id)).armies - st.armies));
|
|
93
|
+
for (const [id, st] of [...state].sort((a, b) => a[0] - b[0])) {
|
|
94
|
+
if (st.owner.kind !== 'player' || !foe(st.owner.playerId) || st.armies === null)
|
|
95
|
+
continue;
|
|
96
|
+
if (!neighborsOf(g, id).some((n) => mineSet.has(n)))
|
|
97
|
+
continue;
|
|
98
|
+
// Visible both times (#69): a stack hidden last turn only came into view.
|
|
99
|
+
const was = visibleState(before.get(id));
|
|
100
|
+
if (was?.owner.kind !== 'player' || was.owner.playerId !== st.owner.playerId || was.armies === null)
|
|
101
|
+
continue;
|
|
102
|
+
let growth = st.armies - was.armies;
|
|
103
|
+
if (growth <= 0)
|
|
104
|
+
continue;
|
|
105
|
+
for (const n of [...neighborsOf(g, id)].sort((a, b) => a - b)) {
|
|
106
|
+
const left = shrinkLeft.get(n);
|
|
107
|
+
if (!left || growth <= 0 || !heldBoth(n, st.owner.playerId))
|
|
108
|
+
continue;
|
|
109
|
+
const take = Math.min(left, growth);
|
|
110
|
+
shrinkLeft.set(n, left - take);
|
|
111
|
+
growth -= take;
|
|
112
|
+
}
|
|
113
|
+
// Projected growth never beats what it could have deployed, every ambiguous army read as
|
|
114
|
+
// deploy (#123, `high`): a stack that walked in beside the fog is massing all the same
|
|
115
|
+
// (lesson 5), but growth no deploy or fog arrival explains is not projected.
|
|
116
|
+
const observedHigh = estimates.get(st.owner.playerId)?.observation?.high;
|
|
117
|
+
if (observedHigh !== undefined)
|
|
118
|
+
growth = Math.min(growth, observedHigh);
|
|
119
|
+
if (growth > 0)
|
|
120
|
+
growthOf.set(id, { from: was.armies, to: st.armies, growth });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
/** Each opponent's team, in a team game (#128): opponents on one team attack together. */
|
|
124
|
+
const teamOf = new Map();
|
|
125
|
+
for (const p of ctx.players ?? [])
|
|
126
|
+
if (carriesTeam(p.team) && foe(p.id))
|
|
127
|
+
teamOf.set(p.id, p.team);
|
|
128
|
+
/**
|
|
129
|
+
* Local Deployment (#128, #293): each opponent's bonuses it could hold (none of their territories
|
|
130
|
+
* shown with another owner), as deploy pools that land only on their own territories. Empty without
|
|
131
|
+
* Local Deployment or under the override.
|
|
132
|
+
*/
|
|
133
|
+
const enemyPools = new Map();
|
|
134
|
+
// #199: the one Local Deployment bound (local-deploy.ts), shared with check_plan's stress test.
|
|
135
|
+
// A what-if `enemyDeploy` is taken as it stands: no pool bounds it.
|
|
136
|
+
// #293 review: with per-territory income, income no pool carries (territories the fog hides) may land
|
|
137
|
+
// anywhere, so what an estimate holds beyond every bonus it could hold counts as free; without it, a
|
|
138
|
+
// border faces only the free income and the pools there.
|
|
139
|
+
const perTerritory = (s.bonusArmyPer ?? 0) > 0;
|
|
140
|
+
if (s.localDeployments && !custom) {
|
|
141
|
+
const foes = [...new Set([...state.values()].flatMap((t) => (t.owner.kind === 'player' && foe(t.owner.playerId) ? [t.owner.playerId] : [])))].sort(byNum);
|
|
142
|
+
for (const [p, pools] of couldHoldBonusPools(g, foes, (t) => {
|
|
143
|
+
const o = ownerShown(state.get(t))?.owner;
|
|
144
|
+
return o === undefined ? undefined : o.kind === 'player' ? o.playerId : null;
|
|
145
|
+
})) {
|
|
146
|
+
enemyPools.set(p, pools);
|
|
147
|
+
const e = estimates.get(p);
|
|
148
|
+
const free = freeIncome(e?.base ?? 0, MIN_ENEMY_DEPLOY, e?.card?.armies ?? 0);
|
|
149
|
+
const pooled = pools.reduce((n, q) => n + q.value, 0);
|
|
150
|
+
const figure = deployOf(p);
|
|
151
|
+
if (perTerritory && figure - pooled > free)
|
|
152
|
+
warnings.push(`Local Deployment with per-territory income: player ${p}'s estimate of ~${figure} is more than its free income +${free} and the +${pooled} of bonuses it could hold, so the ${figure - pooled - free} beyond them is taken as per-territory income the fog hides, which may be deployed anywhere: every border faces it.`);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* What `player` may deploy on any of `on` (#128, #293): its whole estimate, except under Local
|
|
157
|
+
* Deployment, where a bonus it could hold pays only into that bonus's territories: its free income
|
|
158
|
+
* (base, never below {@link MIN_ENEMY_DEPLOY}, plus a Reinforcement card) plus the pools that contain
|
|
159
|
+
* one of `on`, never above the estimate ({@link enemyDeployReaching}). A tracked total or a prior above
|
|
160
|
+
* that never lands on one border. `figure` replaces the estimate (an untrusted opponent's, #275).
|
|
161
|
+
*/
|
|
162
|
+
const deployReaching = (player, on, figure = deployOf(player)) => {
|
|
163
|
+
const pools = enemyPools.get(player);
|
|
164
|
+
if (!pools)
|
|
165
|
+
return figure;
|
|
166
|
+
const e = estimates.get(player);
|
|
167
|
+
return enemyDeployReaching(figure, freeIncome(e?.base ?? 0, MIN_ENEMY_DEPLOY, e?.card?.armies ?? 0), pools, on, perTerritory);
|
|
168
|
+
};
|
|
169
|
+
/**
|
|
170
|
+
* #120: what the owner of enemy territory `t` may add there before my attack lands — its deploy
|
|
171
|
+
* estimate (under Local Deployment, what reaches `t`), or its growth there per turn when larger
|
|
172
|
+
* (rule 1t). 0 for a territory no opponent holds.
|
|
173
|
+
*/
|
|
174
|
+
const reinforcementAt = (t) => {
|
|
175
|
+
const st = state.get(t);
|
|
176
|
+
if (st?.owner.kind !== 'player' || !foe(st.owner.playerId))
|
|
177
|
+
return 0;
|
|
178
|
+
return Math.max(deployReaching(st.owner.playerId, [t]), growthOf.get(t)?.growth ?? 0);
|
|
179
|
+
};
|
|
180
|
+
/** Fewest armies on a territory that hold against `threat` attackers. */
|
|
181
|
+
const holdArmies = (threat) => {
|
|
182
|
+
let a = 0;
|
|
183
|
+
while ((toTake(a) ?? Infinity) <= threat)
|
|
184
|
+
a++;
|
|
185
|
+
return a;
|
|
186
|
+
};
|
|
187
|
+
/**
|
|
188
|
+
* #163: the threat to my `t` as a Bomb would leave it. A Bomb halves my stack before the attack
|
|
189
|
+
* (the smaller half stays; a commander is unharmed), so it holds only with twice the armies: the
|
|
190
|
+
* threat becomes the attack that the doubled stack just holds against. Where toTake is flat
|
|
191
|
+
* across 2·armies+u−1 and 2·armies+u (luck, weighted rounding) no threat maps to a hold of exactly
|
|
192
|
+
* 2·armies+u, so this rounds up to the next hold a threat can express: larger, never smaller.
|
|
193
|
+
* The threat unchanged when no opponent may hold a Bomb.
|
|
194
|
+
*/
|
|
195
|
+
const bombSized = (t, threat) => {
|
|
196
|
+
if (!bombOn)
|
|
197
|
+
return threat;
|
|
198
|
+
const u = mineSet.has(t) ? unitsAt(t) : 0;
|
|
199
|
+
const armies = Math.max(0, holdArmies(threat) - u);
|
|
200
|
+
return armies > 0 ? Math.max(threat, toTake(2 * armies + u - 1) ?? threat) : threat;
|
|
201
|
+
};
|
|
202
|
+
/** The most defenders one attack of `attackers` takes ({@link toTake}); -1 when it takes none. */
|
|
203
|
+
const reachMemo = new Map();
|
|
204
|
+
const takesAlone = (attackers) => {
|
|
205
|
+
if (!reachMemo.has(attackers))
|
|
206
|
+
reachMemo.set(attackers, holdArmies(attackers) - 1);
|
|
207
|
+
return reachMemo.get(attackers);
|
|
208
|
+
};
|
|
209
|
+
/**
|
|
210
|
+
* The armies a softening attack of `n` kills, in a separate-attack threat: the luck-free share,
|
|
211
|
+
* rounded straight (S2) — deliberately not the game's luck and rounding. Under luck,
|
|
212
|
+
* {@link guaranteedKills} is the fewest kills luck allows, which would understate a threat
|
|
213
|
+
* whose last attack ({@link toTake}) is sized pessimistically for me; the luck-free share is
|
|
214
|
+
* what the softener kills on average, under either rounding.
|
|
215
|
+
*/
|
|
216
|
+
const killsOf = (n) => guaranteedKills(n, rates.offensiveKillRate, 0, 'StraightRound');
|
|
217
|
+
/**
|
|
218
|
+
* #164: the opponent holding `id` when its owner shows and the fog hides its armies (Dense and
|
|
219
|
+
* Heavy fog): a threat of unknown size, never unseen land and never a target. Else `undefined`.
|
|
220
|
+
*/
|
|
221
|
+
function hiddenFoe(id) {
|
|
222
|
+
const st = state.get(id);
|
|
223
|
+
if (!st || visibleState(st) || !ownerShown(st) || st.owner.kind !== 'player' || !foe(st.owner.playerId))
|
|
224
|
+
return undefined;
|
|
225
|
+
return st.owner.playerId;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* #164: what a stack of `player` the fog hides may move: its unaccounted armies from the tracker
|
|
229
|
+
* (`unexplained`: earned and not seen since), the guard staying; 0 without a track (the guard alone).
|
|
230
|
+
*/
|
|
231
|
+
function hiddenMovable(player) {
|
|
232
|
+
const pool = hiddenPool(player);
|
|
233
|
+
return pool.cap === null ? pool.unexplained : Math.min(pool.unexplained, pool.cap);
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* #164: the tracker's unaccounted armies of `player` and the cap on what one hidden stack moves,
|
|
237
|
+
* {@link HIDDEN_POOL_INCOMES} turns of its income (`null` without an income figure).
|
|
238
|
+
*/
|
|
239
|
+
function hiddenPool(player) {
|
|
240
|
+
const tr = input.tracks?.find((x) => x.playerId === player);
|
|
241
|
+
// Its income, a Reinforcement card left out: the card is counted once, in the deploy.
|
|
242
|
+
const e = estimates.get(player);
|
|
243
|
+
const income = Math.max(tr?.income ?? 0, (e?.estimate ?? 0) - (e?.card?.armies ?? 0));
|
|
244
|
+
return {
|
|
245
|
+
unexplained: Math.max(0, Math.floor(tr?.unexplained ?? 0)),
|
|
246
|
+
cap: income > 0 ? HIDDEN_POOL_INCOMES * income : null,
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* #164: large stacks that left view (the tracker's `lostStacks`, for {@link LOST_STACK_TURNS}
|
|
251
|
+
* turns after the last sighting), by my territory each can attack
|
|
252
|
+
* this turn: one move a turn since the turn it was last seen, never through my land, onto a
|
|
253
|
+
* territory the fog hides next to mine (fogged, or its owner's with the armies hidden). `via` is
|
|
254
|
+
* the nearest such territory (then id); `from` the earliest turn it could attack there.
|
|
255
|
+
*/
|
|
256
|
+
const lostAt = new Map();
|
|
257
|
+
/** #164: lost stacks that cannot attack my `t` this turn but can stand beside it (`via`) by next turn. */
|
|
258
|
+
const lostSoon = [];
|
|
259
|
+
/** #164: arrivals assume one move a turn; under Multi-attack a stack can chain moves and come sooner. */
|
|
260
|
+
const multiNote = s.multiAttack ? ' (one move a turn assumed: with Multi-attack on it can arrive sooner)' : '';
|
|
261
|
+
if (turnNow !== null)
|
|
262
|
+
for (const tr of [...(input.tracks ?? [])].sort((a, b) => a.playerId - b.playerId)) {
|
|
263
|
+
if (!foe(tr.playerId))
|
|
264
|
+
continue;
|
|
265
|
+
for (const l of tr.lostStacks ?? []) {
|
|
266
|
+
const elapsed = turnNow - l.turn;
|
|
267
|
+
const movable = Math.max(0, l.armies - guard);
|
|
268
|
+
if (elapsed < 1 || elapsed > LOST_STACK_TURNS || movable <= 0 || !g.territoryById.has(l.territoryId))
|
|
269
|
+
continue;
|
|
270
|
+
const dist = bfsDistances(g, [l.territoryId], { passable: (x) => !mineSet.has(x) });
|
|
271
|
+
for (const t of mine) {
|
|
272
|
+
const via = neighborsOf(g, t)
|
|
273
|
+
.filter((n) => {
|
|
274
|
+
const d = dist.get(n);
|
|
275
|
+
if (d === undefined || d > elapsed || mineSet.has(n) || visibleState(state.get(n)))
|
|
276
|
+
return false;
|
|
277
|
+
const o = ownerShown(state.get(n))?.owner;
|
|
278
|
+
return o === undefined || (o.kind === 'player' && o.playerId === tr.playerId);
|
|
279
|
+
})
|
|
280
|
+
.sort((a, b) => dist.get(a) - dist.get(b) || a - b)[0];
|
|
281
|
+
if (via === undefined) {
|
|
282
|
+
// Not there yet: where it can stand next to `t` by next turn (a territory beside `t`
|
|
283
|
+
// it can reach in one more move), warned of a turn ahead.
|
|
284
|
+
if (elapsed + 1 > LOST_STACK_TURNS)
|
|
285
|
+
continue;
|
|
286
|
+
const soon = neighborsOf(g, t)
|
|
287
|
+
.filter((n) => !mineSet.has(n) && (dist.get(n) ?? Infinity) <= elapsed + 1)
|
|
288
|
+
.sort((a, b) => dist.get(a) - dist.get(b) || a - b)[0];
|
|
289
|
+
if (soon !== undefined)
|
|
290
|
+
lostSoon.push({ player: tr.playerId, seenOn: l.territoryId, turn: l.turn, armies: l.armies, movable, t, via: soon });
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
lostAt.set(t, [
|
|
294
|
+
...(lostAt.get(t) ?? []),
|
|
295
|
+
{ player: tr.playerId, seenOn: l.territoryId, turn: l.turn, armies: l.armies, movable, via, from: l.turn + dist.get(via) },
|
|
296
|
+
]);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
{
|
|
301
|
+
// One line per stack, naming each border it reaches (the first MAX_NAMED_REVEALS, then a count).
|
|
302
|
+
const byStack = new Map();
|
|
303
|
+
for (const [t, ls] of [...lostAt].sort((a, b) => a[0] - b[0]))
|
|
304
|
+
for (const l of ls) {
|
|
305
|
+
const key = `${l.player}|${l.seenOn}|${l.turn}`;
|
|
306
|
+
const e = byStack.get(key) ?? { l, at: [] };
|
|
307
|
+
e.at.push(`${label(t)} from turn ${l.from} (through ${label(l.via)})`);
|
|
308
|
+
byStack.set(key, e);
|
|
309
|
+
}
|
|
310
|
+
for (const { l, at } of byStack.values()) {
|
|
311
|
+
const more = at.length > MAX_NAMED_REVEALS ? ` and ${at.length - MAX_NAMED_REVEALS} more` : '';
|
|
312
|
+
rationale.push(`Player ${l.player}'s stack of ${l.armies} armies last seen on ${label(l.seenOn)} on turn ${l.turn} left view: it can attack ${at.slice(0, MAX_NAMED_REVEALS).join(', ')}${more}, so each one's worst case counts it as a separate threat of ${l.movable}${multiNote}.`);
|
|
313
|
+
}
|
|
314
|
+
// A turn ahead: one warning per stack, naming each border it can stand beside by next turn.
|
|
315
|
+
const soonBy = new Map();
|
|
316
|
+
for (const l of lostSoon) {
|
|
317
|
+
const key = `${l.player}|${l.seenOn}|${l.turn}`;
|
|
318
|
+
const e = soonBy.get(key) ?? { l, at: [] };
|
|
319
|
+
e.at.push(`${label(l.via)}, next to my ${label(l.t)}`);
|
|
320
|
+
soonBy.set(key, e);
|
|
321
|
+
}
|
|
322
|
+
for (const { l, at } of soonBy.values()) {
|
|
323
|
+
const more = at.length > MAX_NAMED_REVEALS ? ` and ${at.length - MAX_NAMED_REVEALS} more` : '';
|
|
324
|
+
warnings.push(`Player ${l.player}'s stack of ${l.armies} armies last seen on ${label(l.seenOn)} on turn ${l.turn} is out of view and can stand on ${at.slice(0, MAX_NAMED_REVEALS).join('; ')}${more}, by next turn, and attack the turn after with up to ${l.movable} plus its deploy: not counted in this turn's holds${multiNote}.`);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
return {
|
|
328
|
+
growthOf,
|
|
329
|
+
teamOf,
|
|
330
|
+
deployReaching,
|
|
331
|
+
reinforcementAt,
|
|
332
|
+
holdArmies,
|
|
333
|
+
bombSized,
|
|
334
|
+
takesAlone,
|
|
335
|
+
killsOf,
|
|
336
|
+
hiddenFoe,
|
|
337
|
+
hiddenMovable,
|
|
338
|
+
hiddenPool,
|
|
339
|
+
lostAt,
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
/** What each opponent can bring against one territory: its stacks, its deploy, its Multi-Attack chains (#199). */
|
|
343
|
+
export function threatForces(pc, ps, src) {
|
|
344
|
+
const { g, board, s, foe, territories: state, mineSet, unitsAt, guard, rates, toTake, ffaLeader, untrustedAt } = pc;
|
|
345
|
+
const { captured } = ps;
|
|
346
|
+
/**
|
|
347
|
+
* G2 (T9, D3): a player a Diplomacy card shields me from only this turn is a foe again next turn:
|
|
348
|
+
* {@link nextTurnAt} (the frontier and a completion's defensibility) counts its stacks.
|
|
349
|
+
*/
|
|
350
|
+
const returning = pc.truce.lookAheadFoes;
|
|
351
|
+
/** #293: under Local Deployment a next-turn judgement counts the visible stacks one step behind a front. */
|
|
352
|
+
const behindNext = s.localDeployments === true && !pc.custom;
|
|
353
|
+
const foeNext = (p) => foe(p) || returning.has(p);
|
|
354
|
+
const { growthOf, teamOf, deployReaching, holdArmies, bombSized, takesAlone, killsOf, hiddenFoe, hiddenMovable, lostAt, } = src;
|
|
355
|
+
/**
|
|
356
|
+
* #199: under Multi-Attack, every visible enemy stack's attack chains ({@link searchChains}: its
|
|
357
|
+
* deploy that reaches it, less the guard, its commander left behind; luck-free, capped) that take
|
|
358
|
+
* one territory or more not mine and then attack a territory — of mine, or one this plan may
|
|
359
|
+
* capture (a territory not its player's own) — by that territory, most armies first. With
|
|
360
|
+
* `standing`, the stack's armies alone, no deploy: armies already there, for the floor tier.
|
|
361
|
+
* Built on first use; empty without Multi-Attack.
|
|
362
|
+
*/
|
|
363
|
+
const chainMemo = new Map();
|
|
364
|
+
const chainsOnto = (t, standing = false) => {
|
|
365
|
+
if (!s.multiAttack)
|
|
366
|
+
return [];
|
|
367
|
+
let memo = chainMemo.get(standing);
|
|
368
|
+
if (!memo) {
|
|
369
|
+
memo = new Map();
|
|
370
|
+
chainMemo.set(standing, memo);
|
|
371
|
+
const sim = simTerritories(board);
|
|
372
|
+
for (const [n, st] of [...state].sort((a, b) => a[0] - b[0])) {
|
|
373
|
+
if (st.owner.kind !== 'player' || !foe(st.owner.playerId) || st.armies === null || hiddenFoe(n) !== undefined)
|
|
374
|
+
continue;
|
|
375
|
+
const player = st.owner.playerId;
|
|
376
|
+
const team = teamOf.get(player);
|
|
377
|
+
searchChains({
|
|
378
|
+
graph: g,
|
|
379
|
+
territories: sim,
|
|
380
|
+
from: n,
|
|
381
|
+
sending: Math.max(0, st.armies - guard) + (standing ? 0 : deployReaching(player, [n])),
|
|
382
|
+
guard,
|
|
383
|
+
...rates,
|
|
384
|
+
hostile: (_id, x) => x.owner === 'neutral' || (typeof x.owner === 'number' && x.owner !== player && (team === undefined || teamOf.get(x.owner) !== team)),
|
|
385
|
+
goOn: (id) => !mineSet.has(id),
|
|
386
|
+
onAttack: (a) => {
|
|
387
|
+
const to = a.path[a.path.length - 1];
|
|
388
|
+
if (a.path.length < 3)
|
|
389
|
+
return;
|
|
390
|
+
memo.set(to, [...(memo.get(to) ?? []), { player, path: a.path, armies: a.sending }]);
|
|
391
|
+
},
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
for (const list of memo.values())
|
|
395
|
+
list.sort((a, b) => b.armies - a.armies || a.player - b.player || a.path.join().localeCompare(b.path.join()));
|
|
396
|
+
}
|
|
397
|
+
return memo.get(t) ?? [];
|
|
398
|
+
};
|
|
399
|
+
/**
|
|
400
|
+
* #199: the strongest chain onto `t` (mine, or a capture) that passes through no territory in
|
|
401
|
+
* `gone`; with `standing`, of the stack's armies alone, no deploy.
|
|
402
|
+
*/
|
|
403
|
+
const chainAt = (t, gone, standing = false) => chainsOnto(t, standing).find((c) => !c.path.some((x) => x !== t && gone(x)));
|
|
404
|
+
/**
|
|
405
|
+
* The enemy force that can hit my `t` next turn (#128). Per opponent: each of its stacks next
|
|
406
|
+
* to `t` (territories in `gone` excluded) is movable armies plus its units, and it may deploy
|
|
407
|
+
* {@link deployReaching} there — onto one stack — plus, with `trend`, its fastest growth when
|
|
408
|
+
* larger. One attack of all of it is the old model (a transfer then an attack); separate attacks
|
|
409
|
+
* each round on their own, so a 1-army softener kills 1 at 60% and the last attack takes the
|
|
410
|
+
* rest: the force reaches max over the last attack L of Σ kills(others) + reach(L). With
|
|
411
|
+
* `allPlayers`, every opponent next to `t` may attack it in the same turn (worst case); else
|
|
412
|
+
* each opponent alone. `player` is the strongest one alone. `null` with no opponent next to it.
|
|
413
|
+
*/
|
|
414
|
+
/**
|
|
415
|
+
* Per opponent, its stacks next to my `t` (territories in `gone` excluded) and what each may
|
|
416
|
+
* move: visible stacks their movable armies and units; #164's hidden stacks its unaccounted
|
|
417
|
+
* armies, once per border (its first hidden stack carries them); stacks that left view
|
|
418
|
+
* ({@link lostAt}), the pool's carrier keeping what they leave of it. With `trend`, its fastest
|
|
419
|
+
* growth there. Shared by {@link forceAt} and the floor tier's armies already next to a border.
|
|
420
|
+
*/
|
|
421
|
+
const stacksAt = (t, gone, trend, nextTurn = false, behind = false) => {
|
|
422
|
+
const isFoe = nextTurn ? foeNext : foe;
|
|
423
|
+
const byPlayer = new Map();
|
|
424
|
+
// #164: a player's unaccounted armies are one pool, in one place at most: its first hidden stack
|
|
425
|
+
// next to `t` carries them; any other hidden stack of it there is the guard alone (movable 0).
|
|
426
|
+
const pooled = new Set();
|
|
427
|
+
const carrier = new Map();
|
|
428
|
+
for (const n of [...neighborsOf(g, t)].sort(byNum)) {
|
|
429
|
+
const st = state.get(n);
|
|
430
|
+
if (gone(n) || st?.owner.kind !== 'player' || !isFoe(st.owner.playerId))
|
|
431
|
+
continue;
|
|
432
|
+
// #164: an owner shown with its armies hidden (Dense / Heavy fog) is a stack of bounded size.
|
|
433
|
+
const hidden = hiddenFoe(n) !== undefined;
|
|
434
|
+
if (st.armies === null && !hidden)
|
|
435
|
+
continue;
|
|
436
|
+
const p = byPlayer.get(st.owner.playerId) ?? { stacks: [], growth: 0 };
|
|
437
|
+
// An enemy commander can join the attack: it fights as COMMANDER_STRENGTH armies.
|
|
438
|
+
const movable = !hidden
|
|
439
|
+
? Math.max(0, st.armies - guard) + unitsAt(n)
|
|
440
|
+
: pooled.has(st.owner.playerId)
|
|
441
|
+
? 0
|
|
442
|
+
: hiddenMovable(st.owner.playerId);
|
|
443
|
+
if (hidden && !pooled.has(st.owner.playerId))
|
|
444
|
+
carrier.set(st.owner.playerId, n);
|
|
445
|
+
if (hidden)
|
|
446
|
+
pooled.add(st.owner.playerId);
|
|
447
|
+
p.stacks.push({ id: n, movable });
|
|
448
|
+
if (trend && !hidden)
|
|
449
|
+
p.growth = Math.max(p.growth, growthOf.get(n)?.growth ?? 0);
|
|
450
|
+
byPlayer.set(st.owner.playerId, p);
|
|
451
|
+
}
|
|
452
|
+
// #164: a large stack that left view and can stand next to `t` by now: a separate stack of its owner.
|
|
453
|
+
for (const l of lostAt.get(t) ?? []) {
|
|
454
|
+
if (gone(l.via))
|
|
455
|
+
continue;
|
|
456
|
+
const p = byPlayer.get(l.player) ?? { stacks: [], growth: 0 };
|
|
457
|
+
const there = p.stacks.find((x) => x.id === l.via);
|
|
458
|
+
if (there)
|
|
459
|
+
there.movable = Math.max(there.movable, l.movable);
|
|
460
|
+
else
|
|
461
|
+
p.stacks.push({ id: l.via, movable: l.movable });
|
|
462
|
+
byPlayer.set(l.player, p);
|
|
463
|
+
}
|
|
464
|
+
// #164: a lost stack's armies left the visible total, so they are part of its owner's
|
|
465
|
+
// unaccounted armies: the pool's carrier keeps only what the lost stacks elsewhere on this
|
|
466
|
+
// border leave of it, so the two together are never more than the larger. A lost stack via the
|
|
467
|
+
// carrier itself is a stack seen there: the carrier keeps at least it.
|
|
468
|
+
for (const [player, id] of carrier) {
|
|
469
|
+
const p = byPlayer.get(player);
|
|
470
|
+
const theirs = (lostAt.get(t) ?? []).filter((l) => l.player === player && !gone(l.via));
|
|
471
|
+
const lostElsewhere = theirs.filter((l) => l.via !== id);
|
|
472
|
+
if (!lostElsewhere.length)
|
|
473
|
+
continue;
|
|
474
|
+
const c = p.stacks.find((x) => x.id === id);
|
|
475
|
+
const viaCarrier = theirs.filter((l) => l.via === id).reduce((n, l) => Math.max(n, l.movable), 0);
|
|
476
|
+
const pool = hiddenMovable(player);
|
|
477
|
+
c.movable = Math.max(viaCarrier, pool - lostElsewhere.reduce((n, l) => n + l.movable, 0));
|
|
478
|
+
}
|
|
479
|
+
// #293: for a next-turn judgement under Local Deployment, its visible stacks one step behind its
|
|
480
|
+
// front (beside one of its stacks next to `t`, not next to `t` themselves) can walk up this turn
|
|
481
|
+
// and attack next turn: each joins the front stack it borders (the lowest id), once.
|
|
482
|
+
if (behind)
|
|
483
|
+
for (const [player, p] of byPlayer) {
|
|
484
|
+
const front = p.stacks.filter((x) => visibleState(state.get(x.id)) !== undefined).map((x) => x.id);
|
|
485
|
+
const seen = new Set([t, ...p.stacks.map((x) => x.id)]);
|
|
486
|
+
const ids = [];
|
|
487
|
+
for (const f of [...front].sort(byNum))
|
|
488
|
+
for (const m of [...neighborsOf(g, f)].sort(byNum)) {
|
|
489
|
+
const st = visibleState(state.get(m));
|
|
490
|
+
if (seen.has(m) || gone(m) || st?.owner.kind !== 'player' || st.owner.playerId !== player || neighborsOf(g, m).includes(t))
|
|
491
|
+
continue;
|
|
492
|
+
seen.add(m);
|
|
493
|
+
const walk = Math.max(0, st.armies - guard) + unitsAt(m);
|
|
494
|
+
if (walk <= 0)
|
|
495
|
+
continue;
|
|
496
|
+
p.stacks.find((x) => x.id === f).movable += walk;
|
|
497
|
+
ids.push(m);
|
|
498
|
+
}
|
|
499
|
+
if (ids.length)
|
|
500
|
+
p.behind = ids.sort(byNum);
|
|
501
|
+
}
|
|
502
|
+
return byPlayer;
|
|
503
|
+
};
|
|
504
|
+
/**
|
|
505
|
+
* #199: the force of a Multi-Attack chain onto my `t`: its player's, its armies all of it (the
|
|
506
|
+
* deploy that reaches its stack is already inside them), no growth or separate deploy.
|
|
507
|
+
*/
|
|
508
|
+
const chainForce = (t, chain) => ({
|
|
509
|
+
player: chain.player,
|
|
510
|
+
movable: chain.armies,
|
|
511
|
+
growth: 0,
|
|
512
|
+
deploy: 0,
|
|
513
|
+
threat: bombSized(t, chain.armies),
|
|
514
|
+
chain,
|
|
515
|
+
});
|
|
516
|
+
const forceAt = (t, gone, o) => {
|
|
517
|
+
const byPlayer = stacksAt(t, gone, o.trend, o.nextTurn === true, o.behind === true);
|
|
518
|
+
// B2 (T2, plan/relations.ts): on a truce hold the partner attacks with its stacks alone — no
|
|
519
|
+
// deploy, no trend, its Multi-Attack chains from the armies standing; `full` asks for the hold
|
|
520
|
+
// the truce relaxed.
|
|
521
|
+
const truced = o.full ? undefined : ps.truce?.relaxed.get(t);
|
|
522
|
+
let chain = chainAt(t, gone);
|
|
523
|
+
if (chain && truced === chain.player)
|
|
524
|
+
chain = chainAt(t, gone, true);
|
|
525
|
+
if (!byPlayer.size)
|
|
526
|
+
return chain ? chainForce(t, chain) : null;
|
|
527
|
+
const each = [...byPlayer]
|
|
528
|
+
.sort((a, b) => a[0] - b[0])
|
|
529
|
+
.map(([player, p]) => {
|
|
530
|
+
// #275 (b): a held bonus's border is sized for an untrusted estimate's figure, never below the estimate
|
|
531
|
+
// (#293: under Local Deployment, what of that figure can reach these stacks).
|
|
532
|
+
const deploy = truced === player
|
|
533
|
+
? 0
|
|
534
|
+
: deployReaching(player, [...p.stacks.map((x) => x.id), ...(p.behind ?? [])], Math.max(pc.deployOf(player), untrustedAt(player, t)));
|
|
535
|
+
const growth = truced === player ? 0 : p.growth;
|
|
536
|
+
const movable = p.stacks.reduce((n, x) => n + x.movable, 0);
|
|
537
|
+
const add = Math.max(deploy, growth);
|
|
538
|
+
return { player, stacks: p.stacks, growth, deploy, movable, add, single: movable + add };
|
|
539
|
+
});
|
|
540
|
+
const best = [...each].sort((a, b) => b.single - a.single || a.player - b.player)[0];
|
|
541
|
+
// Separate attacks: try each stack as the last attack, its owner's deploy on it; every other
|
|
542
|
+
// opponent in the group lands its deploy on its own largest stack.
|
|
543
|
+
let split;
|
|
544
|
+
let splitTakes = -1;
|
|
545
|
+
// Opponents on one team coordinate; players of an FFA each attack alone (two of them landing
|
|
546
|
+
// on one border in the same turn is a warning, {@link pileOnAt}, not a hold).
|
|
547
|
+
const groups = [];
|
|
548
|
+
for (const e of each) {
|
|
549
|
+
const team = o.allPlayers ? teamOf.get(e.player) : undefined;
|
|
550
|
+
const mates = team === undefined ? undefined : groups.find((gr) => teamOf.get(gr[0].player) === team);
|
|
551
|
+
if (mates)
|
|
552
|
+
mates.push(e);
|
|
553
|
+
else
|
|
554
|
+
groups.push([e]);
|
|
555
|
+
}
|
|
556
|
+
// #201: the FFA leader holds against every adjacent opponent together — unless `solo` (#235:
|
|
557
|
+
// a border whose joint hold does not pay is sized for each opponent alone, as in any FFA).
|
|
558
|
+
if (o.pileOn || (o.allPlayers && ffaLeader && !o.solo))
|
|
559
|
+
groups.splice(0, groups.length, each);
|
|
560
|
+
for (const group of groups) {
|
|
561
|
+
const count = group.reduce((n, e) => n + e.stacks.length, 0);
|
|
562
|
+
if (count < 2)
|
|
563
|
+
continue;
|
|
564
|
+
for (const last of group)
|
|
565
|
+
for (const L of last.stacks) {
|
|
566
|
+
const attacks = [];
|
|
567
|
+
for (const e of group) {
|
|
568
|
+
const big = [...e.stacks].sort((a, b) => b.movable - a.movable || a.id - b.id)[0];
|
|
569
|
+
const on = e === last ? L : big;
|
|
570
|
+
for (const x of e.stacks)
|
|
571
|
+
if (x !== L)
|
|
572
|
+
attacks.push(x.movable + (x === on ? e.add : 0));
|
|
573
|
+
}
|
|
574
|
+
const lastArmies = L.movable + last.add;
|
|
575
|
+
const softeners = attacks.filter((a) => a > 0);
|
|
576
|
+
const takes = softeners.reduce((n, a) => n + killsOf(a), 0) + takesAlone(lastArmies);
|
|
577
|
+
if (takes > splitTakes) {
|
|
578
|
+
splitTakes = takes;
|
|
579
|
+
split = { attacks: [...softeners, lastArmies], takes, players: group.map((e) => e.player) };
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
let threat = best.single;
|
|
584
|
+
if (split && split.takes > takesAlone(best.single))
|
|
585
|
+
threat = Math.max(threat, toTake(split.takes) ?? threat);
|
|
586
|
+
else
|
|
587
|
+
split = undefined;
|
|
588
|
+
// #199: a Multi-Attack chain that lands more than the stacks next to it is the threat, and
|
|
589
|
+
// the force is its player's: the chain (its deploy included) is all of it.
|
|
590
|
+
if (chain && chain.armies > threat)
|
|
591
|
+
return chainForce(t, chain);
|
|
592
|
+
return {
|
|
593
|
+
player: best.player,
|
|
594
|
+
movable: best.movable,
|
|
595
|
+
growth: best.growth,
|
|
596
|
+
deploy: best.deploy,
|
|
597
|
+
// #163: sized as if a Bomb halved my stack first ({@link bombSized}).
|
|
598
|
+
threat: bombSized(t, threat),
|
|
599
|
+
...(split ? { split } : {}),
|
|
600
|
+
};
|
|
601
|
+
};
|
|
602
|
+
/**
|
|
603
|
+
* The strongest visible enemy force that could hit `t` next turn ({@link forceAt}, every
|
|
604
|
+
* opponent next to it, trend included). `null` with no enemy next to it.
|
|
605
|
+
*/
|
|
606
|
+
const threatAt = (t, gone) => {
|
|
607
|
+
// #235: a leader's border whose joint hold does not pay is judged against each opponent alone.
|
|
608
|
+
const f = forceAt(t, gone, { trend: true, allPlayers: true, solo: ps.soloHeld.has(t) });
|
|
609
|
+
return f ? { player: f.player, threat: f.threat } : null;
|
|
610
|
+
};
|
|
611
|
+
/**
|
|
612
|
+
* {@link threatAt} for next turn (G2): the same force, with the players a Diplomacy card shields me
|
|
613
|
+
* from only this turn counted again ({@link foeNext}). The same as threatAt when there is none.
|
|
614
|
+
*/
|
|
615
|
+
const nextTurnAt = (t, gone) => {
|
|
616
|
+
if (!returning.size && !behindNext)
|
|
617
|
+
return threatAt(t, gone);
|
|
618
|
+
const f = forceAt(t, gone, { trend: true, allPlayers: true, solo: ps.soloHeld.has(t), nextTurn: true, behind: behindNext });
|
|
619
|
+
return f ? { player: f.player, threat: f.threat } : null;
|
|
620
|
+
};
|
|
621
|
+
/**
|
|
622
|
+
* The expected (not worst-case) attack on my `t` next turn (issue #59): per player, its
|
|
623
|
+
* movable armies (and units, #128) next to `t` plus its deploy estimate — no trend projection,
|
|
624
|
+
* one opponent at a time, its stacks attacking separately when that takes more. 0 with none.
|
|
625
|
+
*/
|
|
626
|
+
const expectedAt = (t) => forceAt(t, (n) => captured.has(n), { trend: false, allPlayers: false })?.threat ?? 0;
|
|
627
|
+
/** Members of a bonus I would hold that a visible enemy could take next turn, given the armies staying on each. */
|
|
628
|
+
const exposure = (members, gone, stays) => {
|
|
629
|
+
const out = [];
|
|
630
|
+
for (const m of members) {
|
|
631
|
+
const th = nextTurnAt(m, gone);
|
|
632
|
+
if (!th)
|
|
633
|
+
continue;
|
|
634
|
+
// My commander defends with the armies on my territory (a capture's units were the enemy's).
|
|
635
|
+
const have = stays(m) + (mineSet.has(m) ? unitsAt(m) : 0);
|
|
636
|
+
const take = toTake(have);
|
|
637
|
+
if (take === null || take > th.threat)
|
|
638
|
+
continue;
|
|
639
|
+
out.push({ id: m, player: th.player, take, need: holdArmies(th.threat) - have });
|
|
640
|
+
}
|
|
641
|
+
return out;
|
|
642
|
+
};
|
|
643
|
+
return {
|
|
644
|
+
chainAt,
|
|
645
|
+
stacksAt,
|
|
646
|
+
forceAt,
|
|
647
|
+
threatAt,
|
|
648
|
+
nextTurnAt,
|
|
649
|
+
expectedAt,
|
|
650
|
+
exposure,
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
/** Rule 1's borders: the strongest force next to each territory of mine, stated in the rationale. */
|
|
654
|
+
export function borderThreats(pc, ps, input, src, forces) {
|
|
655
|
+
const { g, board, game: ctx, foe, custom, estimates, incomePrior, incomePriorSkipped, enemyDeploy, territories: state, label, mine, mineSet, armiesOf, unitsAt, uncounted, uncountedKind, bombOn, toTake, turnNow, holdPasses, myCommanders, s, baseIncome, rates, } = pc;
|
|
656
|
+
const { warnings, rationale } = ps;
|
|
657
|
+
const { growthOf, holdArmies, hiddenFoe, lostAt, teamOf, deployReaching, bombSized } = src;
|
|
658
|
+
/** #226: the game pays per territory (BonusArmyPer). */
|
|
659
|
+
const perTerritory = (s.bonusArmyPer ?? 0) > 0;
|
|
660
|
+
/** #226: what the bonuses it could still hold add to what it could earn (its territories' pay aside). */
|
|
661
|
+
const possibleOf = (e) => e.couldEarn - territoryIncome(e.couldHold, baseIncome, s.bonusArmyPer ?? 0);
|
|
662
|
+
const { forceAt } = forces;
|
|
663
|
+
// ---- 1. defence ----
|
|
664
|
+
const borders = new Map();
|
|
665
|
+
/** Every visible enemy player with a stack next to one of my territories. */
|
|
666
|
+
const facing = new Set();
|
|
667
|
+
/**
|
|
668
|
+
* The strongest visible enemy threat to my `t` (territories in `gone` excluded), or `null` with none
|
|
669
|
+
* next to it. Pure: callers judge hypothetical boards with it, so what a border is actually sized
|
|
670
|
+
* for (its `worst` included, #201) is read from `borders`, never from a side table.
|
|
671
|
+
*/
|
|
672
|
+
/**
|
|
673
|
+
* #274: the worst case on my commander's territory `t`: per opponent (a team together; as the
|
|
674
|
+
* FFA leader every opponent together), its whole deploy — at least my own income, as
|
|
675
|
+
* warapp_submit_turn sizes its replies, unless the caller gave `enemyDeploy` — plus the movable
|
|
676
|
+
* armies of every visible stack of its within two moves of `t` (`gone` excluded). `undefined`
|
|
677
|
+
* with none in reach.
|
|
678
|
+
*/
|
|
679
|
+
const commanderWorstAt = (t, gone) => {
|
|
680
|
+
const within = new Set();
|
|
681
|
+
for (const n of neighborsOf(g, t)) {
|
|
682
|
+
within.add(n);
|
|
683
|
+
for (const m of neighborsOf(g, n))
|
|
684
|
+
if (m !== t)
|
|
685
|
+
within.add(m);
|
|
686
|
+
}
|
|
687
|
+
const groups = new Map();
|
|
688
|
+
for (const n of [...within].sort(byNum)) {
|
|
689
|
+
const st = state.get(n);
|
|
690
|
+
if (gone(n) || st?.owner.kind !== 'player' || !foe(st.owner.playerId) || st.armies === null)
|
|
691
|
+
continue;
|
|
692
|
+
const p = st.owner.playerId;
|
|
693
|
+
const team = teamOf.get(p);
|
|
694
|
+
const key = pc.ffaLeader ? 'all' : team !== undefined ? `team ${team}` : `player ${p}`;
|
|
695
|
+
const gr = groups.get(key) ?? { players: new Map(), stacks: 0 };
|
|
696
|
+
gr.players.set(p, [...(gr.players.get(p) ?? []), n]);
|
|
697
|
+
gr.stacks += Math.max(0, st.armies - pc.guard) + unitsAt(n);
|
|
698
|
+
groups.set(key, gr);
|
|
699
|
+
}
|
|
700
|
+
// A what-if `enemyDeploy` is the caller's plausible income: taken as it stands.
|
|
701
|
+
const mineIncome = custom ? 0 : Math.max(0, pc.income - pc.cardArmies);
|
|
702
|
+
let worst;
|
|
703
|
+
for (const gr of groups.values()) {
|
|
704
|
+
const deploy = Math.max(mineIncome, [...gr.players].reduce((n, [p, on]) => n + deployReaching(p, on), 0));
|
|
705
|
+
const threat = deploy + gr.stacks;
|
|
706
|
+
if (!worst || threat > worst.threat)
|
|
707
|
+
worst = { deploy, stacks: gr.stacks, players: [...gr.players.keys()].sort(byNum), threat };
|
|
708
|
+
}
|
|
709
|
+
return worst;
|
|
710
|
+
};
|
|
711
|
+
const borderAt = (t, gone) => {
|
|
712
|
+
// #235: a leader's border whose joint hold does not pay is sized for each opponent alone.
|
|
713
|
+
const solo = ps.soloHeld.has(t);
|
|
714
|
+
const f = forceAt(t, gone, { trend: true, allPlayers: true, solo });
|
|
715
|
+
// #274 review: under Multi-Attack a stack two moves away can chain through my land onto my
|
|
716
|
+
// commander's territory (the chains of forceAt never go through it): its worst case sizes it too,
|
|
717
|
+
// where the commander stays. Not on the step it walks to: a chain onto it runs through the territory
|
|
718
|
+
// it walks from, whose transit hold (plan/commander.ts) is what stops it.
|
|
719
|
+
if (!f) {
|
|
720
|
+
if (!myCommanders.has(t) || s.multiAttack !== true || pc.commanderAt?.retreat?.to === t)
|
|
721
|
+
return null;
|
|
722
|
+
const w = commanderWorstAt(t, gone);
|
|
723
|
+
if (!w)
|
|
724
|
+
return null;
|
|
725
|
+
const threat = bombSized(t, w.threat);
|
|
726
|
+
return { id: t, player: w.players[0], movable: w.stacks, growth: 0, deploy: w.deploy, threat, commanderWorst: { deploy: w.deploy, stacks: w.stacks, players: w.players } };
|
|
727
|
+
}
|
|
728
|
+
// #274: my commander's territory is held against the worst case, never less than the visible threat.
|
|
729
|
+
if (myCommanders.has(t)) {
|
|
730
|
+
const w = commanderWorstAt(t, gone);
|
|
731
|
+
const threat = w ? bombSized(t, w.threat) : 0;
|
|
732
|
+
if (w && threat > f.threat)
|
|
733
|
+
return { id: t, ...f, threat, commanderWorst: { deploy: w.deploy, stacks: w.stacks, players: w.players } };
|
|
734
|
+
return { id: t, ...f };
|
|
735
|
+
}
|
|
736
|
+
// #235: the leader's joint threat, with the strongest single opponent's beside it.
|
|
737
|
+
const alone = () => {
|
|
738
|
+
if (solo || !pc.ffaLeader || !f.split || f.split.players.length < 2)
|
|
739
|
+
return undefined;
|
|
740
|
+
const a = forceAt(t, gone, { trend: true, allPlayers: true, solo: true });
|
|
741
|
+
return a && a.threat < f.threat ? a.threat : undefined;
|
|
742
|
+
};
|
|
743
|
+
// #201, behind: sized for the expected attack (#59's {@link expectedAt}: every adjacent player's
|
|
744
|
+
// movable armies next to it plus its whole deploy estimate, the largest of them), not the worst
|
|
745
|
+
// case — the trend projection above the deploy. The deploy is counted in full on each border, so
|
|
746
|
+
// no border is left short of what one deploy landing there takes: the gamble is only the growth
|
|
747
|
+
// trend above the deploy, and with none it is a no-op. (Sizing for the movable stacks alone broke
|
|
748
|
+
// #118, and one stack beside two such borders splits its deploy to take both.) Separate attacks, Multi-Attack
|
|
749
|
+
// chains and Bomb sizing are no gamble here (they keep the worst case), nor my commander's
|
|
750
|
+
// territory (rule 1k holds it against the whole deploy), nor an `enemyDeploy` override.
|
|
751
|
+
if (holdPasses === 'expected' && !myCommanders.has(t) && !f.split && !f.chain && !bombOn && !custom) {
|
|
752
|
+
const e = forceAt(t, gone, { trend: false, allPlayers: true, solo });
|
|
753
|
+
if (e && !e.split && !e.chain && e.threat < f.threat)
|
|
754
|
+
return { id: t, ...f, threat: e.threat, worst: f.threat };
|
|
755
|
+
}
|
|
756
|
+
const a = alone();
|
|
757
|
+
return { id: t, ...f, ...(a !== undefined ? { alone: a } : {}) };
|
|
758
|
+
};
|
|
759
|
+
for (const t of mine) {
|
|
760
|
+
for (const n of neighborsOf(g, t)) {
|
|
761
|
+
const st = state.get(n);
|
|
762
|
+
if (st?.owner.kind === 'player' && foe(st.owner.playerId) && (st.armies !== null || hiddenFoe(n) !== undefined))
|
|
763
|
+
facing.add(st.owner.playerId);
|
|
764
|
+
}
|
|
765
|
+
for (const l of lostAt.get(t) ?? [])
|
|
766
|
+
if (estimates.has(l.player))
|
|
767
|
+
facing.add(l.player);
|
|
768
|
+
const b = borderAt(t, () => false);
|
|
769
|
+
if (b)
|
|
770
|
+
borders.set(t, b);
|
|
771
|
+
if (b?.commanderWorst) {
|
|
772
|
+
const w = b.commanderWorst;
|
|
773
|
+
rationale.push(`My commander's territory ${label(t)} is held against the worst case (#274), ~${b.threat}: ${w.players.length > 1 ? `players ${w.players.join(' and ')}` : `player ${w.players[0]}`}'s whole deploy, ~${w.deploy} (never below my own income), plus the ${w.stacks} movable armies ${w.players.length > 1 ? 'they have' : 'it has'} within two moves of it.`);
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
// #199: say where a Multi-Attack chain sets a border's threat.
|
|
777
|
+
for (const b of [...borders.values()].filter((x) => x.chain).sort((x, y) => y.chain.armies - x.chain.armies || x.id - y.id).slice(0, MAX_NAMED_REVEALS)) {
|
|
778
|
+
const c = b.chain;
|
|
779
|
+
const via = c.path.slice(1, -1).map(label).join(' then ');
|
|
780
|
+
warnings.push(`Multi-Attack chain: player ${c.player}'s stack on ${label(c.path[0])} can take ${via} and attack ${label(b.id)} with ~${c.armies} armies (its deploy included, luck-free): that is the threat counted there.`);
|
|
781
|
+
}
|
|
782
|
+
// #128: an enemy unit the board gives no strength for is in no threat: say so.
|
|
783
|
+
for (const e of [...state.keys()].sort(byNum)) {
|
|
784
|
+
const st = state.get(e);
|
|
785
|
+
if (st.owner.kind !== 'player' || !foe(st.owner.playerId) || !uncounted(e))
|
|
786
|
+
continue;
|
|
787
|
+
const next = neighborsOf(g, e).filter((n) => mineSet.has(n));
|
|
788
|
+
if (next.length)
|
|
789
|
+
warnings.push(`${label(e)} (player ${st.owner.playerId}) holds ${uncountedKind(e)}, whose strength the board does not carry: the threat to ${next.map(label).join(', ')} counts its armies only.`);
|
|
790
|
+
}
|
|
791
|
+
/**
|
|
792
|
+
* Borders that hold at the start of the turn on the armies they have (#121): their surplus is
|
|
793
|
+
* what they hold beyond that, and a capture from one keeps what holds it.
|
|
794
|
+
*/
|
|
795
|
+
const safeAtStart = new Set([...borders.values()]
|
|
796
|
+
.filter((b) => (toTake(armiesOf(b.id) + unitsAt(b.id)) ?? Infinity) > b.threat)
|
|
797
|
+
.map((b) => b.id));
|
|
798
|
+
for (const [e, gr] of growthOf) {
|
|
799
|
+
// Name the most exposed of my territories next to it (fewest armies, then id).
|
|
800
|
+
const t = neighborsOf(g, e)
|
|
801
|
+
.filter((n) => mineSet.has(n))
|
|
802
|
+
.sort((a, b) => armiesOf(a) - armiesOf(b) || a - b)[0];
|
|
803
|
+
const b = borders.get(t);
|
|
804
|
+
const next = b.movable + Math.max(b.deploy, b.growth);
|
|
805
|
+
const after = b.movable + b.growth + Math.max(b.deploy, b.growth);
|
|
806
|
+
warnings.push(`${label(e)} is building: +${gr.growth}/turn (${gr.from} → ${gr.to}); at this rate ${label(t)} needs ${holdArmies(next)} to hold next turn and ${holdArmies(after)} the turn after`);
|
|
807
|
+
}
|
|
808
|
+
for (const b of borders.values())
|
|
809
|
+
if (b.growth > b.deploy)
|
|
810
|
+
rationale.push(`Threat on ${label(b.id)} uses the trend: player ${b.player}'s stack next to it grows +${b.growth}/turn, more than the ~${b.deploy} deploy estimate, so ~${b.threat}.`);
|
|
811
|
+
if (borders.size) {
|
|
812
|
+
if (custom)
|
|
813
|
+
warnings.push(`Enemy deploy estimate: threat checks assume ~${enemyDeploy} (your estimate); enemy income is unknown, so they could deploy more.`);
|
|
814
|
+
else {
|
|
815
|
+
const opening = openingArmies(g, board, { turn: turnNow, previous: input.previousBoard });
|
|
816
|
+
// #199: a player whose only threat is a chain has its deploy inside that chain: explain it too.
|
|
817
|
+
const estimated = new Set(facing);
|
|
818
|
+
for (const b of borders.values())
|
|
819
|
+
if (b.chain && estimates.has(b.chain.player))
|
|
820
|
+
estimated.add(b.chain.player);
|
|
821
|
+
// #235: a free-for-all with no teams whose opponents border the fog, and no prior: say why.
|
|
822
|
+
// A player out (eliminated, booted, surrendered) is no opponent the prior skips, whatever it still holds.
|
|
823
|
+
const out = new Set((ctx.players ?? []).filter((p) => (p.state ?? 'Playing') !== 'Playing').map((p) => p.id));
|
|
824
|
+
const fogged = [...estimates.values()].filter((e) => foe(e.playerId) && e.fogBeside && !out.has(e.playerId)).map((e) => e.playerId).sort(byNum);
|
|
825
|
+
if (incomePriorSkipped && fogged.length)
|
|
826
|
+
warnings.push(`No fog prior for the opponents beside the fog (${fogged.length === 1 ? 'player' : 'players'} ${fogged.join(', ')}) in this free-for-all: ${incomePriorSkipped}; their estimates rest on what the board shows, each a lower bound under fog.`);
|
|
827
|
+
for (const p of [...estimated].sort(byNum)) {
|
|
828
|
+
const e = estimates.get(p);
|
|
829
|
+
const visible = `base ${e.base} + visible bonuses +${e.bonusIncome} = ${e.base + e.bonusIncome}`;
|
|
830
|
+
if (e.observation) {
|
|
831
|
+
const o = e.observation;
|
|
832
|
+
const turns = input.turn !== undefined ? `turn ${input.turn - 1} → turn ${input.turn}` : 'previous board → this board';
|
|
833
|
+
const shown = o.reveals.slice(0, MAX_NAMED_REVEALS).map(label).join(', ');
|
|
834
|
+
const more = o.reveals.length > MAX_NAMED_REVEALS ? ` and ${o.reveals.length - MAX_NAMED_REVEALS} more` : '';
|
|
835
|
+
// #226: my failed attack's kills, counted back into what stood there.
|
|
836
|
+
if (o.attacked.length)
|
|
837
|
+
rationale.push(`Player ${p}: my failed attack${o.attacked.length === 1 ? '' : 's'} on ${o.attacked.map(label).join(', ')} killed ~${o.attackKills} of its defenders (at the ${rates.offensiveKillRate}% kill rate, from the orders I sent last turn), which stood there too: they count back into its observed deploy (after + kills − before, a lower bound${o.grewFromFog.some((x) => o.attacked.includes(x)) ? '; beside the fog, read as deploy only up to the turn\'s bound' : ''}).`);
|
|
838
|
+
// #226: in a per-territory game a large reveal says it holds more than is in view; still not income.
|
|
839
|
+
const revealed = o.reveals.reduce((n, id) => n + armiesOf(id), 0);
|
|
840
|
+
if (perTerritory && revealed > e.estimate - (e.card?.armies ?? 0))
|
|
841
|
+
warnings.push(`Player ${p}: ${revealed} armies came into view on ${o.reveals.length} ${o.reveals.length === 1 ? 'territory' : 'territories'} (fog reveals, not income); with income per territory, stacks that size say it holds more territories than the ${e.held} in view, so its ~${e.estimate - (e.card?.armies ?? 0)} estimate may be far too low.`);
|
|
842
|
+
rationale.push(`Observed deploy for player ${p}, ${turns}: +${e.observedRaw}/turn over ${o.counted.length} territories visible on both boards (${o.captured.length} captured${o.captured.length ? `, ${o.fromFog.length} from the fog` : ''}); ${o.reveals.length} skipped as fog reveals${o.reveals.length ? ` (${shown}${more}): not shown with an owner and armies last turn (fogged, armies hidden, or not yet picked), so what they hold is not income` : ''}.`);
|
|
843
|
+
// #294: each grown stack's growth split three ways, so the arithmetic can be checked on the board.
|
|
844
|
+
if (o.stacks.length) {
|
|
845
|
+
const grown = [...o.stacks].sort((a, b) => b.growth - a.growth || a.territoryId - b.territoryId);
|
|
846
|
+
const parts = grown.slice(0, MAX_NAMED_REVEALS).map((x) => {
|
|
847
|
+
const why = [
|
|
848
|
+
...x.moved.map((m) => `${m.armies} could be a move from ${label(m.from)} in view`),
|
|
849
|
+
...(x.fog ? [`${x.fog} could have come out of the fog`] : []),
|
|
850
|
+
...(x.deploy ? [`${x.deploy} can only be deploy`] : []),
|
|
851
|
+
];
|
|
852
|
+
return `${label(x.territoryId)} +${x.growth} (${why.join(', ')})`;
|
|
853
|
+
});
|
|
854
|
+
const rest = grown.length > MAX_NAMED_REVEALS ? ` and ${grown.length - MAX_NAMED_REVEALS} more` : '';
|
|
855
|
+
rationale.push(`Player ${p}'s growth by stack, ${turns}: ${parts.join('; ')}${rest}.`);
|
|
856
|
+
}
|
|
857
|
+
// A stack that arrived from the fog by a capture is a threat, never income (#86).
|
|
858
|
+
for (const id of o.fromFog) {
|
|
859
|
+
const where = neighborsOf(g, id).some((n) => mineSet.has(n)) ? 'stack next to you' : 'stack';
|
|
860
|
+
rationale.push(`Player ${p}'s ${where}: ${armiesOf(id)} on ${label(id)} (threat), arrived from the fog by a capture: a move, not income.`);
|
|
861
|
+
}
|
|
862
|
+
// #123: the ambiguous readings, each named with the other way it could read. #293: under Local
|
|
863
|
+
// Deployment growth outside every bonus it could hold is cut at its free income instead.
|
|
864
|
+
const fogReason = (x) => {
|
|
865
|
+
const twice = `beyond twice the ~${x.expected} it was expected to deploy`;
|
|
866
|
+
const cut = x.localCut;
|
|
867
|
+
if (!cut)
|
|
868
|
+
return twice;
|
|
869
|
+
const local = `in no bonus it could hold: under Local Deployment only its free income +${cut.free} could be deployed there`;
|
|
870
|
+
const all = x.grewFromFog.every((id) => cut.territories.includes(id));
|
|
871
|
+
return all ? local : `${cut.territories.map(label).join(', ')} ${local}; elsewhere ${twice}`;
|
|
872
|
+
};
|
|
873
|
+
if (o.grewFromFog.length) {
|
|
874
|
+
rationale.push(`Player ${p}: ${o.fogGrowth} of its growth on ${o.grewFromFog.map(label).join(', ')} (${fogReason(o)}) is next to the fog: read as a move out of the fog, not income — though it may be income the fog hides (observed +${o.low}–${o.high} either way).`);
|
|
875
|
+
}
|
|
876
|
+
if (o.reinforced.length)
|
|
877
|
+
rationale.push(`Player ${p} took ${o.reinforced.map(label).join(', ')} with more than its visible stack next to ${o.reinforced.length === 1 ? 'it' : 'them'} sent: read as armies deployed on that stack before it attacked (deploy-then-capture), though a stack out of the fog may have joined (observed +${o.low}–${o.high} either way).`);
|
|
878
|
+
// #271: what the turn's evidence added or took away.
|
|
879
|
+
if (o.repelledFloor > 0)
|
|
880
|
+
rationale.push(`Player ${p} attacked ${o.repelled.map(label).join(', ')} and failed: what I lost there needed more attackers than its stacks beside ${o.repelled.length === 1 ? 'it' : 'them'} could send at the start of the turn (from the orders I sent last turn), so it deployed at least +${o.repelledFloor}, fog or not.`);
|
|
881
|
+
if (o.unseenAttackers.length)
|
|
882
|
+
rationale.push(`Player ${p} took ${o.unseenAttackers.map(label).join(', ')} from a neutral in view with ${o.unseenAttackerArmies} attackers more than its stacks in view sent: read as deploy up to twice the ~${o.expected ?? 0} it was expected to deploy, the rest a stack out of the fog (observed +${o.low}–${o.high} either way); repeated, warapp_track_opponents reads it as income.`);
|
|
883
|
+
if (o.arrivals > 0)
|
|
884
|
+
rationale.push(`Player ${p}: ${o.arrivals} of the armies on its capture${o.captured.length === 1 ? '' : 's'} could have come from its stacks in view last turn beside ${o.captured.length === 1 ? 'it' : 'them'}, hidden now: arrivals, not deploy.`);
|
|
885
|
+
if (o.emptied.length)
|
|
886
|
+
rationale.push(`Player ${p} took ${o.emptied.map(label).join(', ')} from you: priced at what the guard you may have left there kills, not your stack last turn (you may have attacked out of it); had it all stood there, it deployed +${o.high}.`);
|
|
887
|
+
if (o.fromFog.length) {
|
|
888
|
+
const n = o.fromFog.length;
|
|
889
|
+
rationale.push(`Player ${p}'s estimated income: ~${e.estimate - (e.card?.armies ?? 0)}/turn (${n} ${n === 1 ? 'stack' : 'stacks'} that arrived from the fog not counted in it).`);
|
|
890
|
+
}
|
|
891
|
+
if (e.observedRaw > e.observedCap)
|
|
892
|
+
warnings.push(`player ${p} was observed to deploy +${e.observedRaw}/turn, more than it could earn on this board (${perTerritory && e.observedCap - possibleOf(e) > e.base
|
|
893
|
+
? `${e.observedCap - possibleOf(e)} for the ${e.couldHold} territories it could hold: its ${e.held} visible and ${e.couldHold - e.held} whose owner is hidden`
|
|
894
|
+
: `base ${e.base} for its ${e.held} visible territories`} + bonuses it could still hold +${possibleOf(e)} = ${e.observedCap}): capped at ${e.observedCap}. Armies moved in from the fog, a Reinforcement card, or a bonus it has lost since may explain the rest.`);
|
|
895
|
+
}
|
|
896
|
+
if (e.tracked !== null) {
|
|
897
|
+
const track = input.tracks.find((t) => t.playerId === p);
|
|
898
|
+
const used = track.turns.filter((x) => e.trackedTurns.includes(x.from));
|
|
899
|
+
rationale.push(`Tracked income for player ${p}: ~${e.tracked}/turn (${incomeBasis(track)}): ${used.map((x) => `turn ${x.from} +${x.observed}`).join(', ')}, each observed deploy a lower bound under fog${e.coverage ? `, read from ${coverageText(e.coverage)}` : ''}; at least its visible base + bonuses ${track.visibleIncome}; used in place of the single-turn observed figure (warapp_track_opponents has the details).`);
|
|
900
|
+
}
|
|
901
|
+
// #294: a tracked figure read from little of its frontier keeps a floor above it.
|
|
902
|
+
if (e.coverageFloor) {
|
|
903
|
+
const f = e.coverageFloor;
|
|
904
|
+
warnings.push(`Player ${p}'s tracked ~${f.tracked} was read from ${coverageText({ ...e.coverage, hiddenBonuses: 0 }).replace(/\)$/, `, under ${Math.round(LOW_COVERAGE * 100)}%)`)}: the estimate is at least ~${f.tracked} × ${f.factor} = ${f.figure} (the factor is unmeasured), since the fog hid most of where it deploys.`);
|
|
905
|
+
}
|
|
906
|
+
// #164: a Reinforcement card the clock says it may hold, on top of its income.
|
|
907
|
+
if (e.card)
|
|
908
|
+
warnings.push(`Player ${p} may hold a Reinforcement card from turn ${e.card.due} (the card clock${e.cardPlayed !== null ? `; it last played one on turn ${e.cardPlayed}` : ''}): +${e.card.armies} added to its deploy, ~${e.estimate} in all, until a deployment above its income is seen; one card at most is counted, though more may be in hand after a long time due.`);
|
|
909
|
+
else if (e.cardPlayed !== null)
|
|
910
|
+
warnings.push(e.source === 'exact'
|
|
911
|
+
? `Player ${p}'s Reinforcement card is taken as played on turn ${e.cardPlayed} (a deployment above its exact income), so none is added until the next can be due; armies the board misread, or that moved into view out of a territory whose armies the fog hid, can look the same, so it may still hold one and the estimate errs low.`
|
|
912
|
+
: `Player ${p}'s Reinforcement card is taken as played on turn ${e.cardPlayed} (a deployment of a card's armies over its visible income), so none is added until the next can be due; income the fog hides can look the same, so it may still hold one and the estimate errs low.`);
|
|
913
|
+
// #164: the income behind the estimate; a card the clock adds is named on top of it.
|
|
914
|
+
const income = e.estimate - (e.card?.armies ?? 0);
|
|
915
|
+
// G2 (D3): Sanctions on it the decoder is sure of — applied to a figure read off the board only.
|
|
916
|
+
if (e.sanctioned) {
|
|
917
|
+
const z = e.sanctioned;
|
|
918
|
+
const pct = z.percentages.map((x) => `${Math.round(x * 100)}%`).join(' then ');
|
|
919
|
+
warnings.push(z.applied
|
|
920
|
+
? `Player ${p} is under Sanctions (${pct}, until turn ${z.untilTurn}, read from the board by an unverified decoder): its estimate is cut from ~${z.before} to ~${income} by the client's rule.`
|
|
921
|
+
: `Player ${p} is under Sanctions (${pct}, until turn ${z.untilTurn}, read from the board by an unverified decoder), but its estimate ~${income} is not cut: ${e.source === 'prior' ? 'it is a prior, a floor guessed from what it could earn, not its income' : `it is ${e.source} from its deploys, which may already carry the cut`}.`);
|
|
922
|
+
}
|
|
923
|
+
const withCard = e.card ? `, plus +${e.card.armies} from its Reinforcement card (~${e.estimate} in all)` : '';
|
|
924
|
+
// #235 1c: the track's newest turn read more with the armies beside the fog as deploys: a label,
|
|
925
|
+
// never income (#123 lesson 5); the higher figure is the caller's to test.
|
|
926
|
+
const cut = e.newestCut;
|
|
927
|
+
if (cut && e.source !== 'exact' && cut.reading > income)
|
|
928
|
+
warnings.push(`Player ${p}'s newest turn (turn ${cut.from} → turn ${cut.to}) reads up to +${cut.reading} if the armies that arrived beside the fog were deploys (+${cut.observed} with those beyond twice the ~${cut.expected ?? '?'} it was expected to deploy read as moves); the estimate keeps ~${income} (${e.source === 'tracked' ? 'tracked' : e.source === 'prior' ? 'the fog prior' : 'its visible base + bonuses'}) because a stack walking in is not income (#123). To test the higher figure, pass enemy_deploy ${cut.reading} to warapp_check_plan.`);
|
|
929
|
+
if (e.source === 'exact') {
|
|
930
|
+
warnings.push(`Enemy deploy estimate for player ${p}: ~${income} (exact: under ${ctx.fog} every territory's owner shows, so its income is ${visible}${e.observed !== null && e.observed > income ? `; the +${e.observed} observed above it is a card or armies the board misread, not income` : ''}); only the army cap, Sanctions and a Reinforcement card are unknown.`);
|
|
931
|
+
continue;
|
|
932
|
+
}
|
|
933
|
+
if (e.source === 'prior') {
|
|
934
|
+
warnings.push(`Enemy deploy estimate for player ${p}: ~${income} (a prior, not an observation: ${(incomePrior.opening?.get(p) ?? -1) > incomePrior.myIncome
|
|
935
|
+
? `its opening simulated from the starts the award of picks proved earns ${incomePrior.opening.get(p)} this turn`
|
|
936
|
+
: `in ${incomePrior.format === 'ffa' ? 'a free-for-all that started even (no teams, every player still in)' : 'a 1v1 that started even'}, an opponent bordering the fog is assumed to earn at least my own income ${incomePrior.myIncome}`}, ${e.priorCap !== null
|
|
937
|
+
? `capped at an even share (1 of ${incomePrior.opponents} opponents) of what the board hides, ${e.priorCap} (all of it would be ${e.couldEarn})`
|
|
938
|
+
: `capped at the most it could earn on this board, ${e.couldEarn}`}${e.priorBlend
|
|
939
|
+
? ` — shrunk toward its ${e.priorBlend.toward === e.tracked ? `tracked ~${e.tracked}` : `visible ${e.priorBlend.toward}`} by the evidence: ${e.priorBlend.turns} observed ${e.priorBlend.turns === 1 ? 'turn' : 'turns'} with ${Math.round(e.priorBlend.share * 100)}% of its ${e.coverage ? 'frontier read' : 'edge in view'} keep ${Math.round(e.priorBlend.weight * 100)}% of the gap from ${e.priorBlend.prior}`
|
|
940
|
+
: ''}; ${visible}${e.tracked !== null ? `, tracked ~${e.tracked}` : e.observed !== null ? `, observed +${e.observed}/turn` : ''})${withCard}; observed deploys are lower bounds under fog, and it could deploy more.`);
|
|
941
|
+
continue;
|
|
942
|
+
}
|
|
943
|
+
if (e.source === 'tracked') {
|
|
944
|
+
warnings.push(`Enemy deploy estimate for player ${p}: ~${income} (tracked over ${e.trackedTurns.length} observed turns, ${e.coverage ? `read from ${coverageText(e.coverage)}; ` : ''}more than ${visible})${withCard}; it holds income the fog hides, and could deploy more.`);
|
|
945
|
+
continue;
|
|
946
|
+
}
|
|
947
|
+
if (e.source === 'observed') {
|
|
948
|
+
warnings.push(`Enemy deploy estimate for player ${p}: ~${income} (observed +${e.observed}/turn: the net growth of its territories visible on both boards plus what its captures from a visible owner cost it, more than ${visible})${withCard}; it holds income the fog hides, and could deploy more.`);
|
|
949
|
+
continue;
|
|
950
|
+
}
|
|
951
|
+
const seen = e.observed !== null ? ` Its deploy was observed +${e.observed}/turn since last turn, below that.` : '';
|
|
952
|
+
warnings.push((opening !== null
|
|
953
|
+
? `Enemy deploy estimate for player ${p}: ~${income} (opening board: every visible player territory holds ${opening}, so no one has deployed yet and every opponent gets its base income, at least ${MIN_ENEMY_DEPLOY})${withCard}; enemy income is unknown, so they could deploy more.`
|
|
954
|
+
: `Enemy deploy estimate for player ${p}: ~${income} (${visible}, at least max(${MIN_ENEMY_DEPLOY}, base); its largest stack next to me (${e.largestStack}) is what can move, not a limit on what it deploys)${withCard}; enemy income beyond its visible bonuses is unknown, so they could deploy more.`) + seen);
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
return {
|
|
959
|
+
borders,
|
|
960
|
+
facing,
|
|
961
|
+
borderAt,
|
|
962
|
+
safeAtStart,
|
|
963
|
+
};
|
|
964
|
+
}
|
|
965
|
+
/**
|
|
966
|
+
* The opponents in view (rule 1e, #45): each visible opponent's territories, the fog's edge, and
|
|
967
|
+
* the weak ones — fully visible, fewer territories than mine, a deploy below my income — with the
|
|
968
|
+
* territories of mine just taken from one. Pure: read from the board at the start of the turn.
|
|
969
|
+
*/
|
|
970
|
+
export function visibleOpponents(pc, input) {
|
|
971
|
+
const { g, me, foe, territories: state, mine, mineSet, deployOf, income } = pc;
|
|
972
|
+
// Visible enemy territories by owner, sorted.
|
|
973
|
+
const ownedBy = new Map();
|
|
974
|
+
for (const [id, st] of [...state].sort((a, b) => a[0] - b[0])) {
|
|
975
|
+
if (st.owner.kind !== 'player' || !foe(st.owner.playerId) || st.armies === null)
|
|
976
|
+
continue;
|
|
977
|
+
ownedBy.set(st.owner.playerId, [...(ownedBy.get(st.owner.playerId) ?? []), id]);
|
|
978
|
+
}
|
|
979
|
+
const ownerOf = (id) => {
|
|
980
|
+
const o = state.get(id)?.owner;
|
|
981
|
+
return o?.kind === 'player' ? o.playerId : undefined;
|
|
982
|
+
};
|
|
983
|
+
const hidden = (n) => {
|
|
984
|
+
const st = state.get(n);
|
|
985
|
+
return !st || st.owner.kind === 'unknown' || st.armies === null;
|
|
986
|
+
};
|
|
987
|
+
// Anything on the board hidden: an opponent may hold territories there no visible one borders.
|
|
988
|
+
const fogAnywhere = [...g.territoryById.keys()].some(hidden);
|
|
989
|
+
/** Its territories with a fogged neighbour: it may hold more in the fog. */
|
|
990
|
+
const fogEdge = (p) => ownedBy.get(p).filter((t) => neighborsOf(g, t).some(hidden));
|
|
991
|
+
const inReach = (p) => ownedBy.get(p).every((t) => neighborsOf(g, t).some((n) => mineSet.has(n)));
|
|
992
|
+
/** Fully visible, fewer territories than mine, and a deploy below my income. */
|
|
993
|
+
const weak = new Set([...ownedBy.keys()].filter((p) => !fogEdge(p).length && ownedBy.get(p).length < mine.length && deployOf(p) < income));
|
|
994
|
+
const previousOwner = new Map((input.previousBoard?.territories ?? []).flatMap((t) => t.owner.kind === 'player' ? [[t.territoryId, t.owner.playerId]] : []));
|
|
995
|
+
/** The weak opponent that held my `id` on the previous board, if any. */
|
|
996
|
+
const recentlyTakenFrom = (id) => {
|
|
997
|
+
const p = previousOwner.get(id);
|
|
998
|
+
return p !== undefined && p !== me && weak.has(p) ? p : undefined;
|
|
999
|
+
};
|
|
1000
|
+
return { ownedBy, ownerOf, hidden, fogAnywhere, fogEdge, inReach, weak, previousOwner, recentlyTakenFrom };
|
|
1001
|
+
}
|