@chrischall/warapp-mcp 0.0.0 → 0.1.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 (177) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +199 -8
  4. package/dist/analysis/award.js +159 -0
  5. package/dist/analysis/bonuses.js +98 -0
  6. package/dist/analysis/breach.js +62 -0
  7. package/dist/analysis/card-support.js +329 -0
  8. package/dist/analysis/card-threats.js +234 -0
  9. package/dist/analysis/cards-in-effect.js +130 -0
  10. package/dist/analysis/chains.js +59 -0
  11. package/dist/analysis/chokepoints.js +140 -0
  12. package/dist/analysis/combat.js +231 -0
  13. package/dist/analysis/commander-safety.js +149 -0
  14. package/dist/analysis/commitments.js +338 -0
  15. package/dist/analysis/exchange.js +155 -0
  16. package/dist/analysis/graph.js +82 -0
  17. package/dist/analysis/guard-off.js +54 -0
  18. package/dist/analysis/guess.js +351 -0
  19. package/dist/analysis/headroom.js +241 -0
  20. package/dist/analysis/hold-diff.js +64 -0
  21. package/dist/analysis/how-lost.js +130 -0
  22. package/dist/analysis/index.js +14 -0
  23. package/dist/analysis/local-deploy.js +159 -0
  24. package/dist/analysis/lookahead.js +108 -0
  25. package/dist/analysis/opponent-profile.js +551 -0
  26. package/dist/analysis/opponents.js +1245 -0
  27. package/dist/analysis/outlook.js +633 -0
  28. package/dist/analysis/overrides.js +60 -0
  29. package/dist/analysis/picks.js +1879 -0
  30. package/dist/analysis/plan/after-leftover.js +140 -0
  31. package/dist/analysis/plan/cap-spend.js +242 -0
  32. package/dist/analysis/plan/captures.js +1195 -0
  33. package/dist/analysis/plan/commander.js +236 -0
  34. package/dist/analysis/plan/completed.js +29 -0
  35. package/dist/analysis/plan/conceded-out.js +131 -0
  36. package/dist/analysis/plan/estimates.js +715 -0
  37. package/dist/analysis/plan/guard-off.js +232 -0
  38. package/dist/analysis/plan/holds.js +1631 -0
  39. package/dist/analysis/plan/leftover.js +760 -0
  40. package/dist/analysis/plan/move-order.js +319 -0
  41. package/dist/analysis/plan/orders.js +317 -0
  42. package/dist/analysis/plan/relations.js +702 -0
  43. package/dist/analysis/plan/report.js +672 -0
  44. package/dist/analysis/plan/shared.js +1218 -0
  45. package/dist/analysis/plan/stand-still.js +823 -0
  46. package/dist/analysis/plan/state.js +44 -0
  47. package/dist/analysis/plan/strike.js +1416 -0
  48. package/dist/analysis/plan/targets.js +651 -0
  49. package/dist/analysis/plan/team.js +299 -0
  50. package/dist/analysis/plan/threats.js +927 -0
  51. package/dist/analysis/plan/transfers.js +328 -0
  52. package/dist/analysis/plan/util.js +5 -0
  53. package/dist/analysis/plan/vacated.js +285 -0
  54. package/dist/analysis/planner.js +2922 -0
  55. package/dist/analysis/player-record.js +144 -0
  56. package/dist/analysis/player.js +268 -0
  57. package/dist/analysis/profile.js +347 -0
  58. package/dist/analysis/relations.js +1030 -0
  59. package/dist/analysis/schedule.js +88 -0
  60. package/dist/analysis/since-last.js +50 -0
  61. package/dist/analysis/static-seats.js +71 -0
  62. package/dist/analysis/stress.js +577 -0
  63. package/dist/analysis/team-brief.js +151 -0
  64. package/dist/analysis/tripwire.js +644 -0
  65. package/dist/analysis/turn-sim.js +259 -0
  66. package/dist/analysis/whereabouts.js +1109 -0
  67. package/dist/board.js +105 -0
  68. package/dist/bundle.js +117959 -36172
  69. package/dist/cards.js +435 -0
  70. package/dist/chat-cursor.js +135 -0
  71. package/dist/chat.js +192 -0
  72. package/dist/client.js +361 -0
  73. package/dist/config.js +62 -0
  74. package/dist/direct/link.js +102 -0
  75. package/dist/direct/session.js +267 -0
  76. package/dist/direct/transport.js +424 -0
  77. package/dist/guess-salt.js +65 -0
  78. package/dist/hosted.js +24 -0
  79. package/dist/index.js +33 -0
  80. package/dist/join-color.js +140 -0
  81. package/dist/live.js +278 -0
  82. package/dist/map-stats.js +152 -0
  83. package/dist/map-store.js +204 -0
  84. package/dist/move-order.js +141 -0
  85. package/dist/my-games.js +180 -0
  86. package/dist/normalize.js +411 -0
  87. package/dist/open-games.js +537 -0
  88. package/dist/outlook-log.js +138 -0
  89. package/dist/path-lock.js +22 -0
  90. package/dist/pick-list.js +193 -0
  91. package/dist/player-record-store.js +229 -0
  92. package/dist/player-states.js +31 -0
  93. package/dist/profile-store.js +677 -0
  94. package/dist/protocol/bundle.js +375 -0
  95. package/dist/protocol/codec.js +556 -0
  96. package/dist/protocol/decoded.js +12 -0
  97. package/dist/protocol/interp.js +1904 -0
  98. package/dist/protocol/methods.js +531 -0
  99. package/dist/protocol/rpc.js +202 -0
  100. package/dist/push/listener.js +393 -0
  101. package/dist/push/packets.js +66 -0
  102. package/dist/push/socketio.js +333 -0
  103. package/dist/push/websocket.js +179 -0
  104. package/dist/redact.js +62 -0
  105. package/dist/relations-store.js +242 -0
  106. package/dist/replay.js +215 -0
  107. package/dist/scalars.js +28 -0
  108. package/dist/scout.js +346 -0
  109. package/dist/stats.js +269 -0
  110. package/dist/strategy/card-clock.js +185 -0
  111. package/dist/strategy/map-notes.js +128 -0
  112. package/dist/strategy/notes.js +2168 -0
  113. package/dist/team-cards.js +84 -0
  114. package/dist/team-orders.js +150 -0
  115. package/dist/teams.js +19 -0
  116. package/dist/tools/award.js +206 -0
  117. package/dist/tools/begin-turn.js +162 -0
  118. package/dist/tools/board.js +77 -0
  119. package/dist/tools/card-advice.js +256 -0
  120. package/dist/tools/card-effects.js +49 -0
  121. package/dist/tools/card-plays.js +434 -0
  122. package/dist/tools/card-support-advice.js +140 -0
  123. package/dist/tools/chat-inbox.js +146 -0
  124. package/dist/tools/chat.js +483 -0
  125. package/dist/tools/check-plan.js +688 -0
  126. package/dist/tools/commander-check.js +102 -0
  127. package/dist/tools/commitments.js +216 -0
  128. package/dist/tools/common.js +143 -0
  129. package/dist/tools/diplomacy.js +342 -0
  130. package/dist/tools/game.js +126 -0
  131. package/dist/tools/guess-view.js +56 -0
  132. package/dist/tools/healthcheck.js +90 -0
  133. package/dist/tools/hints.js +34 -0
  134. package/dist/tools/how-lost.js +154 -0
  135. package/dist/tools/index.js +142 -0
  136. package/dist/tools/join-game.js +327 -0
  137. package/dist/tools/leave-game.js +181 -0
  138. package/dist/tools/live-context.js +339 -0
  139. package/dist/tools/live.js +404 -0
  140. package/dist/tools/map-stats.js +117 -0
  141. package/dist/tools/map.js +133 -0
  142. package/dist/tools/my-games.js +123 -0
  143. package/dist/tools/open-games.js +104 -0
  144. package/dist/tools/opponents.js +151 -0
  145. package/dist/tools/order-options.js +135 -0
  146. package/dist/tools/picks.js +292 -0
  147. package/dist/tools/profile-hook.js +156 -0
  148. package/dist/tools/profile-opponents.js +121 -0
  149. package/dist/tools/profile-reads.js +99 -0
  150. package/dist/tools/push.js +385 -0
  151. package/dist/tools/relations.js +611 -0
  152. package/dist/tools/resolve.js +45 -0
  153. package/dist/tools/route.js +36 -0
  154. package/dist/tools/scout.js +87 -0
  155. package/dist/tools/session.js +163 -0
  156. package/dist/tools/strategy.js +200 -0
  157. package/dist/tools/stress-opponents.js +83 -0
  158. package/dist/tools/surrender.js +240 -0
  159. package/dist/tools/survival.js +189 -0
  160. package/dist/tools/team-brief.js +266 -0
  161. package/dist/tools/team-source.js +222 -0
  162. package/dist/tools/team.js +182 -0
  163. package/dist/tools/turn.js +2761 -0
  164. package/dist/tools/uncommit.js +160 -0
  165. package/dist/tools/where.js +275 -0
  166. package/dist/tools/write-kit.js +158 -0
  167. package/dist/transport-bridge.js +33 -0
  168. package/dist/trend.js +452 -0
  169. package/dist/version.js +4 -0
  170. package/manifest.json +174 -4
  171. package/mint.yaml +101 -14
  172. package/package.json +11 -6
  173. package/server.json +40 -3
  174. package/skills/warapp-api/SKILL.md +95 -4
  175. package/skills/warapp-api/references/scout.mjs +348 -0
  176. package/skills/warapp-api/scripts/warapp.sh +69 -8
  177. package/skills/warapp-mcp/SKILL.md +969 -21
@@ -0,0 +1,62 @@
1
+ // The breach cost of a border (#275, pattern 2): with the guard off every interior territory may
2
+ // hold 0, so one breach by a large stack puts everything behind the border one move away. Pure and
3
+ // deterministic; ties resolve on ascending ids.
4
+ //
5
+ // The territories a border `t` alone shields are my territories within BREACH_DEPTH (2) steps of it
6
+ // through my holdings that face no enemy themselves (no neighbour of a foe, none in the fog), and
7
+ // whose only front within BREACH_DEPTH steps (through my holdings) is `t`: a territory a second front
8
+ // also reaches is that front's too, so no breach cost is counted twice. Only a hollow territory
9
+ // counts (`hollow`, the caller's test: in the planner, none of my territories beside it, itself
10
+ // included, holds the stack that would come through; a 120-army stack one step behind answers a
11
+ // breach, #214's boards). The cost is the positive
12
+ // bonuses I hold in full with a member among them, leaving out every bonus `t` itself is in (losing
13
+ // `t` breaks those already). The planner adds per-territory income itself.
14
+ import { bonusTerritories } from './bonuses.js';
15
+ import { neighborsOf } from './graph.js';
16
+ /** How far behind a border a breach reaches: the stack takes the border, then walks on. */
17
+ export const BREACH_DEPTH = 2;
18
+ const byNum = (a, b) => a - b;
19
+ /** My territories within `depth` steps of `from` through `holdings` (`from` itself left out). */
20
+ function within(graph, holdings, from, depth) {
21
+ const dist = new Map([[from, 0]]);
22
+ let frontier = [from];
23
+ for (let d = 1; d <= depth; d++) {
24
+ const next = [];
25
+ for (const x of frontier)
26
+ for (const n of neighborsOf(graph, x))
27
+ if (holdings.has(n) && !dist.has(n)) {
28
+ dist.set(n, d);
29
+ next.push(n);
30
+ }
31
+ frontier = next;
32
+ }
33
+ dist.delete(from);
34
+ return dist;
35
+ }
36
+ /**
37
+ * What a breach of my border `t` opens (see the header). `front(x)`: my `x` faces an enemy or the
38
+ * fog. `skip`: territories already counted elsewhere (what losing `t` cuts off, #235). `hollow(x)`:
39
+ * a breach walks into `x` (default: always). Empty when `t` is not mine or not a front.
40
+ */
41
+ export function breachBehind(graph, holdings, front, t, skip = new Set(), hollow = () => true) {
42
+ const none = { ids: [], bonuses: [], income: 0 };
43
+ if (!holdings.has(t) || !front(t))
44
+ return none;
45
+ const ids = [...within(graph, holdings, t, BREACH_DEPTH).keys()]
46
+ .filter((x) => !skip.has(x) && !front(x) && hollow(x))
47
+ .filter((x) => [...within(graph, holdings, x, BREACH_DEPTH).keys()].filter(front).every((y) => y === t))
48
+ .sort(byNum);
49
+ if (!ids.length)
50
+ return none;
51
+ const inside = new Set(ids);
52
+ const bonuses = [];
53
+ for (const b of [...graph.bonusById.values()].sort((a, c) => a.id - c.id)) {
54
+ if (b.value <= 0)
55
+ continue;
56
+ const ts = bonusTerritories(graph, b.id);
57
+ if (!ts.length || ts.includes(t) || !ts.every((x) => holdings.has(x)) || !ts.some((x) => inside.has(x)))
58
+ continue;
59
+ bonuses.push({ id: b.id, value: b.value });
60
+ }
61
+ return { ids, bonuses, income: bonuses.reduce((n, b) => n + b.value, 0) };
62
+ }
@@ -0,0 +1,329 @@
1
+ // Where to play the cards warapp_submit_turn can play but the planner never does (PLAN-TEAMS part D2):
2
+ // Diplomacy on the opponent pressing me hardest when two or more are, Sanctions on the leader, Airlift
3
+ // onto a border of mine or a teammate's that falls without it, and Gift as team support (a territory
4
+ // that completes a teammate's bonus); and (G2) Spy, Reconnaissance and Surveillance only where the fog
5
+ // hides what the plan needs. Advice only: nothing here changes the plan or its orders. Pure and
6
+ // deterministic (ties on ascending id); no I/O.
7
+ //
8
+ // Rules (docs/STRATEGY.md, the wiki's card pages): a Diplomacy card stops attacks between its two
9
+ // players from the turn after it is played; Sanctions cut the target's income from its next turn (a
10
+ // negative percentage raises it); an Airlift lands after the deploys and before every attack, and armies
11
+ // landing on a teammate's territory become the teammate's; a Gift moves a territory and its armies after
12
+ // the airlifts and before the attacks. The card plays' encodings are UNVERIFIED live (V9).
13
+ import { bonusTerritories } from './bonuses.js';
14
+ import { COMMANDER_STRENGTH } from './combat.js';
15
+ import { reader } from './card-threats.js';
16
+ import { neighborsOf } from './graph.js';
17
+ import { ownerShown, visibleState } from './plan/shared.js';
18
+ /**
19
+ * Each opponent in contact with me (a visible stack beside a territory of mine), with the armies my
20
+ * borders must keep against it alone: what a Diplomacy card with it frees. Strongest pressure first
21
+ * (then ascending id).
22
+ */
23
+ export function pressures(cb) {
24
+ const r = reader(cb);
25
+ const by = new Map();
26
+ for (const b of r.ids) {
27
+ if (!r.isMine(b))
28
+ continue;
29
+ const cmd = r.commanderOf(b, (q) => q === cb.me);
30
+ for (const [player, reach] of r.reachByPlayer(b)) {
31
+ const p = by.get(player) ?? { player, armies: 0, takes: [], borders: [] };
32
+ p.borders.push(b);
33
+ p.armies += r.holdNeed(reach, cmd) + (cmd ? COMMANDER_STRENGTH : 0);
34
+ if (r.toTake(r.after(b) + (cmd ? COMMANDER_STRENGTH : 0)) <= reach)
35
+ p.takes.push(b);
36
+ by.set(player, p);
37
+ }
38
+ }
39
+ return [...by.values()].sort((a, b) => b.armies - a.armies || a.player - b.player);
40
+ }
41
+ /**
42
+ * Diplomacy on the opponent pressing me hardest, when two or more opponents are in contact (with
43
+ * one, peace with it is peace with everyone: the card is a truce for nothing). An opponent already at
44
+ * peace with me by a Diplomacy card in force is passed over, and so is a truce partner whose truce
45
+ * already covers every border it touches — unless the card adds protection: the truce is in notice
46
+ * (it ends), or the partner presses a border the truce does not cover. Either way it is said.
47
+ * `undefined` with fewer than two opponents in contact.
48
+ */
49
+ export function diplomacyAdvice(cb, opts = {}) {
50
+ const all = pressures(cb);
51
+ if (all.length < 2)
52
+ return undefined;
53
+ const skipped = [];
54
+ for (const p of all) {
55
+ if (opts.atPeace?.has(p.player)) {
56
+ skipped.push(`player ${p.player}: a Diplomacy card between you is already in force`);
57
+ continue;
58
+ }
59
+ const truce = opts.truces?.find((t) => t.player === p.player);
60
+ let overTruce;
61
+ if (truce) {
62
+ const covered = new Set(truce.coveredMine);
63
+ const open = p.borders.filter((b) => !covered.has(b));
64
+ if (truce.state === 'notice') {
65
+ overTruce = `your truce with player ${p.player} is in notice${truce.endsTurn !== undefined ? ` (it ends turn ${truce.endsTurn})` : ''}, and a Diplomacy card is enforced by the game`;
66
+ }
67
+ else if (open.length) {
68
+ overTruce = `your truce with player ${p.player} does not cover ${open.join(', ')}, which it presses`;
69
+ }
70
+ else {
71
+ skipped.push(`player ${p.player}: your truce already covers every border it presses, so the card adds nothing the truce does not`);
72
+ continue;
73
+ }
74
+ }
75
+ if (p.armies <= 0)
76
+ break;
77
+ const takes = p.takes.length ? `; as the plan leaves them it can take ${p.takes.join(', ')}` : '';
78
+ return {
79
+ player: p.player,
80
+ pressure: p,
81
+ ...(overTruce ? { overTruce } : {}),
82
+ why: `Diplomacy with player ${p.player}: of the ${all.length} opponents beside you it presses hardest — your borders ${p.borders.join(', ')} ` +
83
+ `keep ${p.armies} armies against it alone${takes}.${overTruce ? ` Played on a truce partner because ${overTruce}.` : ''}`,
84
+ skipped,
85
+ };
86
+ }
87
+ return { why: 'Hold the Diplomacy card: no opponent beside you is worth it this turn.', skipped };
88
+ }
89
+ /**
90
+ * Sanctions on the strongest opponent (the leader, or the strongest other player when I lead); with a
91
+ * negative percentage the card raises income, so on me. G2: an opponent in `pass` (a truce partner, a
92
+ * player a Diplomacy card keeps at peace with me) is passed over, its reason stated. `undefined` with no
93
+ * opponent in sight.
94
+ */
95
+ export function sanctionsAdvice(input) {
96
+ const { me, players, percentage } = input;
97
+ if (percentage !== undefined && percentage < 0) {
98
+ return { player: me, why: `Sanctions on yourself: this game's percentage is negative (${Math.round(percentage * 100)}%), so the card raises the target's income.` };
99
+ }
100
+ const ranked = [...players].sort((a, b) => b.strength - a.strength || a.playerId - b.playerId);
101
+ const opponents = ranked.filter((p) => p.playerId !== me);
102
+ if (!opponents.length)
103
+ return undefined;
104
+ const skipped = opponents.flatMap((p) => (input.pass?.has(p.playerId) ? [`player ${p.playerId}: ${input.pass.get(p.playerId)}`] : []));
105
+ const passed = skipped.length ? ` Passed over: ${skipped.join('; ')}.` : '';
106
+ const top = opponents.find((p) => !input.pass?.has(p.playerId));
107
+ if (!top)
108
+ return { why: `Hold the Sanctions card: no opponent in sight is one to sanction.${passed}`, skipped };
109
+ const lead = ranked[0].playerId === me;
110
+ const pct = percentage !== undefined ? ` by ${Math.round(percentage * 100)}%` : '';
111
+ const strongest = top === opponents[0];
112
+ return {
113
+ player: top.playerId,
114
+ why: `Sanctions on player ${top.playerId}: ${lead ? `you lead, and it is the strongest opponent${strongest ? '' : ' left'}` : strongest ? 'it leads' : 'it is the strongest opponent left'} on strength (visible armies + ` +
115
+ `income: ${top.strength}). A sanction cuts its income${pct} from its next turn, so a cut costs the largest player most; play it the turn before you attack.${passed}`,
116
+ ...(skipped.length ? { skipped } : {}),
117
+ };
118
+ }
119
+ /**
120
+ * An Airlift onto a territory that falls this turn without it — mine as the plan leaves it, or (in a
121
+ * team game) a teammate's with the deploys it has entered; never one the plan moves armies out of — from a territory of mine with armies to
122
+ * spare (what stands there after the deploys, less what the plan moves out of it and what it must
123
+ * keep to hold). A commander's territory first, then the most armies at stake, then ascending id; the
124
+ * first one a source can save. `undefined` when none.
125
+ */
126
+ export function airliftAdvice(cb) {
127
+ const r = reader(cb);
128
+ const teammateDeploy = (t) => (cb.board.teammateOrders ?? []).reduce((a, e) => a + (e.orders?.deploys ?? []).filter((d) => d.territoryId === t).reduce((x, d) => x + d.armies, 0), 0);
129
+ const friendOf = (t) => {
130
+ const p = r.ownerOf(t);
131
+ return p !== undefined && cb.friends?.has(p) ? p : undefined;
132
+ };
133
+ const targets = [];
134
+ for (const t of r.ids) {
135
+ const teammate = friendOf(t);
136
+ if (!r.isMine(t) && teammate === undefined)
137
+ continue;
138
+ // A border the plan withdraws from is given up on purpose: no airlift into it.
139
+ if (teammate === undefined && r.outOf(t) > 0)
140
+ continue;
141
+ if (r.state.get(t)?.armies === null)
142
+ continue;
143
+ const reach = r.reachOf(t);
144
+ if (!reach)
145
+ continue;
146
+ const owner = teammate ?? cb.me;
147
+ const commander = r.commanderOf(t, (q) => q === owner);
148
+ const armies = teammate === undefined ? r.after(t) : r.armiesOf(t) + teammateDeploy(t);
149
+ const need = r.holdNeed(reach.reach, commander) - armies;
150
+ if (need <= 0)
151
+ continue;
152
+ targets.push({ id: t, ...(teammate !== undefined ? { teammate } : {}), armies, commander, player: reach.player, reach: reach.reach, need });
153
+ }
154
+ targets.sort((a, b) => Number(b.commander) - Number(a.commander) || b.armies - a.armies || a.id - b.id);
155
+ // What each territory of mine can spare: after the deploys, less the plan's moves out of it, less what it
156
+ // keeps to hold (a commander's own territory keeps its hold too).
157
+ const spare = new Map();
158
+ for (const s of r.ids) {
159
+ if (!r.isMine(s))
160
+ continue;
161
+ const reach = r.reachOf(s)?.reach;
162
+ const keep = Math.max(r.guard, reach === undefined ? 0 : r.holdNeed(reach, r.commanderOf(s, (q) => q === cb.me)));
163
+ const can = Math.min(r.armiesOf(s) + r.deployAt(s) - r.outOf(s), r.after(s)) - keep;
164
+ if (can > 0)
165
+ spare.set(s, can);
166
+ }
167
+ for (const t of targets) {
168
+ let best;
169
+ for (const [s, can] of spare) {
170
+ if (s === t.id || can < t.need)
171
+ continue;
172
+ if (best === undefined || can > spare.get(best) || (can === spare.get(best) && s < best))
173
+ best = s;
174
+ }
175
+ if (best === undefined)
176
+ continue;
177
+ const where = t.teammate !== undefined ? `your teammate ${t.teammate}'s ${t.id}` : `${t.id}`;
178
+ return {
179
+ from: best,
180
+ to: t.id,
181
+ armies: t.need,
182
+ ...(t.teammate !== undefined ? { teammate: t.teammate } : {}),
183
+ player: t.player,
184
+ reach: t.reach,
185
+ commander: t.commander,
186
+ why: `Airlift ${t.need} from ${best} to ${where}${t.commander ? ' (a commander stands there)' : ''}: its ${t.armies} fall to player ${t.player}'s ~${t.reach}, ` +
187
+ `and ${t.armies + t.need} hold; the airlift lands before any attack.` +
188
+ (t.teammate !== undefined ? " The armies become your teammate's, and hold only if your teammate keeps them there: say so in team chat." : ''),
189
+ };
190
+ }
191
+ return undefined;
192
+ }
193
+ /**
194
+ * A Gift as team support: my members of a bonus a teammate is nearer to holding, when giving them
195
+ * completes it (every other member is the teammate's) and I hold enough Gift cards — never a territory
196
+ * with a special unit on it (war.app refuses it) or one the plan moves armies out of. The most valuable
197
+ * bonus first, then ascending id. `undefined` when none.
198
+ */
199
+ export function giftAdvice(cb, shared, gifts) {
200
+ if (gifts <= 0)
201
+ return undefined;
202
+ const r = reader(cb);
203
+ const ok = (t) => !(r.state.get(t)?.specialUnits ?? []).length && r.outOf(t) === 0;
204
+ const best = [...shared]
205
+ .filter((b) => b.nearer !== null && b.nearer !== cb.me && !b.others.length && b.teammates.length === 1 && b.mine.length <= gifts && b.mine.every(ok))
206
+ .sort((a, b) => b.value - a.value || a.bonusId - b.bonusId)[0];
207
+ if (!best)
208
+ return undefined;
209
+ const mate = best.teammates[0].player;
210
+ const borders = best.mine.filter((t) => r.reachOf(t) !== undefined);
211
+ return {
212
+ player: mate,
213
+ bonus: best.bonusId,
214
+ value: best.value,
215
+ territories: [...best.mine],
216
+ why: `Gift ${best.mine.join(', ')} to your teammate ${mate}: it holds every other member of bonus ${best.bonusId}, so the gift completes it ` +
217
+ `(+${best.value} a turn for the team; a bonus pays only the player who holds all of it).` +
218
+ (borders.length ? ` ${borders.join(', ')} ${borders.length === 1 ? 'faces' : 'face'} an opponent: your teammate must hold ${borders.length === 1 ? 'it' : 'them'}.` : ''),
219
+ };
220
+ }
221
+ /**
222
+ * G2: where an information card reveals something the plan needs — never with fog off, and never just
223
+ * to see more. Three needs, read off the board: a border of mine whose neighbour the fog hides (its
224
+ * armies unknown: an opponent may stand there), a bonus I am completing (I hold half its members or more, not all) with
225
+ * a member the fog hides, and an opponent with no territory in view. Spy goes on an unseen opponent, else
226
+ * on the owner shown beside the most hidden stacks next to me; Surveillance on the bonus I am completing
227
+ * that is nearest done (then the most valuable, then ascending id), else the bonus worth the most with a
228
+ * hidden border of mine in it; Reconnaissance on the hidden territory next to the most of mine (then the
229
+ * most armies of mine beside it, then ascending id), else a hidden member of the bonus I am completing.
230
+ * `hold` says, for a card held with nothing to reveal, why it is kept. Pure; ties on ascending id.
231
+ */
232
+ export function intelAdvice(cb, opts) {
233
+ if (opts.fog === 'NoFog' || !opts.held.size)
234
+ return { advice: [], hold: [] };
235
+ const r = reader(cb);
236
+ const hidden = (t) => !visibleState(r.state.get(t));
237
+ const mineNext = (t) => neighborsOf(cb.graph, t).filter((n) => r.isMine(n));
238
+ // A border of mine whose neighbour the fog hides.
239
+ const blind = r.ids
240
+ .filter((t) => !r.isMine(t) && hidden(t) && mineNext(t).length)
241
+ .map((t) => ({ t, next: mineNext(t).length, armies: mineNext(t).reduce((a, n) => a + r.armiesOf(n), 0) }))
242
+ .sort((a, b) => b.next - a.next || b.armies - a.armies || a.t - b.t);
243
+ // A bonus I am completing with a member the fog hides.
244
+ const building = cb.graph.map.bonuses
245
+ .filter((b) => b.value > 0)
246
+ .map((b) => {
247
+ const ts = bonusTerritories(cb.graph, b.id);
248
+ const held = ts.filter((t) => r.isMine(t)).length;
249
+ return { id: b.id, value: b.value, size: ts.length, held, fogged: ts.filter((t) => !r.isMine(t) && hidden(t)) };
250
+ })
251
+ .filter((b) => b.size > 0 && 2 * b.held >= b.size && b.held < b.size && b.fogged.length)
252
+ .sort((a, b) => b.held / b.size - a.held / a.size || b.value - a.value || a.id - b.id);
253
+ // An opponent with no territory in view.
254
+ const inView = new Set(r.ids.flatMap((t) => {
255
+ const s = ownerShown(r.state.get(t));
256
+ return s?.owner.kind === 'player' ? [s.owner.playerId] : [];
257
+ }));
258
+ const unseen = [...opts.opponents].filter((p) => p !== cb.me && !cb.friends?.has(p) && !inView.has(p)).sort((a, b) => a - b);
259
+ // An owner shown beside me whose stack the fog hides (owner-only fog).
260
+ const shownBeside = new Map();
261
+ for (const { t } of blind) {
262
+ const s = ownerShown(r.state.get(t));
263
+ if (s?.owner.kind === 'player' && r.foe(s.owner.playerId))
264
+ shownBeside.set(s.owner.playerId, (shownBeside.get(s.owner.playerId) ?? 0) + 1);
265
+ }
266
+ const hiddenStacks = [...shownBeside].sort((a, b) => b[1] - a[1] || a[0] - b[0])[0];
267
+ const advice = [];
268
+ const hold = [];
269
+ const nothing = (card) => hold.push(`Hold the ${card} card: the fog hides nothing the plan needs this turn (no hidden border of yours, no bonus you are completing with a fogged member, no opponent out of view).`);
270
+ if (opts.held.has('Spy')) {
271
+ if (unseen.length) {
272
+ const p = unseen[0];
273
+ advice.push({ card: 'Spy', player: p, why: `Spy on player ${p}: none of its territories is in view, so its income and stacks are unknown to the plan.` });
274
+ }
275
+ else if (hiddenStacks) {
276
+ const [p, n] = hiddenStacks;
277
+ advice.push({
278
+ card: 'Spy',
279
+ player: p,
280
+ why: `Spy on player ${p}: the fog hides the armies on ${n === 1 ? 'its territory' : `${n} of its territories`} beside yours, so the threat there is a guess.`,
281
+ });
282
+ }
283
+ else
284
+ nothing('Spy');
285
+ }
286
+ if (opts.held.has('Surveillance')) {
287
+ const b = building[0];
288
+ if (b) {
289
+ advice.push({
290
+ card: 'Surveillance',
291
+ bonus: b.id,
292
+ why: `Surveillance on bonus ${b.id}: you hold ${b.held} of its ${b.size} territories and the fog hides ${b.fogged.join(', ')}, so what finishing it costs is a guess.`,
293
+ });
294
+ }
295
+ else {
296
+ const blindSet = new Set(blind.map((x) => x.t));
297
+ const best = cb.graph.map.bonuses
298
+ .filter((x) => x.value > 0)
299
+ .map((x) => ({ id: x.id, value: x.value, n: bonusTerritories(cb.graph, x.id).filter((t) => blindSet.has(t)).length }))
300
+ .filter((x) => x.n > 0)
301
+ .sort((a, c) => c.value - a.value || c.n - a.n || a.id - c.id)[0];
302
+ if (best)
303
+ advice.push({
304
+ card: 'Surveillance',
305
+ bonus: best.id,
306
+ why: `Surveillance on bonus ${best.id} (+${best.value}): the fog hides ${best.n} of its territories beside yours, so who holds it, and what they earn, is a guess.`,
307
+ });
308
+ else
309
+ nothing('Surveillance');
310
+ }
311
+ }
312
+ if (opts.held.has('Reconnaissance')) {
313
+ const x = blind[0];
314
+ if (x) {
315
+ advice.push({
316
+ card: 'Reconnaissance',
317
+ target: x.t,
318
+ why: `Reconnaissance on ${x.t}: it borders ${x.next} of your territories (${x.armies} armies) and the fog hides what stands there.`,
319
+ });
320
+ }
321
+ else if (building[0]) {
322
+ const t = building[0].fogged[0];
323
+ advice.push({ card: 'Reconnaissance', target: t, why: `Reconnaissance on ${t}: a member of bonus ${building[0].id}, which you are completing, hidden by the fog.` });
324
+ }
325
+ else
326
+ nothing('Reconnaissance');
327
+ }
328
+ return { advice, hold };
329
+ }
@@ -0,0 +1,234 @@
1
+ // Cards the planner does not play, read against its plan (#163): my Bomb (where halving a stack
2
+ // changes a hold, a capture or a commander kill, else hold it), an opponent's Bomb (borders that
3
+ // hold only while unbombed), an opponent's Emergency Blockade (attacks that would die against the
4
+ // wall) and my own (a conceded border where the wall kills more than I give up). Pure and
5
+ // deterministic (ties on ascending territory id); no I/O.
6
+ //
7
+ // Rules (the wiki's Bomb_Card, Turn_phases, Emergency Blockade; docs/STRATEGY.md): a Bomb hits a
8
+ // territory next to one of mine after the deployments and before every move, and kills half its
9
+ // armies — a commander is reported unharmed. An Emergency Blockade turns a territory into a
10
+ // neutral of its armies (that turn's deploy included) times the multiplier, before the attacks;
11
+ // special units count for nothing on it. UNVERIFIED: how war.app rounds the half (each side is
12
+ // read in its worst case: a bombed enemy keeps the larger half, a bombed stack of mine the
13
+ // smaller) and the wall (rounded to the nearest army here).
14
+ import { armiesToTake, COMMANDER_STRENGTH, DEFAULT_DEFENSIVE_KILL_RATE, straightKills } from './combat.js';
15
+ import { neighborsOf } from './graph.js';
16
+ import { bonusTerritories } from './bonuses.js';
17
+ /** The common reads over the board and the plan (shared with card-support.ts). */
18
+ export function reader(cb) {
19
+ const state = new Map(cb.board.territories.map((t) => [t.territoryId, t]));
20
+ const guard = cb.settings?.oneArmyStandsGuard === false ? 0 : 1;
21
+ const rates = {
22
+ ...(cb.settings?.offensiveKillRate !== undefined ? { offensiveKillRate: cb.settings.offensiveKillRate } : {}),
23
+ ...(cb.settings?.defensiveKillRate !== undefined ? { defensiveKillRate: cb.settings.defensiveKillRate } : {}),
24
+ };
25
+ const ownerOf = (t) => {
26
+ const o = state.get(t)?.owner;
27
+ return o?.kind === 'player' ? o.playerId : undefined;
28
+ };
29
+ const isMine = (t) => ownerOf(t) === cb.me;
30
+ const foe = (p) => p !== undefined && p !== cb.me && !cb.friends?.has(p);
31
+ const armiesOf = (t) => state.get(t)?.armies ?? 0;
32
+ const commanderOf = (t, who) => (state.get(t)?.specialUnits ?? []).some((u) => u.kind === 'commander' && who(u.playerId));
33
+ const deployAt = (t) => cb.deploys.filter((d) => d.territoryId === t).reduce((a, d) => a + d.armies, 0);
34
+ const outOf = (t) => cb.moves.filter((m) => m.from === t).reduce((a, m) => a + m.armies, 0);
35
+ const transfersInto = (t) => cb.moves.filter((m) => m.to === t && m.kind === 'transfer' && isMine(m.from)).reduce((a, m) => a + m.armies, 0);
36
+ const attacksOn = (t) => cb.moves.filter((m) => m.to === t && m.kind === 'attack').reduce((a, m) => a + m.armies, 0);
37
+ /** My armies on `t` once the plan's deploys and moves have run (captures not counted). */
38
+ const after = (t) => armiesOf(t) + deployAt(t) - outOf(t) + transfersInto(t);
39
+ const toTake = (d) => armiesToTake(d, rates) ?? Infinity;
40
+ const ids = [...state.keys()].sort((a, b) => a - b);
41
+ /**
42
+ * Each opponent's stacks next to `t` plus its deploy (the strongest one), with `bombed` halved by
43
+ * a bomb. The bomb lands after the deploys, so the worst case is taken: an owner with another
44
+ * stack next to `t` deploys there, unhalved (d + ⌈a/2⌉ + the other stacks, less the guards); one
45
+ * whose only stack next to `t` is the bombed one deploys on it, and the deploy is halved with it
46
+ * (⌈(a + d)/2⌉ less the guard).
47
+ */
48
+ const reachOf = (t, bombed) => {
49
+ const by = new Map();
50
+ for (const n of neighborsOf(cb.graph, t)) {
51
+ const p = ownerOf(n);
52
+ if (!foe(p) || state.get(n)?.armies === null)
53
+ continue;
54
+ const e = by.get(p) ?? { others: 0, hasOther: false };
55
+ if (n === bombed)
56
+ e.bombed = armiesOf(n);
57
+ else {
58
+ e.others += Math.max(0, armiesOf(n) - guard);
59
+ e.hasOther = true;
60
+ }
61
+ by.set(p, e);
62
+ }
63
+ const d = cb.enemyDeploy;
64
+ let best;
65
+ for (const [player, e] of [...by].sort((a, b) => a[0] - b[0])) {
66
+ const reach = e.bombed === undefined
67
+ ? d + e.others
68
+ : e.hasOther
69
+ ? d + e.others + Math.max(0, Math.ceil(e.bombed / 2) - guard)
70
+ : Math.max(0, Math.ceil((e.bombed + d) / 2) - guard);
71
+ if (!best || reach > best.reach)
72
+ best = { player, reach };
73
+ }
74
+ return best;
75
+ };
76
+ /** Each opponent's reach at `t` alone (its movable stacks next to `t` plus its deploy), by player. */
77
+ const reachByPlayer = (t) => {
78
+ const by = new Map();
79
+ for (const n of neighborsOf(cb.graph, t)) {
80
+ const p = ownerOf(n);
81
+ if (!foe(p) || state.get(n)?.armies === null)
82
+ continue;
83
+ by.set(p, (by.get(p) ?? cb.enemyDeploy) + Math.max(0, armiesOf(n) - guard));
84
+ }
85
+ return by;
86
+ };
87
+ /** The fewest armies on `t` (its commander there counted apart) that `reach` cannot take. */
88
+ const holdNeed = (reach, commander) => {
89
+ const extra = commander ? COMMANDER_STRENGTH : 0;
90
+ let h = 0;
91
+ while (toTake(h + extra) <= reach)
92
+ h++;
93
+ return h;
94
+ };
95
+ return { state, guard, rates, ownerOf, isMine, foe, armiesOf, commanderOf, deployAt, outOf, transfersInto, attacksOn, after, toTake, ids, reachOf, reachByPlayer, holdNeed };
96
+ }
97
+ const KIND_RANK = { commander: 0, hold: 1, capture: 2 };
98
+ /**
99
+ * Where to play my Bomb this turn: an opponent's territory next to mine where halving its armies
100
+ * plus the owner's deploy (a commander unharmed) makes a commander kill, a hold or a capture that
101
+ * fails without it — in that order, then the bigger stack. Else hold the card: the threat of it
102
+ * keeps the opponent from stacking, and is worth more than a blast that changes nothing.
103
+ */
104
+ export function bombAdvice(cb) {
105
+ const r = reader(cb);
106
+ const best = [];
107
+ for (const t of r.ids) {
108
+ const p = r.ownerOf(t);
109
+ if (!r.foe(p) || r.state.get(t)?.armies === null)
110
+ continue;
111
+ if (cb.noBomb?.has(t))
112
+ continue;
113
+ const borders = neighborsOf(cb.graph, t).filter(r.isMine);
114
+ if (!borders.length)
115
+ continue;
116
+ const n = r.armiesOf(t) + cb.enemyDeploy;
117
+ const left = Math.ceil(n / 2);
118
+ const cmd = r.commanderOf(t, (q) => q === p) ? COMMANDER_STRENGTH : 0;
119
+ const planned = r.attacksOn(t);
120
+ const free = planned + borders.reduce((a, b) => a + Math.max(0, r.after(b) - r.guard), 0);
121
+ const label = `player ${p}'s ${r.armiesOf(t)} + its deploy of ${cb.enemyDeploy} on ${t}`;
122
+ if (cmd > 0 && r.toTake(left + cmd) <= free && r.toTake(n + cmd) > free) {
123
+ best.push({ target: t, kind: 'commander', stake: n, why: `halving ${label} leaves ${left} with its commander, which my ${free} next to it can kill (not the whole ${n})` });
124
+ continue;
125
+ }
126
+ const held = borders.filter((b) => {
127
+ const reach = r.reachOf(b)?.reach ?? 0;
128
+ const bombed = r.reachOf(b, t)?.reach ?? 0;
129
+ const need = r.toTake(r.after(b) + (r.commanderOf(b, (q) => q === cb.me) ? COMMANDER_STRENGTH : 0));
130
+ return need <= reach && need > bombed;
131
+ });
132
+ if (held.length) {
133
+ best.push({ target: t, kind: 'hold', stake: n, why: `halving ${label} leaves too few to take ${held.join(', ')}, which fall${held.length === 1 ? 's' : ''} to it unbombed` });
134
+ continue;
135
+ }
136
+ if (planned > 0 ? r.toTake(n + cmd) > planned && r.toTake(left + cmd) <= planned : r.toTake(left + cmd) <= free && r.toTake(n + cmd) > free) {
137
+ const sent = planned > 0 ? planned : free;
138
+ best.push({ target: t, kind: 'capture', stake: n, why: `halving ${label} lets my ${sent} take it even if the owner deploys there (it needs ${r.toTake(n + cmd)} unbombed)` });
139
+ }
140
+ }
141
+ best.sort((a, b) => KIND_RANK[a.kind] - KIND_RANK[b.kind] || b.stake - a.stake || a.target - b.target);
142
+ const top = best[0];
143
+ if (!top) {
144
+ return {
145
+ why: 'Hold the Bomb: halving no stack next to me changes a hold, a capture or a commander kill this turn, and while I hold it the opponent cannot safely stack.',
146
+ };
147
+ }
148
+ return { target: top.target, kind: top.kind, why: `Bomb ${top.target}: ${top.why}.` };
149
+ }
150
+ /**
151
+ * My borders (after the plan) that hold against the opponent's reach unbombed but fall once a
152
+ * bomb halves them: the bomb lands after my deploys and before every move, so it halves what
153
+ * stands there (moves out are cut from what is left; transfers in still arrive). Ascending id.
154
+ */
155
+ export function bombExposure(cb) {
156
+ const r = reader(cb);
157
+ const out = [];
158
+ for (const b of r.ids) {
159
+ if (!r.isMine(b))
160
+ continue;
161
+ const reach = r.reachOf(b);
162
+ if (!reach)
163
+ continue;
164
+ const cmd = r.commanderOf(b, (q) => q === cb.me);
165
+ const extra = cmd ? COMMANDER_STRENGTH : 0;
166
+ const armies = r.after(b);
167
+ const kept = Math.floor((r.armiesOf(b) + r.deployAt(b)) / 2);
168
+ const bombed = Math.max(0, kept - r.outOf(b)) + r.transfersInto(b);
169
+ if (r.toTake(armies + extra) > reach.reach && r.toTake(bombed + extra) <= reach.reach) {
170
+ out.push({ territory: b, armies, bombed, reach: reach.reach, player: reach.player, commander: cmd });
171
+ }
172
+ }
173
+ return out;
174
+ }
175
+ /** The wall an Emergency Blockade makes of `armies` at `multiplier` (rounded: unverified). */
176
+ const wallOf = (armies, multiplier) => Math.round(Math.max(0, armies) * multiplier);
177
+ /**
178
+ * The planned attacks on an opponent's territory that its Emergency Blockade would stop: the
179
+ * owner turns it into a neutral of (its armies + its deploy) × the multiplier before the attacks,
180
+ * and what I send cannot take that. Ascending target id.
181
+ */
182
+ export function wallThreats(cb, multiplier) {
183
+ const r = reader(cb);
184
+ const out = [];
185
+ for (const t of r.ids) {
186
+ const p = r.ownerOf(t);
187
+ if (!r.foe(p))
188
+ continue;
189
+ const attackers = r.attacksOn(t);
190
+ if (attackers <= 0)
191
+ continue;
192
+ const wall = wallOf(r.armiesOf(t) + cb.enemyDeploy, multiplier);
193
+ if (r.toTake(wall) > attackers)
194
+ out.push({ target: t, player: p, attackers, wall });
195
+ }
196
+ return out;
197
+ }
198
+ /**
199
+ * Where my Emergency Blockade pays: a border the plan concedes, where the wall of my armies there
200
+ * (this turn's deploy included) times the multiplier kills more of the stack that can reach it
201
+ * than the armies I give up — never on my commander's territory (it would be lost with it),
202
+ * never on one the plan moves armies out of (they would be lost with it: the wall comes before the
203
+ * moves) and never on a member of a bonus I hold whole at the start of the turn (I need it). The best by
204
+ * kills over armies given up, then ascending id; `undefined` when none pays.
205
+ */
206
+ export function wallOffer(cb, multiplier, conceded) {
207
+ const r = reader(cb);
208
+ const defence = cb.settings?.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE;
209
+ const held = (id) => cb.graph.map.bonuses.some((bonus) => {
210
+ if (bonus.value <= 0)
211
+ return false;
212
+ const members = bonusTerritories(cb.graph, bonus.id);
213
+ return members.includes(id) && members.every(r.isMine);
214
+ });
215
+ let best;
216
+ for (const c of [...conceded].sort((a, b) => a - b)) {
217
+ // A border the plan withdraws from is skipped: the wall turns it neutral before the moves, so
218
+ // the armies the plan moves out of it would be lost with it.
219
+ if (!r.isMine(c) || r.commanderOf(c, (q) => q === cb.me) || held(c) || r.outOf(c) > 0)
220
+ continue;
221
+ const reach = r.reachOf(c);
222
+ if (!reach)
223
+ continue;
224
+ const givesUp = r.armiesOf(c) + r.deployAt(c);
225
+ const wall = wallOf(givesUp, multiplier);
226
+ const kills = Math.min(reach.reach, straightKills(wall, defence));
227
+ if (kills <= givesUp)
228
+ continue;
229
+ const offer = { territory: c, givesUp, wall, player: reach.player, reach: reach.reach, kills };
230
+ if (!best || kills - givesUp > best.kills - best.givesUp)
231
+ best = offer;
232
+ }
233
+ return best;
234
+ }