@chessar/engine 0.0.0-stage → 0.1.1
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/CHANGELOG.md +16 -0
- package/LICENSE +201 -0
- package/NOTICE +5 -0
- package/README.md +78 -2
- package/TRADEMARKS.md +3 -0
- package/dist/board.d.ts +24 -0
- package/dist/board.js +83 -0
- package/dist/events.d.ts +122 -0
- package/dist/events.js +214 -0
- package/dist/formation.d.ts +38 -0
- package/dist/formation.js +271 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +9 -0
- package/dist/kit/bench.d.ts +32 -0
- package/dist/kit/bench.js +36 -0
- package/dist/kit/cli.d.ts +2 -0
- package/dist/kit/cli.js +107 -0
- package/dist/kit/fixtures.d.ts +14 -0
- package/dist/kit/fixtures.js +27 -0
- package/dist/kit/helpers.d.ts +39 -0
- package/dist/kit/helpers.js +138 -0
- package/dist/kit/index.d.ts +6 -0
- package/dist/kit/index.js +8 -0
- package/dist/kit/protocol.d.ts +59 -0
- package/dist/kit/protocol.js +86 -0
- package/dist/kit/references.d.ts +40 -0
- package/dist/kit/references.js +341 -0
- package/dist/kit/sim.d.ts +99 -0
- package/dist/kit/sim.js +197 -0
- package/dist/legality.d.ts +82 -0
- package/dist/legality.js +350 -0
- package/dist/moves.d.ts +21 -0
- package/dist/moves.js +105 -0
- package/dist/tick.d.ts +27 -0
- package/dist/tick.js +107 -0
- package/dist/types.d.ts +148 -0
- package/dist/types.js +89 -0
- package/docs/line-protocol.md +69 -0
- package/docs/rules.md +158 -0
- package/package.json +60 -4
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
// Copyright 2026 Andrius Jaškauskas
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
import { attackers, cellKey, hasLegalMove, isInCheck, kingOf, legalPlacements, piecesOf, placeSource, } from '../index.js';
|
|
4
|
+
import { ANY, VALUE, allMoves, chebyshev, deliversCheck, deliversMateNear, exposure, nearbyEnemyKings, nearestKing, pickPlaceGreedy, pressure, withMove, } from './helpers.js';
|
|
5
|
+
/** The reference opponents of the test kit: weaker, readable players to measure a bot against. */
|
|
6
|
+
export const REFERENCES = ['smart', 'brawler', 'turtle', 'trickster', 'pack'];
|
|
7
|
+
const EVAL_STYLES = ['smart', 'brawler', 'turtle', 'trickster'];
|
|
8
|
+
const isEvalStyle = (s) => EVAL_STYLES.includes(s);
|
|
9
|
+
export const STYLES = {
|
|
10
|
+
// Intelligent baseline — keep the army together, bring the rear up.
|
|
11
|
+
smart: {
|
|
12
|
+
gain: 10,
|
|
13
|
+
exposure: 9,
|
|
14
|
+
pressure: 3,
|
|
15
|
+
approach: 0.55,
|
|
16
|
+
cohesion: 5,
|
|
17
|
+
enemyPressure: 2,
|
|
18
|
+
hangMult: 1,
|
|
19
|
+
checkBonus: 0,
|
|
20
|
+
topN: 1,
|
|
21
|
+
},
|
|
22
|
+
// Strong fights: press, trade, hunt — still no lone scout races.
|
|
23
|
+
brawler: {
|
|
24
|
+
gain: 14,
|
|
25
|
+
exposure: 5,
|
|
26
|
+
pressure: 5.5,
|
|
27
|
+
approach: 1.2,
|
|
28
|
+
cohesion: 3,
|
|
29
|
+
enemyPressure: 1,
|
|
30
|
+
hangMult: 0.55,
|
|
31
|
+
checkBonus: 90,
|
|
32
|
+
topN: 1,
|
|
33
|
+
},
|
|
34
|
+
// Extra defensive: cling, refuse hangs, shield King.
|
|
35
|
+
turtle: {
|
|
36
|
+
gain: 6,
|
|
37
|
+
exposure: 16,
|
|
38
|
+
pressure: 1.2,
|
|
39
|
+
approach: 0.15,
|
|
40
|
+
cohesion: 8,
|
|
41
|
+
enemyPressure: 5.5,
|
|
42
|
+
hangMult: 1.5,
|
|
43
|
+
checkBonus: 0,
|
|
44
|
+
topN: 1,
|
|
45
|
+
},
|
|
46
|
+
// Trickster: checks & chaos among near-best moves.
|
|
47
|
+
trickster: {
|
|
48
|
+
gain: 8,
|
|
49
|
+
exposure: 7,
|
|
50
|
+
pressure: 2.5,
|
|
51
|
+
approach: 0.4,
|
|
52
|
+
cohesion: 3.5,
|
|
53
|
+
enemyPressure: 2,
|
|
54
|
+
hangMult: 0.8,
|
|
55
|
+
checkBonus: 240,
|
|
56
|
+
topN: 3,
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
/** Prefer staying roughly within this Chebyshev distance of the own King (pack cohesion). */
|
|
60
|
+
const FORMATION = 6;
|
|
61
|
+
/** Don't press inside this distance until the rear has caught up (pack siege). */
|
|
62
|
+
const STANDOFF = 5;
|
|
63
|
+
function pickTied(tied, rng) {
|
|
64
|
+
return tied[Math.floor(rng() * tied.length)];
|
|
65
|
+
}
|
|
66
|
+
/** How far the furthest friendly non-King is from the single target King. */
|
|
67
|
+
function armyRearDistTo(s, playerId, target) {
|
|
68
|
+
let max = 0;
|
|
69
|
+
for (const p of piecesOf(s, playerId)) {
|
|
70
|
+
if (p.type === 'K')
|
|
71
|
+
continue;
|
|
72
|
+
max = Math.max(max, chebyshev(p, target));
|
|
73
|
+
}
|
|
74
|
+
return max;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Pack / standoff (medium): develop as an army, hold distance until the rear arrives.
|
|
78
|
+
* In check: escape that minimises material loss (no Queen-for-pawn).
|
|
79
|
+
*/
|
|
80
|
+
export function pickPack(s, playerId, rng = Math.random, movesOf = allMoves) {
|
|
81
|
+
const moves = movesOf(s, playerId);
|
|
82
|
+
if (!moves.length)
|
|
83
|
+
return null;
|
|
84
|
+
const ownKing = kingOf(s, playerId);
|
|
85
|
+
const kings = ownKing ? nearbyEnemyKings(s, playerId, ownKing) : [];
|
|
86
|
+
const target = ownKing ? nearestKing(ownKing, kings) : null;
|
|
87
|
+
const rear = target ? armyRearDistTo(s, playerId, target) : 0;
|
|
88
|
+
const armyReady = !target || rear <= FORMATION + 2;
|
|
89
|
+
const inCheck = isInCheck(s, playerId);
|
|
90
|
+
const mine = piecesOf(s, playerId);
|
|
91
|
+
let bestScore = -Infinity;
|
|
92
|
+
const tied = [];
|
|
93
|
+
const consider = (m, score) => {
|
|
94
|
+
if (score > bestScore) {
|
|
95
|
+
bestScore = score;
|
|
96
|
+
tied.length = 0;
|
|
97
|
+
tied.push(m);
|
|
98
|
+
}
|
|
99
|
+
else if (score === bestScore) {
|
|
100
|
+
tied.push(m);
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
for (const m of moves) {
|
|
104
|
+
const piece = s.pieces.get(m.pieceId);
|
|
105
|
+
let score = 0;
|
|
106
|
+
if (deliversMateNear(s, playerId, m, kings)) {
|
|
107
|
+
consider(m, 1_000_000);
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (inCheck) {
|
|
111
|
+
// Minimise loss: material gained minus post-move exposure (Queen×pawn hang loses).
|
|
112
|
+
const gain = m.capture !== null ? VALUE[s.pieces.get(m.capture).type] : 0;
|
|
113
|
+
score = withMove(s, m, () => gain * 10 - exposure(s, playerId, mine) * 100);
|
|
114
|
+
// Mild preference to step the King clear rather than fling a piece.
|
|
115
|
+
if (piece.type === 'K')
|
|
116
|
+
score += 5;
|
|
117
|
+
consider(m, score);
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (m.capture !== null) {
|
|
121
|
+
const victim = s.pieces.get(m.capture);
|
|
122
|
+
const val = VALUE[victim.type];
|
|
123
|
+
const hang = withMove(s, m, () => attackers(s, m.to, playerId).length > 0);
|
|
124
|
+
if (!hang) {
|
|
125
|
+
if (armyReady || val >= 5)
|
|
126
|
+
score += 8_000 + val * 80;
|
|
127
|
+
else if (val >= 3)
|
|
128
|
+
score += 400 + val * 40;
|
|
129
|
+
else
|
|
130
|
+
score += 50;
|
|
131
|
+
}
|
|
132
|
+
else if (val > VALUE[piece.type] && armyReady) {
|
|
133
|
+
score += 1_500 + val * 20;
|
|
134
|
+
}
|
|
135
|
+
else {
|
|
136
|
+
score -= 800;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (deliversCheck(s, playerId, m, kings))
|
|
140
|
+
score += armyReady ? 500 : 20;
|
|
141
|
+
if (piece.type !== 'K' && target) {
|
|
142
|
+
const before = chebyshev(piece, target);
|
|
143
|
+
const after = chebyshev(m.to, target);
|
|
144
|
+
const progress = before - after;
|
|
145
|
+
const lead = rear - before;
|
|
146
|
+
if (progress > 0 && before >= rear - 1)
|
|
147
|
+
score += progress * 70 + 90;
|
|
148
|
+
else if (progress > 0 && lead >= 2)
|
|
149
|
+
score -= progress * 55;
|
|
150
|
+
else if (progress > 0 && armyReady)
|
|
151
|
+
score += progress * 20;
|
|
152
|
+
else if (progress > 0)
|
|
153
|
+
score += progress * 8;
|
|
154
|
+
else if (progress < 0 && lead >= 2)
|
|
155
|
+
score += 25;
|
|
156
|
+
if (!armyReady && after < STANDOFF && before >= STANDOFF)
|
|
157
|
+
score -= 120;
|
|
158
|
+
if (!armyReady && after < STANDOFF)
|
|
159
|
+
score -= (STANDOFF - after) * 25;
|
|
160
|
+
}
|
|
161
|
+
if (piece.type !== 'K' && ownKing) {
|
|
162
|
+
const formDist = chebyshev(m.to, ownKing);
|
|
163
|
+
if (formDist > FORMATION)
|
|
164
|
+
score -= (formDist - FORMATION) * 45;
|
|
165
|
+
const fromOwn = chebyshev(piece, ownKing);
|
|
166
|
+
if (fromOwn > FORMATION && chebyshev(m.to, ownKing) < fromOwn)
|
|
167
|
+
score += 30;
|
|
168
|
+
}
|
|
169
|
+
else if (piece.type === 'K') {
|
|
170
|
+
score -= 100;
|
|
171
|
+
if (ownKing) {
|
|
172
|
+
const army = mine.filter((p) => p.type !== 'K');
|
|
173
|
+
if (army.length) {
|
|
174
|
+
const cx = army.reduce((a, p) => a + p.x, 0) / army.length;
|
|
175
|
+
const cy = army.reduce((a, p) => a + p.y, 0) / army.length;
|
|
176
|
+
const before = Math.max(Math.abs(ownKing.x - cx), Math.abs(ownKing.y - cy));
|
|
177
|
+
const after = Math.max(Math.abs(m.to.x - cx), Math.abs(m.to.y - cy));
|
|
178
|
+
score += (before - after) * 15;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
consider(m, score);
|
|
183
|
+
}
|
|
184
|
+
if (!tied.length)
|
|
185
|
+
return moves[Math.floor(rng() * moves.length)];
|
|
186
|
+
return pickTied(tied, rng);
|
|
187
|
+
}
|
|
188
|
+
function scoreStyledMove(s, me, m, style) {
|
|
189
|
+
const myK = kingOf(s, me);
|
|
190
|
+
if (!myK)
|
|
191
|
+
return -Infinity;
|
|
192
|
+
const mine = piecesOf(s, me);
|
|
193
|
+
const kings = nearbyEnemyKings(s, me, myK);
|
|
194
|
+
const target = nearestKing(myK, kings);
|
|
195
|
+
const piece = s.pieces.get(m.pieceId);
|
|
196
|
+
const from = { x: piece.x, y: piece.y };
|
|
197
|
+
const gain = m.capture !== null ? VALUE[s.pieces.get(m.capture).type] : 0;
|
|
198
|
+
return withMove(s, m, () => {
|
|
199
|
+
for (const k of kings) {
|
|
200
|
+
if (isInCheck(s, k.owner) && !hasLegalMove(s, k.owner))
|
|
201
|
+
return 1e6;
|
|
202
|
+
}
|
|
203
|
+
const exp = exposure(s, me, mine);
|
|
204
|
+
let sc = gain * style.gain - exp * style.exposure;
|
|
205
|
+
if (piece.type !== 'K') {
|
|
206
|
+
const atk = attackers(s, m.to, me);
|
|
207
|
+
if (atk.length) {
|
|
208
|
+
const cheapest = Math.min(...atk.map((a) => (a.type === 'K' ? 100 : VALUE[a.type])));
|
|
209
|
+
const defended = attackers(s, m.to, ANY).some((q) => q.owner === me && q.id !== piece.id);
|
|
210
|
+
const loss = defended ? Math.max(0, VALUE[piece.type] - cheapest) : VALUE[piece.type];
|
|
211
|
+
if (loss >= gain && loss > 0)
|
|
212
|
+
sc -= (1_000 + loss * 80) * style.hangMult;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (target) {
|
|
216
|
+
sc += pressure(s, me, target) * style.pressure;
|
|
217
|
+
if (piece.type !== 'K') {
|
|
218
|
+
const before = chebyshev(from, target);
|
|
219
|
+
const after = chebyshev(m.to, target);
|
|
220
|
+
const progress = before - after;
|
|
221
|
+
const rear = armyRearDistTo(s, me, target);
|
|
222
|
+
// Advance the lagging wing; don't let a scout race ahead alone.
|
|
223
|
+
if (progress > 0 && before >= rear - 1)
|
|
224
|
+
sc += progress * style.approach * 3 + style.cohesion;
|
|
225
|
+
else if (progress > 0 && rear - before >= 3)
|
|
226
|
+
sc -= progress * style.cohesion;
|
|
227
|
+
else if (progress > 0)
|
|
228
|
+
sc += progress * style.approach;
|
|
229
|
+
const formDist = chebyshev(m.to, myK);
|
|
230
|
+
if (formDist > 6)
|
|
231
|
+
sc -= (formDist - 6) * style.cohesion;
|
|
232
|
+
const fromOwn = chebyshev(from, myK);
|
|
233
|
+
if (fromOwn > 6 && chebyshev(m.to, myK) < fromOwn)
|
|
234
|
+
sc += style.cohesion * 2;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
let enemyPressure = 0;
|
|
238
|
+
for (const k of kings)
|
|
239
|
+
enemyPressure = Math.max(enemyPressure, pressure(s, k.owner, myK));
|
|
240
|
+
sc -= enemyPressure * style.enemyPressure;
|
|
241
|
+
if (piece.type === 'K')
|
|
242
|
+
sc -= 1;
|
|
243
|
+
if (style.checkBonus && deliversCheck(s, me, m, kings))
|
|
244
|
+
sc += style.checkBonus;
|
|
245
|
+
return sc;
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
function pickTopN(scored, topN, rng) {
|
|
249
|
+
scored.sort((a, b) => b.score - a.score);
|
|
250
|
+
const floor = scored[Math.min(topN, scored.length) - 1].score;
|
|
251
|
+
const pool = scored.filter((x) => x.score + 1e-9 >= floor).map((x) => x.m);
|
|
252
|
+
return pickTied(pool, rng);
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Eval strategy: material − exposure + pressure on one target King − pressure on own King + mild approach +
|
|
256
|
+
* cohesion; mate = +∞. Personalities (`brawler` / `turtle` / `trickster`) reuse this search with different weights.
|
|
257
|
+
*/
|
|
258
|
+
export function pickSmart(s, me, rng = Math.random, movesOf = allMoves) {
|
|
259
|
+
return pickEval(s, me, rng, STYLES.smart, movesOf);
|
|
260
|
+
}
|
|
261
|
+
export function pickEval(s, me, rng = Math.random, style = STYLES.smart, movesOf = allMoves) {
|
|
262
|
+
const myK = kingOf(s, me);
|
|
263
|
+
if (!myK)
|
|
264
|
+
return null;
|
|
265
|
+
const moves = movesOf(s, me);
|
|
266
|
+
if (!moves.length)
|
|
267
|
+
return null;
|
|
268
|
+
const scored = moves.map((m) => ({ m, score: scoreStyledMove(s, me, m, style) }));
|
|
269
|
+
return pickTopN(scored, style.topN, rng);
|
|
270
|
+
}
|
|
271
|
+
/** Score a placement the same way styled eval scores a quiet gain (ghost piece on board). */
|
|
272
|
+
function scorePlace(s, me, type, to, style = STYLES.smart) {
|
|
273
|
+
const myK = kingOf(s, me);
|
|
274
|
+
if (!myK)
|
|
275
|
+
return -Infinity;
|
|
276
|
+
const kings = nearbyEnemyKings(s, me, myK);
|
|
277
|
+
const target = nearestKing(myK, kings);
|
|
278
|
+
const ghost = { id: -2, owner: me, type, x: to.x, y: to.y, fresh: false };
|
|
279
|
+
s.pieces.set(ghost.id, ghost);
|
|
280
|
+
s.board.set(cellKey(to.x, to.y), ghost.id);
|
|
281
|
+
try {
|
|
282
|
+
for (const k of kings) {
|
|
283
|
+
if (isInCheck(s, k.owner) && !hasLegalMove(s, k.owner))
|
|
284
|
+
return 1e6;
|
|
285
|
+
}
|
|
286
|
+
let sc = VALUE[type] * style.gain;
|
|
287
|
+
const atk = attackers(s, to, me);
|
|
288
|
+
if (atk.length) {
|
|
289
|
+
const cheapest = Math.min(...atk.map((a) => (a.type === 'K' ? 100 : VALUE[a.type])));
|
|
290
|
+
const defended = attackers(s, to, ANY).some((q) => q.owner === me && q.id !== ghost.id);
|
|
291
|
+
const loss = defended ? Math.max(0, VALUE[type] - cheapest) : VALUE[type];
|
|
292
|
+
sc -= loss * style.exposure;
|
|
293
|
+
}
|
|
294
|
+
if (target)
|
|
295
|
+
sc += pressure(s, me, target) * style.pressure;
|
|
296
|
+
let enemyPressure = 0;
|
|
297
|
+
for (const k of kings)
|
|
298
|
+
enemyPressure = Math.max(enemyPressure, pressure(s, k.owner, myK));
|
|
299
|
+
sc -= enemyPressure * style.enemyPressure;
|
|
300
|
+
return sc;
|
|
301
|
+
}
|
|
302
|
+
finally {
|
|
303
|
+
s.board.delete(cellKey(to.x, to.y));
|
|
304
|
+
s.pieces.delete(ghost.id);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* The action of a reference opponent for its turn, or null when it has none.
|
|
309
|
+
* A mate raid is free material that disappears when someone else is quicker, so the eval styles take from it first,
|
|
310
|
+
* the best-scored piece (the Queen) first; otherwise they weigh placements against moves.
|
|
311
|
+
*/
|
|
312
|
+
export function referenceAction(name, s, playerId, rng = Math.random, movesOf = allMoves) {
|
|
313
|
+
if (isEvalStyle(name)) {
|
|
314
|
+
const style = STYLES[name];
|
|
315
|
+
const raidTakes = legalPlacements(s, playerId).filter((p) => placeSource(s, playerId, p.type)?.kind === 'raid');
|
|
316
|
+
if (raidTakes.length) {
|
|
317
|
+
const best = raidTakes
|
|
318
|
+
.map(({ type, to }) => ({ type, to, score: scorePlace(s, playerId, type, to, style) }))
|
|
319
|
+
.sort((a, b) => b.score - a.score)[0];
|
|
320
|
+
return { kind: 'place', type: best.type, to: best.to };
|
|
321
|
+
}
|
|
322
|
+
const scored = [];
|
|
323
|
+
for (const { type, to } of legalPlacements(s, playerId)) {
|
|
324
|
+
scored.push({ action: { kind: 'place', type, to }, score: scorePlace(s, playerId, type, to, style) });
|
|
325
|
+
}
|
|
326
|
+
for (const m of movesOf(s, playerId)) {
|
|
327
|
+
scored.push({ action: { kind: 'move', ...m }, score: scoreStyledMove(s, playerId, m, style) });
|
|
328
|
+
}
|
|
329
|
+
if (!scored.length)
|
|
330
|
+
return null;
|
|
331
|
+
scored.sort((a, b) => b.score - a.score);
|
|
332
|
+
const floor = scored[Math.min(style.topN, scored.length) - 1].score;
|
|
333
|
+
const pool = scored.filter((x) => x.score + 1e-9 >= floor).map((x) => x.action);
|
|
334
|
+
return pool[Math.floor(rng() * pool.length)];
|
|
335
|
+
}
|
|
336
|
+
const place = pickPlaceGreedy(s, playerId);
|
|
337
|
+
if (place)
|
|
338
|
+
return place;
|
|
339
|
+
const move = pickPack(s, playerId, rng, movesOf);
|
|
340
|
+
return move ? { kind: 'move', ...move } : null;
|
|
341
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { type GameEvent, type PieceType, type Snapshot, type WorldConfig, type WorldState } from '../index.js';
|
|
2
|
+
import { type Action, type MovePick } from './helpers.js';
|
|
3
|
+
import { type Fixture } from './fixtures.js';
|
|
4
|
+
/** What a bot is shown on its turn. */
|
|
5
|
+
export interface TurnView {
|
|
6
|
+
/** The whole board. A bot may look at it freely and must not change it. */
|
|
7
|
+
state: WorldState;
|
|
8
|
+
/** The bot's own army id. */
|
|
9
|
+
me: string;
|
|
10
|
+
/** Turn counter of the game: one per cycle. */
|
|
11
|
+
turn: number;
|
|
12
|
+
/** Every legal move of the army. */
|
|
13
|
+
moves: MovePick[];
|
|
14
|
+
/** Every legal placement of the army (a capture-recruit or a take from a mate raid). */
|
|
15
|
+
places: {
|
|
16
|
+
type: PieceType;
|
|
17
|
+
to: {
|
|
18
|
+
x: number;
|
|
19
|
+
y: number;
|
|
20
|
+
};
|
|
21
|
+
}[];
|
|
22
|
+
/** A seeded random source: the same seed gives the same game. */
|
|
23
|
+
rng: () => number;
|
|
24
|
+
}
|
|
25
|
+
/** A bot: look at the turn, answer with an action, or null to pass. */
|
|
26
|
+
export type Bot = (view: TurnView) => Action | null | Promise<Action | null>;
|
|
27
|
+
export interface Participant {
|
|
28
|
+
name: string;
|
|
29
|
+
bot: Bot;
|
|
30
|
+
}
|
|
31
|
+
/** One line of a JSONL recording. */
|
|
32
|
+
export type RecordLine = {
|
|
33
|
+
type: 'start';
|
|
34
|
+
seed: number;
|
|
35
|
+
fixture: string | null;
|
|
36
|
+
config: WorldConfig;
|
|
37
|
+
armies: {
|
|
38
|
+
id: string;
|
|
39
|
+
name: string;
|
|
40
|
+
}[];
|
|
41
|
+
} | {
|
|
42
|
+
type: 'batch';
|
|
43
|
+
turn: number;
|
|
44
|
+
actor: string | null;
|
|
45
|
+
events: GameEvent[];
|
|
46
|
+
} | {
|
|
47
|
+
type: 'rejected';
|
|
48
|
+
turn: number;
|
|
49
|
+
actor: string;
|
|
50
|
+
reason: string;
|
|
51
|
+
} | {
|
|
52
|
+
type: 'end';
|
|
53
|
+
result: GameResult;
|
|
54
|
+
};
|
|
55
|
+
export interface ArmyResult {
|
|
56
|
+
id: string;
|
|
57
|
+
name: string;
|
|
58
|
+
alive: boolean;
|
|
59
|
+
captures: number;
|
|
60
|
+
mates: number;
|
|
61
|
+
material: number;
|
|
62
|
+
/** Turn on which the army left the board; null while it stands. */
|
|
63
|
+
endedAt: number | null;
|
|
64
|
+
/** Why it left (`mate`, `surrender`, ...), null while it stands. */
|
|
65
|
+
endReason: string | null;
|
|
66
|
+
/** Actions the rules refused. */
|
|
67
|
+
rejected: number;
|
|
68
|
+
}
|
|
69
|
+
export interface GameResult {
|
|
70
|
+
seed: number;
|
|
71
|
+
fixture: string | null;
|
|
72
|
+
turns: number;
|
|
73
|
+
/** The last army standing, or null when the turn cap ended the game. */
|
|
74
|
+
winner: string | null;
|
|
75
|
+
armies: ArmyResult[];
|
|
76
|
+
}
|
|
77
|
+
export interface GameOptions {
|
|
78
|
+
seed?: number;
|
|
79
|
+
/** A fixed starting position (a fixture or its name); needs exactly one spot per participant. Absent: the world's own spawn rule. */
|
|
80
|
+
fixture?: Fixture | string;
|
|
81
|
+
/** The game ends after this many cycles. Default 300. */
|
|
82
|
+
maxTurns?: number;
|
|
83
|
+
config?: Partial<WorldConfig>;
|
|
84
|
+
/** Called with every record line as it happens (a JSONL recorder writes each as one line). */
|
|
85
|
+
record?: (line: RecordLine) => void;
|
|
86
|
+
}
|
|
87
|
+
/** A small seeded random source (mulberry32). */
|
|
88
|
+
export declare function seededRandom(seed: number): () => number;
|
|
89
|
+
/**
|
|
90
|
+
* Plays one game to the end: every army spawns, then each cycle the clock advances, the world's housekeeping runs and
|
|
91
|
+
* every army that is ready is asked for its action. Deterministic for a given seed, fixture and set of bots.
|
|
92
|
+
*/
|
|
93
|
+
export declare function runGame(participants: Participant[], opts?: GameOptions): Promise<GameResult>;
|
|
94
|
+
/** Rebuilds the final state of a recorded game from its JSONL lines. */
|
|
95
|
+
export declare function replay(lines: RecordLine[]): {
|
|
96
|
+
state: WorldState;
|
|
97
|
+
snapshot: Snapshot;
|
|
98
|
+
result: GameResult | null;
|
|
99
|
+
};
|
package/dist/kit/sim.js
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
// Copyright 2026 Andrius Jaškauskas
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
import { applyEvent, captureIdAt, captureRecruits, checkMove, checkPlace, collectCheckTimeouts, collectRaidCloses, collectStalls, collectZoneShrink, createWorld, findSpawn, legalPlacements, makeConfig, materialScores, newPlayer, placeSource, settleEvents, warlordStack, toSnapshot, endReasonOf, } from '../index.js';
|
|
4
|
+
import { allMoves } from './helpers.js';
|
|
5
|
+
import { fixtureByName, fixtureRadius } from './fixtures.js';
|
|
6
|
+
/** A small seeded random source (mulberry32). */
|
|
7
|
+
export function seededRandom(seed) {
|
|
8
|
+
let a = seed >>> 0;
|
|
9
|
+
return () => {
|
|
10
|
+
a = (a + 0x6d2b79f5) >>> 0;
|
|
11
|
+
let t = a;
|
|
12
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
13
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
14
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
const START = 1_000_000;
|
|
18
|
+
/**
|
|
19
|
+
* Plays one game to the end: every army spawns, then each cycle the clock advances, the world's housekeeping runs and
|
|
20
|
+
* every army that is ready is asked for its action. Deterministic for a given seed, fixture and set of bots.
|
|
21
|
+
*/
|
|
22
|
+
export async function runGame(participants, opts = {}) {
|
|
23
|
+
if (participants.length < 2)
|
|
24
|
+
throw new Error('a game needs at least two armies');
|
|
25
|
+
const seed = opts.seed ?? 1;
|
|
26
|
+
const maxTurns = opts.maxTurns ?? 300;
|
|
27
|
+
const fixture = typeof opts.fixture === 'string' ? fixtureByName(opts.fixture) : opts.fixture;
|
|
28
|
+
if (fixture && fixture.spots.length !== participants.length) {
|
|
29
|
+
throw new Error(`fixture "${fixture.name}" has ${fixture.spots.length} spots for ${participants.length} armies`);
|
|
30
|
+
}
|
|
31
|
+
const config = makeConfig(opts.config);
|
|
32
|
+
const s = createWorld(config);
|
|
33
|
+
const emit = opts.record ?? (() => { });
|
|
34
|
+
let now = START;
|
|
35
|
+
let turn = 0;
|
|
36
|
+
let nextPieceId = 1;
|
|
37
|
+
const ids = participants.map((_, i) => `a${i}`);
|
|
38
|
+
const rngs = participants.map((_, i) => seededRandom(seed * 1009 + i));
|
|
39
|
+
const rejected = new Map(ids.map((id) => [id, 0]));
|
|
40
|
+
const ends = new Map();
|
|
41
|
+
const commit = (events, actor) => {
|
|
42
|
+
settleEvents(s, now, events, actor);
|
|
43
|
+
for (const e of events) {
|
|
44
|
+
const reason = endReasonOf(e);
|
|
45
|
+
if (reason && 'playerId' in e)
|
|
46
|
+
ends.set(e.playerId, { turn, reason });
|
|
47
|
+
}
|
|
48
|
+
if (events.length)
|
|
49
|
+
emit({ type: 'batch', turn, actor, events });
|
|
50
|
+
};
|
|
51
|
+
emit({ type: 'start', seed, fixture: fixture?.name ?? null, config, armies: participants.map((p, i) => ({ id: ids[i], name: p.name })) });
|
|
52
|
+
if (fixture) {
|
|
53
|
+
// The zone must hold every formation before the first one is placed.
|
|
54
|
+
const radius = fixtureRadius(fixture, config);
|
|
55
|
+
if (radius !== s.radius)
|
|
56
|
+
commit([{ type: 'zone', radius }], null);
|
|
57
|
+
}
|
|
58
|
+
participants.forEach((p, i) => {
|
|
59
|
+
const player = newPlayer(ids[i], p.name, '#888888', { kind: 'agent' });
|
|
60
|
+
const events = [];
|
|
61
|
+
const spot = fixture ? { ...fixture.spots[i], radius: s.radius } : findSpawn(s);
|
|
62
|
+
if (spot.radius !== s.radius)
|
|
63
|
+
events.push({ type: 'zone', radius: spot.radius });
|
|
64
|
+
const pieces = warlordStack(spot.x, spot.y).map((c) => ({
|
|
65
|
+
...c,
|
|
66
|
+
id: nextPieceId++,
|
|
67
|
+
owner: player.id,
|
|
68
|
+
fresh: c.type === 'P',
|
|
69
|
+
}));
|
|
70
|
+
events.push({ type: 'spawned', resumed: false, player: { ...player, alive: true, spawnedAt: now }, pieces });
|
|
71
|
+
commit(events, null);
|
|
72
|
+
});
|
|
73
|
+
const alive = () => [...s.players.values()].filter((p) => p.alive);
|
|
74
|
+
while (turn < maxTurns && alive().length > 1) {
|
|
75
|
+
turn++;
|
|
76
|
+
now += config.cooldownMs;
|
|
77
|
+
const housekeeping = [];
|
|
78
|
+
collectStalls(s, now, housekeeping);
|
|
79
|
+
collectCheckTimeouts(s, now, housekeeping);
|
|
80
|
+
collectZoneShrink(s, housekeeping);
|
|
81
|
+
collectRaidCloses(s, now, housekeeping);
|
|
82
|
+
commit(housekeeping, null);
|
|
83
|
+
for (const [i, p] of participants.entries()) {
|
|
84
|
+
const id = ids[i];
|
|
85
|
+
const pl = s.players.get(id);
|
|
86
|
+
if (!pl.alive || now < pl.readyAt)
|
|
87
|
+
continue;
|
|
88
|
+
const view = {
|
|
89
|
+
state: s,
|
|
90
|
+
me: id,
|
|
91
|
+
turn,
|
|
92
|
+
moves: allMoves(s, id),
|
|
93
|
+
places: legalPlacements(s, id),
|
|
94
|
+
rng: rngs[i],
|
|
95
|
+
};
|
|
96
|
+
const action = await p.bot(view);
|
|
97
|
+
if (!action)
|
|
98
|
+
continue;
|
|
99
|
+
const events = applyAction(s, id, action, now, () => nextPieceId++);
|
|
100
|
+
if (typeof events === 'string') {
|
|
101
|
+
rejected.set(id, rejected.get(id) + 1);
|
|
102
|
+
emit({ type: 'rejected', turn, actor: id, reason: events });
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
commit(events, id);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const scores = materialScores(s);
|
|
109
|
+
const standing = alive();
|
|
110
|
+
const result = {
|
|
111
|
+
seed,
|
|
112
|
+
fixture: fixture?.name ?? null,
|
|
113
|
+
turns: turn,
|
|
114
|
+
winner: standing.length === 1 ? standing[0].id : null,
|
|
115
|
+
armies: participants.map((p, i) => {
|
|
116
|
+
const id = ids[i];
|
|
117
|
+
const pl = s.players.get(id);
|
|
118
|
+
return {
|
|
119
|
+
id,
|
|
120
|
+
name: p.name,
|
|
121
|
+
alive: pl.alive,
|
|
122
|
+
captures: pl.captures,
|
|
123
|
+
mates: pl.mates,
|
|
124
|
+
material: scores.get(id) ?? 0,
|
|
125
|
+
endedAt: ends.get(id)?.turn ?? null,
|
|
126
|
+
endReason: ends.get(id)?.reason ?? null,
|
|
127
|
+
rejected: rejected.get(id),
|
|
128
|
+
};
|
|
129
|
+
}),
|
|
130
|
+
};
|
|
131
|
+
emit({ type: 'end', result });
|
|
132
|
+
return result;
|
|
133
|
+
}
|
|
134
|
+
/** The events of one action, or the rule that refuses it. */
|
|
135
|
+
function applyAction(s, id, action, now, newId) {
|
|
136
|
+
if (action.kind === 'move') {
|
|
137
|
+
const p = s.pieces.get(action.pieceId);
|
|
138
|
+
if (!p)
|
|
139
|
+
return 'illegal_move';
|
|
140
|
+
const capture = captureIdAt(s, p, action.to);
|
|
141
|
+
const reason = checkMove(s, id, action.pieceId, action.to, capture, now);
|
|
142
|
+
if (reason)
|
|
143
|
+
return reason;
|
|
144
|
+
const victim = capture !== null ? s.pieces.get(capture) : undefined;
|
|
145
|
+
return [
|
|
146
|
+
{
|
|
147
|
+
type: 'moved',
|
|
148
|
+
playerId: id,
|
|
149
|
+
pieceId: p.id,
|
|
150
|
+
from: { x: p.x, y: p.y },
|
|
151
|
+
to: action.to,
|
|
152
|
+
captured: capture,
|
|
153
|
+
capturedOwner: victim?.owner,
|
|
154
|
+
capturedType: victim?.type,
|
|
155
|
+
recruit: victim ? captureRecruits(s, id, victim) : undefined,
|
|
156
|
+
at: now,
|
|
157
|
+
},
|
|
158
|
+
];
|
|
159
|
+
}
|
|
160
|
+
const reason = checkPlace(s, id, action.type, action.to, now);
|
|
161
|
+
if (reason)
|
|
162
|
+
return reason;
|
|
163
|
+
const source = placeSource(s, id, action.type);
|
|
164
|
+
if (!source)
|
|
165
|
+
return 'no_pending_place';
|
|
166
|
+
// A recruited or raided pawn is a fresh pawn: it keeps its 2-cell first step.
|
|
167
|
+
const piece = { id: newId(), owner: id, type: action.type, x: action.to.x, y: action.to.y, fresh: action.type === 'P' };
|
|
168
|
+
const events = [
|
|
169
|
+
source.kind === 'raid'
|
|
170
|
+
? { type: 'placed', playerId: id, piece, kind: 'raid', raidId: source.raidId, at: now }
|
|
171
|
+
: { type: 'placed', playerId: id, piece, kind: 'recruit', at: now },
|
|
172
|
+
];
|
|
173
|
+
if (source.kind === 'raid') {
|
|
174
|
+
// The take that empties the pool closes the raid in the same batch.
|
|
175
|
+
const raid = s.raids.find((r) => r.id === source.raidId);
|
|
176
|
+
const left = Object.values(raid.pool).reduce((n, c) => n + c, 0) - 1;
|
|
177
|
+
if (left === 0)
|
|
178
|
+
events.push({ type: 'raidClosed', raidId: raid.id, at: now, reason: 'empty' });
|
|
179
|
+
}
|
|
180
|
+
return events;
|
|
181
|
+
}
|
|
182
|
+
/** Rebuilds the final state of a recorded game from its JSONL lines. */
|
|
183
|
+
export function replay(lines) {
|
|
184
|
+
const start = lines.find((l) => l.type === 'start');
|
|
185
|
+
if (!start)
|
|
186
|
+
throw new Error('recording has no start line');
|
|
187
|
+
const state = createWorld(start.config);
|
|
188
|
+
let result = null;
|
|
189
|
+
for (const l of lines) {
|
|
190
|
+
if (l.type === 'batch')
|
|
191
|
+
for (const e of l.events)
|
|
192
|
+
applyEvent(state, e);
|
|
193
|
+
else if (l.type === 'end')
|
|
194
|
+
result = l.result;
|
|
195
|
+
}
|
|
196
|
+
return { state, snapshot: toSnapshot(state), result };
|
|
197
|
+
}
|