@chrischall/warapp-mcp 0.7.0 → 0.8.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.
Files changed (53) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +2 -2
  4. package/dist/analysis/card-support.js +12 -4
  5. package/dist/analysis/coalition.js +55 -0
  6. package/dist/analysis/local-deploy.js +14 -0
  7. package/dist/analysis/opponents.js +2 -1
  8. package/dist/analysis/picks.js +270 -37
  9. package/dist/analysis/plan/after-leftover.js +26 -4
  10. package/dist/analysis/plan/captures.js +76 -13
  11. package/dist/analysis/plan/completed.js +8 -1
  12. package/dist/analysis/plan/conceded-out.js +16 -11
  13. package/dist/analysis/plan/deploy-estimates.js +513 -0
  14. package/dist/analysis/plan/doomed-out.js +135 -0
  15. package/dist/analysis/plan/estimates.js +3 -1
  16. package/dist/analysis/plan/free-capture.js +34 -0
  17. package/dist/analysis/plan/holds.js +8 -309
  18. package/dist/analysis/plan/horizon.js +42 -0
  19. package/dist/analysis/plan/leftover.js +43 -5
  20. package/dist/analysis/plan/observe.js +896 -0
  21. package/dist/analysis/plan/orders.js +35 -1
  22. package/dist/analysis/plan/report.js +10 -4
  23. package/dist/analysis/plan/shared.js +4 -1376
  24. package/dist/analysis/plan/stand-still.js +5 -3
  25. package/dist/analysis/plan/state.js +12 -0
  26. package/dist/analysis/plan/strike-stack.js +467 -0
  27. package/dist/analysis/plan/strike.js +3 -463
  28. package/dist/analysis/plan/targets.js +213 -26
  29. package/dist/analysis/plan/threats.js +12 -4
  30. package/dist/analysis/plan/transfers.js +24 -1
  31. package/dist/analysis/plan/two-move.js +1 -1
  32. package/dist/analysis/plan/withdraw.js +316 -0
  33. package/dist/analysis/planner.js +54 -11
  34. package/dist/analysis/player.js +4 -0
  35. package/dist/analysis/relations.js +8 -2
  36. package/dist/analysis/stress.js +1 -1
  37. package/dist/bundle.js +8008 -7184
  38. package/dist/my-games.js +2 -0
  39. package/dist/open-games.js +94 -10
  40. package/dist/tools/card-advice.js +26 -11
  41. package/dist/tools/card-support-advice.js +17 -1
  42. package/dist/tools/check-plan.js +2 -1
  43. package/dist/tools/commander-check.js +2 -1
  44. package/dist/tools/decision-capture.js +4 -2
  45. package/dist/tools/join-game.js +44 -8
  46. package/dist/tools/live.js +33 -5
  47. package/dist/tools/open-games.js +2 -2
  48. package/dist/tools/picks.js +120 -47
  49. package/dist/tools/turn.js +43 -4
  50. package/dist/version.js +1 -1
  51. package/manifest.json +1 -1
  52. package/package.json +1 -1
  53. package/server.json +2 -2
@@ -1,10 +1,8 @@
1
- import { commerceRules } from '../../commerce.js';
2
- import { LEAD_ARMIES } from '../opponents.js';
3
1
  import { bonusTerritories } from '../bonuses.js';
4
- import { armiesForChance, armiesToTake, DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE, fewestAttackersToKill, fewestAttackersToTake, guaranteedKills, luckFraction, specialUnitStrength, straightKills, } from '../combat.js';
5
- import { neighborsOf } from '../graph.js';
6
- import { armyCapIncome, boardIncome, DEFAULT_BASE_INCOME, incomeRules, territoryIncome } from '../player.js';
2
+ import { armiesForChance, armiesToTake, DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE, luckFraction, } from '../combat.js';
3
+ import { DEFAULT_BASE_INCOME } from '../player.js';
7
4
  import { byNum } from './util.js';
5
+ export * from './observe.js';
8
6
  /** A bonus is uneconomic when its remaining capture cost exceeds this many turns of its value… */
9
7
  export const PAYBACK_TURNS = 10;
10
8
  /**
@@ -284,1374 +282,4 @@ export function guaranteedFallsReaching(saveCosts, reaches, deploy) {
284
282
  export function fogPaceIncome(p, myIncome) {
285
283
  return p.basis === 'map' ? Math.max(0, Math.floor(p.income ?? 0)) : Math.ceil(Math.max(0, myIncome) * (p.ratio ?? 0) - 1e-9);
286
284
  }
287
- /**
288
- * Fog levels that hide a territory's armies. The live board names war.app's StandingFogLevel
289
- * (1 You, 2 Visible, 3 OwnerOnly, 4 Fogged; the client refuses a deploy on 3 or 4 as "fogged");
290
- * a GameFeed standing may spell it as a word or as the raw number (every GameFeed scalar is a
291
- * string).
292
- */
293
- const HIDDEN_FOG = /fog|owneronly|^\s*[34]\s*$/i;
294
- /** Fog levels that hide a territory's owner too (StandingFogLevel 4, Fogged). */
295
- const OWNER_HIDDEN_FOG = /fog|^\s*4\s*$/i;
296
- /**
297
- * `t` when a board shows both its owner (a player or a neutral) and its armies, else
298
- * `undefined`: a fogged territory (owner unknown, armies `null`), or one whose fog level hides
299
- * its armies even if a placeholder owner or count came with it (issue #69).
300
- *
301
- * One exception: an entry named `"OwnerOnly"` that still carries a count is fog level 2
302
- * (Visible) from a board cache written before #69, which misnamed it; every current board nulls
303
- * an owner-only territory's armies, and the old cache left level 3 unnamed (`"3"`).
304
- */
305
- export function visibleState(t) {
306
- if (!t || t.armies === null)
307
- return undefined;
308
- if (t.owner.kind !== 'player' && t.owner.kind !== 'neutral')
309
- return undefined;
310
- if (t.fogLevel !== undefined && HIDDEN_FOG.test(t.fogLevel) && !/^\s*owneronly\s*$/i.test(t.fogLevel))
311
- return undefined;
312
- return t;
313
- }
314
- /**
315
- * `t` when a board shows its owner (a player or a neutral), whatever its armies: visible, or
316
- * owner-only (light fog); `undefined` when fogged, even under a placeholder owner.
317
- */
318
- export function ownerShown(t) {
319
- if (!t || (t.owner.kind !== 'player' && t.owner.kind !== 'neutral'))
320
- return undefined;
321
- if (t.fogLevel !== undefined && OWNER_HIDDEN_FOG.test(t.fogLevel))
322
- return undefined;
323
- return t;
324
- }
325
- /** #294: {@link FrontierCoverage} of one opponent on one observed turn. Pure. */
326
- export function frontierCoverage(g, board, previous, playerId) {
327
- const now = new Map(board.territories.map((t) => [t.territoryId, t]));
328
- const before = new Map(previous.territories.map((t) => [t.territoryId, t]));
329
- const its = (id) => {
330
- const st = ownerShown(now.get(id));
331
- return st?.owner.kind === 'player' && st.owner.playerId === playerId;
332
- };
333
- const shownIts = [...g.territoryById.keys()].filter(its);
334
- const frontier = new Set();
335
- let inView = 0;
336
- for (const t of shownIts) {
337
- const ns = neighborsOf(g, t);
338
- if (ns.every(its))
339
- continue;
340
- frontier.add(t);
341
- const a = visibleState(now.get(t));
342
- const b = visibleState(before.get(t));
343
- if (a && b)
344
- inView++;
345
- for (const n of ns)
346
- if (!ownerShown(now.get(n)))
347
- frontier.add(n);
348
- }
349
- let hiddenBonuses = 0;
350
- for (const bonus of g.map.bonuses) {
351
- const ts = bonusTerritories(g, bonus.id);
352
- if (bonus.value <= 0 || !ts.length)
353
- continue;
354
- const taken = ts.some((t) => {
355
- const st = ownerShown(now.get(t));
356
- return st !== undefined && !(st.owner.kind === 'player' && st.owner.playerId === playerId);
357
- });
358
- if (!taken && ts.some((t) => !ownerShown(now.get(t))))
359
- hiddenBonuses++;
360
- }
361
- const share = frontier.size ? inView / frontier.size : shownIts.length ? 1 : 0;
362
- return { inView, frontier: frontier.size, share, hiddenBonuses };
363
- }
364
- /** #294: {@link TrackCoverage} over `turns` (those carrying a coverage); `null` when none does. */
365
- export function trackCoverage(turns) {
366
- const withIt = turns.filter((x) => x.coverage !== undefined);
367
- if (!withIt.length)
368
- return null;
369
- const inView = withIt.reduce((n, x) => n + x.coverage.inView, 0);
370
- const frontier = withIt.reduce((n, x) => n + x.coverage.frontier, 0);
371
- const range = (xs) => ({ min: Math.min(...xs), max: Math.max(...xs) });
372
- return {
373
- turns: withIt.map((x) => x.from),
374
- inView: range(withIt.map((x) => x.coverage.inView)),
375
- frontier: range(withIt.map((x) => x.coverage.frontier)),
376
- share: frontier ? inView / frontier : withIt.reduce((n, x) => n + x.coverage.share, 0) / withIt.length,
377
- hiddenBonuses: withIt.at(-1).coverage.hiddenBonuses,
378
- };
379
- }
380
- /**
381
- * #294: "1 of ~4 frontier territories (25%)" (a range, "1–2 of ~4–5", when the turns differ; the share
382
- * is Σ read ÷ Σ frontier), and ", N bonus(es) it could hold out of view" when any: the words beside a
383
- * tracked figure.
384
- */
385
- export function coverageText(c) {
386
- const b = c.hiddenBonuses;
387
- const range = (r) => (r.min === r.max ? `${r.min}` : `${r.min}–${r.max}`);
388
- return `${range(c.inView)} of ~${range(c.frontier)} frontier territories (${Math.round(c.share * 100)}%)${b ? `, ${b} ${b === 1 ? 'bonus' : 'bonuses'} it could hold out of view` : ''}`;
389
- }
390
- /**
391
- * #226: what my failed attacks on `playerId` killed, by target, on the turn `before` → `after`: each
392
- * move of mine onto a territory it holds on both boards (shown with armies both times), from a
393
- * source mine on both (one that fell may have been taken before my attack ran), kills
394
- * round(armies × the offensive kill rate) — a straight-rounded expectation, which luck can move.
395
- * The board reads that loss as a shrink. The opponent tracker's `measureOrders` counts the same.
396
- */
397
- export function failedAttackKills(g, before, after, me, playerId, orders, rates = {}) {
398
- const offensive = rates.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE;
399
- const out = new Map();
400
- for (const m of failedAttackMoves(g, before, after, me, playerId, orders))
401
- out.set(m.to, (out.get(m.to) ?? 0) + straightKills(Math.max(0, m.armies), offensive));
402
- return out;
403
- }
404
- /**
405
- * The moves {@link failedAttackKills} counts: each move of mine onto a territory `playerId` holds on
406
- * both boards (shown with armies both times), from a source mine on both. #240 review: the armies
407
- * {@link repulsedAttacks} reports are these moves' too, so they match the kills.
408
- */
409
- function failedAttackMoves(g, before, after, me, playerId, orders) {
410
- const was = new Map(before.territories.map((t) => [t.territoryId, t]));
411
- const now = new Map(after.territories.map((t) => [t.territoryId, t]));
412
- const owns = (t, p) => {
413
- const v = visibleState(t);
414
- return v?.owner.kind === 'player' && v.owner.playerId === p;
415
- };
416
- return orders.moves.filter((m) => g.territoryById.has(m.to) &&
417
- owns(was.get(m.from), me) &&
418
- owns(now.get(m.from), me) &&
419
- owns(was.get(m.to), playerId) &&
420
- owns(now.get(m.to), playerId));
421
- }
422
- /**
423
- * #271 review: the territories an order of mine touched that `orders.moves` does not carry, so what
424
- * they held after my orders is not known: a move order in `sent` beyond the plain ones `moves` keeps on
425
- * the same pair (#165 leaves out Transfer Only, Attack Only and percentage orders), both its ends; and
426
- * each territory a card play names (an Airlift's `from` and `to`, a card's `target`).
427
- */
428
- function ordersNotInMoves(orders) {
429
- const out = new Set();
430
- const key = (from, to) => `${from}>${to}`;
431
- const carried = new Map();
432
- for (const m of orders.moves)
433
- carried.set(key(m.from, m.to), (carried.get(key(m.from, m.to)) ?? 0) + 1);
434
- for (const o of orders.sent ?? []) {
435
- const left = carried.get(key(o.from, o.to)) ?? 0;
436
- if (left > 0)
437
- carried.set(key(o.from, o.to), left - 1);
438
- else
439
- out.add(o.from).add(o.to);
440
- }
441
- for (const c of orders.cards ?? [])
442
- for (const id of [c.from, c.to, c.target])
443
- if (id !== undefined)
444
- out.add(id);
445
- return out;
446
- }
447
- /**
448
- * My holds (mine, with armies, on both boards) that lost armies my orders do not explain, by id: the
449
- * defenders were my armies there plus what I deployed there, less what I sent out; what the later
450
- * board shows less (what I moved in from a territory mine on the earlier board counted on top) is what
451
- * an attack on it that failed killed. A hold I attacked out of and failed is skipped: the survivors of
452
- * my own attack came back to it, so its loss is not known. So is a hold an order `moves` does not carry
453
- * touched (#271 review, {@link ordersNotInMoves}: a Transfer Only, Attack Only or percentage order, a
454
- * card play), and a transfer from a source one touched is not surely whole. The opponent tracker's attacks on my holds
455
- * and the #271 bound ({@link repelledFloor}) both read these.
456
- */
457
- export function holdLosses(g, before, after, me, orders, guard = 1) {
458
- const was = new Map(before.territories.map((t) => [t.territoryId, t]));
459
- const now = new Map(after.territories.map((t) => [t.territoryId, t]));
460
- const owns = (t, p) => t?.owner.kind === 'player' && t.owner.playerId === p;
461
- const held = (id) => owns(visibleState(was.get(id)), me) && owns(visibleState(now.get(id)), me);
462
- const deployed = new Map();
463
- for (const d of orders.deploys)
464
- deployed.set(d.territoryId, (deployed.get(d.territoryId) ?? 0) + Math.max(0, d.armies));
465
- const sent = new Map();
466
- const came = new Map();
467
- /** The sources of what `came`, by the hold they sent to. */
468
- const cameFrom = new Map();
469
- const failedFrom = new Set();
470
- const untracked = ordersNotInMoves(orders);
471
- for (const m of orders.moves) {
472
- const armies = Math.max(0, m.armies);
473
- sent.set(m.from, (sent.get(m.from) ?? 0) + armies);
474
- if (held(m.to) && owns(visibleState(was.get(m.from)), me)) {
475
- came.set(m.to, (came.get(m.to) ?? 0) + armies);
476
- if (armies > 0)
477
- cameFrom.set(m.to, (cameFrom.get(m.to) ?? new Set()).add(m.from));
478
- }
479
- if (!owns(visibleState(was.get(m.to)), me) && !owns(visibleState(now.get(m.to)), me))
480
- failedFrom.add(m.from);
481
- }
482
- /**
483
- * #271 review: a source that surely sent all ordered from it ({@link HoldLoss.inflowSure}): mine on
484
- * both boards, no failed attack of mine out of it, nothing moved into it (when that arrived is not
485
- * known), and it shows exactly what my orders leave there. An order sends what is left down to the
486
- * guard, so a loss before it shows only when my orders leave more than the guard there; else only
487
- * when no other player (nor the fog) was beside it to attack or bomb it.
488
- */
489
- const sentWhole = (id) => {
490
- if (!held(id) || failedFrom.has(id) || came.has(id) || untracked.has(id))
491
- return false;
492
- const left = visibleState(was.get(id)).armies + (deployed.get(id) ?? 0) - (sent.get(id) ?? 0);
493
- if (left < 0 || visibleState(now.get(id)).armies !== left)
494
- return false;
495
- if (left > guard)
496
- return true;
497
- return neighborsOf(g, id).every((n) => {
498
- const o = ownerShown(was.get(n))?.owner;
499
- return o !== undefined && (o.kind === 'neutral' || (o.kind === 'player' && o.playerId === me));
500
- });
501
- };
502
- const out = [];
503
- for (const id of [...new Set(after.territories.map((t) => t.territoryId))].sort(byNum)) {
504
- if (!g.territoryById.has(id) || !held(id) || failedFrom.has(id) || untracked.has(id))
505
- continue;
506
- const standing = visibleState(was.get(id)).armies + (deployed.get(id) ?? 0);
507
- const defenders = Math.max(0, standing - (sent.get(id) ?? 0));
508
- const loss = defenders + (came.get(id) ?? 0) - visibleState(now.get(id)).armies;
509
- const inflowSure = [...(cameFrom.get(id) ?? [])].every(sentWhole);
510
- if (loss > 0)
511
- out.push({ territoryId: id, defenders, loss, standing, inflowSure });
512
- }
513
- return out;
514
- }
515
- /**
516
- * #271: a failed attack on a hold of mine is a measurement, the mirror of #226. My loss there
517
- * ({@link holdLosses}: what my orders do not explain) needed at least {@link fewestAttackersToKill}
518
- * attackers (every attacker killing its most, luck included), and without Multi-Attack each army
519
- * moves once, so they all came from its territories beside the hold at the start of the turn: their
520
- * armies then (less the guard) plus what it deployed there. A hold counts only when every neighbour
521
- * showed its owner on the earlier board, every territory of `playerId` beside it showed its armies,
522
- * and `playerId` is the only other player beside it. Over every such hold the bound is the larger of
523
- * the best single hold and all of them together (the attackers summed against the stacks beside any
524
- * of them, each counted once).
525
- * #271 review: a hold reads only when what I moved in surely arrived whole ({@link HoldLoss.inflowSure}),
526
- * so the bound uses the least my orders can have brought. On a turn an opponent may have played a Bomb
527
- * card (`bomb`, {@link bombPossibleOn}), which halves a territory of mine beside the bomber after the
528
- * deploys and reads as an attack, the most it could take (half the stack before any move, rounded up)
529
- * is left out of the loss first. Orders cached without `sent` or `cards` (before they were kept) bound
530
- * nothing: an order `moves` leaves out, or a card play, may have moved armies out of a hold.
531
- */
532
- export function repelledFloor(g, before, after, me, playerId, orders, settings = {}, guard = (settings.oneArmyStandsGuard ?? true) ? 1 : 0, bomb = false) {
533
- const none = { territories: [], attackers: 0, supply: 0, floor: 0 };
534
- // #271 review: orders cached before `sent` and `cards` were kept may have left out an order or a card
535
- // play that moved armies out of a hold: what ran is unknown, so they bound nothing.
536
- if (settings.multiAttack || !orders.sent || !orders.cards)
537
- return none;
538
- const was = new Map(before.territories.map((t) => [t.territoryId, t]));
539
- const sendable = (id) => {
540
- const st = visibleState(was.get(id));
541
- return Math.max(0, st.armies - guard) + specialUnitStrength(st.specialUnits?.filter((u) => u.playerId === playerId));
542
- };
543
- const holds = [];
544
- for (const h of holdLosses(g, before, after, me, orders, guard)) {
545
- if (!h.inflowSure)
546
- continue;
547
- const loss = h.loss - (bomb ? Math.ceil(h.standing / 2) : 0);
548
- if (loss <= 0)
549
- continue;
550
- const ns = neighborsOf(g, h.territoryId);
551
- if (ns.some((n) => !ownerShown(was.get(n))))
552
- continue;
553
- const others = new Set();
554
- const beside = [];
555
- let hidden = false;
556
- for (const n of ns) {
557
- const o = ownerShown(was.get(n)).owner;
558
- if (o.kind !== 'player' || o.playerId === me)
559
- continue;
560
- others.add(o.playerId);
561
- if (o.playerId === playerId) {
562
- if (!visibleState(was.get(n)))
563
- hidden = true;
564
- beside.push(n);
565
- }
566
- }
567
- if (hidden || others.size !== 1 || !others.has(playerId))
568
- continue;
569
- const attackers = fewestAttackersToKill(loss, settings, settings.luckModifier, settings.roundingMode);
570
- if (attackers === null)
571
- continue;
572
- holds.push({ id: h.territoryId, attackers, beside });
573
- }
574
- if (!holds.length)
575
- return none;
576
- const supplyOf = (ids) => [...new Set(ids)].reduce((n, id) => n + sendable(id), 0);
577
- let best = { ...none, territories: holds.map((h) => h.id) };
578
- const all = {
579
- attackers: holds.reduce((n, h) => n + h.attackers, 0),
580
- supply: supplyOf(holds.flatMap((h) => h.beside)),
581
- };
582
- best = { ...best, ...all, floor: Math.max(0, all.attackers - all.supply) };
583
- for (const h of holds) {
584
- const supply = supplyOf(h.beside);
585
- if (h.attackers - supply > best.floor)
586
- best = { ...best, attackers: h.attackers, supply, floor: h.attackers - supply };
587
- }
588
- return best;
589
- }
590
- /**
591
- * #418 (the owner's decision of 2026-11-20: proof may always raise an estimate): the fewest armies that
592
- * can kill `defenders` however the attack is split into orders. One attack of `a` kills at most
593
- * round(a × the best kill rate luck allows) (straight; weighted rounding rounds up a fraction); a split
594
- * gains most per army at the smallest attack, so the most kills per army is the best over small attacks.
595
- */
596
- function fewestAttackersAnySplit(defenders, settings) {
597
- if (defenders <= 0)
598
- return 0;
599
- let perArmy = 0;
600
- for (let a = 1; a <= 20; a++) {
601
- // The most kills `a` attackers can make: the largest k with fewestAttackersToKill(k) ≤ a.
602
- let k = 0;
603
- for (;;) {
604
- const need = fewestAttackersToKill(k + 1, settings, settings.luckModifier, settings.roundingMode);
605
- if (need === null || need > a)
606
- break;
607
- k++;
608
- }
609
- perArmy = Math.max(perArmy, k / a);
610
- }
611
- return perArmy > 0 ? Math.ceil(defenders / perArmy - 1e-9) : null;
612
- }
613
- /**
614
- * #418: a capture with every source army in view proves a minimum deploy. Without Multi-Attack each army
615
- * moves once, so every attacker on a territory it took — and every army that then moved in — came from
616
- * its territories beside the target at the start of the turn: their armies then (less the guard, a
617
- * commander as 7) plus what it deployed on them. What arrived is at least what stands there now plus the
618
- * attacker the last defender surely killed ({@link guaranteedKills} of one), and at least the fewest
619
- * armies that kill every defender however the attack was split ({@link fewestAttackersAnySplit}); what
620
- * that leaves beyond the supply was deployed.
621
- * A capture reads only when: the target was a neutral or mine, shown with its armies, and its now, shown
622
- * with its armies, no special unit on it; every neighbour of the target showed its owner on the earlier
623
- * board and each of its showed its armies (a hidden one may have sent a stack); no other player borders
624
- * the target on either board (it may have worn the defenders down first); and, when the target was mine
625
- * or borders mine, my orders are known in full (`sent` and `cards`) and none of them leaves the target,
626
- * enters it or plays a card on it (a move of mine out of it leaves fewer defenders; an attack of mine in
627
- * kills some first). A Bomb it may have played (`bomb`) halves the defenders first. Over every such
628
- * capture the floor is the larger of the best single capture and all of them together (their attackers
629
- * summed against the stacks beside any of them, each counted once), as {@link repelledFloor} does.
630
- */
631
- export function captureFloor(g, before, after, playerId, settings = {}, guard = (settings.oneArmyStandsGuard ?? true) ? 1 : 0, opts = {}) {
632
- const none = { territories: [], attackers: 0, supply: 0, floor: 0 };
633
- if (settings.multiAttack)
634
- return none;
635
- const was = new Map(before.territories.map((t) => [t.territoryId, t]));
636
- const now = new Map(after.territories.map((t) => [t.territoryId, t]));
637
- const { me, orders } = opts;
638
- const ordersKnown = !!orders?.sent && !!orders.cards;
639
- const touchedByMe = (id) => !ordersKnown ||
640
- orders.sent.some((m) => m.from === id || m.to === id) ||
641
- orders.moves.some((m) => m.from === id || m.to === id) ||
642
- orders.cards.some((c) => c.from === id || c.to === id || c.target === id);
643
- const its = (t) => t?.owner.kind === 'player' && t.owner.playerId === playerId;
644
- const sendable = (id) => {
645
- const st = visibleState(was.get(id));
646
- return Math.max(0, st.armies - guard) + specialUnitStrength(st.specialUnits?.filter((u) => u.playerId === playerId));
647
- };
648
- const lastKill = guaranteedKills(1, settings.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE, settings.luckModifier, settings.roundingMode);
649
- const caps = [];
650
- for (const t of [...after.territories].sort((a, b) => a.territoryId - b.territoryId)) {
651
- const id = t.territoryId;
652
- if (!g.territoryById.has(id))
653
- continue;
654
- const a = visibleState(t);
655
- const b = visibleState(was.get(id));
656
- if (!its(a) || !b || its(b) || a.specialUnits?.length || b.specialUnits?.length)
657
- continue;
658
- const mineBefore = me !== undefined && b.owner.kind === 'player' && b.owner.playerId === me;
659
- if (b.owner.kind !== 'neutral' && !mineBefore)
660
- continue;
661
- const ns = neighborsOf(g, id);
662
- let ok = true;
663
- let bordersMe = false;
664
- const beside = [];
665
- for (const n of ns) {
666
- const o = ownerShown(was.get(n));
667
- if (!o) {
668
- ok = false;
669
- break;
670
- }
671
- for (const side of [o, ownerShown(now.get(n))]) {
672
- if (side?.owner.kind !== 'player' || side.owner.playerId === playerId)
673
- continue;
674
- if (side.owner.playerId === me)
675
- bordersMe = true;
676
- else
677
- ok = false;
678
- }
679
- if (its(o)) {
680
- if (!visibleState(o))
681
- ok = false;
682
- else
683
- beside.push(n);
684
- }
685
- }
686
- if (!ok || ((mineBefore || bordersMe) && touchedByMe(id)))
687
- continue;
688
- const defenders = opts.bomb ? Math.floor(b.armies / 2) : b.armies;
689
- const kill = fewestAttackersAnySplit(defenders, settings);
690
- if (kill === null)
691
- continue;
692
- const attackers = Math.max(kill, a.armies + (defenders > 0 ? lastKill : 0));
693
- caps.push({ id, attackers, beside });
694
- }
695
- if (!caps.length)
696
- return none;
697
- const supplyOf = (ids) => [...new Set(ids)].reduce((n, id) => n + sendable(id), 0);
698
- const all = { attackers: caps.reduce((n, c) => n + c.attackers, 0), supply: supplyOf(caps.flatMap((c) => c.beside)) };
699
- let best = { territories: caps.map((c) => c.id), ...all, floor: Math.max(0, all.attackers - all.supply) };
700
- for (const c of caps) {
701
- const supply = supplyOf(c.beside);
702
- if (c.attackers - supply > best.floor)
703
- best = { ...best, attackers: c.attackers, supply, floor: c.attackers - supply };
704
- }
705
- return best;
706
- }
707
- /** #240: the turns {@link repulsedAttacks} looks back over, ending on the board being planned. */
708
- export const REPULSE_WINDOW = 3;
709
- /** #240: failed, reinforced attacks on one territory within the window that make it repulsed. */
710
- export const REPULSE_MIN = 2;
711
- /**
712
- * #240: repeated failure is evidence. Over my board history (`boards`, the newest being the board
713
- * being planned; consecutive turns only, each with my cached orders — `TurnBoard.orders`, what
714
- * warapp_submit_turn sent), a failed attack of mine on a territory — its owner the same player on
715
- * both boards, my source mine on both ({@link failedAttackKills}) — whose owner reinforced it: its
716
- * armies after plus what my attack killed exceed its armies before (after = before + deploys and
717
- * transfers in − kills). A territory with such an attack on {@link REPULSE_MIN} or more of the last
718
- * {@link REPULSE_WINDOW} turns, still that player's on the newest board, is reported, by id. Kill
719
- * counts are straight-rounded expectations: luck can move them. Pure; unknown orders give nothing.
720
- */
721
- export function repulsedAttacks(g, boards, me, rates = {}) {
722
- const sorted = [...boards].sort((a, b) => a.turn - b.turn);
723
- const newest = sorted[sorted.length - 1];
724
- if (!newest)
725
- return [];
726
- // #240 review: kept per territory and owner, so failed attacks on a territory under an earlier
727
- // owner never hide those under its newest one (the filter below keeps the newest owner's only).
728
- const found = new Map();
729
- for (let i = 0; i + 1 < sorted.length; i++) {
730
- const was = sorted[i];
731
- const now = sorted[i + 1];
732
- if (!was.orders || now.turn !== was.turn + 1 || was.turn < newest.turn - REPULSE_WINDOW)
733
- continue;
734
- const orders = was.orders;
735
- const before = new Map(was.board.territories.map((t) => [t.territoryId, t]));
736
- const after = new Map(now.board.territories.map((t) => [t.territoryId, t]));
737
- const owners = new Set();
738
- for (const m of orders.moves) {
739
- const o = visibleState(before.get(m.to))?.owner;
740
- if (o?.kind === 'player' && o.playerId !== me)
741
- owners.add(o.playerId);
742
- }
743
- for (const p of [...owners].sort(byNum)) {
744
- for (const [t, kills] of [...failedAttackKills(g, was.board, now.board, me, p, orders, rates)].sort(([a], [b]) => a - b)) {
745
- const b = visibleState(before.get(t)).armies;
746
- const a = visibleState(after.get(t)).armies;
747
- if (kills <= 0 || a + kills <= b)
748
- continue;
749
- const armies = failedAttackMoves(g, was.board, now.board, me, p, orders)
750
- .filter((m) => m.to === t)
751
- .reduce((n, m) => n + Math.max(0, m.armies), 0);
752
- // #361: a single-army jab never tries to take it (one army takes no defended territory): no evidence.
753
- if (armies <= 1)
754
- continue;
755
- const attack = { turn: was.turn, armies, before: b, after: a, kills };
756
- const key = `${t}:${p}`;
757
- const entry = found.get(key);
758
- if (!entry)
759
- found.set(key, { territoryId: t, playerId: p, attacks: [attack] });
760
- else
761
- entry.attacks.push(attack);
762
- }
763
- }
764
- }
765
- const latest = new Map(newest.board.territories.map((t) => [t.territoryId, t]));
766
- return [...found.values()]
767
- .filter((r) => {
768
- const o = visibleState(latest.get(r.territoryId))?.owner;
769
- return r.attacks.length >= REPULSE_MIN && o?.kind === 'player' && o.playerId === r.playerId;
770
- })
771
- .sort((a, b) => a.territoryId - b.territoryId);
772
- }
773
- /**
774
- * One opponent's deploy last turn as seen across two boards (issues #57, #69): the *net*
775
- * change of its visible armies plus what it visibly lost attacking, floored at 0. Only
776
- * territories visible on both boards count ({@link visibleState}): one hidden last time
777
- * (fogged, or under a fog level that hid its armies) only came into view, so it is a fog
778
- * reveal whoever holds it now — never growth, never a capture.
779
- * - under it both times: armies now − armies then, shrinks included — a transfer between
780
- * its own territories nets to zero, so it is never read as deploy;
781
- * - taken from another visible owner (another player, me included, or a visible neutral): what
782
- * the capture cost it — the attackers the previous defenders killed at the game's defensive
783
- * kill rate (`straightKills`, as in `armiesToTake`); taken from me (given `context.me`), the
784
- * defenders are the guard I may have left, not my stack last turn (#123, `emptied`: I may have
785
- * attacked out of it) — plus the armies now on it up to what its territories next to it, shown
786
- * on both boards, visibly sent away (their total shrink, each army claimed by one capture only):
787
- * those moved in from a visible source, whose shrink they cancel, so source shrink + destination
788
- * gain nets to the attrition (issue #86). An unchanged visible neighbour sent nothing, so it
789
- * explains nothing. The rest, when a neighbour was hidden on either board, is ambiguous (#123):
790
- * a deploy on a visible source that shrank into it (`reinforced`), or a move out of the fog —
791
- * never income (`fromFog`), still a threat to the borders next to it. With every neighbour in
792
- * view it can only be a deploy on the source.
793
- * - growth on its territory next to a hidden one is ambiguous the same way (`grewFromFog`).
794
- * Ambiguous armies count as deploy while the turn's total stays within {@link ambiguousBound}
795
- * (twice `context.expected`, never past `context.most`); the rest are moves. Without `expected`,
796
- * growth is all deploy and a capture's surplus counts up to `most` (none without it, #86).
797
- * `low` and `high` read every ambiguous army one way or the other (fog moves and the guard, or
798
- * deploys and my stack standing there).
799
- * Not counted: armies it lost on a territory it attacked but did not take. The defender's
800
- * count there also moves with the defender's own deploys and transfers (mine included —
801
- * this board says nothing about my orders), so the loss cannot be read off it; leaving it
802
- * out keeps the figure a lower bound (the failed attack's losses still shrink its source). The
803
- * opponent tracker adds it back when my orders that turn are known (#119, `measureOrders`).
804
- * Given those orders here (`context.myOrders`, #226), the defenders my failed attack killed on a
805
- * territory that stayed its count back into its growth there (`attacked`, `attackKills`): after =
806
- * before + deploy + transfers in − kills, so deploy ≥ after + kills − before — beside the fog an
807
- * ambiguous growth like any other, read as deploy up to the turn's bound. #271: given those orders,
808
- * a failed attack on a hold of mine bounds the deploy from below ({@link repelledFloor}: `deploy`,
809
- * `low` and `high` never below it), and so does a capture with every source army in view (#418,
810
- * {@link captureFloor}: proof may always raise an estimate). A capture also claims, after the visible sources, what its stacks
811
- * in view last turn and hidden now could have sent (`arrivals`: no figure counts them but `high`); a
812
- * capture of a neutral beside the fog that no visible source sent into reads the attackers it needed
813
- * beyond its cost ({@link fewestAttackersToTake}) as ambiguous, deploy up to the bound
814
- * (`unseenAttackers`; the tracker reads a pattern of them as income), the rest a move out of the fog.
815
- * One turn only, not smoothed (the tracker reads a history). Transfers in from (or out to) the
816
- * fog still bias it — income in the fog is unseen anyway.
817
- */
818
- export function observeDeploy(g, board, previous, playerId, rates = {}, context = {}) {
819
- const { signed: _signed, ...o } = observeSigned(g, board, previous, playerId, rates, context);
820
- return o;
821
- }
822
- /**
823
- * {@link observeDeploy} with its total before the floor at 0 (`signed`): the opponent tracker
824
- * adds what my own orders measure (#119) to it before flooring.
825
- */
826
- export function observeSigned(g, board, previous, playerId, rates = {}, context = {}) {
827
- const before = new Map(previous.territories.map((t) => [t.territoryId, t]));
828
- let total = 0;
829
- /** What `low` and `high` differ from `total` by. */
830
- let lowExtra = 0;
831
- let highExtra = 0;
832
- const counted = [];
833
- const captured = [];
834
- const fromFog = [];
835
- let fogArmies = 0;
836
- const reveals = [];
837
- const reinforced = [];
838
- const emptied = [];
839
- let emptiedHigh = 0;
840
- /**
841
- * The ambiguous armies (#123): growth on its held territories next to a hidden one (a stack
842
- * may have walked in) and a capture's surplus over what a visible source that shrank into it
843
- * sent (deploy-then-capture, or a stack out of the fog joined). Read after the loop against
844
- * one bound, the same for both ({@link ambiguousBound}).
845
- */
846
- const ambiguous = [];
847
- const now = new Map(board.territories.map((t) => [t.territoryId, t]));
848
- const defensive = rates.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE;
849
- const guard = Math.max(0, context.guard ?? 1);
850
- // #226: my failed attacks' kills, by target: they count back into its growth there.
851
- const kills = context.me !== undefined && context.myOrders
852
- ? failedAttackKills(g, previous, board, context.me, playerId, context.myOrders, rates)
853
- : new Map();
854
- const killsAt = (id) => kills.get(id) ?? 0;
855
- /** Held by the observed player (`playerId`, not me) and shown with armies on both boards. */
856
- const heldBothTimes = (id) => {
857
- const a = visibleState(now.get(id));
858
- const b = visibleState(before.get(id));
859
- return a?.owner.kind === 'player' && a.owner.playerId === playerId && b?.owner.kind === 'player' && b.owner.playerId === playerId;
860
- };
861
- /**
862
- * What each of its territories shown with armies on both boards visibly sent away (its
863
- * shrink): the most a capture next to it can have received from it. A capture draws on it
864
- * (ascending ids), so two captures never both claim the same armies. What my failed attack killed
865
- * there (#226: these are exactly {@link failedAttackKills}' targets) is a loss, not armies sent
866
- * away, so it is taken out of the shrink.
867
- */
868
- const shrinkLeft = new Map();
869
- for (const t of board.territories)
870
- if (g.territoryById.has(t.territoryId) && heldBothTimes(t.territoryId))
871
- shrinkLeft.set(t.territoryId, Math.max(0, visibleState(before.get(t.territoryId)).armies - t.armies - killsAt(t.territoryId)));
872
- /** Not shown with armies on both boards: armies could have left it unseen. */
873
- const hidden = (id) => !visibleState(now.get(id)) || !visibleState(before.get(id));
874
- // #294: each grown stack's growth split, against its own copy of the shrinks (captures claim theirs below).
875
- // The stacks with no hidden neighbour claim first (what they leave can only be deploy, so a shrink
876
- // taken by a stack beside the fog would turn a move into a false "can only be deploy"), then those
877
- // beside the fog; each in id order, and reported in id order.
878
- const stacks = [];
879
- const shrinkForSplit = new Map(shrinkLeft);
880
- const grown = [...shrinkLeft.keys()]
881
- .sort(byNum)
882
- .map((id) => ({
883
- id,
884
- growth: visibleState(now.get(id)).armies - visibleState(before.get(id)).armies + killsAt(id),
885
- beside: neighborsOf(g, id).some(hidden),
886
- }))
887
- .filter((x) => x.growth > 0);
888
- for (const { id, growth, beside } of [...grown.filter((x) => !x.beside), ...grown.filter((x) => x.beside)]) {
889
- let left = growth;
890
- const moved = [];
891
- for (const n of [...neighborsOf(g, id)].sort(byNum)) {
892
- const can = shrinkForSplit.get(n);
893
- if (!can || !left)
894
- continue;
895
- const take = Math.min(can, left);
896
- shrinkForSplit.set(n, can - take);
897
- left -= take;
898
- moved.push({ from: n, armies: take });
899
- }
900
- stacks.push({ territoryId: id, growth, moved, fog: beside ? left : 0, deploy: beside ? 0 : left });
901
- }
902
- stacks.sort((a, b) => a.territoryId - b.territoryId);
903
- /**
904
- * #271 (3): its territories shown with armies on the earlier board and hidden on the later one: what
905
- * each could have sent (its armies less the guard), the most a capture beside it can have received
906
- * from it. Claimed after `shrinkLeft`, in ascending ids, each army once.
907
- * #271 review, a known under-read: a stack hidden now is claimed whether or not it emptied, and it is
908
- * usually hidden because the capture took my territory and my sight of it with it. So a real
909
- * deploy-then-capture beside a source in view both times and such a stack reads its surplus as an
910
- * arrival (counted only in `high`), not deploy. Accepted: a merge read as deploy once read +45.
911
- */
912
- const hiddenLeft = new Map();
913
- for (const t of previous.territories) {
914
- const b = visibleState(t);
915
- if (!g.territoryById.has(t.territoryId) || b?.owner.kind !== 'player' || b.owner.playerId !== playerId)
916
- continue;
917
- if (!visibleState(now.get(t.territoryId)))
918
- hiddenLeft.set(t.territoryId, Math.max(0, b.armies - guard));
919
- }
920
- let arrivals = 0;
921
- const unseenAttackers = [];
922
- let unseenAttackerArmies = 0;
923
- for (const t of [...board.territories].sort((a, b) => a.territoryId - b.territoryId)) {
924
- if (!g.territoryById.has(t.territoryId) || !visibleState(t))
925
- continue;
926
- if (t.owner.kind !== 'player' || t.owner.playerId !== playerId)
927
- continue;
928
- const was = visibleState(before.get(t.territoryId));
929
- if (!was) {
930
- reveals.push(t.territoryId);
931
- continue;
932
- }
933
- counted.push(t.territoryId);
934
- const ns = [...neighborsOf(g, t.territoryId)].sort((a, b) => a - b);
935
- if (was.owner.kind === 'player' && was.owner.playerId === playerId) {
936
- // #226: what my failed attack killed there stood there too: defenders after = before + deploy
937
- // + transfers in − kills.
938
- const growth = t.armies - was.armies + killsAt(t.territoryId);
939
- if (growth > 0 && ns.some(hidden))
940
- ambiguous.push({ id: t.territoryId, armies: growth, kind: 'growth' });
941
- else
942
- total += growth;
943
- }
944
- else {
945
- captured.push(t.territoryId);
946
- // What the capture cost it, always. Taken from me (#123), the defenders were what I left
947
- // there, which this board cannot tell (I may have attacked out of it): priced at the guard,
948
- // my stack last turn the high reading.
949
- if (context.me !== undefined && was.owner.kind === 'player' && was.owner.playerId === context.me) {
950
- const least = straightKills(Math.min(was.armies, guard), defensive);
951
- total += least;
952
- highExtra += straightKills(was.armies, defensive) - least;
953
- emptiedHigh += straightKills(was.armies, defensive) - least;
954
- emptied.push(t.territoryId);
955
- }
956
- else
957
- total += straightKills(was.armies, defensive);
958
- // The armies standing there only as far as a visible source's shrink accounts for them
959
- // (it cancels them). Beyond that, with a neighbour that was hidden on either board: when a
960
- // visible source did shrink into it, the attack came from that stack and the rest was
961
- // deployed on it first (deploy-then-capture, #123); when none did, the rest arrived from
962
- // the fog — a move, not income (#86). With no hidden neighbour, the rest can only be a
963
- // deploy on a visible source before it attacked.
964
- let arrived = t.armies;
965
- let claimed = 0;
966
- for (const n of ns) {
967
- const left = shrinkLeft.get(n);
968
- if (!left || !arrived)
969
- continue;
970
- const take = Math.min(left, arrived);
971
- shrinkLeft.set(n, left - take);
972
- arrived -= take;
973
- claimed += take;
974
- total += take;
975
- }
976
- // #271 (3): its stacks in view last turn beside it, hidden now, may have moved in: arrivals.
977
- let came = 0;
978
- for (const n of ns) {
979
- const left = hiddenLeft.get(n);
980
- if (!left || !arrived)
981
- continue;
982
- const take = Math.min(left, arrived);
983
- hiddenLeft.set(n, left - take);
984
- arrived -= take;
985
- came += take;
986
- }
987
- arrivals += came;
988
- // Had its source stayed put (hidden now, it may have), they were deployed: the high reading.
989
- highExtra += came;
990
- if (arrived > 0 && ns.some(hidden)) {
991
- // #271 (2): a neutral in view needed attackers; what stands there beyond what its stacks in
992
- // view sent, up to what that need leaves standing, came from out of sight.
993
- let unseen = 0;
994
- if (was.owner.kind === 'neutral') {
995
- const need = fewestAttackersToTake(was.armies, rates, rates.luckModifier, rates.roundingMode);
996
- const cost = straightKills(was.armies, defensive);
997
- unseen = need === null ? 0 : Math.min(arrived, Math.max(0, need - cost - claimed - came));
998
- if (unseen > 0) {
999
- unseenAttackers.push(t.territoryId);
1000
- // The attackers out of sight: what the capture needed less what came from view
1001
- // (need − claimed − came), within what stands there.
1002
- unseenAttackerArmies += unseen + cost;
1003
- }
1004
- }
1005
- if (claimed > 0)
1006
- ambiguous.push({ id: t.territoryId, armies: arrived, kind: 'capture' });
1007
- else {
1008
- if (unseen > 0)
1009
- ambiguous.push({ id: t.territoryId, armies: unseen, kind: 'needed' });
1010
- const rest = arrived - unseen;
1011
- if (rest > 0) {
1012
- fromFog.push(t.territoryId);
1013
- fogArmies += rest;
1014
- highExtra += rest;
1015
- }
1016
- }
1017
- }
1018
- else
1019
- total += arrived;
1020
- }
1021
- }
1022
- // #123: the ambiguous armies, read as deploy up to one bound on the turn's deploy — the same
1023
- // bound for growth beside the fog and a reinforced capture's surplus, shared in id order —
1024
- // and the rest as moves out of the fog. The low reading takes all of them out, the high one
1025
- // counts all of them.
1026
- const grewFromFog = [];
1027
- let fogGrowth = 0;
1028
- const bound = ambiguousBound(context);
1029
- // Without an expected deploy (a board-only reading), growth is all deploy, as before #123.
1030
- if (bound === null)
1031
- for (const x of ambiguous)
1032
- if (x.kind === 'growth')
1033
- total += x.armies;
1034
- // A board-only reading (neither `expected` nor `most`) has no room at all: a negative total (a
1035
- // stack of its own that shrank into the fog) must not make room for a capture's surplus.
1036
- let room = bound === null && context.most === undefined ? 0 : Math.max(0, (bound ?? Math.max(0, context.most)) - total);
1037
- // #293: under Local Deployment, the territories a bonus pool could have paid into on the turn read
1038
- // (the bonuses it could hold on the earlier board); growth beside the fog elsewhere draws on `freeLeft`.
1039
- const local = rates.localDeployments === true && bound !== null && context.localFree !== undefined;
1040
- const pooledOn = new Set();
1041
- if (local)
1042
- for (const b of g.map.bonuses) {
1043
- if (b.value <= 0)
1044
- continue;
1045
- const ts = bonusTerritories(g, b.id);
1046
- const possible = ts.every((t) => {
1047
- const o = ownerShown(before.get(t))?.owner;
1048
- return o === undefined || (o.kind === 'player' && o.playerId === playerId);
1049
- });
1050
- if (possible)
1051
- for (const t of ts)
1052
- pooledOn.add(t);
1053
- }
1054
- let freeLeft = Math.max(0, context.localFree ?? 0);
1055
- const localCut = [];
1056
- // #293 review: a walled growth's walk draws on the shrink the captures left (`shrinkLeft`, after
1057
- // the capture loop), less what the other grown stacks' splits took (their growth already nets it),
1058
- // in ascending ids: one claim pass, so one neighbour's shrink never offsets a capture and a walk both.
1059
- const walled = (x) => local && x.kind === 'growth' && !pooledOn.has(x.id);
1060
- const walkLeft = new Map(shrinkLeft);
1061
- if (local) {
1062
- const walledIds = new Set(ambiguous.filter(walled).map((x) => x.id));
1063
- for (const st of stacks)
1064
- if (!walledIds.has(st.territoryId))
1065
- for (const m of st.moved)
1066
- walkLeft.set(m.from, Math.max(0, (walkLeft.get(m.from) ?? 0) - m.armies));
1067
- }
1068
- for (const x of [...ambiguous].sort((a, b) => a.id - b.id)) {
1069
- if (bound === null && x.kind === 'growth') {
1070
- lowExtra -= x.armies;
1071
- continue;
1072
- }
1073
- // #293: a walk from a neighbour in view (the growth split) nets its shrink; the rest is deploy only
1074
- // as far as the free income still reaches.
1075
- const isWalled = walled(x);
1076
- let walk = 0;
1077
- if (isWalled)
1078
- for (const n of [...neighborsOf(g, x.id)].sort(byNum)) {
1079
- const can = walkLeft.get(n);
1080
- if (!can || walk >= x.armies)
1081
- continue;
1082
- const take = Math.min(can, x.armies - walk);
1083
- walkLeft.set(n, can - take);
1084
- walk += take;
1085
- }
1086
- total += walk;
1087
- room = Math.max(0, room - walk);
1088
- const deployed = Math.min(x.armies - walk, room, isWalled ? freeLeft : Infinity);
1089
- if (isWalled)
1090
- freeLeft -= deployed;
1091
- room -= deployed;
1092
- total += deployed;
1093
- lowExtra -= deployed;
1094
- const moved = x.armies - walk - deployed;
1095
- if (isWalled && moved > 0)
1096
- localCut.push(x.id);
1097
- highExtra += moved;
1098
- if (x.kind === 'capture') {
1099
- if (deployed > 0)
1100
- reinforced.push(x.id);
1101
- if (moved > 0)
1102
- fromFog.push(x.id);
1103
- }
1104
- else if (x.kind === 'needed') {
1105
- if (moved > 0 && !fromFog.includes(x.id))
1106
- fromFog.push(x.id);
1107
- }
1108
- else if (moved > 0) {
1109
- grewFromFog.push(x.id);
1110
- fogGrowth += moved;
1111
- }
1112
- fogArmies += moved;
1113
- }
1114
- fromFog.sort((a, b) => a - b);
1115
- // #271 (1): a failed attack on a hold of mine bounds its deploy from below, fog or not.
1116
- const repelled = context.me !== undefined && context.myOrders
1117
- ? repelledFloor(g, previous, board, context.me, playerId, context.myOrders, rates, guard, context.bomb === true)
1118
- : { territories: [], floor: 0 };
1119
- // #418: a capture with every source army in view proves a minimum deploy, fog or not.
1120
- const proof = captureFloor(g, previous, board, playerId, rates, guard, {
1121
- ...(context.me !== undefined ? { me: context.me } : {}),
1122
- orders: context.myOrders,
1123
- bomb: context.bomb === true,
1124
- });
1125
- const floor = Math.max(repelled.floor, proof.floor);
1126
- return {
1127
- stacks,
1128
- deploy: Math.max(0, total, floor),
1129
- signed: total,
1130
- counted,
1131
- captured,
1132
- fromFog,
1133
- fogArmies,
1134
- reveals,
1135
- reinforced,
1136
- grewFromFog,
1137
- fogGrowth,
1138
- ...(localCut.length ? { localCut: { free: Math.max(0, context.localFree ?? 0), territories: localCut } } : {}),
1139
- expected: context.expected ?? null,
1140
- attacked: [...kills.keys()].sort(byNum),
1141
- attackKills: [...kills.values()].reduce((n, k) => n + k, 0),
1142
- emptied,
1143
- emptiedHigh,
1144
- arrivals,
1145
- unseenAttackers,
1146
- unseenAttackerArmies,
1147
- repelled: repelled.territories,
1148
- repelledFloor: repelled.floor,
1149
- proven: proof.territories,
1150
- captureFloor: proof.floor,
1151
- low: Math.max(0, total + lowExtra, floor),
1152
- high: Math.max(0, total + highExtra, floor),
1153
- };
1154
- }
1155
- /**
1156
- * How much more than it was expected to deploy an opponent may earn unseen (#123 review): under
1157
- * fog the visible income reads 2–3× low (#119), so ambiguous armies count as deploy up to twice
1158
- * the expected figure. A one-off stack out of the fog is not read as a phantom income; a steady
1159
- * hidden bonus (as large as the visible income) still is, and the tracker, which raises the
1160
- * expected figure to its carried income, learns a larger one over a few turns.
1161
- */
1162
- export const HIDDEN_INCOME_FACTOR = 2;
1163
- /**
1164
- * The most an opponent's deploy may total once ambiguous armies are counted (#123): twice what
1165
- * it was expected to deploy ({@link HIDDEN_INCOME_FACTOR}), never more than it could earn
1166
- * (`most`). Null without an expected figure: then growth is all deploy and a capture's surplus
1167
- * counts up to `most` (none without it, #86).
1168
- */
1169
- function ambiguousBound(context) {
1170
- if (context.expected === undefined)
1171
- return null;
1172
- const twice = HIDDEN_INCOME_FACTOR * Math.max(0, context.expected);
1173
- return context.most !== undefined ? Math.min(Math.max(0, context.most), twice) : twice;
1174
- }
1175
- /** {@link observeDeploy}'s deploy figure alone. */
1176
- export function observedDeploy(g, board, previous, playerId, rates = {}) {
1177
- return observeDeploy(g, board, previous, playerId, rates).deploy;
1178
- }
1179
- /**
1180
- * The army count every visible player territory holds, when they all hold the same one (the
1181
- * initial allotment). Neutrals are left out (#128): their stacks are not the starting stacks on
1182
- * ordinary maps, so counting them meant this never fired. Only the first turn can be the opening
1183
- * board (#128): with a previous board, or a known turn past the first, equal stacks are a
1184
- * coincidence of the mid-game, and reading them as the opening would drop visible bonuses.
1185
- */
1186
- export function openingArmies(g, board, when = {}) {
1187
- if (when.previous !== undefined || (when.turn !== null && when.turn !== undefined && when.turn > 1))
1188
- return null;
1189
- const counts = new Set();
1190
- for (const t of board.territories)
1191
- if (g.territoryById.has(t.territoryId) && t.armies !== null && t.owner.kind === 'player')
1192
- counts.add(t.armies);
1193
- return counts.size === 1 ? [...counts][0] : null;
1194
- }
1195
- /**
1196
- * #368: an opponent's tracked figure as of each of its last three consecutive observed turns — the most
1197
- * it was seen to earn (`earned`) over that turn and the two before it, the tracker's max-observed window —
1198
- * when it rose on both steps; else `null` (fewer than three consecutive turns, or a step not a rise).
1199
- */
1200
- export function risingTracked(turns) {
1201
- const n = turns.length;
1202
- if (n < 3)
1203
- return null;
1204
- for (let i = n - 2; i < n; i++)
1205
- if (turns[i].from !== turns[i - 1].from + 1)
1206
- return null;
1207
- const asOf = (i) => Math.max(...turns.slice(Math.max(0, i - 2), i + 1).map((x) => x.earned));
1208
- const series = [asOf(n - 3), asOf(n - 2), asOf(n - 1)];
1209
- return series[0] < series[1] && series[1] < series[2] ? series : null;
1210
- }
1211
- /**
1212
- * Per-opponent enemy deploy estimates, one per visible enemy player (sorted by
1213
- * id): base income plus the bonuses that player visibly holds in full, never
1214
- * below max({@link MIN_ENEMY_DEPLOY}, base income). Its stack next to me does not
1215
- * limit it — income held in plain view can all be deployed on my border, however
1216
- * small the stack there. Bonuses in the fog are unseen, so this is what the
1217
- * visible board supports. On the opening board (every visible player territory holds
1218
- * the same count, with no previous board and `when.turn` unknown or the first) every
1219
- * opponent gets the floor.
1220
- */
1221
- export function enemyDeployEstimates(g, board, me, settings = {}, previous, tracks, prior, when = {}) {
1222
- const owner = new Map();
1223
- const armies = new Map();
1224
- const seenNow = new Map();
1225
- for (const t of board.territories)
1226
- if (g.territoryById.has(t.territoryId))
1227
- seenNow.set(t.territoryId, t);
1228
- // Owners count whatever the armies: an owner-only territory (light fog) is visibly held, so
1229
- // it counts toward base income and the bonuses held in full. Only stacks need the armies.
1230
- for (const t of board.territories) {
1231
- if (!g.territoryById.has(t.territoryId) || t.owner.kind !== 'player')
1232
- continue;
1233
- owner.set(t.territoryId, t.owner.playerId);
1234
- if (t.armies !== null)
1235
- armies.set(t.territoryId, t.armies);
1236
- }
1237
- const players = [...new Set([...owner.values()].filter((p) => p !== me))].sort(byNum);
1238
- const opening = openingArmies(g, board, { turn: when.turn, previous }) !== null;
1239
- // #164: under No, Light and Dense fog every owner shows, so income is exact — when this board
1240
- // shows every territory's owner too (the setting is a name, never compared by position).
1241
- const ownersAll = when.fog !== undefined &&
1242
- OWNERS_SHOWN_FOG.has(when.fog) &&
1243
- g.map.territories.every((t) => ownerShown(seenNow.get(t.id)) !== undefined);
1244
- const minimum = Math.max(0, Math.floor(settings.baseIncome ?? DEFAULT_BASE_INCOME));
1245
- const per = settings.bonusArmyPer ?? 0;
1246
- // #418: my income on the board (cards aside) and my armies in view, against which a rising track is weighed.
1247
- const myLand = new Set();
1248
- let myArmies = 0;
1249
- for (const [t, p] of owner)
1250
- if (p === me) {
1251
- myLand.add(t);
1252
- myArmies += armies.get(t) ?? 0;
1253
- }
1254
- const myBoardIncome = boardIncome(g, myLand, { base: minimum, per }).total;
1255
- return players.map((playerId) => {
1256
- // Its visible territories are a lower bound on what it holds, so on its
1257
- // per-territory income too.
1258
- const theirs = new Set();
1259
- for (const [t, p] of owner)
1260
- if (p === playerId)
1261
- theirs.add(t);
1262
- const held = theirs.size;
1263
- const base = territoryIncome(held, minimum, per);
1264
- // The one income rule (#85) over what it visibly holds; `bonusIncome` is what it adds to the base.
1265
- const bonusIncome = boardIncome(g, theirs, { base: minimum, per }).total - base;
1266
- let adjacent = 0;
1267
- let any = 0;
1268
- for (const [t, p] of owner) {
1269
- if (p !== playerId)
1270
- continue;
1271
- const a = armies.get(t);
1272
- if (a === undefined)
1273
- continue;
1274
- any = Math.max(any, a);
1275
- if (neighborsOf(g, t).some((n) => owner.get(n) === me))
1276
- adjacent = Math.max(adjacent, a);
1277
- }
1278
- const largestStack = adjacent || any;
1279
- // Every opponent earns at least the game's base income (never below the 5 minimum), and
1280
- // never less than the bonuses it visibly holds: its stack next to me limits neither.
1281
- const floor = Math.max(MIN_ENEMY_DEPLOY, base);
1282
- const visible = opening ? floor : Math.max(floor, base + bonusIncome);
1283
- // What it was seen to deploy is cut only by what it could earn
1284
- // (#69): its base plus every bonus none of whose territories someone else visibly holds
1285
- // (an owner-only territory is visibly held: its owner shows). Both come from this board,
1286
- // so a bonus it lost since last turn is out, though it may have paid for that deploy.
1287
- let possible = 0;
1288
- /** #235: of `possible`, the bonuses it visibly holds in full (no share of them goes to another). */
1289
- let possibleOwn = 0;
1290
- for (const b of g.map.bonuses) {
1291
- const ts = bonusTerritories(g, b.id);
1292
- if (b.value <= 0 || !ts.length)
1293
- continue;
1294
- const taken = ts.some((t) => {
1295
- const st = ownerShown(seenNow.get(t));
1296
- return st !== undefined && !(st.owner.kind === 'player' && st.owner.playerId === playerId);
1297
- });
1298
- if (!taken)
1299
- possible += b.value;
1300
- if (!taken && ts.every((t) => theirs.has(t)))
1301
- possibleOwn += b.value;
1302
- }
1303
- // #226: with per-territory income, the territories it could hold pay at the rate: its visible
1304
- // ones and every one whose owner this board hides (it may hold any of them).
1305
- const couldHold = per > 0
1306
- ? g.map.territories.filter((t) => {
1307
- const st = ownerShown(seenNow.get(t.id));
1308
- return st === undefined || (st.owner.kind === 'player' && st.owner.playerId === playerId) || theirs.has(t.id);
1309
- }).length
1310
- : held;
1311
- const couldEarn = territoryIncome(couldHold, minimum, per) + possible;
1312
- // #119: the fog prior. In a symmetric-start 1v1 an opponent bordering the fog earns at least
1313
- // what I earn, capped at what it could earn on this board. It only ever raises the figure.
1314
- const fogBeside = [...theirs].some((t) => neighborsOf(g, t).some((n) => !ownerShown(seenNow.get(n))));
1315
- // #166: with its starts proven, its opening simulated from them raises the prior when it earns
1316
- // more than I do; never lowers it (the simulation is a simple player, and #119's evidence read low).
1317
- const priorBase = Math.max(prior?.myIncome ?? 0, prior?.opening?.get(playerId) ?? 0);
1318
- // #235: in a free-for-all the hidden part of the board is shared: an even share of the hidden
1319
- // territories and of the bonuses it could still hold (its own in full), never above couldEarn.
1320
- const k = prior?.format === 'ffa' && (prior.opponents ?? 0) > 1 ? prior.opponents : 0;
1321
- const priorCap = prior && k > 0
1322
- ? Math.min(couldEarn, territoryIncome(held + Math.ceil((couldHold - held) / k), minimum, per) + possibleOwn + Math.ceil((possible - possibleOwn) / k))
1323
- : null;
1324
- const priorFull = prior && fogBeside ? Math.min(Math.max(0, Math.floor(priorBase)), priorCap ?? couldEarn) : null;
1325
- // #444: incomes other players stated scale this one's prior down by their ratio to mine (never up).
1326
- const statedRatio = prior?.stated && !prior.stated.players.some((x) => x.id === playerId) ? prior.stated.ratio : null;
1327
- const priorFigure = priorFull !== null && statedRatio !== null ? Math.min(priorFull, Math.ceil(priorFull * statedRatio - 1e-9)) : priorFull;
1328
- // #419: the past winners' pace, as the prior is figured (capped, scaled, only beside the fog), when above it.
1329
- const paceIncome = prior?.winnerPace ? fogPaceIncome(prior.winnerPace, prior.myIncome) : null;
1330
- const paceFull = paceIncome !== null && fogBeside && paceIncome > priorBase ? Math.min(paceIncome, priorCap ?? couldEarn) : null;
1331
- const paceFigure = paceFull !== null && statedRatio !== null ? Math.min(paceFull, Math.ceil(paceFull * statedRatio - 1e-9)) : paceFull;
1332
- const paceTop = paceFigure !== null && priorFigure !== null && paceFigure > priorFigure ? paceFigure : null;
1333
- // A track over enough turns replaces the single-turn observed figure (S3).
1334
- const track = tracks?.find((t) => t.playerId === playerId);
1335
- const usable = track && track.income !== null && track.turns.length >= TRACKED_MIN_TURNS ? track : undefined;
1336
- const tracked = usable ? usable.income : null;
1337
- // #235 review: does the track end on this board? Its newest observed turn then ends at the turn
1338
- // being planned (the newest board's turn, when that is not given: tracks end on `board`).
1339
- const newestTurn = when.turn ?? usable?.lastTurn ?? null;
1340
- const newest = usable?.turns.at(-1);
1341
- const trackEndsNow = newest !== undefined && newest.to === newestTurn;
1342
- // #123: what it was expected to deploy before this observation (its visible income, and its
1343
- // tracked income when it has a usable track, else the prior): ambiguous armies beyond twice that
1344
- // are moves out of the fog ({@link ambiguousBound}); a capture from me is priced at the guard.
1345
- // With a track the prior stays out of the bound, and the reading is no part of the estimate
1346
- // (#235 1c): the track replaces it. A track that ends on this board has read the newest turn
1347
- // already, so the turn is read with that track's own bound (`ObservedTurn.expected`), and the
1348
- // rationale's observed line agrees with the tracker and with the label below.
1349
- const trackBound = trackEndsNow ? newest.expected : undefined;
1350
- const observation = previous
1351
- ? observeDeploy(g, board, previous, playerId, settings, {
1352
- me,
1353
- guard: (settings.oneArmyStandsGuard ?? true) ? 1 : 0,
1354
- expected: Math.max(visible, trackBound ?? tracked ?? priorFull ?? 0),
1355
- most: couldEarn,
1356
- // #293: under Local Deployment, growth beside the fog outside every bonus it could hold is
1357
- // deploy only up to its free income.
1358
- ...(settings.localDeployments
1359
- ? { localFree: localFreeOn(base, MIN_ENEMY_DEPLOY, when.reinforcement ?? settings.opponentReinforcement, when.turn == null ? null : when.turn - 1) }
1360
- : {}),
1361
- ...(when.previousOrders ? { myOrders: when.previousOrders } : {}),
1362
- // #271 review: the turn read is the one before the turn planned.
1363
- ...(bombPossibleOn(settings, when.turn == null ? null : when.turn - 1) ? { bomb: true } : {}),
1364
- })
1365
- : null;
1366
- // #235 1c: the track's newest turn, when it ends on this board and its bound cut armies that
1367
- // arrived beside the fog (or joined a capture): what that turn reads with them all as deploys.
1368
- // A label only: a stack walking in is not income (#123 lesson 5), so the estimate stays.
1369
- const newestCut = trackEndsNow && newest.high > newest.raw && (newest.grewFromFog.length > 0 || newest.reinforced.length > 0)
1370
- ? {
1371
- from: newest.from,
1372
- to: newest.to,
1373
- observed: newest.observed,
1374
- reading: Math.min(newest.high, newest.cap),
1375
- expected: newest.expected ?? null,
1376
- }
1377
- : null;
1378
- const observedCap = observation ? couldEarn : null;
1379
- const observedRaw = observation?.deploy ?? null;
1380
- const observed = observation ? Math.min(observation.deploy, observedCap) : null;
1381
- // A usable track replaces the single-turn observed figure (S3; #235 1c: its newest reading too).
1382
- const seenSource = tracked !== null
1383
- ? tracked > visible
1384
- ? 'tracked'
1385
- : 'visible'
1386
- : observed !== null && observed > visible
1387
- ? 'observed'
1388
- : 'visible';
1389
- const seen = seenSource === 'tracked' ? tracked : seenSource === 'observed' ? observed : visible;
1390
- // #235: the prior shrinks toward that evidence: the more consecutive observed turns, and the more
1391
- // of its edge in view, the less of its lead it keeps.
1392
- let priorBlend = null;
1393
- if (priorFigure !== null && usable) {
1394
- const toward = Math.max(tracked, visible);
1395
- if (priorFigure > toward) {
1396
- // The consecutive observed turns up to the newest board; a run that stopped earlier is none.
1397
- let turns = trackEndsNow ? 1 : 0;
1398
- const run = usable.turns;
1399
- for (let i = run.length - 1; turns > 0 && i > 0 && run[i - 1].from === run[i].from - 1; i--)
1400
- turns++;
1401
- const edge = new Set();
1402
- for (const t of theirs)
1403
- for (const n of neighborsOf(g, t))
1404
- if (!theirs.has(n))
1405
- edge.add(n);
1406
- const edgeShare = edge.size ? [...edge].filter((n) => ownerShown(seenNow.get(n)) !== undefined).length / edge.size : 0;
1407
- // #294: each turn of the run weighs what it read of its frontier (this board's edge for a turn
1408
- // that carries no coverage).
1409
- const evidence = run.slice(run.length - turns).reduce((n, x) => n + (x.coverage?.share ?? edgeShare), 0);
1410
- const share = turns ? evidence / turns : edgeShare;
1411
- const weight = PRIOR_EVIDENCE_TURNS / (PRIOR_EVIDENCE_TURNS + evidence);
1412
- const figure = toward + Math.ceil(weight * (priorFigure - toward) - 1e-9);
1413
- priorBlend = { prior: priorFigure, toward, turns, share, weight, figure };
1414
- }
1415
- }
1416
- const priorUsed = priorBlend ? priorBlend.figure : priorFigure;
1417
- // #164: with every owner shown, its income is base + held bonuses exactly; a deploy above it was
1418
- // a card (or armies the board misread), never income.
1419
- const exact = ownersAll && !opening ? Math.max(0, base + bonusIncome) : null;
1420
- const source = exact !== null ? 'exact' : priorUsed !== null && priorUsed > seen ? 'prior' : seenSource;
1421
- // #294: what its tracked figure was read from (#368: while that is little, thin evidence below).
1422
- const coverage = usable ? trackCoverage(usable.turns.filter((x) => usable.incomeTurns.includes(x.from))) : null;
1423
- // #444: an untracked opponent whose prior a stated income scaled: #368's midpoint between what is in
1424
- // view (or observed) and that prior.
1425
- const statedMid = statedRatio !== null && source === 'prior' && !usable ? seen + Math.ceil((priorUsed - seen) / 2 - 1e-9) : null;
1426
- const chosen = source === 'exact' ? exact : source === 'prior' ? (statedMid ?? priorUsed) : seen;
1427
- // #368 (owner decision of 2026-11-19: on a hidden opponent, choose the middle until we learn
1428
- // otherwise): thin evidence — its tracked figure read from under LOW_COVERAGE of its frontier —
1429
- // sizes it for the midpoint between the lower bound (what is in view or tracked, raised to the
1430
- // trend's next step when its tracked figure rose two turns running, #418: unless I lead it on armies
1431
- // in view and on income — above its tracked figure, or with LEAD_ARMIES × its armies above what it
1432
- // earned before the newest rise) and the upper bound (the fog
1433
- // prior whole, else the most it could earn), moved toward what the evidence gives as the coverage
1434
- // nears LOW_COVERAGE. A rising track read from more of its frontier only raises the estimate to that
1435
- // lower bound. Never the maximum.
1436
- let thinEvidence = null;
1437
- if (source !== 'exact' && usable && tracked !== null) {
1438
- // #418: no trend step on an opponent I lead on income (its tracked figure) and on armies in view.
1439
- // #418 review: with LEAD_ARMIES × its armies in view, the income lead is judged against what it
1440
- // earned before the newest rise (or its visible income) instead: an over-read tracked figure must
1441
- // not switch off the gate meant to stop it. (On that judgement alone, with a bare army lead, the
1442
- // calibration lost 3 of 4 changed samples further below truth.)
1443
- let theirArmies = 0;
1444
- for (const t of theirs)
1445
- theirArmies += armies.get(t) ?? 0;
1446
- const risen = risingTracked(usable.turns);
1447
- const leadIt = risen !== null &&
1448
- myArmies > theirArmies &&
1449
- (myBoardIncome > Math.max(visible, tracked) || (myArmies >= LEAD_ARMIES * theirArmies && myBoardIncome > Math.max(visible, risen[1])));
1450
- const rising = leadIt ? null : risen;
1451
- const thinCoverage = coverage !== null && coverage.share < LOW_COVERAGE;
1452
- if (thinCoverage || rising) {
1453
- const trend = rising ? Math.min(couldEarn, rising[2] + Math.ceil((rising[2] - rising[0]) / 2 - 1e-9)) : null;
1454
- const lower = Math.min(couldEarn, Math.max(visible, tracked, trend ?? 0));
1455
- // #419: the top of its range is the larger of the prior and the past winners' pace.
1456
- const upper = Math.max(lower, Math.min(couldEarn, paceTop ?? priorFigure ?? couldEarn));
1457
- const midpoint = lower + Math.ceil((upper - lower) / 2 - 1e-9);
1458
- // What the evidence gives without thin evidence (the track, or #235's prior shrunk toward it),
1459
- // never below the lower bound: the figure meets it at LOW_COVERAGE, so it does not jump there.
1460
- const toward = Math.min(couldEarn, Math.max(lower, chosen));
1461
- const weight = thinCoverage ? Math.max(0, 1 - coverage.share / LOW_COVERAGE) : 0;
1462
- const figure = toward + Math.ceil(weight * (midpoint - toward) - 1e-9);
1463
- // Thin coverage: the figure replaces the estimate, up or down. A rising track alone: a raise only.
1464
- if (thinCoverage || figure > chosen)
1465
- thinEvidence = {
1466
- coverage: coverage ? coverage.share : null,
1467
- rising,
1468
- tracked,
1469
- prior: priorFigure,
1470
- trend,
1471
- lower,
1472
- upper,
1473
- midpoint,
1474
- toward,
1475
- weight,
1476
- figure,
1477
- ...(paceTop !== null && prior?.winnerPace
1478
- ? {
1479
- pace: {
1480
- figure: paceTop,
1481
- basis: prior.winnerPace.basis,
1482
- afterTurn: prior.winnerPace.afterTurn,
1483
- games: prior.winnerPace.games,
1484
- ...(prior.winnerPace.ratio !== undefined ? { ratio: prior.winnerPace.ratio } : {}),
1485
- },
1486
- }
1487
- : {}),
1488
- };
1489
- }
1490
- }
1491
- const income = thinEvidence ? thinEvidence.figure : chosen;
1492
- // #368: the figure thin evidence chose names its source: the prior when there is one and the figure
1493
- // lies above the lower bound, else the track.
1494
- const finalSource = thinEvidence
1495
- ? thinEvidence.prior !== null && thinEvidence.figure > thinEvidence.lower
1496
- ? 'prior'
1497
- : 'tracked'
1498
- : source;
1499
- // #164: a Reinforcement card, from the turn the clock says one can be in hand, until a deployment
1500
- // above its income is seen; the next card is due a card's capturing turns after the last one
1501
- // (pieces carry over while a card is held), never before the turn after the play.
1502
- // A play is seen as a deploy (its low reading) above the income that turn: exactly, when every
1503
- // owner shows; under fog only a jump of the card's armies over its visible income counts (a
1504
- // smaller excess may be a bonus the fog hides — and the tracked income then carries the jump).
1505
- const played = [];
1506
- if (when.reinforcement) {
1507
- const above = (low, income) => (exact !== null ? low > income : low >= income + when.reinforcement.armies);
1508
- for (const x of track?.turns ?? [])
1509
- if (above(x.low, x.visibleIncome))
1510
- played.push(x.from);
1511
- // Last turn's deploy was paid by last turn's income: what it held on the previous board (a
1512
- // bonus it lost since paid for it), never below this board's figure.
1513
- if (observation && previous && when.turn !== null && when.turn !== undefined) {
1514
- const before = new Set();
1515
- for (const t of previous.territories)
1516
- if (g.territoryById.has(t.territoryId) && t.owner.kind === 'player' && t.owner.playerId === playerId)
1517
- before.add(t.territoryId);
1518
- const paid = boardIncome(g, before, { base: minimum, per }).total;
1519
- if (above(observation.low, Math.max(exact ?? visible, paid)))
1520
- played.push(when.turn - 1);
1521
- }
1522
- }
1523
- let card = null;
1524
- let cardPlayed = null;
1525
- if (when.reinforcement && when.turn !== null && when.turn !== undefined) {
1526
- const r = when.reinforcement;
1527
- let due = r.firstTurn;
1528
- let cards = 0;
1529
- for (const t of [...new Set(played)].sort(byNum)) {
1530
- if (t < due || t >= when.turn)
1531
- continue;
1532
- cards++;
1533
- cardPlayed = t;
1534
- due = r.turnsPerCard === null ? Infinity : Math.max(t + 1, r.firstTurn + cards * Math.max(1, r.turnsPerCard));
1535
- }
1536
- if (when.turn >= due && r.armies > 0)
1537
- card = { armies: r.armies, due };
1538
- }
1539
- const estimate = income + (card?.armies ?? 0);
1540
- return {
1541
- playerId,
1542
- estimate,
1543
- held,
1544
- base,
1545
- bonusIncome,
1546
- largestStack,
1547
- opening,
1548
- observed,
1549
- observedRaw,
1550
- observedCap,
1551
- couldEarn,
1552
- couldHold,
1553
- observation,
1554
- tracked,
1555
- newestCut,
1556
- trackedTurns: usable ? usable.incomeTurns : [],
1557
- prior: priorFigure,
1558
- priorBlend,
1559
- coverage,
1560
- priorCap,
1561
- fogBeside,
1562
- source: finalSource,
1563
- thinEvidence,
1564
- exact,
1565
- card,
1566
- cardPlayed,
1567
- ...(priorFull !== null && priorFigure < priorFull ? { stated: { full: priorFull, scaled: priorFigure, lower: seen, midpoint: statedMid } } : {}),
1568
- };
1569
- });
1570
- }
1571
- /**
1572
- * Default enemy deploy: the largest {@link enemyDeployEstimates} figure among the
1573
- * players with a stack next to me — visible, or its owner shown and its armies hidden (#164) —
1574
- * at least {@link MIN_ENEMY_DEPLOY}. Pass the turn, fog setting and Reinforcement clock (`when`)
1575
- * and the fog prior {@link planEnemyEstimates} uses, or a mid-game board of equal stacks reads as
1576
- * the opening board (#128), an opponent's card is left out (#164), and the figure disagrees with
1577
- * the planner's. Unlike the planner's, it does not know the teams: a teammate counts.
1578
- */
1579
- export function defaultEnemyDeploy(g, board, me, settings = {}, previous, tracks, prior, when = {}) {
1580
- const mineIds = new Set(board.territories.flatMap((t) => (t.owner.kind === 'player' && t.owner.playerId === me ? [t.territoryId] : [])));
1581
- const next = new Set();
1582
- for (const t of board.territories) {
1583
- if (t.owner.kind !== 'player' || t.owner.playerId === me)
1584
- continue;
1585
- if (t.armies === null && (ownerShown(t) === undefined || visibleState(t)))
1586
- continue;
1587
- if (!g.territoryById.has(t.territoryId))
1588
- continue;
1589
- if (neighborsOf(g, t.territoryId).some((n) => mineIds.has(n)))
1590
- next.add(t.owner.playerId);
1591
- }
1592
- return enemyDeployEstimates(g, board, me, settings, previous, tracks, prior, when).reduce((m, e) => (next.has(e.playerId) ? Math.max(m, e.estimate) : m), MIN_ENEMY_DEPLOY);
1593
- }
1594
- /**
1595
- * This turn's income on the board, cards aside: {@link boardIncome} over the territories `me`
1596
- * holds, cut by the game's army cap (#253, {@link armyCapIncome}: min(income, round(cap × income)
1597
- * − my armies on the board)). warapp_plan_turn and warapp_submit_turn both use it (plus the armies
1598
- * of the card plays in their orders, which the cap leaves alone), so the plan's deploy total is the
1599
- * total the submit check requires.
1600
- */
1601
- export function incomeFor(g, board, me, settings) {
1602
- return incomeDetail(g, board, me, settings).income;
1603
- }
1604
- /**
1605
- * Another player's income from what the board shows, before any army cap: base, bonuses and cities
1606
- * over the territories it visibly holds. The cap is not applied (#253): its fogged armies are
1607
- * unknown, so a cut from its visible armies alone would depend on the fog. My own income is
1608
- * {@link incomeFor}.
1609
- */
1610
- export function visibleIncomeFor(g, board, player, settings) {
1611
- const held = new Set();
1612
- let cities = 0;
1613
- for (const t of board.territories)
1614
- if (g.territoryById.has(t.territoryId) && t.owner.kind === 'player' && t.owner.playerId === player) {
1615
- held.add(t.territoryId);
1616
- cities += t.cities ?? 0;
1617
- }
1618
- return boardIncome(g, held, incomeRules(settings)).total + cityGold(cities, settings);
1619
- }
1620
- /**
1621
- * #332: the gold a commerce game's cities pay each turn (CityIncome each), part of the income like a bonus (the client's
1622
- * income function adds it after base and bonuses, before the army cap). 0 outside a commerce game with city income.
1623
- */
1624
- export function cityGold(cities, settings) {
1625
- const per = commerceRules(settings)?.cityIncome ?? 0;
1626
- return cities > 0 && per > 0 ? cities * per : 0;
1627
- }
1628
- /**
1629
- * {@link incomeFor} with the army cap's arithmetic: `cap` when the game has one and every territory
1630
- * of mine shows its armies (my own always should); `capUnknown` when one does not, and the income is
1631
- * then left uncut. The cap reads my armies from the start-of-turn standing as war.app showed it:
1632
- * callers may pass a board with the award or a prior merged in (livePlanSetup's `board`), which must
1633
- * never change my own territories' armies — a merge that did would move the cap's cut.
1634
- */
1635
- export function incomeDetail(g, board, me, settings) {
1636
- const held = new Set();
1637
- let armies = 0;
1638
- let unread = false;
1639
- let cities = 0;
1640
- for (const t of board.territories) {
1641
- if (!g.territoryById.has(t.territoryId) || t.owner.kind !== 'player' || t.owner.playerId !== me)
1642
- continue;
1643
- held.add(t.territoryId);
1644
- cities += t.cities ?? 0;
1645
- if (t.armies === null)
1646
- unread = true;
1647
- else
1648
- armies += t.armies;
1649
- }
1650
- const income = boardIncome(g, held, incomeRules(settings)).total + cityGold(cities, settings);
1651
- if (settings?.armyCap === undefined || settings.armyCap === null || !(settings.armyCap > 0))
1652
- return { income };
1653
- if (unread)
1654
- return { income, capUnknown: true };
1655
- const cap = armyCapIncome(income, settings.armyCap, armies);
1656
- return { income: cap.received, cap };
1657
- }
285
+ export * from './deploy-estimates.js';