@chrischall/warapp-mcp 0.0.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +4 -4
- package/.claude-plugin/plugin.json +2 -2
- package/README.md +211 -9
- package/dist/analysis/accept-surrender.js +56 -0
- package/dist/analysis/award.js +159 -0
- package/dist/analysis/bonuses.js +98 -0
- package/dist/analysis/breach.js +62 -0
- package/dist/analysis/calibrate.js +239 -0
- package/dist/analysis/card-support.js +329 -0
- package/dist/analysis/card-threats.js +234 -0
- package/dist/analysis/cards-in-effect.js +130 -0
- package/dist/analysis/chains.js +59 -0
- package/dist/analysis/chokepoints.js +140 -0
- package/dist/analysis/combat.js +231 -0
- package/dist/analysis/commander-safety.js +149 -0
- package/dist/analysis/commitments.js +338 -0
- package/dist/analysis/exchange.js +155 -0
- package/dist/analysis/finished-game.js +136 -0
- package/dist/analysis/game-lessons.js +217 -0
- package/dist/analysis/graph.js +82 -0
- package/dist/analysis/guard-off.js +54 -0
- package/dist/analysis/guess.js +351 -0
- package/dist/analysis/headroom.js +241 -0
- package/dist/analysis/hold-diff.js +64 -0
- package/dist/analysis/how-lost.js +130 -0
- package/dist/analysis/index.js +14 -0
- package/dist/analysis/local-deploy.js +179 -0
- package/dist/analysis/lookahead.js +108 -0
- package/dist/analysis/opponent-profile.js +552 -0
- package/dist/analysis/opponents.js +1253 -0
- package/dist/analysis/outlook.js +695 -0
- package/dist/analysis/overrides.js +60 -0
- package/dist/analysis/picks.js +1879 -0
- package/dist/analysis/plan/after-leftover.js +140 -0
- package/dist/analysis/plan/cap-spend.js +242 -0
- package/dist/analysis/plan/captures.js +1195 -0
- package/dist/analysis/plan/commander.js +236 -0
- package/dist/analysis/plan/completed.js +29 -0
- package/dist/analysis/plan/conceded-out.js +131 -0
- package/dist/analysis/plan/estimates.js +715 -0
- package/dist/analysis/plan/guard-off.js +232 -0
- package/dist/analysis/plan/holds.js +1631 -0
- package/dist/analysis/plan/leftover.js +760 -0
- package/dist/analysis/plan/move-order.js +319 -0
- package/dist/analysis/plan/orders.js +317 -0
- package/dist/analysis/plan/relations.js +702 -0
- package/dist/analysis/plan/report.js +672 -0
- package/dist/analysis/plan/shared.js +1405 -0
- package/dist/analysis/plan/stand-still.js +823 -0
- package/dist/analysis/plan/state.js +44 -0
- package/dist/analysis/plan/strike.js +1416 -0
- package/dist/analysis/plan/targets.js +651 -0
- package/dist/analysis/plan/team.js +299 -0
- package/dist/analysis/plan/threats.js +1001 -0
- package/dist/analysis/plan/transfers.js +328 -0
- package/dist/analysis/plan/util.js +5 -0
- package/dist/analysis/plan/vacated.js +285 -0
- package/dist/analysis/planner.js +2927 -0
- package/dist/analysis/player-record.js +144 -0
- package/dist/analysis/player.js +268 -0
- package/dist/analysis/profile.js +347 -0
- package/dist/analysis/relations.js +1030 -0
- package/dist/analysis/schedule.js +88 -0
- package/dist/analysis/since-last.js +50 -0
- package/dist/analysis/static-seats.js +71 -0
- package/dist/analysis/stress.js +584 -0
- package/dist/analysis/team-brief.js +151 -0
- package/dist/analysis/tripwire.js +644 -0
- package/dist/analysis/turn-sim.js +259 -0
- package/dist/analysis/whereabouts.js +1112 -0
- package/dist/board.js +105 -0
- package/dist/bundle.js +121082 -36148
- package/dist/calibration-source.js +75 -0
- package/dist/cards.js +435 -0
- package/dist/chat-cursor.js +135 -0
- package/dist/chat.js +265 -0
- package/dist/client.js +439 -0
- package/dist/config.js +62 -0
- package/dist/direct/link.js +102 -0
- package/dist/direct/session.js +267 -0
- package/dist/direct/transport.js +424 -0
- package/dist/finished-store.js +357 -0
- package/dist/guess-salt.js +65 -0
- package/dist/hosted.js +24 -0
- package/dist/index.js +33 -0
- package/dist/join-color.js +140 -0
- package/dist/lessons-store.js +356 -0
- package/dist/live.js +287 -0
- package/dist/map-details.js +127 -0
- package/dist/map-stats.js +160 -0
- package/dist/map-store.js +242 -0
- package/dist/move-order.js +141 -0
- package/dist/my-games.js +218 -0
- package/dist/normalize.js +443 -0
- package/dist/notifications.js +143 -0
- package/dist/open-games.js +537 -0
- package/dist/outlook-log.js +165 -0
- package/dist/path-lock.js +22 -0
- package/dist/pick-list.js +193 -0
- package/dist/player-record-store.js +231 -0
- package/dist/player-states.js +31 -0
- package/dist/profile-store.js +727 -0
- package/dist/protocol/bundle.js +375 -0
- package/dist/protocol/codec.js +556 -0
- package/dist/protocol/decoded.js +12 -0
- package/dist/protocol/interp.js +1904 -0
- package/dist/protocol/methods.js +615 -0
- package/dist/protocol/rpc.js +202 -0
- package/dist/push/listener.js +393 -0
- package/dist/push/packets.js +66 -0
- package/dist/push/socketio.js +333 -0
- package/dist/push/websocket.js +179 -0
- package/dist/redact.js +62 -0
- package/dist/relations-store.js +242 -0
- package/dist/replay.js +227 -0
- package/dist/scalars.js +28 -0
- package/dist/scout.js +346 -0
- package/dist/stats.js +291 -0
- package/dist/strategy/card-clock.js +185 -0
- package/dist/strategy/map-notes.js +128 -0
- package/dist/strategy/notes.js +2223 -0
- package/dist/surrender-pending.js +126 -0
- package/dist/team-cards.js +84 -0
- package/dist/team-orders.js +150 -0
- package/dist/teams.js +19 -0
- package/dist/tools/accept-surrender.js +311 -0
- package/dist/tools/award.js +206 -0
- package/dist/tools/begin-turn.js +162 -0
- package/dist/tools/board.js +77 -0
- package/dist/tools/card-advice.js +256 -0
- package/dist/tools/card-effects.js +49 -0
- package/dist/tools/card-plays.js +434 -0
- package/dist/tools/card-support-advice.js +140 -0
- package/dist/tools/chat-inbox.js +158 -0
- package/dist/tools/chat-read-mark.js +179 -0
- package/dist/tools/chat.js +525 -0
- package/dist/tools/check-plan.js +689 -0
- package/dist/tools/commander-check.js +103 -0
- package/dist/tools/commitments.js +216 -0
- package/dist/tools/common.js +143 -0
- package/dist/tools/diplomacy.js +342 -0
- package/dist/tools/end-of-game.js +384 -0
- package/dist/tools/game.js +151 -0
- package/dist/tools/guess-view.js +56 -0
- package/dist/tools/healthcheck.js +90 -0
- package/dist/tools/hints.js +34 -0
- package/dist/tools/how-lost.js +154 -0
- package/dist/tools/index.js +152 -0
- package/dist/tools/join-game.js +327 -0
- package/dist/tools/leave-game.js +181 -0
- package/dist/tools/live-context.js +339 -0
- package/dist/tools/live.js +404 -0
- package/dist/tools/map-details.js +88 -0
- package/dist/tools/map-stats.js +130 -0
- package/dist/tools/map.js +141 -0
- package/dist/tools/my-games.js +193 -0
- package/dist/tools/notifications.js +484 -0
- package/dist/tools/open-games.js +104 -0
- package/dist/tools/opponents.js +163 -0
- package/dist/tools/order-options.js +135 -0
- package/dist/tools/past-games.js +94 -0
- package/dist/tools/picks.js +305 -0
- package/dist/tools/profile-hook.js +156 -0
- package/dist/tools/profile-opponents.js +121 -0
- package/dist/tools/profile-reads.js +99 -0
- package/dist/tools/push.js +445 -0
- package/dist/tools/relations.js +611 -0
- package/dist/tools/resolve.js +45 -0
- package/dist/tools/route.js +36 -0
- package/dist/tools/scout.js +87 -0
- package/dist/tools/session.js +163 -0
- package/dist/tools/strategy.js +257 -0
- package/dist/tools/stress-opponents.js +83 -0
- package/dist/tools/surrender-pending.js +74 -0
- package/dist/tools/surrender.js +247 -0
- package/dist/tools/survival.js +189 -0
- package/dist/tools/team-brief.js +266 -0
- package/dist/tools/team-source.js +222 -0
- package/dist/tools/team.js +178 -0
- package/dist/tools/turn.js +2825 -0
- package/dist/tools/uncommit.js +160 -0
- package/dist/tools/where.js +300 -0
- package/dist/tools/write-kit.js +164 -0
- package/dist/transport-bridge.js +33 -0
- package/dist/trend.js +577 -0
- package/dist/version.js +4 -0
- package/manifest.json +194 -4
- package/mint.yaml +106 -14
- package/package.json +11 -6
- package/server.json +40 -3
- package/skills/warapp-api/SKILL.md +95 -4
- package/skills/warapp-api/references/scout.mjs +348 -0
- package/skills/warapp-api/scripts/warapp.sh +69 -8
- package/skills/warapp-mcp/SKILL.md +1096 -21
|
@@ -0,0 +1,715 @@
|
|
|
1
|
+
import { holdsSeat } from '../../player-states.js';
|
|
2
|
+
import { isTeamGame, teammatesOf } from '../../teams.js';
|
|
3
|
+
import { bonusTerritories } from '../bonuses.js';
|
|
4
|
+
import { CHAIN_MAX_STEPS } from '../chains.js';
|
|
5
|
+
import { armiesForChance, armiesToTake, DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE, luckFraction, specialUnitStrength, straightKills, winChance, } from '../combat.js';
|
|
6
|
+
import { neighborsOf } from '../graph.js';
|
|
7
|
+
import { OUTLOOK_TURNS } from '../outlook.js';
|
|
8
|
+
import { boardIncome, DEFAULT_BASE_INCOME } from '../player.js';
|
|
9
|
+
import { AHEAD_PRESSURE_FACTOR, captureCost, combatSettings, DECIDED_PAYBACK_MIN, defaultMinWinChance, enemyDeployEstimates, HOLD_FALL_CHANCE, LUCK_WIN_CHANCE, MIN_ENEMY_DEPLOY, minWinChanceOf, ownerShown, PAYBACK_TURNS, PRESSURE_FACTOR, pressureMargin, SECOND_FRONT_LEAD, visibleState, } from './shared.js';
|
|
10
|
+
import { AHEAD_RATIO, BEHIND_RATIO, gameProfile } from '../profile.js';
|
|
11
|
+
import { byNum } from './util.js';
|
|
12
|
+
import { sanctionedIncome } from '../cards-in-effect.js';
|
|
13
|
+
import { truceOf } from './relations.js';
|
|
14
|
+
import { teamFocusOf } from './team.js';
|
|
15
|
+
import { neutralizeSeats, staticSeats } from '../static-seats.js';
|
|
16
|
+
import { commanderPlace } from './commander.js';
|
|
17
|
+
/**
|
|
18
|
+
* The fog prior to apply (#119, {@link EnemyIncomePrior}): only when the game says the start was
|
|
19
|
+
* symmetric (`symmetricStart`), with no teams, and every seated player still playing — a 1v1 (one
|
|
20
|
+
* opponent), or (#226) a free-for-all, where every opponent beside the fog gets the same prior. A
|
|
21
|
+
* game with a player out (eliminated, booted, surrendered) gets none: a survivor may have absorbed
|
|
22
|
+
* its territories, or I may have, so the start no longer says who earns what. Without a player list,
|
|
23
|
+
* only one opponent in sight counts (a 1v1 as far as the board tells). #235: in a free-for-all with
|
|
24
|
+
* no teams (two or more opponents seated) that gets none, `skipped` says why.
|
|
25
|
+
*/
|
|
26
|
+
function fogPrior(board, me, ctx, myIncome) {
|
|
27
|
+
const players = (ctx.players ?? []).filter((p) => holdsSeat(p.state));
|
|
28
|
+
if (isTeamGame(players))
|
|
29
|
+
return { prior: undefined };
|
|
30
|
+
const ffa = players.filter((p) => p.id !== me).length > 1;
|
|
31
|
+
const why = (reason) => ({ prior: undefined, ...(ffa ? { skipped: reason } : {}) });
|
|
32
|
+
if (ctx.symmetricStart !== true)
|
|
33
|
+
return why(ctx.unevenStart ?? 'the game does not say every player started even');
|
|
34
|
+
const out = players.filter((p) => (p.state ?? 'Playing') !== 'Playing' && p.id !== me).sort((a, b) => a.id - b.id);
|
|
35
|
+
if (out.length)
|
|
36
|
+
return why(`${out.map((p) => `player ${p.id} is out (${p.state})`).join(', ')}, and a survivor may have absorbed its territories, so the start no longer says who earns what`);
|
|
37
|
+
const opponents = players.length
|
|
38
|
+
? players.filter((p) => p.id !== me).length
|
|
39
|
+
: new Set(board.territories.flatMap((t) => (t.owner.kind === 'player' && t.owner.playerId !== me ? [t.owner.playerId] : []))).size;
|
|
40
|
+
if (opponents < 1 || (!players.length && opponents !== 1))
|
|
41
|
+
return { prior: undefined };
|
|
42
|
+
return {
|
|
43
|
+
prior: {
|
|
44
|
+
myIncome: Math.max(0, myIncome),
|
|
45
|
+
...(opponents > 1 ? { format: 'ffa', opponents } : {}),
|
|
46
|
+
...(ctx.opening ? { opening: ctx.opening } : {}),
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/** The players on `me`'s team (#128), from the game's player list; none in a no-team game. */
|
|
51
|
+
export function alliesOf(me, players) {
|
|
52
|
+
const mine = players?.find((p) => p.id === me);
|
|
53
|
+
return new Set(mine ? teammatesOf(players ?? [], mine).map((p) => p.id) : []);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The per-opponent deploy estimates a plan works from: {@link enemyDeployEstimates} with the fog
|
|
57
|
+
* prior (#119, {@link fogPrior}) when the game context allows it, and the turn being played (the
|
|
58
|
+
* opening board is the first turn's only, #128). {@link planTurn} and warapp_check_plan both use
|
|
59
|
+
* it, so they work from the same figures. `income` is my board income, card armies left out.
|
|
60
|
+
* #253: with `incomeCap` (the army cap's arithmetic for this turn) `income` is what the cap leaves,
|
|
61
|
+
* and the fog prior reads it with the cut added back: the cap is mine alone, so the prior compares
|
|
62
|
+
* what I earn, not what I am paid. Without it, `income` is read as given.
|
|
63
|
+
* Every visible player is listed, teammates included (the caller filters them).
|
|
64
|
+
*/
|
|
65
|
+
export function planEnemyEstimates(input) {
|
|
66
|
+
const ctx = input.game ?? {};
|
|
67
|
+
// #270: a static seat (out, no AI on it) deploys nothing: its territories read as neutrals.
|
|
68
|
+
const seats = staticSeats(ctx.players, ctx.endRules, input.me);
|
|
69
|
+
const board = neutralizeSeats(input.board, seats);
|
|
70
|
+
const previousBoard = input.previousBoard ? neutralizeSeats(input.previousBoard, seats) : undefined;
|
|
71
|
+
const tracks = input.tracks?.filter((t) => !seats.has(t.playerId));
|
|
72
|
+
const capCut = input.incomeCap ? Math.max(0, Math.floor(input.incomeCap.uncapped - input.incomeCap.received)) : 0;
|
|
73
|
+
const { prior, skipped } = fogPrior(board, input.me, ctx, input.income + capCut);
|
|
74
|
+
const turn = input.turn ?? ctx.turn ?? null;
|
|
75
|
+
const estimates = enemyDeployEstimates(input.graph, board, input.me, input.settings ?? {}, previousBoard, tracks, prior, {
|
|
76
|
+
turn,
|
|
77
|
+
fog: ctx.fog,
|
|
78
|
+
reinforcement: ctx.reinforcement,
|
|
79
|
+
...(previousBoard && input.previousOrders ? { previousOrders: input.previousOrders } : {}),
|
|
80
|
+
});
|
|
81
|
+
return { estimates: applySanctions(estimates, input.sanctions ?? []), prior, ...(skipped ? { priorSkipped: skipped } : {}) };
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* G2 (PLAN-TEAMS D3): each estimate under the Sanctions on its player. A figure read off the board
|
|
85
|
+
* (`visible`, `exact`) is income before any cut, so its income (the Reinforcement card left out) is
|
|
86
|
+
* cut by the client's rule ({@link sanctionedIncome}); an observed, tracked or prior figure is left
|
|
87
|
+
* whole — an observed deploy may already carry the cut — and marked not applied. Unchanged without.
|
|
88
|
+
*/
|
|
89
|
+
export function applySanctions(estimates, sanctions) {
|
|
90
|
+
if (!sanctions.length)
|
|
91
|
+
return estimates;
|
|
92
|
+
return estimates.map((e) => {
|
|
93
|
+
const on = sanctions.filter((x) => x.player === e.playerId);
|
|
94
|
+
if (!on.length)
|
|
95
|
+
return e;
|
|
96
|
+
const percentages = on.map((x) => x.percentage);
|
|
97
|
+
const card = e.card?.armies ?? 0;
|
|
98
|
+
const before = e.estimate - card;
|
|
99
|
+
const applied = e.source === 'visible' || e.source === 'exact';
|
|
100
|
+
const untilTurn = Math.max(...on.map((x) => x.untilTurn));
|
|
101
|
+
return {
|
|
102
|
+
...e,
|
|
103
|
+
...(applied ? { estimate: sanctionedIncome(before, percentages) + card } : {}),
|
|
104
|
+
sanctioned: { percentages, untilTurn, before, applied },
|
|
105
|
+
};
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
/** The opponents' estimates, the game profile and the goal it picks (rule 0p). */
|
|
109
|
+
function opponentsCtx(input) {
|
|
110
|
+
const { graph: g, board, me } = input;
|
|
111
|
+
const s = input.settings ?? {};
|
|
112
|
+
const baseIncome = Math.max(0, Math.floor(s.baseIncome ?? DEFAULT_BASE_INCOME));
|
|
113
|
+
const opts = input.options ?? {};
|
|
114
|
+
const income = Math.max(0, Math.floor(input.income));
|
|
115
|
+
// #253: what I earn before the army cap's cut. The fog prior and the standing compare economies,
|
|
116
|
+
// and the cap is mine alone, so they read it; what I deploy (`income`) is what the cap leaves.
|
|
117
|
+
const capCut = input.incomeCap ? Math.max(0, Math.floor(input.incomeCap.uncapped - input.incomeCap.received)) : 0;
|
|
118
|
+
const earnedIncome = income + capCut;
|
|
119
|
+
const ctx = input.game ?? {};
|
|
120
|
+
/** My teammates (#128): players on my team, never a threat, a target or an estimate. */
|
|
121
|
+
const allies = alliesOf(me, ctx.players);
|
|
122
|
+
/** Not me, not a teammate: whose deploy is estimated. */
|
|
123
|
+
const notAlly = (p) => p !== me && !allies.has(p);
|
|
124
|
+
/** The turn being planned, when known (the opening board is the first turn's only, #128). */
|
|
125
|
+
const turnNow = input.turn ?? ctx.turn ?? null;
|
|
126
|
+
const { estimates: allEstimates, prior: incomePrior, priorSkipped: incomePriorSkipped } = planEnemyEstimates({
|
|
127
|
+
graph: g,
|
|
128
|
+
board,
|
|
129
|
+
me,
|
|
130
|
+
income: earnedIncome - Math.max(0, Math.floor(input.cardArmies ?? 0)),
|
|
131
|
+
settings: s,
|
|
132
|
+
...(input.previousBoard ? { previousBoard: input.previousBoard } : {}),
|
|
133
|
+
...(input.previousOrders ? { previousOrders: input.previousOrders } : {}),
|
|
134
|
+
...(input.tracks ? { tracks: input.tracks } : {}),
|
|
135
|
+
game: ctx,
|
|
136
|
+
turn: turnNow,
|
|
137
|
+
...(input.sanctions?.length ? { sanctions: input.sanctions } : {}),
|
|
138
|
+
});
|
|
139
|
+
const estimateList = allEstimates.filter((e) => notAlly(e.playerId));
|
|
140
|
+
/** An opponent's income: its deploy estimate less the Reinforcement card the clock adds (#164). */
|
|
141
|
+
const incomeOf = (e) => e.estimate - (e.card?.armies ?? 0);
|
|
142
|
+
// ---- 0p. the game profile ----
|
|
143
|
+
const profile = gameProfile({
|
|
144
|
+
graph: g,
|
|
145
|
+
board,
|
|
146
|
+
me,
|
|
147
|
+
players: ctx.players ?? [],
|
|
148
|
+
settings: {
|
|
149
|
+
...(s.luckModifier !== undefined ? { luckModifier: s.luckModifier } : {}),
|
|
150
|
+
...(s.roundingMode !== undefined ? { roundingMode: s.roundingMode } : {}),
|
|
151
|
+
...(ctx.cards !== undefined ? { cards: ctx.cards } : {}),
|
|
152
|
+
...(s.localDeployments !== undefined ? { localDeployments: s.localDeployments } : {}),
|
|
153
|
+
...(s.noSplit !== undefined ? { noSplit: s.noSplit } : {}),
|
|
154
|
+
...(ctx.commanders !== undefined ? { commanders: ctx.commanders } : {}),
|
|
155
|
+
...(ctx.fog !== undefined ? { fog: ctx.fog } : {}),
|
|
156
|
+
...(s.offensiveKillRate !== undefined ? { offensiveKillRate: s.offensiveKillRate } : {}),
|
|
157
|
+
...(s.defensiveKillRate !== undefined ? { defensiveKillRate: s.defensiveKillRate } : {}),
|
|
158
|
+
...(s.oneArmyStandsGuard !== undefined ? { oneArmyStandsGuard: s.oneArmyStandsGuard } : {}),
|
|
159
|
+
},
|
|
160
|
+
...(ctx.turn !== undefined ? { turn: ctx.turn } : {}),
|
|
161
|
+
...(ctx.picking !== undefined ? { picking: ctx.picking } : {}),
|
|
162
|
+
...(ctx.endRules ? { endRules: ctx.endRules } : {}),
|
|
163
|
+
income: earnedIncome,
|
|
164
|
+
// #164 x #167: an opponent's Reinforcement card is a one-off deploy, not income: the standing
|
|
165
|
+
// and the FFA ranking read each estimate less its card. PLAN-TEAMS C3: teammates' estimates go
|
|
166
|
+
// too, for the team standing (the profile keeps them off the opponents' side).
|
|
167
|
+
estimates: allEstimates.filter((e) => e.playerId !== me).map((e) => ({ ...e, estimate: incomeOf(e) })),
|
|
168
|
+
// #275 (b): an untrusted opponent is compared at its figure, and the game is never even while it runs
|
|
169
|
+
// (not under a what-if enemy_deploy, which sizes everything itself).
|
|
170
|
+
...(input.untrusted?.length && input.options?.enemyDeploy === undefined ? { untrusted: input.untrusted.map((u) => ({ playerId: u.player, deploy: u.deploy })) } : {}),
|
|
171
|
+
// #94: opponents the tracker found with nothing in view, for the 'unknown' standing note.
|
|
172
|
+
unseen: (input.tracks ?? []).flatMap((t) => t.earnedAtLeast ? [{ playerId: t.playerId, turnsUnseen: t.turnsUnseen, turnsUnseenAtLeast: t.turnsUnseenAtLeast, earnedAtLeast: t.earnedAtLeast.total }] : []),
|
|
173
|
+
});
|
|
174
|
+
// B2: the truces in force (plan/relations.ts). T9: a player an enforced truce holds is no foe.
|
|
175
|
+
const truce = truceOf(input, { notFoe: (p) => !notAlly(p), format: profile.format, turnNow });
|
|
176
|
+
/** A player whose stacks threaten me and whose territories I may attack: not me, not a teammate. */
|
|
177
|
+
const foe = (p) => notAlly(p) && !truce.enforced.has(p);
|
|
178
|
+
/** The profile picks the goal and tunes the scoring (rule 0p): adapting, with no explicit goal. */
|
|
179
|
+
const auto = opts.adapt === true && opts.goal === undefined;
|
|
180
|
+
/** Rule 0p.3: behind on income. */
|
|
181
|
+
const behind = auto && profile.standing === 'behind';
|
|
182
|
+
/** Rule 0p.3 (#72): behind on income in a 1v1 — strike (stay balanced, break first), never defend. */
|
|
183
|
+
const strike = behind && profile.format === '1v1';
|
|
184
|
+
const goal = opts.goal ?? (behind && !strike ? 'defend' : 'balanced');
|
|
185
|
+
const balanced = goal === 'balanced';
|
|
186
|
+
/** Rule 0p.3: behind — size attacks at the minimum (no pressure margin). */
|
|
187
|
+
const minimal = behind;
|
|
188
|
+
/** Rule 0p.3: ahead in a 1v1 — pressure allowed at {@link AHEAD_PRESSURE_FACTOR}. */
|
|
189
|
+
const pressureFactor = auto && profile.format === '1v1' && profile.standing === 'ahead' ? AHEAD_PRESSURE_FACTOR : PRESSURE_FACTOR;
|
|
190
|
+
/** The pressure margin over an estimated deploy: none when sizing at the minimum. */
|
|
191
|
+
const marginFor = (d) => (minimal ? 0 : pressureMargin(d));
|
|
192
|
+
/** Goals that refuse to complete a bonus they cannot hold (R3); the others only warn. */
|
|
193
|
+
const guarded = balanced || goal === 'defend';
|
|
194
|
+
const focus = new Set(opts.focusBonusIds ?? []);
|
|
195
|
+
const reserve = Math.min(income, Math.max(0, Math.floor(opts.reserve ?? 0)));
|
|
196
|
+
const custom = opts.enemyDeploy !== undefined;
|
|
197
|
+
const mineAtStart = new Set(board.territories.flatMap((t) => (t.owner.kind === 'player' && t.owner.playerId === me ? [t.territoryId] : [])));
|
|
198
|
+
// As {@link defaultEnemyDeploy}, over the opponents only (teammates out, #128).
|
|
199
|
+
const enemyDeploy = custom
|
|
200
|
+
? Math.max(0, Math.floor(opts.enemyDeploy))
|
|
201
|
+
: estimateList.reduce((m, e) => board.territories.some((t) => t.owner.kind === 'player' &&
|
|
202
|
+
t.owner.playerId === e.playerId &&
|
|
203
|
+
(t.armies !== null || (ownerShown(t) !== undefined && !visibleState(t))) &&
|
|
204
|
+
g.territoryById.has(t.territoryId) &&
|
|
205
|
+
neighborsOf(g, t.territoryId).some((n) => mineAtStart.has(n)))
|
|
206
|
+
? Math.max(m, e.estimate)
|
|
207
|
+
: m, MIN_ENEMY_DEPLOY);
|
|
208
|
+
const estimates = new Map(estimateList.map((e) => [e.playerId, e]));
|
|
209
|
+
/** The deploy assumed for one opponent's threat: the override, else its own estimate. */
|
|
210
|
+
const deployOf = (player) => (custom ? enemyDeploy : (estimates.get(player)?.estimate ?? MIN_ENEMY_DEPLOY));
|
|
211
|
+
/** One opponent's income per turn: {@link deployOf} less the Reinforcement card it adds (#164). */
|
|
212
|
+
const incomeOfPlayer = (player) => {
|
|
213
|
+
const e = custom ? undefined : estimates.get(player);
|
|
214
|
+
return e ? incomeOf(e) : deployOf(player);
|
|
215
|
+
};
|
|
216
|
+
// #275 (b): the untrusted marks, and the members of the positive bonuses I hold in full at the start.
|
|
217
|
+
const untrusted = new Map((custom ? [] : (input.untrusted ?? [])).map((u) => [u.player, Math.max(0, Math.floor(u.deploy))]));
|
|
218
|
+
const guardedByHeld = new Set();
|
|
219
|
+
if (untrusted.size)
|
|
220
|
+
for (const b of g.map.bonuses) {
|
|
221
|
+
if (b.value <= 0)
|
|
222
|
+
continue;
|
|
223
|
+
const ts = bonusTerritories(g, b.id);
|
|
224
|
+
if (ts.length && ts.every((t) => mineAtStart.has(t)))
|
|
225
|
+
for (const t of ts)
|
|
226
|
+
guardedByHeld.add(t);
|
|
227
|
+
}
|
|
228
|
+
const untrustedAt = (player, t) => (guardedByHeld.has(t) ? (untrusted.get(player) ?? 0) : 0);
|
|
229
|
+
/**
|
|
230
|
+
* #201: the planning horizon. Once the outlook (#178) says the game is decided — winning or losing
|
|
231
|
+
* for OUTLOOK_TURNS turns running — every payback test counts the turns the game has left instead
|
|
232
|
+
* of PAYBACK_TURNS: the loser's strength over the winner's income per turn (winning: the strongest
|
|
233
|
+
* opponent's strength, its high when bounded, over my income; losing: mine over the strongest
|
|
234
|
+
* opponent's deploy estimate), at least DECIDED_PAYBACK_MIN, at most PAYBACK_TURNS. Adapting only.
|
|
235
|
+
* #208: winning on the likely high alone (`estimated`) counts that likely high, said as an estimate.
|
|
236
|
+
* #228: losing on the estimate (`estimated`: mine far below the likely high, corroborated by the
|
|
237
|
+
* main front or my income) counts the same figures as losing on the bound, said as an estimate.
|
|
238
|
+
*/
|
|
239
|
+
const decidedGame = (() => {
|
|
240
|
+
const o = opts.outlook;
|
|
241
|
+
const last = o?.turns.at(-1);
|
|
242
|
+
if (!auto || !o || !last || (o.state !== 'winning' && o.state !== 'losing'))
|
|
243
|
+
return undefined;
|
|
244
|
+
const likely = o.state === 'winning' && last.estimated && last.likely ? last.likely.high : undefined;
|
|
245
|
+
const lostOnEstimate = o.state === 'losing' && last.estimated === true;
|
|
246
|
+
const loser = likely ?? (o.state === 'winning' ? (last.strongest ? (last.strongest.high ?? last.strongest.low) : 0) : last.mine);
|
|
247
|
+
const rate = o.state === 'winning' ? income : last.strongest ? incomeOfPlayer(last.strongest.playerId) : 0;
|
|
248
|
+
if (rate <= 0)
|
|
249
|
+
return undefined;
|
|
250
|
+
const turns = Math.min(PAYBACK_TURNS, Math.max(DECIDED_PAYBACK_MIN, Math.ceil(loser / rate)));
|
|
251
|
+
return turns < PAYBACK_TURNS ? { state: o.state, turns, loser, rate, ...(likely !== undefined || lostOnEstimate ? { estimated: true } : {}) } : undefined;
|
|
252
|
+
})();
|
|
253
|
+
/** The turns every payback test counts: {@link PAYBACK_TURNS}, or fewer once the game is decided (#201). */
|
|
254
|
+
const paybackTurns = decidedGame?.turns ?? PAYBACK_TURNS;
|
|
255
|
+
return {
|
|
256
|
+
g,
|
|
257
|
+
board,
|
|
258
|
+
me,
|
|
259
|
+
s,
|
|
260
|
+
baseIncome,
|
|
261
|
+
opts,
|
|
262
|
+
income,
|
|
263
|
+
earnedIncome,
|
|
264
|
+
...(input.incomeCap ? { incomeCap: input.incomeCap } : {}),
|
|
265
|
+
game: ctx,
|
|
266
|
+
allies,
|
|
267
|
+
foe,
|
|
268
|
+
teamFocus: teamFocusOf(board, allies, foe),
|
|
269
|
+
truce,
|
|
270
|
+
turnNow,
|
|
271
|
+
incomePrior,
|
|
272
|
+
incomePriorSkipped,
|
|
273
|
+
estimateList,
|
|
274
|
+
incomeOf,
|
|
275
|
+
profile,
|
|
276
|
+
auto,
|
|
277
|
+
behind,
|
|
278
|
+
strike,
|
|
279
|
+
goal,
|
|
280
|
+
balanced,
|
|
281
|
+
minimal,
|
|
282
|
+
pressureFactor,
|
|
283
|
+
marginFor,
|
|
284
|
+
guarded,
|
|
285
|
+
focus,
|
|
286
|
+
reserve,
|
|
287
|
+
custom,
|
|
288
|
+
mineAtStart,
|
|
289
|
+
enemyDeploy,
|
|
290
|
+
estimates,
|
|
291
|
+
deployOf,
|
|
292
|
+
incomeOfPlayer,
|
|
293
|
+
untrustedAt,
|
|
294
|
+
decidedGame,
|
|
295
|
+
paybackTurns,
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
/** The territories as the board shows them, and what holding them is worth (#70, #85, #125). */
|
|
299
|
+
function boardCtx(input, o) {
|
|
300
|
+
const { g, board, me, s, baseIncome, income, focus } = o;
|
|
301
|
+
const state = new Map();
|
|
302
|
+
for (const t of board.territories)
|
|
303
|
+
if (g.territoryById.has(t.territoryId))
|
|
304
|
+
state.set(t.territoryId, t);
|
|
305
|
+
const label = (id) => `${g.territoryById.get(id).name} (#${id})`;
|
|
306
|
+
const bonusName = (id) => `${g.bonusById.get(id).name} (#${id})`;
|
|
307
|
+
const isMine = (id) => {
|
|
308
|
+
const o = state.get(id)?.owner;
|
|
309
|
+
return o?.kind === 'player' && o.playerId === me;
|
|
310
|
+
};
|
|
311
|
+
const mine = [...state.keys()].filter(isMine).sort(byNum);
|
|
312
|
+
const mineSet = new Set(mine);
|
|
313
|
+
// Next turn's income (#85): this turn's, less its card armies, moved by what the one income rule
|
|
314
|
+
// ({@link boardIncome}) says the holdings `after` change — bonuses completed (negative ones
|
|
315
|
+
// too), per-territory armies, the floor at 0.
|
|
316
|
+
const incomeRulesNow = { base: baseIncome, per: s.bonusArmyPer ?? 0 };
|
|
317
|
+
const boardIncomeNow = boardIncome(g, mineSet, incomeRulesNow).total;
|
|
318
|
+
const cardArmies = Math.max(0, Math.floor(input.cardArmies ?? 0));
|
|
319
|
+
/**
|
|
320
|
+
* The income change (#70, #85) from holding `after` instead of what I held at the start: the one
|
|
321
|
+
* income rule's ({@link boardIncome}) total over `after` less its total now — every bonus whose
|
|
322
|
+
* completion changes (negative ones and superbonuses included), per-territory armies, and the
|
|
323
|
+
* floor at 0 on both sides, so a change computed below the floor is what war.app pays.
|
|
324
|
+
* Next income, R3, rule 4c's scoring and its guard all read it.
|
|
325
|
+
*/
|
|
326
|
+
const incomeGain = (after) => boardIncome(g, after, incomeRulesNow).total - boardIncomeNow;
|
|
327
|
+
/** Next income after a change of `gain`: this turn's, less its card armies, moved by `gain`. */
|
|
328
|
+
const nextIncomeWith = (gain) => Math.max(0, income - cardArmies + gain);
|
|
329
|
+
const incomeAfter = (after) => nextIncomeWith(incomeGain(after));
|
|
330
|
+
const armiesOf = (id) => state.get(id)?.armies ?? 0;
|
|
331
|
+
// #274: where my commander stands, and its step toward safety when it walks this turn: within
|
|
332
|
+
// COMMANDER_CLEAR_MOVES moves of an enemy or fogged territory, with a territory of mine farther
|
|
333
|
+
// from all of them reachable (plan/commander.ts). Only with one commander of mine on the board.
|
|
334
|
+
const myCommanderHomes = mine.filter((id) => (state.get(id)?.specialUnits ?? []).some((u) => u.kind === 'commander' && u.playerId === me));
|
|
335
|
+
const hostile = [...state.values()]
|
|
336
|
+
.filter((t) => t.owner.kind === 'unknown' || t.armies === null || (t.owner.kind === 'player' && t.owner.playerId !== me && !o.allies.has(t.owner.playerId)))
|
|
337
|
+
.map((t) => t.territoryId);
|
|
338
|
+
const place = myCommanderHomes.length === 1 ? commanderPlace(g, myCommanderHomes[0], (t) => mineSet.has(t), hostile) : undefined;
|
|
339
|
+
const commanderAt = place && o.opts.commanderWalks === false ? { territory: place.territory, distance: place.distance, pinned: true } : place;
|
|
340
|
+
const leaving = commanderAt?.retreat?.from;
|
|
341
|
+
/**
|
|
342
|
+
* The armies the special units on `id` fight as (a commander: {@link COMMANDER_STRENGTH}); #274: my
|
|
343
|
+
* commander walking away this turn is not counted where it stood (nor, until it lands, where it goes).
|
|
344
|
+
*/
|
|
345
|
+
const unitsAt = (id) => specialUnitStrength(id === leaving ? state.get(id)?.specialUnits?.filter((u) => !(u.kind === 'commander' && u.playerId === me)) : state.get(id)?.specialUnits);
|
|
346
|
+
/**
|
|
347
|
+
* #128: a territory holding a special unit whose strength the board does not carry (a boss, a
|
|
348
|
+
* custom unit): it counts as 0 everywhere, so no attack on it is sized as sure.
|
|
349
|
+
*/
|
|
350
|
+
const uncounted = (id) => (state.get(id)?.specialUnits ?? []).some((u) => u.kind !== 'commander');
|
|
351
|
+
const uncountedKind = (id) => [...new Set((state.get(id)?.specialUnits ?? []).filter((u) => u.kind !== 'commander').map((u) => (u.kind === 'boss' ? 'a boss' : u.kind === 'custom' ? 'a custom unit' : 'a special unit')))].join(' and ');
|
|
352
|
+
/** What a territory defends as now: its armies plus its special units. */
|
|
353
|
+
const defenceAt = (id) => armiesOf(id) + unitsAt(id);
|
|
354
|
+
// ---- income change (#70): the one computation nextIncome, R3 and the negative-bonus rules use ----
|
|
355
|
+
const bonusTs = new Map(g.map.bonuses.map((b) => [b.id, bonusTerritories(g, b.id)]));
|
|
356
|
+
/** The bonuses each territory is in (superbonuses through their members included). */
|
|
357
|
+
const bonusesWith = new Map();
|
|
358
|
+
for (const [id, ts] of bonusTs)
|
|
359
|
+
for (const t of ts)
|
|
360
|
+
bonusesWith.set(t, [...(bonusesWith.get(t) ?? []), id]);
|
|
361
|
+
/**
|
|
362
|
+
* Bonuses complete over `after` that were not complete at the start of the turn, sorted by id.
|
|
363
|
+
* Such a bonus has a territory in `after` that was not mine at the start, so only the bonuses of
|
|
364
|
+
* those territories are looked at (every bonus on the map was, many times a plan: #172 review).
|
|
365
|
+
*/
|
|
366
|
+
const completedBy = (after) => completedOver((t) => after.has(t), after);
|
|
367
|
+
/**
|
|
368
|
+
* {@link completedBy} over the territories `holds` says are held, given every one of them that
|
|
369
|
+
* was not mine at the start (`fresh`; mine are skipped).
|
|
370
|
+
*/
|
|
371
|
+
const completedOver = (holds, fresh) => {
|
|
372
|
+
const out = new Set();
|
|
373
|
+
for (const t of fresh) {
|
|
374
|
+
if (mineSet.has(t))
|
|
375
|
+
continue;
|
|
376
|
+
for (const id of bonusesWith.get(t) ?? [])
|
|
377
|
+
if (!out.has(id) && bonusTs.get(id).every(holds))
|
|
378
|
+
out.add(id);
|
|
379
|
+
}
|
|
380
|
+
return [...out].sort(byNum);
|
|
381
|
+
};
|
|
382
|
+
/**
|
|
383
|
+
* The per-territory income (#125; Extra Armies for Territories) that `k` more territories add to
|
|
384
|
+
* what I hold now: floor(territories / per) over the base, at 1/per a territory once past it (a
|
|
385
|
+
* fraction, so a capture that does not cross a multiple of `per` still counts its share). 0 off.
|
|
386
|
+
*/
|
|
387
|
+
const territoryShare = (k) => {
|
|
388
|
+
const per = s.bonusArmyPer ?? 0;
|
|
389
|
+
if (per <= 0 || k <= 0)
|
|
390
|
+
return 0;
|
|
391
|
+
const now = mine.length;
|
|
392
|
+
const exact = (n) => Math.max(baseIncome, n / per);
|
|
393
|
+
return Math.round((exact(now + k) - exact(now)) * 100) / 100;
|
|
394
|
+
};
|
|
395
|
+
/** Income a turn that capturing `_t` adds on its own (#125): its bonuses' and its per-territory share. */
|
|
396
|
+
const plainWorth = (_t, gain) => Math.max(gain, territoryShare(1));
|
|
397
|
+
/** `t` is in a bonus the caller focused: the negative-bonus rules never refuse it. */
|
|
398
|
+
const inFocus = (t) => [...focus].some((id) => bonusTs.get(id)?.includes(t));
|
|
399
|
+
return {
|
|
400
|
+
territories: state,
|
|
401
|
+
label,
|
|
402
|
+
bonusName,
|
|
403
|
+
isMine,
|
|
404
|
+
mine,
|
|
405
|
+
mineSet,
|
|
406
|
+
boardIncomeNow,
|
|
407
|
+
cardArmies,
|
|
408
|
+
incomeGain,
|
|
409
|
+
nextIncomeWith,
|
|
410
|
+
incomeAfter,
|
|
411
|
+
armiesOf,
|
|
412
|
+
unitsAt,
|
|
413
|
+
uncounted,
|
|
414
|
+
uncountedKind,
|
|
415
|
+
defenceAt,
|
|
416
|
+
bonusTs,
|
|
417
|
+
bonusesWith,
|
|
418
|
+
completedBy,
|
|
419
|
+
completedOver,
|
|
420
|
+
territoryShare,
|
|
421
|
+
plainWorth,
|
|
422
|
+
inFocus,
|
|
423
|
+
commanderAt,
|
|
424
|
+
vacated: input.vacated ?? new Map(),
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
/** The combat model (S2, #126): kill rates, luck, rounding, and what a capture or a hold costs. */
|
|
428
|
+
function combatCtx(o, b) {
|
|
429
|
+
const { g, board, me, s, opts, foe } = o;
|
|
430
|
+
const { territories: state, isMine, armiesOf, defenceAt } = b;
|
|
431
|
+
const guard = (s.oneArmyStandsGuard ?? true) ? 1 : 0;
|
|
432
|
+
/** #163: an opponent may hold a Bomb: every hold is sized as if its stack were halved first. */
|
|
433
|
+
const bombOn = opts.opponentsMayHoldBomb === true;
|
|
434
|
+
const rates = {
|
|
435
|
+
offensiveKillRate: s.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE,
|
|
436
|
+
defensiveKillRate: s.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE,
|
|
437
|
+
};
|
|
438
|
+
/** The exact combat model's settings (S2): kill rates, luck, rounding. */
|
|
439
|
+
const combat = combatSettings(s);
|
|
440
|
+
const chanceOf = (armies, defenders) => winChance(armies, defenders, combat);
|
|
441
|
+
/** The least win chance an ordinary capture is sized for (S2; #126: 95% by default with luck on). */
|
|
442
|
+
const minWin = opts.minWinChance !== undefined ? minWinChanceOf(opts.minWinChance) : defaultMinWinChance(s);
|
|
443
|
+
/** Exact results: 0% luck under straight rounding, where every chance is 0 or 1. */
|
|
444
|
+
const exactCombat = !combat.luck && combat.rounding !== 'WeightedRandom';
|
|
445
|
+
/**
|
|
446
|
+
* #126: the chance each capture of `t` is sized for, so the captures a bonus still needs reach
|
|
447
|
+
* {@link minWin} together: minWin^(1/k), k the most members not mine of any positive bonus `t`
|
|
448
|
+
* is in (1 outside a bonus). 1 when minWin is.
|
|
449
|
+
*/
|
|
450
|
+
const missingOf = new Map();
|
|
451
|
+
const heldAtStart = new Set(board.territories.flatMap((t) => (t.owner.kind === 'player' && t.owner.playerId === me ? [t.territoryId] : [])));
|
|
452
|
+
for (const bonus of g.map.bonuses) {
|
|
453
|
+
if (bonus.value <= 0)
|
|
454
|
+
continue;
|
|
455
|
+
const ts = bonusTerritories(g, bonus.id);
|
|
456
|
+
const missing = ts.filter((x) => !heldAtStart.has(x)).length;
|
|
457
|
+
for (const x of ts)
|
|
458
|
+
missingOf.set(x, Math.max(missingOf.get(x) ?? 1, missing));
|
|
459
|
+
}
|
|
460
|
+
const chanceAt = (t) => (minWin >= 1 ? 1 : minWin ** (1 / (missingOf.get(t) ?? 1)));
|
|
461
|
+
const costMemo = new Map();
|
|
462
|
+
/** An ordinary capture's size against `defenders`, at `chance` (default {@link minWin}). */
|
|
463
|
+
const costOf = (defenders, chance = minWin) => {
|
|
464
|
+
const key = `${defenders}|${chance}`;
|
|
465
|
+
if (!costMemo.has(key))
|
|
466
|
+
costMemo.set(key, captureCost(defenders, s, chance));
|
|
467
|
+
return costMemo.get(key);
|
|
468
|
+
};
|
|
469
|
+
/** An ordinary capture of `t`'s size against `defenders` (default what defends it now), at {@link chanceAt}. */
|
|
470
|
+
const costAt = (t, defenders = defenceAt(t)) => costOf(defenders, chanceAt(t));
|
|
471
|
+
/** {@link toTake} by defenders, for this plan's settings. */
|
|
472
|
+
const takeMemo = new Map();
|
|
473
|
+
/**
|
|
474
|
+
* The attack that takes `defenders` (holds, threats, retakes): `armiesToTake` with exact results;
|
|
475
|
+
* else (#126) the fewest attackers whose win chance exceeds {@link HOLD_FALL_CHANCE}, so a stack
|
|
476
|
+
* that "needs N to take, above the threat" falls to that threat at most that often.
|
|
477
|
+
*/
|
|
478
|
+
const toTake = (defenders) => {
|
|
479
|
+
if (exactCombat)
|
|
480
|
+
return armiesToTake(defenders, rates);
|
|
481
|
+
if (!takeMemo.has(defenders))
|
|
482
|
+
takeMemo.set(defenders, defenders <= 0 ? 1 : armiesForChance(defenders, HOLD_FALL_CHANCE + 1e-9, combat));
|
|
483
|
+
return takeMemo.get(defenders);
|
|
484
|
+
};
|
|
485
|
+
/**
|
|
486
|
+
* What capturing `x` costs the economy (#125): the armies its attackers lose (the defenders'
|
|
487
|
+
* kills at the defensive rate) plus the one army left on it — not the armies sent, whose
|
|
488
|
+
* survivors are still mine. That one army is waived when a territory of mine beside it that
|
|
489
|
+
* faces no visible enemy already has idle armies enough to take it (nothing is deployed for
|
|
490
|
+
* it). Infinity when it cannot be taken.
|
|
491
|
+
*/
|
|
492
|
+
const econCostAt = (x) => {
|
|
493
|
+
const c = costAt(x);
|
|
494
|
+
if (c === null)
|
|
495
|
+
return Infinity;
|
|
496
|
+
const lost = Math.min(c - 1, straightKills(defenceAt(x), rates.defensiveKillRate));
|
|
497
|
+
const idle = neighborsOf(g, x).some((n) => isMine(n) &&
|
|
498
|
+
armiesOf(n) - guard >= c &&
|
|
499
|
+
!neighborsOf(g, n).some((y) => {
|
|
500
|
+
const o = state.get(y)?.owner;
|
|
501
|
+
return o?.kind === 'player' && foe(o.playerId);
|
|
502
|
+
}));
|
|
503
|
+
return lost + (idle ? 0 : 1);
|
|
504
|
+
};
|
|
505
|
+
const luck = luckFraction(s.luckModifier);
|
|
506
|
+
const weightedRounding = s.roundingMode !== undefined && s.roundingMode !== 'StraightRound';
|
|
507
|
+
const noSplit = s.noSplit === true;
|
|
508
|
+
return {
|
|
509
|
+
guard,
|
|
510
|
+
bombOn,
|
|
511
|
+
rates,
|
|
512
|
+
combat,
|
|
513
|
+
chanceOf,
|
|
514
|
+
minWin,
|
|
515
|
+
exactCombat,
|
|
516
|
+
heldAtStart,
|
|
517
|
+
chanceAt,
|
|
518
|
+
costOf,
|
|
519
|
+
costAt,
|
|
520
|
+
toTake,
|
|
521
|
+
econCostAt,
|
|
522
|
+
luck,
|
|
523
|
+
weightedRounding,
|
|
524
|
+
noSplit,
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
/** Where I stand on armies (#167, #201, rule 0p.3), and the rules that switches. */
|
|
528
|
+
function standingCtx(o, b) {
|
|
529
|
+
const { me, opts, foe, profile, auto } = o;
|
|
530
|
+
const { territories: state, mine, unitsAt } = b;
|
|
531
|
+
/**
|
|
532
|
+
* #167: my army lead over the largest opponent in view — my visible armies and special units over
|
|
533
|
+
* theirs (Infinity with no opponent in view). Rule 0p.2 scales with it, and above
|
|
534
|
+
* SECOND_FRONT_LEAD× it is off.
|
|
535
|
+
*/
|
|
536
|
+
const armyLead = (() => {
|
|
537
|
+
const by = new Map();
|
|
538
|
+
for (const [id, st] of state)
|
|
539
|
+
if (st.owner.kind === 'player' && st.armies !== null)
|
|
540
|
+
by.set(st.owner.playerId, (by.get(st.owner.playerId) ?? 0) + st.armies + unitsAt(id));
|
|
541
|
+
const my = by.get(me) ?? 0;
|
|
542
|
+
const rival = [...by].filter(([p]) => foe(p)).sort((a, b) => b[1] - a[1] || a[0] - b[0])[0];
|
|
543
|
+
return { my, rival: rival?.[0], theirs: rival?.[1] ?? 0, ratio: rival && rival[1] > 0 ? my / rival[1] : Infinity };
|
|
544
|
+
})();
|
|
545
|
+
/**
|
|
546
|
+
* #167: adapting (rule 0p), the lead switches rule 0p.2 off. Visible armies only, so under fog a
|
|
547
|
+
* strong player showing one small stack would inflate it: the lever also needs me first in the
|
|
548
|
+
* profile's FFA ranking on strength (armies + STRENGTH_INCOME_TURNS × income), when there is one.
|
|
549
|
+
*/
|
|
550
|
+
const leadLever = opts.adapt === true &&
|
|
551
|
+
opts.goal === undefined &&
|
|
552
|
+
armyLead.rival !== undefined &&
|
|
553
|
+
armyLead.ratio > SECOND_FRONT_LEAD &&
|
|
554
|
+
(profile.ranking === undefined || profile.ranking.myRank === 1);
|
|
555
|
+
/**
|
|
556
|
+
* #167: a clear FFA leader that is not me (strength at least AHEAD_RATIO × the next player's): the
|
|
557
|
+
* player the others combine against, never a second front.
|
|
558
|
+
*/
|
|
559
|
+
const clearLeader = (() => {
|
|
560
|
+
const r = profile.ranking;
|
|
561
|
+
if (!(opts.adapt === true && opts.goal === undefined) || !r || r.commonThreat === null || r.players.length < 2)
|
|
562
|
+
return undefined;
|
|
563
|
+
return r.players[0].strength >= AHEAD_RATIO * r.players[1].strength ? r.commonThreat : undefined;
|
|
564
|
+
})();
|
|
565
|
+
/**
|
|
566
|
+
* #201: I lead this free-for-all on strength (adapting, two or more opponents left): the others
|
|
567
|
+
* may combine against me, so a border is held against every adjacent opponent together, and a
|
|
568
|
+
* break is sized to land against its owner's one deploy.
|
|
569
|
+
*/
|
|
570
|
+
const ffaLeader = opts.adapt === true && opts.goal === undefined && profile.format === 'ffa' && profile.opponents >= 2 && profile.ranking?.leader === me;
|
|
571
|
+
/**
|
|
572
|
+
* #201: fund holds by the standing (adapting). Ahead: every held bonus is held for the worst case
|
|
573
|
+
* (each border against the whole deploy) before any capture, completions included. Behind: each
|
|
574
|
+
* border is sized for the expected attack (#59: movable armies next to it plus the whole deploy
|
|
575
|
+
* estimate), not the worst case the growth trend projects, and the plan says what that gambles —
|
|
576
|
+
* only the trend above the deploy, never the deploy itself (sizing below it broke #118);
|
|
577
|
+
* my commander's territory is never sized so (1k). Ahead, a held bonus never waits behind the
|
|
578
|
+
* expansion share either.
|
|
579
|
+
*/
|
|
580
|
+
const holdPasses = opts.adapt === true && opts.goal === undefined
|
|
581
|
+
? profile.standing === 'ahead'
|
|
582
|
+
? 'worst'
|
|
583
|
+
: profile.standing === 'behind'
|
|
584
|
+
? 'expected'
|
|
585
|
+
: undefined
|
|
586
|
+
: undefined;
|
|
587
|
+
/** "3.3×" */
|
|
588
|
+
const leadText = () => (Number.isFinite(armyLead.ratio) ? `${(Math.round(armyLead.ratio * 10) / 10).toFixed(1)}×` : 'unbounded (no opponent army in view)');
|
|
589
|
+
/** My territories where my own commander stands: must-hold (rule 1k). */
|
|
590
|
+
const myCommanders = new Set(mine.filter((id) => (state.get(id)?.specialUnits ?? []).some((u) => u.kind === 'commander' && u.playerId === me)));
|
|
591
|
+
// #274: a commander that walks this turn is pinned where it goes, no longer where it stood.
|
|
592
|
+
const step = b.commanderAt?.retreat;
|
|
593
|
+
if (step) {
|
|
594
|
+
myCommanders.delete(step.from);
|
|
595
|
+
myCommanders.add(step.to);
|
|
596
|
+
}
|
|
597
|
+
// ---- rule 0p.3 (#72): behind on armies ----
|
|
598
|
+
// Adapting in a 1v1: my visible armies against the strongest opponent's visible armies, each
|
|
599
|
+
// with the special units standing on them (a commander fights as COMMANDER_STRENGTH). Behind
|
|
600
|
+
// (below BEHIND_RATIO×, strictly, as the plan states) means no trade below even: a combined
|
|
601
|
+
// capture of a player's territory whose attacks lose more armies than they kill is not made.
|
|
602
|
+
// A single capture needs no check: it kills every defender and loses at most
|
|
603
|
+
// round(defenders × defensive rate) ≤ defenders, so it never trades below even (pinned by
|
|
604
|
+
// tests at unusual kill rates) — revisit this if single-capture sizing ever changes.
|
|
605
|
+
let armiesBehindVs;
|
|
606
|
+
if (auto && profile.format === '1v1') {
|
|
607
|
+
const totals = new Map();
|
|
608
|
+
for (const st of state.values())
|
|
609
|
+
if (st.owner.kind === 'player' && st.armies !== null)
|
|
610
|
+
totals.set(st.owner.playerId, (totals.get(st.owner.playerId) ?? 0) + st.armies + specialUnitStrength(st.specialUnits));
|
|
611
|
+
const myArmies = totals.get(me) ?? 0;
|
|
612
|
+
const [rival, theirs] = [...totals]
|
|
613
|
+
.filter(([p]) => foe(p))
|
|
614
|
+
.sort((a, b) => b[1] - a[1] || a[0] - b[0])[0] ?? [undefined, 0];
|
|
615
|
+
if (rival !== undefined && theirs > 0 && myArmies < BEHIND_RATIO * theirs)
|
|
616
|
+
armiesBehindVs = { myArmies, rival, theirs };
|
|
617
|
+
}
|
|
618
|
+
return {
|
|
619
|
+
armyLead,
|
|
620
|
+
leadLever,
|
|
621
|
+
clearLeader,
|
|
622
|
+
ffaLeader,
|
|
623
|
+
holdPasses,
|
|
624
|
+
leadText,
|
|
625
|
+
myCommanders,
|
|
626
|
+
armiesBehindVs,
|
|
627
|
+
armiesBehind: armiesBehindVs !== undefined,
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
/** Everything a planning pass reads and never changes (the estimates phase). */
|
|
631
|
+
export function planContext(input) {
|
|
632
|
+
const o = opponentsCtx(input);
|
|
633
|
+
const b = boardCtx(input, o);
|
|
634
|
+
return { ...o, ...b, ...combatCtx(o, b), ...standingCtx(o, b) };
|
|
635
|
+
}
|
|
636
|
+
/**
|
|
637
|
+
* The rationale and warnings that state what the estimates phase decided: the goal and the profile
|
|
638
|
+
* behind it (rule 0p), a decided game (#201), being behind on armies (rule 0p.3), the combat model's
|
|
639
|
+
* settings (S2, #126), a possible Bomb (#163), Multi-Attack and No-Split (#124). The first lines of
|
|
640
|
+
* every plan, in this order.
|
|
641
|
+
*/
|
|
642
|
+
export function noteEstimates(ctx, state) {
|
|
643
|
+
const { board, s, opts, earnedIncome: income, estimateList, profile, auto, strike, goal, minimal, pressureFactor, decidedGame } = ctx;
|
|
644
|
+
const { rates, minWin, exactCombat, bombOn, luck, weightedRounding, noSplit, armiesBehindVs } = ctx;
|
|
645
|
+
const { warnings, rationale } = state;
|
|
646
|
+
const profileText = `${profile.format}, ${profile.phase}, ${profile.standing}`;
|
|
647
|
+
if (opts.adapt && opts.goal !== undefined) {
|
|
648
|
+
rationale.push(`Goal ${goal} was given explicitly, so it overrides the game profile (${profileText}): none of the profile's rules apply.`);
|
|
649
|
+
// Also a warning: live, a script that always passed `goal: balanced` switched the 1v1 rules
|
|
650
|
+
// (strike stack, breaks before expansion) off for two whole games, and nobody noticed.
|
|
651
|
+
warnings.push(`Goal ${goal} was given explicitly, so none of the game-profile rules for ${profile.format === 'ffa' ? 'an FFA' : profile.format === 'teams' ? 'a team game' : 'a 1v1'} apply this turn (standing ${profile.standing}): leave the goal out to let the profile choose it and apply them.`);
|
|
652
|
+
}
|
|
653
|
+
else if (auto) {
|
|
654
|
+
const strongest = estimateList.reduce((m, e) => Math.max(m, e.estimate), 0);
|
|
655
|
+
rationale.push(strike
|
|
656
|
+
? `Goal balanced from the game profile (${profileText}): behind on income (${income} against ~${strongest}) in a 1v1 — strike: break the opponent's bonuses with minimal attacks before expansion that completes nothing (holds of my own bonuses that pay for themselves still come first), sized at the minimum (no extra margin beyond what the rules require).`
|
|
657
|
+
: minimal
|
|
658
|
+
? `Goal defend from the game profile (${profileText}): behind on income (${income} against ~${strongest}), so defend first and size attacks at the minimum (no extra margin beyond what the rules require).`
|
|
659
|
+
: `Goal balanced from the game profile (${profileText}): the base goal.`);
|
|
660
|
+
if (pressureFactor !== PRESSURE_FACTOR)
|
|
661
|
+
rationale.push(`Ahead in a 1v1 (${income} against ~${strongest}): keep attacking — pressure on an opponent next to the fog is allowed when each capture costs up to ${pressureFactor}× a typical neutral capture (instead of ${PRESSURE_FACTOR}×).`);
|
|
662
|
+
}
|
|
663
|
+
if (decidedGame)
|
|
664
|
+
rationale.push(`Outlook (#201): ${decidedGame.state} for ${OUTLOOK_TURNS} turns running${decidedGame.state === 'losing' && decidedGame.estimated ? ' (on an estimate under fog, #228: not a bound)' : ''}, so the game is decided — ${decidedGame.state === 'winning'
|
|
665
|
+
? `the strongest opponent's ${decidedGame.estimated ? 'likely strength' : 'strength'} of ${decidedGame.loser}${decidedGame.estimated ? ' (an estimate, not a bound)' : ''} over my income of ${decidedGame.rate}`
|
|
666
|
+
: `my strength of ${decidedGame.loser} over the strongest opponent's ~${decidedGame.rate} a turn`} leaves ~${decidedGame.turns} turns, so every payback test counts ${decidedGame.turns} turns instead of ${PAYBACK_TURNS}.`);
|
|
667
|
+
if (armiesBehindVs) {
|
|
668
|
+
const { myArmies, rival, theirs } = armiesBehindVs;
|
|
669
|
+
rationale.push(`Behind on armies (${myArmies} visible against player ${rival}'s ${theirs}): no trade below even — a capture of a player's territory whose attacks lose more armies than they kill is not made.`);
|
|
670
|
+
}
|
|
671
|
+
if (!board.verified)
|
|
672
|
+
warnings.push('Board state comes from an unverified parser of the GameFeed standing; check it against the game.');
|
|
673
|
+
if (luck > 0)
|
|
674
|
+
warnings.push(minWin < 1
|
|
675
|
+
? `Luck is ${Math.round(luck * 100)}%: each capture is sized for at least a ${Math.round(minWin * 100)}% win chance (min_win_chance${opts.minWinChance === undefined ? `, ${Math.round(LUCK_WIN_CHANCE * 100)}% by default with luck on` : ''}), so it can fail; each attack's winChance says how likely it is.`
|
|
676
|
+
: `Luck is ${Math.round(luck * 100)}%: each capture is sized to be certain (min_win_chance 1: the fewest armies whose every roll takes it); each attack's winChance says how likely it is.`);
|
|
677
|
+
if (s.offensiveKillRate === undefined || s.defensiveKillRate === undefined)
|
|
678
|
+
warnings.push(`Kill rates missing from the game settings; assuming ${rates.offensiveKillRate}% offense, ${rates.defensiveKillRate}% defense.`);
|
|
679
|
+
if (s.roundingMode === 'WeightedRandom')
|
|
680
|
+
warnings.push(`This game uses ${s.roundingMode} rounding: capture and hold sizes are computed under it (a fraction of a kill can round either way), and each attack's winChance says how likely it is.`);
|
|
681
|
+
else if (weightedRounding)
|
|
682
|
+
warnings.push(`Capture costs assume straight rounding; this game uses ${s.roundingMode}, which the combat model does not know.`);
|
|
683
|
+
if (minWin < 1)
|
|
684
|
+
rationale.push(`Captures are sized for at least a ${Math.round(minWin * 100)}% win chance (min_win_chance), not a guaranteed take: each gets the fewest armies whose exact win chance reaches it, and the captures a bonus still needs reach it together (each at that chance to the power 1/k, k the bonus's missing members). Attacks sized for a worst case (finishing a player off, fog pressure, commander strikes) stay certain: their win chance is 1.`);
|
|
685
|
+
if (!exactCombat)
|
|
686
|
+
rationale.push(`Holds are sized so the attack assumed wins at most ${Math.round(HOLD_FALL_CHANCE * 100)}%: "need N to take" is the smallest attack that wins more often than that${luck > 0 ? ` at ${Math.round(luck * 100)}% luck` : ''}${weightedRounding ? ` under ${s.roundingMode} rounding` : ''}.`);
|
|
687
|
+
if (bombOn)
|
|
688
|
+
rationale.push('An opponent may hold a Bomb (#163): it halves one territory of mine next to it after the deploys and before any move, so every hold here is sized as if its stack were halved first (my commander unharmed), and the leftover goes to two stacks, not one, unless it concentrates for an attack.');
|
|
689
|
+
if (s.multiAttack)
|
|
690
|
+
rationale.push(`Multi-attack is on: the plan does not chain its own attacks from captured territories, but an enemy stack's chain — a capture, then the survivors on from it, through territories not mine — counts as a threat to the territory of mine, or the capture, it reaches (luck-free, at most ${CHAIN_MAX_STEPS} attacks deep).`);
|
|
691
|
+
if (noSplit) {
|
|
692
|
+
rationale.push('No-Split: each territory issues at most one attack or transfer this turn, and it sends the whole stack (every army there, this turn\'s deploys included, less the guard); a territory that would split keeps its first (best) order, and one that must hold issues none.');
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
/** The plan for a player holding no territory: nothing to deploy or move. */
|
|
696
|
+
export function emptyPlan(ctx, state) {
|
|
697
|
+
const { me, goal, profile, income, cardArmies, enemyDeploy } = ctx;
|
|
698
|
+
const { warnings, rationale } = state;
|
|
699
|
+
warnings.push(`Player ${me} holds no territories on this board, so there is nothing to deploy or move.`);
|
|
700
|
+
return {
|
|
701
|
+
goal,
|
|
702
|
+
profile,
|
|
703
|
+
deploys: [],
|
|
704
|
+
moves: [],
|
|
705
|
+
expected: { captures: [], bonusesCompleted: [], nextIncome: Math.max(0, income - cardArmies) },
|
|
706
|
+
warnings,
|
|
707
|
+
rationale,
|
|
708
|
+
enemyDeploy,
|
|
709
|
+
conceded: [],
|
|
710
|
+
cardAdvice: null,
|
|
711
|
+
multiSourceCaptures: [],
|
|
712
|
+
frontier: { borders: 0, enemyBorders: 0, holdCost: 0, income },
|
|
713
|
+
offence: [],
|
|
714
|
+
};
|
|
715
|
+
}
|