@chessar/engine 0.0.0-stage → 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.
package/dist/events.js ADDED
@@ -0,0 +1,214 @@
1
+ // Copyright 2026 Andrius Jaškauskas
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { addPiece, cellKey, materialScores, piecesOf, recruitsOnCapture, removePiece } from './board.js';
4
+ /** Shown whenever a leave credits nobody; the rule lives in docs/rules.md. */
5
+ export const NO_CREDIT_RULE = 'left outside the escape window: no credit, no rating change';
6
+ /** The end of an army by one event, or null when the event ends nothing. Pure: the server, the client and the tests share it. */
7
+ export function endReasonOf(e) {
8
+ switch (e.type) {
9
+ case 'mated':
10
+ return 'mate';
11
+ case 'surrendered':
12
+ return e.credited?.length ? 'escape' : 'surrender';
13
+ case 'despawned':
14
+ return e.reason === 'idle' ? 'idle' : 'kick';
15
+ case 'hibernated':
16
+ return 'hibernate';
17
+ default:
18
+ return null;
19
+ }
20
+ }
21
+ /** One plain sentence for an end (`name` turns a player id into a name). Null when the event ends nothing. */
22
+ export function endText(e, name) {
23
+ const reason = endReasonOf(e);
24
+ if (!reason)
25
+ return null;
26
+ const list = (ids) => ids.map(name).join(', ');
27
+ switch (e.type) {
28
+ case 'mated':
29
+ return e.by ? `checkmated by ${name(e.by)}${e.assists.length ? ` (assist: ${list(e.assists)})` : ''}` : 'checkmated: nobody credited';
30
+ case 'surrendered':
31
+ return reason === 'escape' ? `left under pressure: credited to ${list(e.credited)}` : `surrendered, ${NO_CREDIT_RULE}`;
32
+ case 'despawned':
33
+ return reason === 'idle' ? 'removed for idling too long: no credit, no rating change' : 'removed when its API key was revoked: no credit, no rating change';
34
+ case 'hibernated':
35
+ return e.reason === 'quiet' ? 'quiet exit: hibernating untouched' : 'earned exit: hibernating with its raid reward';
36
+ default:
37
+ return null;
38
+ }
39
+ }
40
+ /** A raider's right to take ends: it moved another piece, was put in check, died or hibernated. */
41
+ function dropRaider(s, id) {
42
+ for (const r of s.raids)
43
+ r.raiders = r.raiders.filter((x) => x !== id);
44
+ }
45
+ /** Clears everything that belongs to one life of an army. */
46
+ function endLife(pl) {
47
+ pl.movesThisLife = 0;
48
+ pl.quietSince = null;
49
+ pl.checkedSince = null;
50
+ pl.checkedBy = null;
51
+ pl.checkDeadline = null;
52
+ pl.matedAt = null;
53
+ pl.matedBy = null;
54
+ pl.leaveUntil = 0;
55
+ pl.pendingPlace = null;
56
+ pl.enPassant = null;
57
+ pl.earnedExit = false;
58
+ pl.touched = false;
59
+ }
60
+ /** Losing a piece: the idle cap no longer applies and the quiet window restarts. Check alone does not call this. */
61
+ function touch(pl, at) {
62
+ pl.touched = true;
63
+ pl.quietSince = at;
64
+ }
65
+ /** Parity only for non-King captures; materialScores is O(pieces). */
66
+ export function captureRecruits(s, moverId, victim) {
67
+ if (victim.type === 'K')
68
+ return false;
69
+ const scores = materialScores(s);
70
+ return recruitsOnCapture(scores.get(moverId) ?? 0, scores.get(victim.owner) ?? 0);
71
+ }
72
+ /** The only way world state changes — the server and every client run exactly this. */
73
+ export function applyEvent(s, e) {
74
+ switch (e.type) {
75
+ case 'zone':
76
+ s.radius = e.radius;
77
+ return;
78
+ case 'spawned':
79
+ s.players.set(e.player.id, { ...e.player });
80
+ for (const p of e.pieces)
81
+ addPiece(s, { ...p });
82
+ return;
83
+ case 'moved': {
84
+ const p = s.pieces.get(e.pieceId);
85
+ const mover = s.players.get(e.playerId);
86
+ mover.pendingPlace = null;
87
+ if (e.captured !== null) {
88
+ const victim = s.pieces.get(e.captured);
89
+ const owner = s.players.get(victim.owner);
90
+ if (owner)
91
+ touch(owner, e.at);
92
+ const recruit = e.recruit ?? captureRecruits(s, e.playerId, victim);
93
+ removePiece(s, e.captured);
94
+ mover.captures++;
95
+ if (recruit)
96
+ mover.pendingPlace = { kind: 'recruit', type: victim.type };
97
+ }
98
+ s.board.delete(cellKey(p.x, p.y));
99
+ // A pawn's 2-cell first step leaves an en passant right on the cell it skipped.
100
+ const double = p.type === 'P' && Math.max(Math.abs(e.to.x - p.x), Math.abs(e.to.y - p.y)) === 2;
101
+ mover.enPassant = double ? { pieceId: p.id, cell: { x: (p.x + e.to.x) / 2, y: (p.y + e.to.y) / 2 } } : null;
102
+ p.x = e.to.x;
103
+ p.y = e.to.y;
104
+ p.fresh = false;
105
+ s.board.set(cellKey(p.x, p.y), p.id);
106
+ mover.readyAt = e.at + s.config.cooldownMs;
107
+ mover.movesThisLife++;
108
+ mover.quietSince = e.at;
109
+ mover.earnedExit = false;
110
+ dropRaider(s, e.playerId);
111
+ return;
112
+ }
113
+ case 'placed': {
114
+ const mover = s.players.get(e.playerId);
115
+ addPiece(s, { ...e.piece });
116
+ mover.readyAt = e.at + s.config.cooldownMs;
117
+ mover.movesThisLife++;
118
+ mover.quietSince = e.at;
119
+ mover.pendingPlace = null;
120
+ mover.enPassant = null;
121
+ mover.earnedExit = e.kind === 'raid';
122
+ if (e.kind !== 'raid')
123
+ dropRaider(s, e.playerId);
124
+ if (e.kind === 'raid') {
125
+ const raid = s.raids.find((r) => r.id === e.raidId);
126
+ const t = e.piece.type;
127
+ if (raid && raid.pool[t] > 0)
128
+ raid.pool[t]--;
129
+ }
130
+ return;
131
+ }
132
+ case 'checkStarted': {
133
+ const pl = s.players.get(e.playerId);
134
+ pl.checkedSince = e.at;
135
+ pl.checkedBy = e.by;
136
+ dropRaider(s, e.playerId);
137
+ // Clock from when the army can move (cooldown does not extend the grace after ready).
138
+ const grace = s.config.checkGraceCycles * s.config.cooldownMs;
139
+ pl.checkDeadline = Math.max(e.at, pl.readyAt) + grace;
140
+ // Idle safety cap no longer applies, but check alone must not restart quiet exit.
141
+ pl.touched = true;
142
+ return;
143
+ }
144
+ case 'checkEnded': {
145
+ const pl = s.players.get(e.playerId);
146
+ pl.checkedSince = null;
147
+ pl.checkedBy = null;
148
+ pl.checkDeadline = null;
149
+ return;
150
+ }
151
+ case 'mateStarted': {
152
+ const pl = s.players.get(e.playerId);
153
+ pl.matedAt = e.at;
154
+ pl.matedBy = e.by;
155
+ return;
156
+ }
157
+ case 'rescued': {
158
+ const pl = s.players.get(e.playerId);
159
+ pl.matedAt = null;
160
+ pl.matedBy = null;
161
+ return;
162
+ }
163
+ case 'mated':
164
+ case 'surrendered':
165
+ case 'despawned': {
166
+ for (const p of piecesOf(s, e.playerId))
167
+ removePiece(s, p.id);
168
+ const victim = s.players.get(e.playerId);
169
+ dropRaider(s, e.playerId);
170
+ if (victim.alive) {
171
+ victim.alive = false;
172
+ victim.deaths++;
173
+ }
174
+ endLife(victim);
175
+ victim.hibernateUntil = 0;
176
+ // Stamp death time into readyAt (unused while dead; spawn resets it). Needed so
177
+ // server prune grace is measured from death, not a leftover move cooldown.
178
+ victim.readyAt = e.at;
179
+ return;
180
+ }
181
+ case 'raidOpened': {
182
+ // Raiders that are gone by the time the event applies (a mutual mate in one batch) lose their rights.
183
+ const raiders = e.raid.raiders.filter((id) => s.players.get(id)?.alive);
184
+ // Every raider counts the mate; a raid with nothing left to take opens nothing.
185
+ if (Object.values(e.raid.pool).some((n) => n > 0))
186
+ s.raids.push({ ...e.raid, pool: { ...e.raid.pool }, raiders });
187
+ for (const id of raiders)
188
+ s.players.get(id).mates++;
189
+ return;
190
+ }
191
+ case 'raidClosed':
192
+ s.raids = s.raids.filter((r) => r.id !== e.raidId);
193
+ return;
194
+ case 'leaving':
195
+ s.players.get(e.playerId).leaveUntil = e.until;
196
+ return;
197
+ case 'enPassantEnded':
198
+ s.players.get(e.playerId).enPassant = null;
199
+ return;
200
+ case 'hibernated': {
201
+ for (const p of piecesOf(s, e.playerId))
202
+ removePiece(s, p.id);
203
+ const pl = s.players.get(e.playerId);
204
+ dropRaider(s, e.playerId);
205
+ pl.alive = false;
206
+ endLife(pl);
207
+ pl.hibernateUntil = e.until;
208
+ return;
209
+ }
210
+ case 'skipped':
211
+ s.players.get(e.playerId).readyAt = e.at + s.config.cooldownMs;
212
+ return;
213
+ }
214
+ }
@@ -0,0 +1,38 @@
1
+ import { type PieceType, type WorldState } from "./types.js";
2
+ /**
3
+ * The Warlord Stack, north row first. The King's cell is the army center.
4
+ * Knights on the open core flanks (can jump out); rooks tucked in the pawn shell.
5
+ */
6
+ export declare const WARLORD_STACK: string[];
7
+ export type LayoutCell = {
8
+ type: PieceType;
9
+ x: number;
10
+ y: number;
11
+ };
12
+ export declare function warlordStack(cx: number, cy: number): LayoutCell[];
13
+ /** Fresh Warlord Stack material — derived from `warlordStack`, not a magic 39. */
14
+ export declare const FRESH_ARMY_MATERIAL: number;
15
+ /**
16
+ * Warlord Stack slots with holes for missing pieces; leftover pieces of any type
17
+ * go on rings around the stack (order Q, R, B, N, P), clockwise from east of King.
18
+ */
19
+ export declare function returnLayout(cx: number, cy: number, army: {
20
+ type: PieceType;
21
+ }[]): LayoutCell[];
22
+ /**
23
+ * Exact no-first-capture check either way, plus new King not attacked.
24
+ * Places `cells` virtually (pawns `fresh`), tests, restores the board exactly.
25
+ * Only inspects pieces within `maxRange + 2` of the footprint (perf).
26
+ */
27
+ export declare function safeFirstMove(s: WorldState, cells: LayoutCell[]): boolean;
28
+ /**
29
+ * Picks an army center on the spawn lattice. Prefer a neighbour of similar army
30
+ * material, then most occupied neighbours, then nearest to the alive-King centroid.
31
+ * Grows the zone by one lattice step when full.
32
+ * Used for spawn, respawn and hibernate return (`cellsAt` = Return Layout when returning).
33
+ */
34
+ export declare function findSpawn(s: WorldState, cellsAt?: (cx: number, cy: number) => LayoutCell[], myMaterial?: number): {
35
+ x: number;
36
+ y: number;
37
+ radius: number;
38
+ };
@@ -0,0 +1,271 @@
1
+ // Copyright 2026 Andrius Jaškauskas
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { addPiece, materialScores, pieceAt, removePiece } from "./board.js";
4
+ import { attackers, pseudoMoves } from "./moves.js";
5
+ import { FOOTPRINT_H, FOOTPRINT_W, PIECE_VALUE, } from "./types.js";
6
+ /**
7
+ * The Warlord Stack, north row first. The King's cell is the army center.
8
+ * Knights on the open core flanks (can jump out); rooks tucked in the pawn shell.
9
+ */
10
+ export const WARLORD_STACK = [".PP.", "PRBP", "NQKN", "PBRP", ".PP."];
11
+ export function warlordStack(cx, cy) {
12
+ return WARLORD_STACK.flatMap((row, r) => [...row].flatMap((ch, c) => ch === "."
13
+ ? []
14
+ : [{ type: ch, x: cx + c - 2, y: cy + 2 - r }]));
15
+ }
16
+ /** Fresh Warlord Stack material — derived from `warlordStack`, not a magic 39. */
17
+ export const FRESH_ARMY_MATERIAL = warlordStack(0, 0).reduce((n, c) => n + PIECE_VALUE[c.type], 0);
18
+ /**
19
+ * Warlord Stack slots with holes for missing pieces; leftover pieces of any type
20
+ * go on rings around the stack (order Q, R, B, N, P), clockwise from east of King.
21
+ */
22
+ export function returnLayout(cx, cy, army) {
23
+ const slots = warlordStack(cx, cy);
24
+ const pool = new Map();
25
+ for (const p of army)
26
+ pool.set(p.type, (pool.get(p.type) ?? 0) + 1);
27
+ const out = [];
28
+ const reserved = new Set(slots.map((s) => `${s.x},${s.y}`));
29
+ for (const slot of slots) {
30
+ const n = pool.get(slot.type) ?? 0;
31
+ if (n <= 0)
32
+ continue;
33
+ pool.set(slot.type, n - 1);
34
+ out.push({ type: slot.type, x: slot.x, y: slot.y });
35
+ }
36
+ // Deterministic extras: Q → R → B → N → P (preserves recruits/rewards on return).
37
+ const EXTRA_ORDER = ["Q", "R", "B", "N", "P"];
38
+ const extras = [];
39
+ for (const t of EXTRA_ORDER) {
40
+ let n = pool.get(t) ?? 0;
41
+ while (n-- > 0)
42
+ extras.push(t);
43
+ }
44
+ let ei = 0;
45
+ for (let ring = 1; ei < extras.length; ring++) {
46
+ for (const [dx, dy] of chebyshevRingClockwiseFromEast(ring)) {
47
+ if (ei >= extras.length)
48
+ break;
49
+ const x = cx + dx;
50
+ const y = cy + dy;
51
+ if (reserved.has(`${x},${y}`))
52
+ continue;
53
+ out.push({ type: extras[ei++], x, y });
54
+ reserved.add(`${x},${y}`);
55
+ }
56
+ }
57
+ return out;
58
+ }
59
+ const chebyshev = (a, b) => Math.max(Math.abs(a.x - b.x), Math.abs(a.y - b.y));
60
+ /** Temp owner for virtual placement — must not collide with real player ids. */
61
+ const SPAWN_OWNER = "\0spawn";
62
+ /**
63
+ * Exact no-first-capture check either way, plus new King not attacked.
64
+ * Places `cells` virtually (pawns `fresh`), tests, restores the board exactly.
65
+ * Only inspects pieces within `maxRange + 2` of the footprint (perf).
66
+ */
67
+ export function safeFirstMove(s, cells) {
68
+ if (!cells.length)
69
+ return true;
70
+ const margin = s.config.maxRange + 2;
71
+ const added = [];
72
+ let nextId = -1;
73
+ for (const c of cells) {
74
+ const p = {
75
+ id: nextId--,
76
+ owner: SPAWN_OWNER,
77
+ type: c.type,
78
+ x: c.x,
79
+ y: c.y,
80
+ fresh: c.type === "P",
81
+ };
82
+ addPiece(s, p);
83
+ added.push(p);
84
+ }
85
+ try {
86
+ const newIds = new Set(added.map((p) => p.id));
87
+ for (const p of added) {
88
+ for (const to of pseudoMoves(s, p)) {
89
+ const hit = pieceAt(s, to.x, to.y);
90
+ if (hit && !newIds.has(hit.id))
91
+ return false;
92
+ }
93
+ }
94
+ for (const p of piecesNear(s, cells, margin)) {
95
+ if (newIds.has(p.id))
96
+ continue;
97
+ for (const to of pseudoMoves(s, p)) {
98
+ const hit = pieceAt(s, to.x, to.y);
99
+ if (hit && newIds.has(hit.id))
100
+ return false;
101
+ }
102
+ }
103
+ const nk = added.find((p) => p.type === "K");
104
+ if (nk && attackers(s, nk, SPAWN_OWNER).length > 0)
105
+ return false;
106
+ return true;
107
+ }
108
+ finally {
109
+ for (const p of added)
110
+ removePiece(s, p.id);
111
+ }
112
+ }
113
+ function cellsInZone(cells, radius) {
114
+ return cells.every((c) => Math.abs(c.x) <= radius && Math.abs(c.y) <= radius);
115
+ }
116
+ function clearForCells(s, cells) {
117
+ for (const c of cells)
118
+ if (pieceAt(s, c.x, c.y))
119
+ return false;
120
+ const gap = s.config.spawnSpacing;
121
+ for (const p of piecesNear(s, cells, gap - 1)) {
122
+ for (const c of cells) {
123
+ if (chebyshev(p, c) < gap)
124
+ return false;
125
+ }
126
+ }
127
+ return true;
128
+ }
129
+ /** Pieces within Chebyshev `margin` of the cells' bounding box — board-index lookups, not a full scan. */
130
+ function piecesNear(s, cells, margin) {
131
+ let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;
132
+ for (const c of cells) {
133
+ x0 = Math.min(x0, c.x);
134
+ x1 = Math.max(x1, c.x);
135
+ y0 = Math.min(y0, c.y);
136
+ y1 = Math.max(y1, c.y);
137
+ }
138
+ const out = [];
139
+ for (let x = x0 - margin; x <= x1 + margin; x++) {
140
+ for (let y = y0 - margin; y <= y1 + margin; y++) {
141
+ const p = pieceAt(s, x, y);
142
+ if (p)
143
+ out.push(p);
144
+ }
145
+ }
146
+ return out;
147
+ }
148
+ /** Slot "belongs" to a King that still sits near its lattice centre (half-pitch). */
149
+ function slotOccupied(kings, cx, cy, stepX, stepY) {
150
+ const reach = Math.floor(Math.min(stepX, stepY) / 2);
151
+ return kings.some((k) => chebyshev(k, { x: cx, y: cy }) <= reach);
152
+ }
153
+ function neighborOccupancy(kings, i, j, stepX, stepY) {
154
+ let n = 0;
155
+ for (let di = -1; di <= 1; di++) {
156
+ for (let dj = -1; dj <= 1; dj++) {
157
+ if (di === 0 && dj === 0)
158
+ continue;
159
+ if (slotOccupied(kings, (i + di) * stepX, (j + dj) * stepY, stepX, stepY))
160
+ n++;
161
+ }
162
+ }
163
+ return n;
164
+ }
165
+ /** Alive Kings in one pass over the pieces (kingOf per player would be O(players × pieces)). */
166
+ function aliveKings(s) {
167
+ const out = [];
168
+ for (const p of s.pieces.values()) {
169
+ if (p.type === "K" && s.players.get(p.owner)?.alive)
170
+ out.push({ x: p.x, y: p.y, owner: p.owner });
171
+ }
172
+ return out;
173
+ }
174
+ function centroid(kings) {
175
+ if (!kings.length)
176
+ return { x: 0, y: 0 };
177
+ let sx = 0;
178
+ let sy = 0;
179
+ for (const k of kings) {
180
+ sx += k.x;
181
+ sy += k.y;
182
+ }
183
+ return { x: sx / kings.length, y: sy / kings.length };
184
+ }
185
+ /**
186
+ * Material of the nearest alive army to a slot (Chebyshev King→slot).
187
+ * Distance ties → smaller |material − myMaterial| (slot ranking then uses occupancy/centre).
188
+ */
189
+ function nearestArmyMaterial(kings, scores, slot, myMaterial) {
190
+ let bestDist = Infinity;
191
+ let bestMat = 0;
192
+ let bestPeer = Infinity;
193
+ for (const k of kings) {
194
+ const d = chebyshev(k, slot);
195
+ const mat = scores.get(k.owner) ?? 0;
196
+ const peer = Math.abs(mat - myMaterial);
197
+ if (d < bestDist || (d === bestDist && peer < bestPeer)) {
198
+ bestDist = d;
199
+ bestMat = mat;
200
+ bestPeer = peer;
201
+ }
202
+ }
203
+ return bestMat;
204
+ }
205
+ /**
206
+ * Picks an army center on the spawn lattice. Prefer a neighbour of similar army
207
+ * material, then most occupied neighbours, then nearest to the alive-King centroid.
208
+ * Grows the zone by one lattice step when full.
209
+ * Used for spawn, respawn and hibernate return (`cellsAt` = Return Layout when returning).
210
+ */
211
+ export function findSpawn(s, cellsAt = (cx, cy) => warlordStack(cx, cy), myMaterial = FRESH_ARMY_MATERIAL) {
212
+ const stepX = FOOTPRINT_W + s.config.spawnSpacing - 1;
213
+ const stepY = FOOTPRINT_H + s.config.spawnSpacing - 1;
214
+ const grow = Math.max(stepX, stepY);
215
+ const kings = aliveKings(s);
216
+ const centre = centroid(kings);
217
+ const scores = materialScores(s);
218
+ for (let radius = s.radius;; radius += grow) {
219
+ let best = null;
220
+ // Outward rings of lattice indices; first ring with a valid slot still competes by score
221
+ // across the whole zone so "next to armies" wins over a lone origin slot when both fit.
222
+ const iMax = Math.ceil(radius / stepX) + 1;
223
+ const jMax = Math.ceil(radius / stepY) + 1;
224
+ for (let i = -iMax; i <= iMax; i++) {
225
+ for (let j = -jMax; j <= jMax; j++) {
226
+ const x = i * stepX;
227
+ const y = j * stepY;
228
+ const cells = cellsAt(x, y);
229
+ if (!cellsInZone(cells, radius))
230
+ continue;
231
+ if (!clearForCells(s, cells))
232
+ continue;
233
+ if (!safeFirstMove(s, cells))
234
+ continue;
235
+ const peer = kings.length
236
+ ? Math.abs(nearestArmyMaterial(kings, scores, { x, y }, myMaterial) -
237
+ myMaterial)
238
+ : 0;
239
+ const score = neighborOccupancy(kings, i, j, stepX, stepY);
240
+ const dist = Math.max(Math.abs(x - centre.x), Math.abs(y - centre.y));
241
+ if (!best ||
242
+ peer < best.peer ||
243
+ (peer === best.peer && score > best.score) ||
244
+ (peer === best.peer && score === best.score && dist < best.dist) ||
245
+ (peer === best.peer &&
246
+ score === best.score &&
247
+ dist === best.dist &&
248
+ (x < best.x || (x === best.x && y < best.y)))) {
249
+ best = { x, y, peer, score, dist };
250
+ }
251
+ }
252
+ }
253
+ if (best)
254
+ return { x: best.x, y: best.y, radius };
255
+ }
256
+ }
257
+ /** Chebyshev ring r, starting east (r,0), clockwise (south → west → north → east). */
258
+ function chebyshevRingClockwiseFromEast(r) {
259
+ const out = [[r, 0]];
260
+ for (let y = -1; y >= -r; y--)
261
+ out.push([r, y]);
262
+ for (let x = r - 1; x >= -r; x--)
263
+ out.push([x, -r]);
264
+ for (let y = -r + 1; y <= r; y++)
265
+ out.push([-r, y]);
266
+ for (let x = -r + 1; x <= r; x++)
267
+ out.push([x, r]);
268
+ for (let y = r - 1; y >= 1; y--)
269
+ out.push([r, y]);
270
+ return out;
271
+ }
@@ -0,0 +1,7 @@
1
+ export * from './types.js';
2
+ export * from './board.js';
3
+ export * from './moves.js';
4
+ export * from './legality.js';
5
+ export * from './formation.js';
6
+ export * from './events.js';
7
+ export * from './tick.js';
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ // Copyright 2026 Andrius Jaškauskas
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ export * from './types.js';
4
+ export * from './board.js';
5
+ export * from './moves.js';
6
+ export * from './legality.js';
7
+ export * from './formation.js';
8
+ export * from './events.js';
9
+ export * from './tick.js';
@@ -0,0 +1,32 @@
1
+ import { type ReferenceName } from './references.js';
2
+ import { type Bot, type GameOptions, type GameResult, type RecordLine } from './sim.js';
3
+ /** A reference opponent as a bot. */
4
+ export declare const referenceBot: (name: ReferenceName) => Bot;
5
+ export declare const isReference: (name: string) => name is ReferenceName;
6
+ export interface BenchOptions extends Omit<GameOptions, 'seed' | 'record'> {
7
+ /** The references to play against: one army each, so `['smart', 'smart']` is a three-army game. */
8
+ opponents: ReferenceName[];
9
+ /** Games to play; game i uses seed `seed + i`. Default 10. */
10
+ games?: number;
11
+ seed?: number;
12
+ /** Receives every record line of every game. */
13
+ record?: (line: RecordLine) => void;
14
+ }
15
+ export interface BenchReport {
16
+ games: number;
17
+ /** Games the bot won as the last army standing. */
18
+ wins: number;
19
+ /** Games ended by the turn cap with the bot still standing. */
20
+ survived: number;
21
+ /** Games the bot was removed from. */
22
+ lost: number;
23
+ captures: number;
24
+ mates: number;
25
+ rejected: number;
26
+ results: GameResult[];
27
+ }
28
+ /**
29
+ * Plays `bot` against the references, rotating its seat so a fixed position favours nobody.
30
+ * The kit scores nothing but what happened: wins, survivals, losses, captures, mates.
31
+ */
32
+ export declare function bench(bot: Bot, opts: BenchOptions): Promise<BenchReport>;
@@ -0,0 +1,36 @@
1
+ // Copyright 2026 Andrius Jaškauskas
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { referenceAction, REFERENCES } from './references.js';
4
+ import { runGame } from './sim.js';
5
+ /** A reference opponent as a bot. */
6
+ export const referenceBot = (name) => (view) => referenceAction(name, view.state, view.me, view.rng);
7
+ export const isReference = (name) => REFERENCES.includes(name);
8
+ /**
9
+ * Plays `bot` against the references, rotating its seat so a fixed position favours nobody.
10
+ * The kit scores nothing but what happened: wins, survivals, losses, captures, mates.
11
+ */
12
+ export async function bench(bot, opts) {
13
+ const games = opts.games ?? 10;
14
+ const seed = opts.seed ?? 1;
15
+ const n = opts.opponents.length + 1;
16
+ const report = { games, wins: 0, survived: 0, lost: 0, captures: 0, mates: 0, rejected: 0, results: [] };
17
+ for (let g = 0; g < games; g++) {
18
+ const seats = [{ name: 'bot', bot }, ...opts.opponents.map((name) => ({ name, bot: referenceBot(name) }))];
19
+ // Rotate: the bot sits in seat g mod n.
20
+ const shift = g % n;
21
+ const order = seats.map((_, i) => seats[(i - shift + n) % n]);
22
+ const result = await runGame(order, { ...opts, seed: seed + g, record: opts.record });
23
+ const me = result.armies.find((a) => a.name === 'bot');
24
+ if (result.winner === me.id)
25
+ report.wins++;
26
+ else if (me.alive)
27
+ report.survived++;
28
+ else
29
+ report.lost++;
30
+ report.captures += me.captures;
31
+ report.mates += me.mates;
32
+ report.rejected += me.rejected;
33
+ report.results.push(result);
34
+ }
35
+ return report;
36
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};