@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,823 @@
|
|
|
1
|
+
// Rule 4e, never stand still (#104, #107, #112, #114, #121, #125; #133): a plan with no capture at
|
|
2
|
+
// all takes the cheapest capture this turn affords — a neutral step toward the closest positive
|
|
3
|
+
// bonus, and in the contact and late phases (the contact fallback) an enemy territory at a trade
|
|
4
|
+
// of at least even, with every other capture that loses nothing — or says why it stands still.
|
|
5
|
+
// planPass runs it where it ran before: after pass 3, before rule 4g's card-piece capture.
|
|
6
|
+
import { straightKills } from '../combat.js';
|
|
7
|
+
import { neighborsOf } from '../graph.js';
|
|
8
|
+
import { lateArrivals } from './holds.js';
|
|
9
|
+
import { byNum } from './util.js';
|
|
10
|
+
/**
|
|
11
|
+
* The helpers rule 4e works with, over the plan as it stands when each is called: what reaches a
|
|
12
|
+
* step, trying one (and undoing it), what a capture loses and leaves exposed, and why a step was
|
|
13
|
+
* not taken. Creating them changes nothing.
|
|
14
|
+
*/
|
|
15
|
+
export function standStillKit(pc, ps, book, threats, hd, tgt, caps) {
|
|
16
|
+
const { income, label, bonusName, unitsAt, defenceAt, bonusTs, rates, chanceOf, toTake, luck, weightedRounding, noSplit, } = pc;
|
|
17
|
+
const { warnings, rationale, avail, locked, captured, moves, incoming, survivorsAt, captureUndo } = ps;
|
|
18
|
+
const { heldNow, orderOf, deploy, spareAt } = book;
|
|
19
|
+
const { threatAt } = threats;
|
|
20
|
+
const { conceded, stayAt } = hd;
|
|
21
|
+
const { targets, borderOf, sizeOf } = tgt;
|
|
22
|
+
const { notCompleted, movableFor, concededSource, defendersSeen, tryCapture, combinedPlan, snapshot } = caps;
|
|
23
|
+
const WITHDRAWS = 'withdraws from a conceded border';
|
|
24
|
+
/** Armies rule 1b withdrew from conceded `x` this turn (they may attack out instead). */
|
|
25
|
+
const withdrawnFrom = (x) => moves.find((m) => m.from === x && m.kind === 'transfer' && m.reason === WITHDRAWS)?.armies ?? 0;
|
|
26
|
+
/**
|
|
27
|
+
* What can reach `t` this turn, as {@link tryCapture} judges it: its best single source's
|
|
28
|
+
* movable armies (my commander's territory keeps what holds it) plus what may still be
|
|
29
|
+
* deployed there. A source that holds its border (locked) or already issues an order
|
|
30
|
+
* (No-Split) is out. A conceded border counts with the armies rule 1b would withdraw and
|
|
31
|
+
* with deploys (#107): rather than stand still it attacks out, and its deploys leave with
|
|
32
|
+
* the attack — but only when no unconceded source can take it alone. On a tie a source that
|
|
33
|
+
* is not conceded wins.
|
|
34
|
+
*/
|
|
35
|
+
const reachOf = (t) => {
|
|
36
|
+
let best = { from: undefined, movable: 0, deploy: 0, reach: 0, viaConceded: false, blocked: [] };
|
|
37
|
+
const blocked = [];
|
|
38
|
+
const tg = targets.get(t);
|
|
39
|
+
for (const x of [...tg.sources].sort(byNum)) {
|
|
40
|
+
const back = conceded.has(x) ? withdrawnFrom(x) : 0;
|
|
41
|
+
// A conceded border kept in place (its garrison stays, not withdrawn) is not holding its
|
|
42
|
+
// border: name it as conceded.
|
|
43
|
+
if (back === 0 && locked.has(x)) {
|
|
44
|
+
blocked.push({ x, why: !conceded.has(x) ? 'hold' : orderOf(x) ? 'split' : 'conceded' });
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (back === 0 && orderOf(x)) {
|
|
48
|
+
blocked.push({ x, why: 'split' });
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
const movable = Math.max(0, movableFor(x, t) + back);
|
|
52
|
+
// Deploys reach a conceded source only through the attack-out path below.
|
|
53
|
+
// #240 review: a repulsed territory's sure size (sizeOf) decides what fits; its cost ranks it.
|
|
54
|
+
const viaConceded = conceded.has(x) && !concededSource(x, t, sizeOf(t));
|
|
55
|
+
const deploy = Math.max(0, spareAt(x));
|
|
56
|
+
const reach = movable + deploy;
|
|
57
|
+
// An unconceded source that can take it alone goes first: a conceded border attacks out
|
|
58
|
+
// only when none can, so its armies are not thrown away for a step another source affords.
|
|
59
|
+
const fits = !conceded.has(x) && reach >= sizeOf(t);
|
|
60
|
+
const bestFits = best.from !== undefined && !conceded.has(best.from) && best.reach >= sizeOf(t);
|
|
61
|
+
if (best.from === undefined ||
|
|
62
|
+
(fits && !bestFits) ||
|
|
63
|
+
(fits === bestFits && (reach > best.reach || (reach === best.reach && best.viaConceded && !viaConceded))))
|
|
64
|
+
best = { from: x, movable, deploy, reach, viaConceded, blocked: [] };
|
|
65
|
+
}
|
|
66
|
+
return best.from === undefined ? { ...best, blocked } : best;
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* Undo rule 1b's withdrawal from conceded `x` so it may attack out (#107); the result redoes
|
|
70
|
+
* it. A conceded border never withdrawn (nowhere to go) needs nothing undone.
|
|
71
|
+
*/
|
|
72
|
+
const reclaim = (x) => {
|
|
73
|
+
const i = moves.findIndex((m) => m.from === x && m.kind === 'transfer' && m.reason === WITHDRAWS);
|
|
74
|
+
if (i < 0)
|
|
75
|
+
return () => { };
|
|
76
|
+
const [m] = moves.splice(i, 1);
|
|
77
|
+
const had = { avail: avail.get(x), incoming: incoming.get(m.to) ?? 0, card: ps.cardAdvice };
|
|
78
|
+
avail.set(x, had.avail + m.armies);
|
|
79
|
+
locked.delete(x);
|
|
80
|
+
if (had.incoming - m.armies > 0)
|
|
81
|
+
incoming.set(m.to, had.incoming - m.armies);
|
|
82
|
+
else
|
|
83
|
+
incoming.delete(m.to);
|
|
84
|
+
const r = rationale.findIndex((l) => l.startsWith(`Withdraw ${m.armies} from ${label(x)} to `));
|
|
85
|
+
const rLine = r >= 0 ? rationale.splice(r, 1)[0] : undefined;
|
|
86
|
+
const w = warnings.findIndex((l) => l.startsWith(`The withdrawal from ${label(x)} only executes`));
|
|
87
|
+
const wLine = w >= 0 ? warnings.splice(w, 1)[0] : undefined;
|
|
88
|
+
if (!moves.some((o) => o.kind === 'transfer' && o.reason === WITHDRAWS))
|
|
89
|
+
ps.cardAdvice = null;
|
|
90
|
+
return () => {
|
|
91
|
+
moves.splice(i, 0, m);
|
|
92
|
+
avail.set(x, had.avail);
|
|
93
|
+
locked.add(x);
|
|
94
|
+
if (had.incoming > 0)
|
|
95
|
+
incoming.set(m.to, had.incoming);
|
|
96
|
+
else
|
|
97
|
+
incoming.delete(m.to);
|
|
98
|
+
if (rLine !== undefined)
|
|
99
|
+
rationale.splice(r, 0, rLine);
|
|
100
|
+
if (wLine !== undefined)
|
|
101
|
+
warnings.splice(w, 0, wLine);
|
|
102
|
+
ps.cardAdvice = had.card;
|
|
103
|
+
};
|
|
104
|
+
};
|
|
105
|
+
/**
|
|
106
|
+
* What capturing `st` is expected to cost (#112): the defensive kills on its attackers at the
|
|
107
|
+
* game's rates, and the armies sent. One source that can take it alone sends its cost and
|
|
108
|
+
* loses the defenders' kills; otherwise the combined capture rule 3a would plan, its every
|
|
109
|
+
* attack's losses (the softeners' and the finisher's) and armies counted — only with no luck
|
|
110
|
+
* and straight rounding, where rule 3a makes one.
|
|
111
|
+
*/
|
|
112
|
+
const lossOf = (st) => {
|
|
113
|
+
const single = { lost: Math.min(st.cost, straightKills(defendersSeen(st.t), rates.defensiveKillRate)), sent: st.cost };
|
|
114
|
+
// Under luck or weighted rounding a combined capture is never made (rule 3a, `tryCombined`):
|
|
115
|
+
// the single source's sizing is the one the plan would use.
|
|
116
|
+
if (st.from === undefined || st.reach >= st.cost || luck > 0 || weightedRounding)
|
|
117
|
+
return single;
|
|
118
|
+
const c = combinedPlan(st.t);
|
|
119
|
+
if (!c)
|
|
120
|
+
return single;
|
|
121
|
+
return {
|
|
122
|
+
lost: c.softeners.reduce((n, x) => n + x.armies - x.survivors, 0) + c.armies - c.survivors,
|
|
123
|
+
sent: c.softeners.reduce((n, x) => n + x.armies, 0) + c.armies,
|
|
124
|
+
};
|
|
125
|
+
};
|
|
126
|
+
/**
|
|
127
|
+
* Every source of the attack on `t` must still hold its border once `t` is taken (#107 in
|
|
128
|
+
* contact; every phase since the opening emptied border stacks live). A source left short gets the deploys still available there that make it hold (they
|
|
129
|
+
* are placed now, so the leftover deploy cannot go elsewhere; the step's undo takes them
|
|
130
|
+
* back). A source that cannot be made to hold is returned, with what stays, the deploys that
|
|
131
|
+
* were available and the threat it faces; else `undefined`. A conceded border is skipped: its
|
|
132
|
+
* armies are given up anyway.
|
|
133
|
+
*/
|
|
134
|
+
const holdLeftShort = (t) => {
|
|
135
|
+
// No-Split (#124): deploys there would leave with the attack, and a source that must hold
|
|
136
|
+
// never attacks (tryCapture): one that protects nothing may be emptied.
|
|
137
|
+
if (noSplit)
|
|
138
|
+
return undefined;
|
|
139
|
+
for (const m of moves) {
|
|
140
|
+
if (m.kind !== 'attack' || m.to !== t || conceded.has(m.from))
|
|
141
|
+
continue;
|
|
142
|
+
const th = threatAt(m.from, (n) => captured.has(n));
|
|
143
|
+
if (!th)
|
|
144
|
+
continue;
|
|
145
|
+
// #215: armies withdrawn into it count only when I am known to move first.
|
|
146
|
+
const stays = stayAt(m.from) - lateArrivals(pc, ps, m.from);
|
|
147
|
+
const holds = (n) => (toTake(stays + n + unitsAt(m.from)) ?? Infinity) > th.threat;
|
|
148
|
+
if (holds(0))
|
|
149
|
+
continue;
|
|
150
|
+
const spare = Math.max(0, spareAt(m.from));
|
|
151
|
+
let n = 1;
|
|
152
|
+
while (n <= spare && !holds(n))
|
|
153
|
+
n++;
|
|
154
|
+
if (n > spare)
|
|
155
|
+
return { from: m.from, stays, spare, threat: th.threat };
|
|
156
|
+
deploy(m.from, n);
|
|
157
|
+
rationale.push(`Deploy ${n} to ${label(m.from)} so it still holds its border after the attack on ${label(t)} (${stays + n} stay against a threat of ${th.threat}).`);
|
|
158
|
+
}
|
|
159
|
+
return undefined;
|
|
160
|
+
};
|
|
161
|
+
/**
|
|
162
|
+
* Why a step that does not fit failed (#121): a source that keeps what holds its border could
|
|
163
|
+
* have afforded it by spending that garrison — then it is the hold it would leave short (as
|
|
164
|
+
* {@link holdLeftShort} words it), else its size. Tried with the keeps off and undone.
|
|
165
|
+
*/
|
|
166
|
+
const sizeOrHold = (st, reason) => {
|
|
167
|
+
const restore = snapshot();
|
|
168
|
+
ps.spendKeeps = true;
|
|
169
|
+
let short;
|
|
170
|
+
try {
|
|
171
|
+
if (st.from !== undefined && conceded.has(st.from))
|
|
172
|
+
return { kind: 'size' };
|
|
173
|
+
const ok = tryCapture(st.t, reason);
|
|
174
|
+
short = ok ? holdLeftShort(st.t) : undefined;
|
|
175
|
+
}
|
|
176
|
+
finally {
|
|
177
|
+
ps.spendKeeps = false;
|
|
178
|
+
restore();
|
|
179
|
+
}
|
|
180
|
+
return short ? { kind: 'hold', ...short } : { kind: 'size' };
|
|
181
|
+
};
|
|
182
|
+
/** The trade of the planned capture of `t`: defenders killed against attackers lost (every attack on it). */
|
|
183
|
+
const tradeOf = (t) => {
|
|
184
|
+
const sent = moves.filter((m) => m.kind === 'attack' && m.to === t);
|
|
185
|
+
// #240 review: a repulsed territory's trade as the plan without the evidence reads it.
|
|
186
|
+
const killed = defendersSeen(t);
|
|
187
|
+
if (sent.length === 1)
|
|
188
|
+
return { lost: straightKills(killed, rates.defensiveKillRate), killed };
|
|
189
|
+
// A combined capture: every attack's losses — the softeners' (their survivors return home)
|
|
190
|
+
// and the finisher's.
|
|
191
|
+
let left = killed;
|
|
192
|
+
let lost = 0;
|
|
193
|
+
for (const m of sent) {
|
|
194
|
+
const kills = Math.min(left, straightKills(m.armies, rates.offensiveKillRate));
|
|
195
|
+
lost += Math.min(m.armies, straightKills(left, rates.defensiveKillRate));
|
|
196
|
+
left -= kills;
|
|
197
|
+
}
|
|
198
|
+
return { lost, killed };
|
|
199
|
+
};
|
|
200
|
+
/**
|
|
201
|
+
* Try one step. From a conceded border (#107) rule 1b's withdrawal is undone first and the
|
|
202
|
+
* border attacks out with deploys, a rationale line saying so. The result undoes it all.
|
|
203
|
+
*/
|
|
204
|
+
const attempt = (st, reason) => {
|
|
205
|
+
const out = st.from !== undefined && conceded.has(st.from) ? st.from : undefined;
|
|
206
|
+
// Neither the snapshot nor a no-op unreclaim puts back the card advice an attack out of a
|
|
207
|
+
// conceded border sets (#114: a candidate only tried and undone must leave none behind).
|
|
208
|
+
const card = ps.cardAdvice;
|
|
209
|
+
const unreclaim = out === undefined ? () => { } : reclaim(out);
|
|
210
|
+
const before = out === undefined ? 0 : movableFor(out, st.t);
|
|
211
|
+
const restore = snapshot();
|
|
212
|
+
if (!tryCapture(st.t, reason, undefined, out)) {
|
|
213
|
+
unreclaim();
|
|
214
|
+
return null;
|
|
215
|
+
}
|
|
216
|
+
const move = [...moves].reverse().find((m) => m.kind === 'attack' && m.to === st.t);
|
|
217
|
+
if (out !== undefined && move.from === out) {
|
|
218
|
+
const need = Math.max(0, sizeOf(st.t, st.cost) - before);
|
|
219
|
+
// Every movable army leaves with the attack: left behind on the conceded border they are
|
|
220
|
+
// lost; at the target they survive.
|
|
221
|
+
const extra = Math.max(0, movableFor(out, st.t));
|
|
222
|
+
if (extra > 0) {
|
|
223
|
+
const sent = move.armies;
|
|
224
|
+
avail.set(out, avail.get(out) - extra);
|
|
225
|
+
move.armies = sent + extra;
|
|
226
|
+
move.winChance = chanceOf(move.armies, defenceAt(st.t));
|
|
227
|
+
survivorsAt.set(st.t, (survivorsAt.get(st.t) ?? 0) + extra);
|
|
228
|
+
captureUndo.set(st.t, () => avail.set(out, avail.get(out) + move.armies));
|
|
229
|
+
const head = `Attack ${label(st.t)} from ${label(out)} with ${sent}`;
|
|
230
|
+
let r = rationale.length - 1;
|
|
231
|
+
while (r >= 0 && !rationale[r].startsWith(`${head}:`) && !rationale[r].startsWith(`${head} (`))
|
|
232
|
+
r--;
|
|
233
|
+
if (r >= 0)
|
|
234
|
+
rationale[r] = `Attack ${label(st.t)} from ${label(out)} with ${move.armies}${rationale[r].slice(head.length)}`;
|
|
235
|
+
}
|
|
236
|
+
rationale.push(`Attack out of conceded ${label(out)} rather than withdraw: its ${before} movable armies${need ? ` (and ${need} deployed there, which leave with the attack)` : ''} take ${label(st.t)}; one capture is worth more than saving them.`);
|
|
237
|
+
// Like the withdrawal it replaces, the attack only runs if the border is still mine.
|
|
238
|
+
warnings.push(`The attack out of ${label(out)} only executes if ${label(out)} is still mine when the order runs; play Order Priority so it goes first.`);
|
|
239
|
+
ps.cardAdvice = 'order-priority';
|
|
240
|
+
}
|
|
241
|
+
else
|
|
242
|
+
unreclaim();
|
|
243
|
+
const viaOut = out !== undefined && move.from === out;
|
|
244
|
+
return () => {
|
|
245
|
+
// restore() rewinds to the snapshot, taken after the reclaim and counting moves, lines
|
|
246
|
+
// and warnings by length: a withdrawal already put back is taken out again first, so
|
|
247
|
+
// the rewind removes only this step and the withdrawal is then put back once.
|
|
248
|
+
const unwind = out === undefined || viaOut ? unreclaim : reclaim(out);
|
|
249
|
+
restore();
|
|
250
|
+
unwind();
|
|
251
|
+
ps.cardAdvice = card;
|
|
252
|
+
};
|
|
253
|
+
};
|
|
254
|
+
/**
|
|
255
|
+
* After `t` is captured in the plan (#114): its survivors and the threat they face, when they
|
|
256
|
+
* cannot hold it next turn (rule 4d's border arithmetic: they need deploys), else `undefined`.
|
|
257
|
+
*/
|
|
258
|
+
const exposure = (t) => {
|
|
259
|
+
const held = heldNow();
|
|
260
|
+
const survivors = survivorsAt.get(t) ?? 0;
|
|
261
|
+
const b = borderOf(t, held, survivors);
|
|
262
|
+
if (!b.enemy || b.need <= 0)
|
|
263
|
+
return undefined;
|
|
264
|
+
return { survivors, threat: threatAt(t, (n) => held.has(n)).threat };
|
|
265
|
+
};
|
|
266
|
+
/** The bonuses `t` would complete that R3 refused, as "name (#id)". */
|
|
267
|
+
const refusedBonuses = (t) => [...notCompleted.keys()]
|
|
268
|
+
.filter((id) => bonusTs.get(id)?.includes(t))
|
|
269
|
+
.sort(byNum)
|
|
270
|
+
.map(bonusName);
|
|
271
|
+
/** Why no neighbour of mine can attack `st`: each holds its border, is conceded, or already issues an order. */
|
|
272
|
+
const blockedText = (st) => `no neighbour of mine can attack it (${st.blocked
|
|
273
|
+
.map(({ x, why }) => why === 'hold'
|
|
274
|
+
? `${label(x)} stays to hold its border`
|
|
275
|
+
: why === 'conceded'
|
|
276
|
+
? `${label(x)} is a conceded border whose armies stay there`
|
|
277
|
+
: `${label(x)} already issues an order under No-Split`)
|
|
278
|
+
.join('; ')})`;
|
|
279
|
+
/** "needs C, and at most R can reach it this turn (M movable on S[, a conceded border] + D to deploy[; the holds took H])". */
|
|
280
|
+
const reachText = (st, held) => st.from === undefined
|
|
281
|
+
? blockedText(st)
|
|
282
|
+
: `it needs ${sizeOf(st.t, st.cost)}, and at most ${st.reach} can reach it this turn (${st.movable} movable on ${label(st.from)}${conceded.has(st.from) ? ', a conceded border,' : ''} + ${st.deploy} to deploy${held > 0 ? `; the holds took ${held}` : ''})`;
|
|
283
|
+
/** "S would stay[, S+D with the D deploys left there,] against a threat of T". */
|
|
284
|
+
const holdText = (f) => `${f.stays} would stay${f.spare > 0 ? `, ${f.stays + f.spare} with the ${f.spare} deploys left there,` : ''} against a threat of ${f.threat}`;
|
|
285
|
+
/** Why `st` was not taken, as a clause after its name. */
|
|
286
|
+
const failText = (st, fail) => {
|
|
287
|
+
if (fail?.kind === '4d')
|
|
288
|
+
return `is refused by rule 4d's frontier stop: the frontier would then need ${fail.holdCost} next turn to hold, more than the next income of ${fail.income}`;
|
|
289
|
+
if (fail?.kind === 'r3') {
|
|
290
|
+
const names = refusedBonuses(st.t);
|
|
291
|
+
return names.length
|
|
292
|
+
? `is refused by rule R3: taking it completes bonus ${names.join(', ')}, which could not be held next turn (see "completing ${names[0]} leaves …: not completed")`
|
|
293
|
+
: 'is refused by rule R3: the bonus it completes could not be held next turn';
|
|
294
|
+
}
|
|
295
|
+
if (fail?.kind === 'split')
|
|
296
|
+
return `is not planned under No-Split: ${label(fail.from)} could take it but already issues an order (one attack or transfer per territory)`;
|
|
297
|
+
if (fail?.kind === 'trade')
|
|
298
|
+
return `is not taken: no single source can afford it, and the combined capture loses ${fail.lost} armies for the ${fail.killed} it kills, a trade below even`;
|
|
299
|
+
if (fail?.kind === 'must-hold')
|
|
300
|
+
return `is not planned under No-Split: ${label(fail.from)} could take it, but its whole stack would go and leave ${fail.stays} against the ~${fail.threat} threat to a border that must hold`;
|
|
301
|
+
if (fail?.kind === 'hold')
|
|
302
|
+
return `is not taken: attacking it would leave ${label(fail.from)} unable to hold its border (${holdText(fail)})`;
|
|
303
|
+
if (st.from === undefined)
|
|
304
|
+
return `cannot be reached: ${blockedText(st)}`;
|
|
305
|
+
// What the holds took before this rule ran (no capture spent anything yet).
|
|
306
|
+
const held = income - ps.budget;
|
|
307
|
+
const size = sizeOf(st.t, st.cost);
|
|
308
|
+
if (st.reach >= size)
|
|
309
|
+
return `is not taken, though ${st.reach} could reach it (it needs ${size}): no single source can deliver them this turn`;
|
|
310
|
+
if (held > 0 && st.reach + held >= size)
|
|
311
|
+
return `does not fit what the holds leave: ${reachText(st, held)}`;
|
|
312
|
+
return `does not fit this turn: ${reachText(st, 0)}`;
|
|
313
|
+
};
|
|
314
|
+
return { reachOf, lossOf, holdLeftShort, sizeOrHold, tradeOf, attempt, exposure, blockedText, holdText, failText };
|
|
315
|
+
}
|
|
316
|
+
// ---- 4e. never stand still (#104, #107) ----
|
|
317
|
+
// A plan with no capture at all (no expansion, break, finishing off or strike), in the opening
|
|
318
|
+
// or expansion phase or with my armies over the army cap, takes the cheapest affordable neutral
|
|
319
|
+
// capture toward the positive bonus with the fewest armies to finish, uneconomic or not. It runs
|
|
320
|
+
// after every hold, so it only spends what they leave. Its steps are ranked by what this turn can
|
|
321
|
+
// afford (#107): the armies that can reach each (its best source's movable armies plus what may
|
|
322
|
+
// still be deployed there) against its cost, then by the bonus's armies to finish. In the contact
|
|
323
|
+
// and late phases (#107) enemy territories it can take at a trade of at least even join them,
|
|
324
|
+
// ranked by the armies each capture loses (#112), and every other capture that loses nothing
|
|
325
|
+
// is taken too.
|
|
326
|
+
export function neverStandStill(pc, ps, book, threats, hd, tgt, caps) {
|
|
327
|
+
const { g, s, opts, income, foe, profile, auto, goal, deployOf, territories: state, label, bonusName, mine, mineSet, armiesOf, unitsAt, uncounted, defenceAt, bonusTs, guard, toTake, leadLever, clearLeader, } = pc;
|
|
328
|
+
const { warnings, rationale, spared, captured } = ps;
|
|
329
|
+
const { gainWith } = book;
|
|
330
|
+
const { growthOf, facing } = threats;
|
|
331
|
+
const { conceded } = hd;
|
|
332
|
+
const { targets, bonusTarget, targetScoreCost, toFinish, plans, finishCost, sizeOf } = tgt;
|
|
333
|
+
const { stopped, outgrows } = caps;
|
|
334
|
+
/**
|
|
335
|
+
* #125: the step rule 4e ranked first and could not afford this turn (its size, nothing else):
|
|
336
|
+
* the leftover saves toward it (rule 5) and idle stacks stage toward it (rule 6).
|
|
337
|
+
*/
|
|
338
|
+
let saveStep;
|
|
339
|
+
/** #235: the stand-still warning, restated once the leftover has chosen where it stages. */
|
|
340
|
+
let standStill;
|
|
341
|
+
if (goal !== 'complete-bonus' && captured.size === 0) {
|
|
342
|
+
const early = profile.phase === 'opening' || profile.phase === 'expansion';
|
|
343
|
+
// In a 1v1 the strike stack (rule 0p.3c, #102) is contact's own answer: it attacks every turn.
|
|
344
|
+
const strikeStackRuns = auto && profile.format === '1v1' && goal !== 'defend' && facing.size > 0;
|
|
345
|
+
// A caller who chose `defend` gets no contact fallback (a `defend` adapt picked still does: its
|
|
346
|
+
// holds come first); one who chose `expand` only its neutral steps.
|
|
347
|
+
const contact = (profile.phase === 'contact' || profile.phase === 'late') && !strikeStackRuns && opts.goal !== 'defend';
|
|
348
|
+
const enemyFallback = contact && opts.goal !== 'expand';
|
|
349
|
+
const cap = s.armyCap ?? null;
|
|
350
|
+
const total = mine.reduce((n, id) => n + armiesOf(id), 0) + income;
|
|
351
|
+
// #253: with the cap's arithmetic known, the fallback fires when the cap cuts this turn's income
|
|
352
|
+
// (armies left standing then cost income next turn); without it, the old test.
|
|
353
|
+
const capCut = pc.incomeCap;
|
|
354
|
+
const capped = capCut ? capCut.cut : cap !== null && cap > 0 && income > 0 && total > cap * income;
|
|
355
|
+
if (early || capped || contact) {
|
|
356
|
+
/** Ascending, safe for Infinity (a bonus that cannot be costed): Infinity − Infinity is NaN. */
|
|
357
|
+
const asc = (a, b) => (a === b ? 0 : a < b ? -1 : 1);
|
|
358
|
+
const toward = [...finishCost]
|
|
359
|
+
.filter(([, f]) => f.net > 0)
|
|
360
|
+
.sort(([a, x], [b, y]) => asc(x.cost, y.cost) || y.value - x.value || a - b);
|
|
361
|
+
const bonusRank = new Map(toward.map(([id], i) => [id, i]));
|
|
362
|
+
const { reachOf, lossOf, holdLeftShort, sizeOrHold, tradeOf, attempt, exposure, blockedText, holdText, failText, } = standStillKit(pc, ps, book, threats, hd, tgt, caps);
|
|
363
|
+
// #107, in contact: every visible enemy territory next to mine (no enemy commander on it)
|
|
364
|
+
// whose capture does not lower income is a candidate. One not already a target is added for this rule (and dropped again
|
|
365
|
+
// unless taken), sized like any capture at the plan's win chance.
|
|
366
|
+
const added = [];
|
|
367
|
+
const enemyTs = [];
|
|
368
|
+
if (enemyFallback)
|
|
369
|
+
for (const t of [...g.territoryById.keys()].sort(byNum)) {
|
|
370
|
+
// #179: a buffer left standing is no candidate (its "Not attacking" line says why).
|
|
371
|
+
if (mineSet.has(t) || captured.has(t) || spared.has(t))
|
|
372
|
+
continue;
|
|
373
|
+
const st = state.get(t);
|
|
374
|
+
if (st?.owner.kind !== 'player' || !foe(st.owner.playerId) || st.armies === null || uncounted(t))
|
|
375
|
+
continue;
|
|
376
|
+
// B2 (T1): never a truce's covered territory.
|
|
377
|
+
if (pc.truce.noTarget(t))
|
|
378
|
+
continue;
|
|
379
|
+
// An enemy commander is rule 1s's, sized for its owner's full deploy: never a fallback.
|
|
380
|
+
if (unitsAt(t) > 0)
|
|
381
|
+
continue;
|
|
382
|
+
const sources = neighborsOf(g, t).filter((n) => mineSet.has(n));
|
|
383
|
+
if (!sources.length || gainWith([t]) < 0)
|
|
384
|
+
continue;
|
|
385
|
+
if (!targets.has(t)) {
|
|
386
|
+
// #240 review: ranked on its plain cost like any target; a territory my attacks failed on
|
|
387
|
+
// repeatedly is still sent its sure size (tryCapture), or not attacked.
|
|
388
|
+
const cost = pc.costAt(t);
|
|
389
|
+
if (cost === null)
|
|
390
|
+
continue;
|
|
391
|
+
targets.set(t, { id: t, cost, enemy: true, sources });
|
|
392
|
+
added.push(t);
|
|
393
|
+
}
|
|
394
|
+
enemyTs.push(t);
|
|
395
|
+
}
|
|
396
|
+
const seen = new Set();
|
|
397
|
+
const steps = toward
|
|
398
|
+
.flatMap(([id, f]) => bonusTs
|
|
399
|
+
.get(id)
|
|
400
|
+
.filter((t) => targets.has(t) && !targets.get(t).enemy && !captured.has(t) && gainWith([t]) >= 0)
|
|
401
|
+
.sort((a, b) => targetScoreCost(a) - targetScoreCost(b) || targets.get(a).cost - targets.get(b).cost || a - b)
|
|
402
|
+
.map((t, k) => ({ t, id, f, k, cost: targets.get(t).cost, ...reachOf(t) })))
|
|
403
|
+
// What this turn can afford first (shortfall 0 fits), then the bonus's armies to finish.
|
|
404
|
+
.sort((a, b) => Math.max(0, a.cost - a.reach) - Math.max(0, b.cost - b.reach) ||
|
|
405
|
+
bonusRank.get(a.id) - bonusRank.get(b.id) ||
|
|
406
|
+
a.k - b.k)
|
|
407
|
+
// A territory in several bonuses: once, toward the first.
|
|
408
|
+
.filter(({ t }) => !seen.has(t) && Boolean(seen.add(t)));
|
|
409
|
+
const fewest = steps.length ? Math.min(...steps.map((x) => x.f.cost)) : Infinity;
|
|
410
|
+
const economicLeft = plans.some((p) => p.remaining.some(bonusTarget));
|
|
411
|
+
const why = [
|
|
412
|
+
...(early
|
|
413
|
+
? [
|
|
414
|
+
economicLeft
|
|
415
|
+
? `${profile.phase} phase: no economic capture fits this turn; standing still is worse than the cheapest expansion`
|
|
416
|
+
: `${profile.phase} phase: nothing passed the economy test; standing still is worse than the cheapest expansion`,
|
|
417
|
+
]
|
|
418
|
+
: contact
|
|
419
|
+
? [
|
|
420
|
+
`${profile.phase} phase: no capture is planned (${economicLeft ? 'no economic capture fits this turn' : 'nothing passed the economy test'}); standing still is worse than the cheapest capture`,
|
|
421
|
+
]
|
|
422
|
+
: []),
|
|
423
|
+
...(capped
|
|
424
|
+
? [
|
|
425
|
+
capCut
|
|
426
|
+
? `my ${capCut.armies} armies on the board reach the army cap of ${capCut.limit} (${capCut.cap}× income ${capCut.uncapped}): income is cut to ${capCut.received}, so armies left standing cost income next turn and spending them is free`
|
|
427
|
+
: `my ${total} armies after deploy exceed the army cap of ${cap * income} (${cap}× income ${income}): armies above it are wasted, so spending them is free`,
|
|
428
|
+
]
|
|
429
|
+
: []),
|
|
430
|
+
].join('; ');
|
|
431
|
+
const reasonOf = ({ id, f }) => `cheapest expansion toward bonus ${bonusName(id)} (+${f.value}, ${toFinish(f.cost, f.fogged, f.fogEach)}, ${f.cost === fewest ? 'the fewest of any bonus in reach' : 'the fewest of any bonus with a capture affordable this turn'})`;
|
|
432
|
+
// ---- #107, in contact: enemy captures ----
|
|
433
|
+
/** Rule 0p.2's setting: an FFA with two or more opponents left. Applied here with or without adapt. */
|
|
434
|
+
const ffaFronts = profile.format === 'ffa' && profile.opponents >= 2 && !leadLever;
|
|
435
|
+
/**
|
|
436
|
+
* The first territory of mine (by id) player `p` could take next turn — its stacks next to it
|
|
437
|
+
* plus max(its deploy estimate, its fastest growth there) against what taking it needs — or
|
|
438
|
+
* `undefined`: `p` cannot currently attack me.
|
|
439
|
+
*/
|
|
440
|
+
const attackableBy = (p) => mine.find((x) => {
|
|
441
|
+
let movable = 0;
|
|
442
|
+
let growth = 0;
|
|
443
|
+
let next = false;
|
|
444
|
+
for (const n of neighborsOf(g, x)) {
|
|
445
|
+
const st = state.get(n);
|
|
446
|
+
if (st?.owner.kind !== 'player' || st.owner.playerId !== p || st.armies === null)
|
|
447
|
+
continue;
|
|
448
|
+
next = true;
|
|
449
|
+
movable += Math.max(0, st.armies - guard) + unitsAt(n);
|
|
450
|
+
growth = Math.max(growth, growthOf.get(n)?.growth ?? 0);
|
|
451
|
+
}
|
|
452
|
+
const take = toTake(defenceAt(x));
|
|
453
|
+
return next && take !== null && take <= movable + Math.max(deployOf(p), growth);
|
|
454
|
+
});
|
|
455
|
+
/** What capturing enemy `t` does to a bonus: breaks one its owner holds in full, or advances one of mine. */
|
|
456
|
+
const enemyBonus = (t, p) => {
|
|
457
|
+
const breaks = g.map.bonuses
|
|
458
|
+
.filter((b) => b.value > 0 && bonusTs.get(b.id).includes(t))
|
|
459
|
+
.sort((a, b) => b.value - a.value || a.id - b.id)
|
|
460
|
+
.find((b) => bonusTs.get(b.id).every((m) => {
|
|
461
|
+
const o = state.get(m)?.owner;
|
|
462
|
+
return o?.kind === 'player' && o.playerId === p;
|
|
463
|
+
}));
|
|
464
|
+
if (breaks)
|
|
465
|
+
return { id: breaks.id, breaks: true };
|
|
466
|
+
const adv = toward.find(([id]) => bonusTs.get(id).includes(t));
|
|
467
|
+
return adv ? { id: adv[0], breaks: false } : undefined;
|
|
468
|
+
};
|
|
469
|
+
/**
|
|
470
|
+
* #240: the bonus capturing `t` completes this turn — every other member already mine (the
|
|
471
|
+
* fallback runs only when nothing is captured) — the most valuable, then the lowest id.
|
|
472
|
+
*/
|
|
473
|
+
const completesOf = (t) => g.map.bonuses
|
|
474
|
+
.filter((b) => b.value > 0 &&
|
|
475
|
+
bonusTs.get(b.id).includes(t) &&
|
|
476
|
+
bonusTs.get(b.id).every((m) => m === t || mineSet.has(m)))
|
|
477
|
+
.sort((a, b) => b.value - a.value || a.id - b.id)[0]?.id;
|
|
478
|
+
const enemySteps = enemyTs.map((t) => {
|
|
479
|
+
const p = state.get(t).owner.playerId;
|
|
480
|
+
const from = attackableBy(p);
|
|
481
|
+
return {
|
|
482
|
+
t,
|
|
483
|
+
cost: targets.get(t).cost,
|
|
484
|
+
player: p,
|
|
485
|
+
bonus: enemyBonus(t, p),
|
|
486
|
+
/** Its owner can attack me now: the territory of mine it could take. */
|
|
487
|
+
front: from,
|
|
488
|
+
/** #240: the bonus this capture completes this turn, if any. */
|
|
489
|
+
completes: completesOf(t),
|
|
490
|
+
secondFront: ffaFronts && from === undefined && p !== clearLeader,
|
|
491
|
+
...reachOf(t),
|
|
492
|
+
};
|
|
493
|
+
});
|
|
494
|
+
const enemyReason = (e) => {
|
|
495
|
+
if (e.completes !== undefined)
|
|
496
|
+
return `cheapest capture: completes bonus ${bonusName(e.completes)} (+${g.bonusById.get(e.completes).value}) from player ${e.player}`;
|
|
497
|
+
if (!e.bonus)
|
|
498
|
+
return `cheapest capture: takes a territory of player ${e.player}`;
|
|
499
|
+
const v = g.bonusById.get(e.bonus.id).value;
|
|
500
|
+
if (e.bonus.breaks)
|
|
501
|
+
return `cheapest capture: breaks bonus ${bonusName(e.bonus.id)} (+${v}) of player ${e.player}`;
|
|
502
|
+
const f = finishCost.get(e.bonus.id);
|
|
503
|
+
return `cheapest capture: advances bonus ${bonusName(e.bonus.id)} (+${v}, ${toFinish(f.cost, f.fogged, f.fogEach)}) from player ${e.player}`;
|
|
504
|
+
};
|
|
505
|
+
// #240 review: what fits is judged on a repulsed territory's sure size.
|
|
506
|
+
const shortOf = (x) => Math.max(0, sizeOf(x.t, x.cost) - x.reach);
|
|
507
|
+
const rank4e = new Map(steps.map((x, i) => [x.t, i]));
|
|
508
|
+
/** #240: the bonus a candidate completes this turn, if any. */
|
|
509
|
+
const completedBy = (p) => (p.kind === 'enemy' ? p.st.completes : completesOf(p.st.t));
|
|
510
|
+
const completing = (p) => completedBy(p) !== undefined;
|
|
511
|
+
const picks = [
|
|
512
|
+
...steps.map((st) => ({ kind: 'neutral', st })),
|
|
513
|
+
...enemySteps.map((st) => ({ kind: 'enemy', st })),
|
|
514
|
+
];
|
|
515
|
+
const loss = new Map(picks.map((p) => [p.st.t, lossOf(p.st)]));
|
|
516
|
+
/**
|
|
517
|
+
* In contact (#114): the survivors a capture leaves on a border that cannot hold next turn
|
|
518
|
+
* (rule 4d's and R3's arithmetic: survivors against the threat at the expected enemy deploy),
|
|
519
|
+
* with that threat. Absent when it can be held or faces no enemy. Filled below, by a trial of
|
|
520
|
+
* each candidate.
|
|
521
|
+
*/
|
|
522
|
+
const risk = new Map();
|
|
523
|
+
/** A candidate's ranking cost in contact (#114): the armies it loses plus its survivors at risk. */
|
|
524
|
+
const costOfPick = (t) => loss.get(t).lost + (risk.get(t)?.survivors ?? 0);
|
|
525
|
+
/** "N survivor(s)". */
|
|
526
|
+
const survivorsText = (n) => `${n} survivor${n === 1 ? '' : 's'}`;
|
|
527
|
+
/**
|
|
528
|
+
* "loses ~N armies" / "loses no armies": what a capture costs (#112); in contact, and when its
|
|
529
|
+
* border cannot hold next turn, ", and its S survivors may fall next turn" (#114).
|
|
530
|
+
*/
|
|
531
|
+
const lossText = (t) => {
|
|
532
|
+
const n = loss.get(t).lost;
|
|
533
|
+
const r = risk.get(t);
|
|
534
|
+
return `${n === 0 ? 'loses no armies' : `loses ~${n} ${n === 1 ? 'army' : 'armies'}`}${r ? `, and its ${survivorsText(r.survivors)} may fall next turn` : ''}`;
|
|
535
|
+
};
|
|
536
|
+
// In contact (#112, #114): affordable first, then the cost (the armies the capture loses plus
|
|
537
|
+
// its survivors at risk), then the armies it sends; breaking or advancing a bonus is only a
|
|
538
|
+
// tie-break. Under rule 0p.2 a capture that opens a second front still comes after every other
|
|
539
|
+
// — unless it completes a bonus this turn (#240). A completion whose cost (the same ranking
|
|
540
|
+
// cost) the bonus repays within the payback horizon goes first among the affordable; one that
|
|
541
|
+
// does not is ranked like any other capture.
|
|
542
|
+
const repays = (p) => {
|
|
543
|
+
const id = completedBy(p);
|
|
544
|
+
return id !== undefined && costOfPick(p.st.t) <= pc.paybackTurns * g.bonusById.get(id).value;
|
|
545
|
+
};
|
|
546
|
+
const teamFocused = (p) => p.kind === 'enemy' && pc.teamFocus.has(p.st.player);
|
|
547
|
+
const keyOf = (p) => [
|
|
548
|
+
p.kind === 'enemy' && p.st.secondFront && !completing(p) ? 1 : 0,
|
|
549
|
+
shortOf(p.st),
|
|
550
|
+
repays(p) ? 0 : 1,
|
|
551
|
+
costOfPick(p.st.t),
|
|
552
|
+
loss.get(p.st.t).sent,
|
|
553
|
+
p.kind === 'enemy' && !p.st.bonus ? 1 : 0,
|
|
554
|
+
// PLAN-TEAMS C3.4: a player my teammate attacks this turn ranks above an equal capture.
|
|
555
|
+
teamFocused(p) ? 0 : 1,
|
|
556
|
+
p.kind === 'neutral' ? rank4e.get(p.st.t) : Infinity,
|
|
557
|
+
p.st.t,
|
|
558
|
+
];
|
|
559
|
+
/** The rank keys before the team focus's (PLAN-TEAMS C3.4). */
|
|
560
|
+
const FOCUS_KEY = 6;
|
|
561
|
+
const reasonFor = (p) => {
|
|
562
|
+
const r = p.kind === 'neutral' ? reasonOf(p.st) : enemyReason(p.st);
|
|
563
|
+
// In contact the reason names what the capture costs (#112).
|
|
564
|
+
if (!contact)
|
|
565
|
+
return r;
|
|
566
|
+
const head = p.kind === 'neutral' ? 'cheapest expansion' : 'cheapest capture';
|
|
567
|
+
return `${head} (${lossText(p.st.t)})${r.slice(head.length)}`;
|
|
568
|
+
};
|
|
569
|
+
const failed = new Map();
|
|
570
|
+
if (contact) {
|
|
571
|
+
// #114: rule 4d is a cost here, not a veto. Each candidate is tried (and undone) to see
|
|
572
|
+
// what its capture leaves exposed; then they are ranked.
|
|
573
|
+
ps.evenTradesOnly = true;
|
|
574
|
+
// #240 review: a repulsed territory ranks as the plan without the evidence ranks it.
|
|
575
|
+
ps.plainRepulsed = true;
|
|
576
|
+
for (const pick of picks) {
|
|
577
|
+
const undo = attempt(pick.st, '');
|
|
578
|
+
if (!undo)
|
|
579
|
+
continue;
|
|
580
|
+
const e = exposure(pick.st.t);
|
|
581
|
+
if (e)
|
|
582
|
+
risk.set(pick.st.t, e);
|
|
583
|
+
undo();
|
|
584
|
+
}
|
|
585
|
+
ps.plainRepulsed = false;
|
|
586
|
+
ps.evenTradesOnly = false;
|
|
587
|
+
picks.sort((a, b) => {
|
|
588
|
+
const x = keyOf(a);
|
|
589
|
+
const y = keyOf(b);
|
|
590
|
+
for (let i = 0; i < x.length; i++)
|
|
591
|
+
if (x[i] !== y[i])
|
|
592
|
+
return x[i] < y[i] ? -1 : 1;
|
|
593
|
+
return 0;
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
let taken;
|
|
597
|
+
ps.evenTradesOnly = contact;
|
|
598
|
+
for (const pick of picks) {
|
|
599
|
+
const st = pick.st;
|
|
600
|
+
const undo = attempt(st, reasonFor(pick));
|
|
601
|
+
if (!undo) {
|
|
602
|
+
const r = ps.refusal;
|
|
603
|
+
failed.set(st.t, r ?? sizeOrHold(st, reasonFor(pick)));
|
|
604
|
+
continue;
|
|
605
|
+
}
|
|
606
|
+
// Every phase, not only contact: a capture that leaves its source to fall is worse than
|
|
607
|
+
// standing still (live, an opening plan sent a 15-stack's every army at a 15-neutral
|
|
608
|
+
// from beside two enemy 15-stacks).
|
|
609
|
+
const short = holdLeftShort(st.t);
|
|
610
|
+
if (short) {
|
|
611
|
+
undo();
|
|
612
|
+
failed.set(st.t, { kind: 'hold', ...short });
|
|
613
|
+
continue;
|
|
614
|
+
}
|
|
615
|
+
// #114: in contact rule 4d is a cost (ranked above), not a veto.
|
|
616
|
+
const stop = contact ? null : outgrows(st.t);
|
|
617
|
+
if (stop === null) {
|
|
618
|
+
taken = pick;
|
|
619
|
+
break;
|
|
620
|
+
}
|
|
621
|
+
undo();
|
|
622
|
+
if (!rationale.includes(stop))
|
|
623
|
+
rationale.push(stop);
|
|
624
|
+
const f = stopped.find((x) => x.t === st.t);
|
|
625
|
+
failed.set(st.t, { kind: '4d', holdCost: f.holdCost, income: f.income });
|
|
626
|
+
}
|
|
627
|
+
ps.evenTradesOnly = false;
|
|
628
|
+
// #107: in the opening, rule 4d's frontier stop must not make the plan stand still: one
|
|
629
|
+
// capture that grows the frontier is better than none (4d still judges every other capture).
|
|
630
|
+
let waived;
|
|
631
|
+
if (!taken && profile.phase === 'opening') {
|
|
632
|
+
const st = steps.find((x) => failed.get(x.t)?.kind === '4d');
|
|
633
|
+
const undo = st ? attempt(st, reasonOf(st)) : null;
|
|
634
|
+
if (st && undo) {
|
|
635
|
+
// The waiver is for the frontier the captured territory adds, never for a source the
|
|
636
|
+
// attack leaves unable to hold: that is checked (and its deploys placed) again here.
|
|
637
|
+
const short = holdLeftShort(st.t);
|
|
638
|
+
if (short) {
|
|
639
|
+
undo();
|
|
640
|
+
failed.set(st.t, { kind: 'hold', ...short });
|
|
641
|
+
}
|
|
642
|
+
else {
|
|
643
|
+
taken = { kind: 'neutral', st };
|
|
644
|
+
waived = failed.get(st.t);
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
// #112, in contact: after the fallback's capture, every other candidate that loses no armies
|
|
649
|
+
// is taken too, by armies sent, then id — when every hold stays covered and income does not
|
|
650
|
+
// fall. Its survivors at risk never exceed the armies it sends, so rule 4d does not stop one
|
|
651
|
+
// either (#114); the rationale says when the new border may fall. A conceded border never
|
|
652
|
+
// attacks out for one. Why one was not taken is kept for the list of dropped candidates.
|
|
653
|
+
const free = [];
|
|
654
|
+
/** Why a candidate that loses nothing was not also taken, as a clause after its name. */
|
|
655
|
+
const freeWhy = new Map();
|
|
656
|
+
if (contact && taken) {
|
|
657
|
+
ps.evenTradesOnly = true;
|
|
658
|
+
const others = picks
|
|
659
|
+
.filter((p) => p !== taken && loss.get(p.st.t).lost === 0)
|
|
660
|
+
.sort((a, b) => loss.get(a.st.t).sent - loss.get(b.st.t).sent || a.st.t - b.st.t);
|
|
661
|
+
for (const pick of others) {
|
|
662
|
+
const t = pick.st.t;
|
|
663
|
+
if (captured.has(t))
|
|
664
|
+
continue;
|
|
665
|
+
if (gainWith([t]) < 0) {
|
|
666
|
+
freeWhy.set(t, 'is not taken: with the captures planned it would lower next income');
|
|
667
|
+
continue;
|
|
668
|
+
}
|
|
669
|
+
const now = { ...reachOf(t), t, cost: pick.st.cost };
|
|
670
|
+
if (now.from === undefined) {
|
|
671
|
+
freeWhy.set(t, `cannot be reached after the first capture: ${blockedText(now)}`);
|
|
672
|
+
continue;
|
|
673
|
+
}
|
|
674
|
+
if (conceded.has(now.from)) {
|
|
675
|
+
freeWhy.set(t, `is not taken: only conceded ${label(now.from)} could still attack it, and a conceded border never attacks out for a capture that only costs nothing`);
|
|
676
|
+
continue;
|
|
677
|
+
}
|
|
678
|
+
const undo = attempt(now, reasonFor(pick));
|
|
679
|
+
if (!undo) {
|
|
680
|
+
freeWhy.set(t, failText(now, ps.refusal ?? { kind: 'size' }));
|
|
681
|
+
continue;
|
|
682
|
+
}
|
|
683
|
+
const lost = tradeOf(t).lost;
|
|
684
|
+
if (lost > 0) {
|
|
685
|
+
undo();
|
|
686
|
+
freeWhy.set(t, `is not taken: after the first capture it would lose ~${lost} ${lost === 1 ? 'army' : 'armies'}, so it no longer costs nothing`);
|
|
687
|
+
continue;
|
|
688
|
+
}
|
|
689
|
+
const short = holdLeftShort(t);
|
|
690
|
+
if (short) {
|
|
691
|
+
undo();
|
|
692
|
+
freeWhy.set(t, failText(now, { kind: 'hold', ...short }));
|
|
693
|
+
continue;
|
|
694
|
+
}
|
|
695
|
+
free.push({ pick, exposed: exposure(t) });
|
|
696
|
+
}
|
|
697
|
+
ps.evenTradesOnly = false;
|
|
698
|
+
}
|
|
699
|
+
// Enemy targets added for this rule and not taken are dropped again.
|
|
700
|
+
for (const t of added)
|
|
701
|
+
if (!captured.has(t))
|
|
702
|
+
targets.delete(t);
|
|
703
|
+
// A capture of a player's territory refused as a trade below even, or for a hold it would
|
|
704
|
+
// leave short: said whatever was taken.
|
|
705
|
+
for (const e of enemySteps) {
|
|
706
|
+
const f = failed.get(e.t);
|
|
707
|
+
if (captured.has(e.t))
|
|
708
|
+
continue;
|
|
709
|
+
if (f?.kind === 'trade')
|
|
710
|
+
warnings.push(`Not attacking ${label(e.t)}: the combined capture loses ${f.lost} armies for the ${f.killed} it kills, a trade below even.`);
|
|
711
|
+
if (f?.kind === 'hold')
|
|
712
|
+
warnings.push(`Not attacking ${label(e.t)}: it would leave ${label(f.from)} unable to hold its border (${holdText(f)}).`);
|
|
713
|
+
}
|
|
714
|
+
if (taken) {
|
|
715
|
+
const t = taken.st.t;
|
|
716
|
+
rationale.push(`Take ${label(t)} though no planned capture is economic: ${why}.`);
|
|
717
|
+
if (waived)
|
|
718
|
+
rationale.push(`Take ${label(t)} though the frontier would then need ${waived.holdCost} next turn to hold, more than the next income of ${waived.income}: rule 4d's frontier stop is waived for this one capture: in the opening, one capture that grows the frontier is better than none (rule 4d still applies to every other capture).`);
|
|
719
|
+
if (taken.kind === 'enemy') {
|
|
720
|
+
const e = taken.st;
|
|
721
|
+
const { lost, killed } = tradeOf(t);
|
|
722
|
+
rationale.push(`Attack on ${label(t)} kills ${killed} for ${lost} lost: a trade of at least even.`);
|
|
723
|
+
if (ffaFronts)
|
|
724
|
+
rationale.push(e.front !== undefined
|
|
725
|
+
? `Player ${e.player} can already attack me (${label(e.front)}): taking ${label(t)} opens no new front.`
|
|
726
|
+
: e.completes !== undefined && e.secondFront
|
|
727
|
+
? `Player ${e.player} cannot attack me now: taking ${label(t)} completes bonus ${bonusName(e.completes)} this turn, so the second front is taken for it.`
|
|
728
|
+
: `Player ${e.player} cannot attack me now: taking ${label(t)} opens a second front (no second front in an FFA), taken only because no neutral capture fits this turn.`);
|
|
729
|
+
}
|
|
730
|
+
else {
|
|
731
|
+
// The bonus with the fewest armies to finish was passed over: say why.
|
|
732
|
+
const st = taken.st;
|
|
733
|
+
const closer = st.f.cost > fewest ? steps.find((x) => x.f.cost === fewest) : undefined;
|
|
734
|
+
if (closer) {
|
|
735
|
+
const fail = failed.get(closer.t);
|
|
736
|
+
rationale.push(`${bonusName(closer.id)} has fewer armies to finish (${closer.f.cost}), but ${fail?.kind === '4d'
|
|
737
|
+
? `rule 4d's frontier stop refuses ${label(closer.t)}`
|
|
738
|
+
: fail?.kind === 'size' || fail === undefined
|
|
739
|
+
? closer.from === undefined
|
|
740
|
+
? `${label(closer.t)} ${failText(closer, fail)}`
|
|
741
|
+
: `${label(closer.t)} needs ${closer.cost} and at most ${closer.reach} can reach it this turn`
|
|
742
|
+
: `${label(closer.t)} ${failText(closer, fail)}`}.`);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
for (const { pick, exposed } of free) {
|
|
746
|
+
const t = pick.st.t;
|
|
747
|
+
rationale.push(`Also take ${label(t)}: it costs nothing (it loses no armies, every hold stays covered and income does not fall)${exposed
|
|
748
|
+
? `; its ${survivorsText(exposed.survivors)} may fall next turn (a threat of ${exposed.threat} against them), no more than the armies it sends`
|
|
749
|
+
: ''}.`);
|
|
750
|
+
if (pick.kind === 'enemy' && ffaFronts && pick.st.secondFront)
|
|
751
|
+
rationale.push(`Player ${pick.st.player} cannot attack me now: taking ${label(t)} opens a second front, taken only because it costs nothing.`);
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
else if (picks[0]) {
|
|
755
|
+
const top = picks[0];
|
|
756
|
+
const head = top.kind === 'neutral'
|
|
757
|
+
? `Standing still: no capture is planned, and the cheapest expansion (${label(top.st.t)}, ${top.st.cost} armies, toward bonus ${bonusName(top.st.id)})`
|
|
758
|
+
: `Standing still: no capture is planned, and the cheapest capture (${label(top.st.t)}, ${sizeOf(top.st.t, top.st.cost)} armies, a territory of player ${top.st.player})`;
|
|
759
|
+
const tail = `${failText(top.st, failed.get(top.st.t))}.`;
|
|
760
|
+
const text = `${head} ${tail}`;
|
|
761
|
+
warnings.push(text);
|
|
762
|
+
const why = failed.get(top.st.t);
|
|
763
|
+
// #235: the source the warning explains the miss by (a failed attempt's, else the best reach).
|
|
764
|
+
const named = why && 'from' in why ? why.from : top.st.from;
|
|
765
|
+
standStill = {
|
|
766
|
+
t: top.st.t,
|
|
767
|
+
text,
|
|
768
|
+
named,
|
|
769
|
+
restate: (stage) => why?.kind === 'hold'
|
|
770
|
+
? `${head} is not taken this turn: the plan stages on ${label(stage)} toward it (the leftover saves there); taking it now would leave ${label(why.from)} unable to hold its border (${holdText(why)}).`
|
|
771
|
+
: `${head} ${failText(top.st, why)}; the plan stages on ${label(stage)} toward it (the leftover saves there).`,
|
|
772
|
+
};
|
|
773
|
+
if (top.kind === 'neutral' && (why === undefined || why.kind === 'size'))
|
|
774
|
+
saveStep = { t: top.st.t, bonusId: top.st.id, cost: top.st.cost };
|
|
775
|
+
}
|
|
776
|
+
// #114, in contact: every candidate the fallback considered and dropped leaves a reason (the
|
|
777
|
+
// top one, when nothing is taken, is in the stand-still warning). One already said elsewhere
|
|
778
|
+
// is not repeated: an enemy capture refused as a trade or for a hold has its "Not attacking"
|
|
779
|
+
// warning.
|
|
780
|
+
const dropped = (contact ? picks : []).flatMap((p) => {
|
|
781
|
+
const t = p.st.t;
|
|
782
|
+
if (captured.has(t) || (!taken && p === picks[0]))
|
|
783
|
+
return [];
|
|
784
|
+
const fail = failed.get(t);
|
|
785
|
+
if (fail && p.kind === 'enemy' && (fail.kind === 'trade' || fail.kind === 'hold'))
|
|
786
|
+
return [];
|
|
787
|
+
if (fail)
|
|
788
|
+
return [`${label(t)} ${failText(p.st, fail)}`];
|
|
789
|
+
const why = freeWhy.get(t);
|
|
790
|
+
if (why)
|
|
791
|
+
return [`${label(t)} ${why}`];
|
|
792
|
+
if (!taken)
|
|
793
|
+
return [`${label(t)} ${failText(p.st, undefined)}`];
|
|
794
|
+
if (shortOf(p.st) > 0)
|
|
795
|
+
return [`${label(t)} ${failText(p.st, undefined)}`];
|
|
796
|
+
const after = `is ranked after ${label(taken.st.t)}`;
|
|
797
|
+
if (p.kind === 'enemy' &&
|
|
798
|
+
p.st.secondFront &&
|
|
799
|
+
!completing(p) &&
|
|
800
|
+
!(taken.kind === 'enemy' && taken.st.secondFront && !completing(taken)))
|
|
801
|
+
return [`${label(t)} ${after}: player ${p.st.player} cannot attack me now, so it is tried only after every other capture`];
|
|
802
|
+
// #240: a completion that repays its cost goes first among the affordable candidates.
|
|
803
|
+
if (repays(taken) && !repays(p))
|
|
804
|
+
return [
|
|
805
|
+
`${label(t)} ${after}: taking ${label(taken.st.t)} completes bonus ${bonusName(completedBy(taken))} this turn, which repays its cost of ${costOfPick(taken.st.t)} within ${pc.paybackTurns} turns`,
|
|
806
|
+
];
|
|
807
|
+
// PLAN-TEAMS C3.4: equal but for the team focus.
|
|
808
|
+
if (teamFocused(taken) && !teamFocused(p) && keyOf(p).slice(0, FOCUS_KEY).every((k, i) => k === keyOf(taken)[i]))
|
|
809
|
+
return [
|
|
810
|
+
`${label(t)} ${after}: they are otherwise equal, and my teammate attacks player ${taken.st.player} this turn (PLAN-TEAMS C3.4: their entered orders, read unverified)`,
|
|
811
|
+
];
|
|
812
|
+
const c = costOfPick(t);
|
|
813
|
+
const tc = costOfPick(taken.st.t);
|
|
814
|
+
return [
|
|
815
|
+
`${label(t)} ${after}: it costs ${c} (${lossText(t)}) against ${tc}${c === tc ? ' (ties go by armies sent, then a bonus, then id)' : ''}`,
|
|
816
|
+
];
|
|
817
|
+
});
|
|
818
|
+
if (dropped.length)
|
|
819
|
+
rationale.push(`Other candidates not taken: ${dropped.join('; ')}.`);
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
return { saveStep, standStill };
|
|
823
|
+
}
|