@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.
@@ -0,0 +1,82 @@
1
+ import { type GameEvent } from './events.js';
2
+ import { type Cell, type Piece, type PieceType, type Raid, type WorldState } from './types.js';
3
+ export type MoveRejection = 'not_joined' | 'dead' | 'cooldown' | 'not_your_piece' | 'collision' | 'illegal_move' | 'in_check' | 'self_check' | 'hibernating' | 'hibernate_locked' | 'not_ready' | 'no_pending_place' | 'pool_empty' | 'bad_type' | 'not_adjacent' | 'occupied' | 'out_of_zone' | 'no_earned_exit' | 'mate_pending';
4
+ export declare function isInCheck(s: WorldState, owner: string): boolean;
5
+ export type CheckLine = {
6
+ attacker: Piece;
7
+ cells: Cell[];
8
+ };
9
+ /**
10
+ * Every piece giving check, plus the empty ray cells strictly between it and the King
11
+ * (sliders only — knight / adjacent pawn or King → `cells: []`).
12
+ */
13
+ export declare function checkLines(s: WorldState, playerId: string): CheckLine[];
14
+ export declare function legalMoves(s: WorldState, pieceId: number): Cell[];
15
+ /**
16
+ * Empty cells Chebyshev-adjacent to the own King, inside the zone.
17
+ * Does not filter self-check — callers use `checkPlace` / `placeLeavesKingAttacked`.
18
+ */
19
+ export declare function placementCells(s: WorldState, playerId: string): Cell[];
20
+ /** The piece types a player may place now: the capture-recruit type first, then the open raid pools, strongest first. */
21
+ export declare function placeTypes(s: WorldState, playerId: string): PieceType[];
22
+ /** Where a placement of `type` comes from: the capture-recruit (preferred, it keeps the pool intact) or the oldest raid with that type left. */
23
+ export declare function placeSource(s: WorldState, playerId: string, type: PieceType): {
24
+ kind: 'recruit';
25
+ } | {
26
+ kind: 'raid';
27
+ raidId: string;
28
+ } | null;
29
+ /**
30
+ * Validates a placement intent. Cooldown is checked last (same order family as checkMove).
31
+ * The type must be the pending capture-recruit, or a type still in the pool of a raid the player is in.
32
+ */
33
+ export declare function checkPlace(s: WorldState, playerId: string, type: PieceType, to: Cell, now: number): MoveRejection | null;
34
+ export type LegalPlace = {
35
+ type: PieceType;
36
+ to: Cell;
37
+ };
38
+ /**
39
+ * Legal placements right now: one entry per (type, cell) that `checkPlace` accepts (cooldown ignored, like
40
+ * `legalMoves`), for every type the player may place. This is the one list a UI may highlight or accept, so what
41
+ * it offers is exactly what the server will take.
42
+ */
43
+ export declare function legalPlacements(s: WorldState, playerId: string): LegalPlace[];
44
+ /** The cells where some placement is legal (see `legalPlacements`), each once. */
45
+ export declare function legalPlaceCells(s: WorldState, playerId: string): Cell[];
46
+ export declare function hasLegalMove(s: WorldState, owner: string): boolean;
47
+ /**
48
+ * Validates a move intent against the current state. `capture` is the piece the client expected on the
49
+ * target cell (null = empty); a mismatch means someone else got there first.
50
+ */
51
+ export declare function checkMove(s: WorldState, playerId: string, pieceId: number, to: Cell, capture: number | null, now: number): MoveRejection | null;
52
+ /** Checkmate right now: in check and no legal move or placement. */
53
+ export declare function isCheckmated(s: WorldState, playerId: string): boolean;
54
+ /** Epoch ms when a pending mate resolves (army removed) unless it breaks first; null if none pending. */
55
+ export declare function mateResolvesAt(s: WorldState, playerId: string): number | null;
56
+ /**
57
+ * The raid a fallen army leaves behind: the army's non-King pieces as counts per type, open to every alive
58
+ * army with a piece attacking its King at that moment. Null only when nobody alive attacks; an empty pool still
59
+ * counts the mate for its raiders but opens nothing (see `raidOpened`).
60
+ */
61
+ export declare function raidOf(s: WorldState, victimId: string, atk: Piece[], at: number): Raid | null;
62
+ /**
63
+ * Raids that end now: pool empty, or no raider keeps the right (rights end in `applyEvent` when a raider moves another
64
+ * piece, is put in check, dies or hibernates) or has a legal cell for a type left. There is no timer.
65
+ */
66
+ export declare function raidsToClose(s: WorldState): {
67
+ raidId: string;
68
+ reason: 'empty' | 'nobody';
69
+ }[];
70
+ /**
71
+ * Shared check-death event: same credit path as a held mate window.
72
+ * Callers: check clock timeout, idle/quiet under check, leave-under-attack.
73
+ */
74
+ export declare function mateRemovalEvents(s: WorldState, playerId: string, at: number, preferredBy?: string | null): GameEvent[];
75
+ /**
76
+ * Checkmate with a rescue window. After every change:
77
+ * - a newly mated King → `mateStarted` (window opens for one cycle, credit fixed to the actor if they attack);
78
+ * - a pending mate that no longer holds → `rescued`;
79
+ * - a pending mate still holding when the window ends → `mated` (army removed).
80
+ * Repeats until stable, because a removal can open lines onto other Kings.
81
+ */
82
+ export declare function evaluateMates(s: WorldState, at: number, actorId?: string | null): GameEvent[];
@@ -0,0 +1,350 @@
1
+ // Copyright 2026 Andrius Jaškauskas
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { cellKey, inZone, kingOf, kingsByOwner, pieceAt, piecesOf } from './board.js';
4
+ import { applyEvent } from './events.js';
5
+ import { attackers, captureIdAt, enPassantVictim, pseudoMoves } from './moves.js';
6
+ import { PIECE_VALUE, PLACEABLE_TYPES, } from './types.js';
7
+ export function isInCheck(s, owner) {
8
+ const k = kingOf(s, owner);
9
+ return !!k && attackers(s, k, owner).length > 0;
10
+ }
11
+ /**
12
+ * Every piece giving check, plus the empty ray cells strictly between it and the King
13
+ * (sliders only — knight / adjacent pawn or King → `cells: []`).
14
+ */
15
+ export function checkLines(s, playerId) {
16
+ const k = kingOf(s, playerId);
17
+ if (!k)
18
+ return [];
19
+ return attackers(s, k, playerId).map((attacker) => ({
20
+ attacker,
21
+ cells: cellsBetween(k, attacker),
22
+ }));
23
+ }
24
+ /** Empty cells on a rook/bishop/queen ray from `from` to `to` (exclusive). */
25
+ function cellsBetween(from, to) {
26
+ const dx = to.x - from.x;
27
+ const dy = to.y - from.y;
28
+ const adx = Math.abs(dx);
29
+ const ady = Math.abs(dy);
30
+ // Non-line (incl. knight): nothing between.
31
+ if (adx && ady && adx !== ady)
32
+ return [];
33
+ const steps = Math.max(adx, ady);
34
+ if (steps <= 1)
35
+ return [];
36
+ const sx = Math.sign(dx);
37
+ const sy = Math.sign(dy);
38
+ const out = [];
39
+ for (let i = 1; i < steps; i++)
40
+ out.push({ x: from.x + sx * i, y: from.y + sy * i });
41
+ return out;
42
+ }
43
+ /** Plays the move on the board, tests the mover's King, then restores the board exactly. */
44
+ function leavesKingAttacked(s, p, to, king = kingOf(s, p.owner)) {
45
+ const from = cellKey(p.x, p.y);
46
+ const dest = cellKey(to.x, to.y);
47
+ const captured = s.board.get(dest);
48
+ const ep = enPassantVictim(s, p, to);
49
+ const epKey = ep ? cellKey(ep.x, ep.y) : null;
50
+ const [ox, oy] = [p.x, p.y];
51
+ if (epKey)
52
+ s.board.delete(epKey);
53
+ s.board.delete(from);
54
+ s.board.set(dest, p.id);
55
+ p.x = to.x;
56
+ p.y = to.y;
57
+ const k = king;
58
+ // Only real attacks within maxRange — no phantom pins from distant sliders.
59
+ const hit = !!k && attackers(s, k, p.owner).length > 0;
60
+ p.x = ox;
61
+ p.y = oy;
62
+ s.board.set(from, p.id);
63
+ if (captured === undefined)
64
+ s.board.delete(dest);
65
+ else
66
+ s.board.set(dest, captured);
67
+ if (epKey)
68
+ s.board.set(epKey, ep.id);
69
+ return hit;
70
+ }
71
+ /** True if placing a friendly piece of `type` on `to` would leave the own King attacked. */
72
+ function placeLeavesKingAttacked(s, owner, type, to) {
73
+ // Temporary piece id that cannot collide with real ids (they start at 1).
74
+ const ghost = { id: -1, owner, type, x: to.x, y: to.y, fresh: false };
75
+ const key = cellKey(to.x, to.y);
76
+ s.pieces.set(ghost.id, ghost);
77
+ s.board.set(key, ghost.id);
78
+ const hit = isInCheck(s, owner);
79
+ s.board.delete(key);
80
+ s.pieces.delete(ghost.id);
81
+ return hit;
82
+ }
83
+ export function legalMoves(s, pieceId) {
84
+ const p = s.pieces.get(pieceId);
85
+ return p ? pseudoMoves(s, p).filter((to) => !leavesKingAttacked(s, p, to)) : [];
86
+ }
87
+ /**
88
+ * Empty cells Chebyshev-adjacent to the own King, inside the zone.
89
+ * Does not filter self-check — callers use `checkPlace` / `placeLeavesKingAttacked`.
90
+ */
91
+ export function placementCells(s, playerId) {
92
+ const k = kingOf(s, playerId);
93
+ if (!k)
94
+ return [];
95
+ const out = [];
96
+ for (let dx = -1; dx <= 1; dx++) {
97
+ for (let dy = -1; dy <= 1; dy++) {
98
+ if (!dx && !dy)
99
+ continue;
100
+ const x = k.x + dx;
101
+ const y = k.y + dy;
102
+ if (!inZone(s, x, y))
103
+ continue;
104
+ if (pieceAt(s, x, y))
105
+ continue;
106
+ out.push({ x, y });
107
+ }
108
+ }
109
+ return out;
110
+ }
111
+ /** The piece types a player may place now: the capture-recruit type first, then the open raid pools, strongest first. */
112
+ export function placeTypes(s, playerId) {
113
+ const out = [];
114
+ const pending = s.players.get(playerId)?.pendingPlace;
115
+ if (pending)
116
+ out.push(pending.type);
117
+ for (const t of PLACEABLE_TYPES) {
118
+ if (!out.includes(t) && s.raids.some((r) => r.raiders.includes(playerId) && r.pool[t] > 0))
119
+ out.push(t);
120
+ }
121
+ return out;
122
+ }
123
+ /** Where a placement of `type` comes from: the capture-recruit (preferred, it keeps the pool intact) or the oldest raid with that type left. */
124
+ export function placeSource(s, playerId, type) {
125
+ if (s.players.get(playerId)?.pendingPlace?.type === type)
126
+ return { kind: 'recruit' };
127
+ const raid = s.raids.find((r) => r.raiders.includes(playerId) && r.pool[type] > 0);
128
+ return raid ? { kind: 'raid', raidId: raid.id } : null;
129
+ }
130
+ /**
131
+ * Validates a placement intent. Cooldown is checked last (same order family as checkMove).
132
+ * The type must be the pending capture-recruit, or a type still in the pool of a raid the player is in.
133
+ */
134
+ export function checkPlace(s, playerId, type, to, now) {
135
+ const player = s.players.get(playerId);
136
+ if (!player)
137
+ return 'not_joined';
138
+ if (!player.alive)
139
+ return 'dead';
140
+ const raider = s.raids.some((r) => r.raiders.includes(playerId));
141
+ if (!player.pendingPlace && !raider)
142
+ return 'no_pending_place';
143
+ if (type === 'K' || !PLACEABLE_TYPES.includes(type))
144
+ return 'bad_type';
145
+ if (!placeSource(s, playerId, type))
146
+ return raider ? 'pool_empty' : 'bad_type';
147
+ if (!inZone(s, to.x, to.y))
148
+ return 'out_of_zone';
149
+ if (pieceAt(s, to.x, to.y))
150
+ return 'occupied';
151
+ const k = kingOf(s, playerId);
152
+ if (!k)
153
+ return 'illegal_move';
154
+ if (Math.max(Math.abs(to.x - k.x), Math.abs(to.y - k.y)) !== 1)
155
+ return 'not_adjacent';
156
+ const inCheck = isInCheck(s, playerId);
157
+ if (placeLeavesKingAttacked(s, playerId, type, to))
158
+ return inCheck ? 'in_check' : 'self_check';
159
+ if (now < player.readyAt)
160
+ return 'cooldown';
161
+ return null;
162
+ }
163
+ /**
164
+ * Legal placements right now: one entry per (type, cell) that `checkPlace` accepts (cooldown ignored, like
165
+ * `legalMoves`), for every type the player may place. This is the one list a UI may highlight or accept, so what
166
+ * it offers is exactly what the server will take.
167
+ */
168
+ export function legalPlacements(s, playerId) {
169
+ const pl = s.players.get(playerId);
170
+ if (!pl?.alive)
171
+ return [];
172
+ const types = placeTypes(s, playerId);
173
+ // Bypass cooldown the same way listLegalMoves ignores it.
174
+ const now = Math.max(pl.readyAt, 0);
175
+ const out = [];
176
+ for (const to of placementCells(s, playerId)) {
177
+ for (const type of types) {
178
+ if (checkPlace(s, playerId, type, to, now) === null)
179
+ out.push({ type, to });
180
+ }
181
+ }
182
+ return out;
183
+ }
184
+ /** The cells where some placement is legal (see `legalPlacements`), each once. */
185
+ export function legalPlaceCells(s, playerId) {
186
+ const seen = new Set();
187
+ const out = [];
188
+ for (const { to } of legalPlacements(s, playerId)) {
189
+ const key = cellKey(to.x, to.y);
190
+ if (seen.has(key))
191
+ continue;
192
+ seen.add(key);
193
+ out.push(to);
194
+ }
195
+ return out;
196
+ }
197
+ export function hasLegalMove(s, owner) {
198
+ // One King lookup for the whole scan: leavesKingAttacked would otherwise rescan every piece per candidate move.
199
+ const king = kingOf(s, owner);
200
+ for (const p of s.pieces.values()) {
201
+ if (p.owner !== owner)
202
+ continue;
203
+ if (pseudoMoves(s, p).some((to) => !leavesKingAttacked(s, p, to, king)))
204
+ return true;
205
+ }
206
+ // A pending recruit or an open raid counts too: otherwise a player with only a legal place would be "stalemated".
207
+ const types = placeTypes(s, owner);
208
+ if (!types.length)
209
+ return false;
210
+ for (const cell of placementCells(s, owner)) {
211
+ for (const type of types) {
212
+ if (!placeLeavesKingAttacked(s, owner, type, cell))
213
+ return true;
214
+ }
215
+ }
216
+ return false;
217
+ }
218
+ /**
219
+ * Validates a move intent against the current state. `capture` is the piece the client expected on the
220
+ * target cell (null = empty); a mismatch means someone else got there first.
221
+ */
222
+ export function checkMove(s, playerId, pieceId, to, capture, now) {
223
+ const player = s.players.get(playerId);
224
+ if (!player)
225
+ return 'not_joined';
226
+ if (!player.alive)
227
+ return 'dead';
228
+ const p = s.pieces.get(pieceId);
229
+ if (!p)
230
+ return 'illegal_move';
231
+ if (p.owner !== playerId)
232
+ return 'not_your_piece';
233
+ if (captureIdAt(s, p, to) !== capture)
234
+ return 'collision';
235
+ if (!pseudoMoves(s, p).some((c) => c.x === to.x && c.y === to.y))
236
+ return 'illegal_move';
237
+ const inCheck = isInCheck(s, playerId);
238
+ if (leavesKingAttacked(s, p, to))
239
+ return inCheck ? 'in_check' : 'self_check';
240
+ // One move per cycle — check does not grant an extra move. In check only answers are legal, with
241
+ // no deadline: answering late just gives the attackers free moves.
242
+ if (now < player.readyAt)
243
+ return 'cooldown';
244
+ return null;
245
+ }
246
+ /** Checkmate right now: in check and no legal move or placement. */
247
+ export function isCheckmated(s, playerId) {
248
+ const king = kingOf(s, playerId);
249
+ return !!king && attackers(s, king, playerId).length > 0 && !hasLegalMove(s, playerId);
250
+ }
251
+ /** Epoch ms when a pending mate resolves (army removed) unless it breaks first; null if none pending. */
252
+ export function mateResolvesAt(s, playerId) {
253
+ const pl = s.players.get(playerId);
254
+ return pl?.alive && pl.matedAt !== null ? pl.matedAt + s.config.cooldownMs : null;
255
+ }
256
+ /**
257
+ * Last-hit credit: `preferred` (the command's actor when the mate starts, the pending `matedBy` when it
258
+ * resolves) if they still attack the King; else the check starter if they still attack; else nobody.
259
+ */
260
+ function credit(s, victimId, atk, preferred) {
261
+ const attacks = (id) => !!id && atk.some((a) => a.owner === id);
262
+ if (attacks(preferred))
263
+ return preferred;
264
+ const checkedBy = s.players.get(victimId)?.checkedBy;
265
+ return attacks(checkedBy) ? checkedBy : null;
266
+ }
267
+ /**
268
+ * The raid a fallen army leaves behind: the army's non-King pieces as counts per type, open to every alive
269
+ * army with a piece attacking its King at that moment. Null only when nobody alive attacks; an empty pool still
270
+ * counts the mate for its raiders but opens nothing (see `raidOpened`).
271
+ */
272
+ export function raidOf(s, victimId, atk, at) {
273
+ const raiders = [...new Set(atk.map((a) => a.owner))].filter((id) => id !== victimId && s.players.get(id)?.alive);
274
+ const pool = { Q: 0, R: 0, B: 0, N: 0, P: 0 };
275
+ for (const p of piecesOf(s, victimId))
276
+ if (p.type !== 'K')
277
+ pool[p.type]++;
278
+ if (!raiders.length)
279
+ return null;
280
+ return { id: `${victimId}@${at}`, victim: victimId, pool, raiders, at };
281
+ }
282
+ /**
283
+ * Raids that end now: pool empty, or no raider keeps the right (rights end in `applyEvent` when a raider moves another
284
+ * piece, is put in check, dies or hibernates) or has a legal cell for a type left. There is no timer.
285
+ */
286
+ export function raidsToClose(s) {
287
+ const out = [];
288
+ for (const r of s.raids) {
289
+ if (!Object.values(r.pool).some((n) => n > 0))
290
+ out.push({ raidId: r.id, reason: 'empty' });
291
+ else if (!r.raiders.some((id) => s.players.get(id)?.alive && legalPlacements(s, id).some((l) => placeSource(s, id, l.type)?.kind === 'raid' && r.pool[l.type] > 0))) {
292
+ out.push({ raidId: r.id, reason: 'nobody' });
293
+ }
294
+ }
295
+ return out;
296
+ }
297
+ /**
298
+ * Shared check-death event: same credit path as a held mate window.
299
+ * Callers: check clock timeout, idle/quiet under check, leave-under-attack.
300
+ */
301
+ export function mateRemovalEvents(s, playerId, at, preferredBy = null) {
302
+ const king = kingOf(s, playerId);
303
+ const atk = king ? attackers(s, king, playerId) : [];
304
+ const by = credit(s, playerId, atk, preferredBy);
305
+ const assists = [...new Set(atk.map((a) => a.owner))].filter((id) => id !== by);
306
+ const raid = raidOf(s, playerId, atk, at);
307
+ return [{ type: 'mated', playerId, by, assists, at }, ...(raid ? [{ type: 'raidOpened', raid }] : [])];
308
+ }
309
+ /**
310
+ * Checkmate with a rescue window. After every change:
311
+ * - a newly mated King → `mateStarted` (window opens for one cycle, credit fixed to the actor if they attack);
312
+ * - a pending mate that no longer holds → `rescued`;
313
+ * - a pending mate still holding when the window ends → `mated` (army removed).
314
+ * Repeats until stable, because a removal can open lines onto other Kings.
315
+ */
316
+ // ponytail: re-checks every alive King after each change, O(players); limit to Kings near the change if it shows up in profiles.
317
+ export function evaluateMates(s, at, actorId = null) {
318
+ const out = [];
319
+ for (;;) {
320
+ const batch = [];
321
+ const kings = kingsByOwner(s);
322
+ for (const pl of s.players.values()) {
323
+ const king = pl.alive ? kings.get(pl.id) : undefined;
324
+ if (!king)
325
+ continue;
326
+ const atk = attackers(s, king, pl.id);
327
+ const mate = atk.length > 0 && !hasLegalMove(s, pl.id);
328
+ if (pl.matedAt === null) {
329
+ if (mate)
330
+ batch.push({ type: 'mateStarted', playerId: pl.id, by: credit(s, pl.id, atk, actorId), at });
331
+ }
332
+ else if (!mate) {
333
+ batch.push({ type: 'rescued', playerId: pl.id, at });
334
+ }
335
+ else if (at >= pl.matedAt + s.config.cooldownMs) {
336
+ const by = credit(s, pl.id, atk, pl.matedBy);
337
+ const assists = [...new Set(atk.map((a) => a.owner))].filter((id) => id !== by);
338
+ batch.push({ type: 'mated', playerId: pl.id, by, assists, at });
339
+ const raid = raidOf(s, pl.id, atk, at);
340
+ if (raid)
341
+ batch.push({ type: 'raidOpened', raid });
342
+ }
343
+ }
344
+ if (!batch.length)
345
+ return out;
346
+ for (const e of batch)
347
+ applyEvent(s, e);
348
+ out.push(...batch);
349
+ }
350
+ }
@@ -0,0 +1,21 @@
1
+ import type { Cell, Piece, WorldState } from './types.js';
2
+ type Dir = readonly [number, number];
3
+ export declare const ORTHO: readonly Dir[];
4
+ export declare const DIAG: readonly Dir[];
5
+ export declare const ALL_DIRS: readonly Dir[];
6
+ export declare const KNIGHT: readonly Dir[];
7
+ /**
8
+ * The enemy pawn `p` would capture by moving diagonally onto the empty cell `to` en passant, if any:
9
+ * an army's pawn that just double-stepped (see `Player.enPassant`) standing beside `p`, with `to` the cell it skipped.
10
+ */
11
+ export declare function enPassantVictim(s: WorldState, p: Piece, to: Cell): Piece | null;
12
+ /** Id of the piece a move of `p` onto `to` captures (the piece on `to`, or the en passant pawn); null if none. */
13
+ export declare function captureIdAt(s: WorldState, p: Piece, to: Cell): number | null;
14
+ /** Moves ignoring self-check. Kings are never captured, so a King's cell is never a target. */
15
+ export declare function pseudoMoves(s: WorldState, p: Piece): Cell[];
16
+ /**
17
+ * Pieces not owned by `defender` that attack `c` within `maxRange`.
18
+ * Kings are attackable here (unlike pseudoMoves).
19
+ */
20
+ export declare function attackers(s: WorldState, c: Cell, defender: string): Piece[];
21
+ export {};
package/dist/moves.js ADDED
@@ -0,0 +1,105 @@
1
+ // Copyright 2026 Andrius Jaškauskas
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { inZone, pieceAt } from './board.js';
4
+ export const ORTHO = [[1, 0], [-1, 0], [0, 1], [0, -1]];
5
+ export const DIAG = [[1, 1], [1, -1], [-1, 1], [-1, -1]];
6
+ export const ALL_DIRS = [...ORTHO, ...DIAG];
7
+ export const KNIGHT = [[1, 2], [2, 1], [2, -1], [1, -2], [-1, -2], [-2, -1], [-2, 1], [-1, 2]];
8
+ /**
9
+ * The enemy pawn `p` would capture by moving diagonally onto the empty cell `to` en passant, if any:
10
+ * an army's pawn that just double-stepped (see `Player.enPassant`) standing beside `p`, with `to` the cell it skipped.
11
+ */
12
+ export function enPassantVictim(s, p, to) {
13
+ if (p.type !== 'P' || pieceAt(s, to.x, to.y))
14
+ return null;
15
+ if (Math.abs(to.x - p.x) !== 1 || Math.abs(to.y - p.y) !== 1)
16
+ return null;
17
+ for (const [dx, dy] of ORTHO) {
18
+ const v = pieceAt(s, p.x + dx, p.y + dy);
19
+ if (!v || v.type !== 'P' || v.owner === p.owner)
20
+ continue;
21
+ const ep = s.players.get(v.owner)?.enPassant;
22
+ if (!ep || ep.pieceId !== v.id || ep.cell.x !== to.x || ep.cell.y !== to.y)
23
+ continue;
24
+ // The skipped cell must be adjacent to the landing cell (the pawn really stepped through it).
25
+ if (Math.abs(v.x - to.x) + Math.abs(v.y - to.y) === 1)
26
+ return v;
27
+ }
28
+ return null;
29
+ }
30
+ /** Id of the piece a move of `p` onto `to` captures (the piece on `to`, or the en passant pawn); null if none. */
31
+ export function captureIdAt(s, p, to) {
32
+ return pieceAt(s, to.x, to.y)?.id ?? enPassantVictim(s, p, to)?.id ?? null;
33
+ }
34
+ /** Moves ignoring self-check. Kings are never captured, so a King's cell is never a target. */
35
+ export function pseudoMoves(s, p) {
36
+ const out = [];
37
+ const look = (x, y) => {
38
+ if (!inZone(s, x, y))
39
+ return null;
40
+ const q = pieceAt(s, x, y);
41
+ if (!q)
42
+ return 'empty';
43
+ return q.owner !== p.owner && q.type !== 'K' ? 'enemy' : null;
44
+ };
45
+ const push = (x, y) => out.push({ x, y });
46
+ switch (p.type) {
47
+ case 'K':
48
+ case 'N':
49
+ for (const [dx, dy] of p.type === 'K' ? ALL_DIRS : KNIGHT)
50
+ if (look(p.x + dx, p.y + dy))
51
+ push(p.x + dx, p.y + dy);
52
+ break;
53
+ case 'P':
54
+ for (const [dx, dy] of ORTHO) {
55
+ if (look(p.x + dx, p.y + dy) !== 'empty')
56
+ continue;
57
+ push(p.x + dx, p.y + dy);
58
+ if (p.fresh && look(p.x + 2 * dx, p.y + 2 * dy) === 'empty')
59
+ push(p.x + 2 * dx, p.y + 2 * dy);
60
+ }
61
+ for (const [dx, dy] of DIAG) {
62
+ const t = look(p.x + dx, p.y + dy);
63
+ if (t === 'enemy' || (t === 'empty' && enPassantVictim(s, p, { x: p.x + dx, y: p.y + dy })))
64
+ push(p.x + dx, p.y + dy);
65
+ }
66
+ break;
67
+ default:
68
+ for (const [dx, dy] of p.type === 'Q' ? ALL_DIRS : p.type === 'R' ? ORTHO : DIAG) {
69
+ for (let i = 1; i <= s.config.maxRange; i++) {
70
+ const t = look(p.x + dx * i, p.y + dy * i);
71
+ if (t)
72
+ push(p.x + dx * i, p.y + dy * i);
73
+ if (t !== 'empty')
74
+ break;
75
+ }
76
+ }
77
+ }
78
+ return out;
79
+ }
80
+ /**
81
+ * Pieces not owned by `defender` that attack `c` within `maxRange`.
82
+ * Kings are attackable here (unlike pseudoMoves).
83
+ */
84
+ export function attackers(s, c, defender) {
85
+ const out = [];
86
+ const range = s.config.maxRange;
87
+ for (const [dx, dy] of KNIGHT) {
88
+ const q = pieceAt(s, c.x + dx, c.y + dy);
89
+ if (q && q.owner !== defender && q.type === 'N')
90
+ out.push(q);
91
+ }
92
+ for (const [dx, dy] of ALL_DIRS) {
93
+ const diag = dx !== 0 && dy !== 0;
94
+ for (let i = 1; i <= range; i++) {
95
+ const q = pieceAt(s, c.x + dx * i, c.y + dy * i);
96
+ if (!q)
97
+ continue;
98
+ const hits = q.type === 'Q' || q.type === (diag ? 'B' : 'R') || (i === 1 && (q.type === 'K' || (diag && q.type === 'P')));
99
+ if (hits && q.owner !== defender)
100
+ out.push(q);
101
+ break;
102
+ }
103
+ }
104
+ return out;
105
+ }
package/dist/tick.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ import { type GameEvent } from './events.js';
2
+ import type { WorldState } from './types.js';
3
+ /**
4
+ * The world's housekeeping that follows from the rules alone, as pure steps over a state.
5
+ * A host (a game server, the bot test kit) calls them in its own tick and adds what only it knows
6
+ * (leaving, quiet exit, idle despawn).
7
+ */
8
+ /** Armies whose en passant right ran out, and armies with no legal move that skip their turn. */
9
+ export declare function collectStalls(s: WorldState, now: number, out: GameEvent[]): void;
10
+ /** An unanswered check past its deadline removes the army, with the same credit as a held mate. */
11
+ export declare function collectCheckTimeouts(s: WorldState, now: number, out: GameEvent[]): void;
12
+ /** Shrink the zone one step toward the density target when the outer ring is empty. */
13
+ export declare function collectZoneShrink(s: WorldState, out: GameEvent[]): void;
14
+ /** Close the mate raids whose pool is empty or that nobody can take from. */
15
+ export declare function collectRaidCloses(s: WorldState, now: number, out: GameEvent[]): void;
16
+ /**
17
+ * Emit checkStarted / checkEnded so every viewer shares who is in check and since when.
18
+ * `actorId` = who just moved or placed; credited as the check starter only if they attack the King.
19
+ * Checks that appear from a removal get `by: null`.
20
+ */
21
+ export declare function syncChecks(s: WorldState, now: number, events: GameEvent[], actorId: string | null): void;
22
+ /**
23
+ * Apply `events`, then add what follows: check starts and ends, mates and their removals.
24
+ * `events` is extended in place. `afterDeaths` sees each group of events once it is applied (a host
25
+ * frees its own bookkeeping for armies that left).
26
+ */
27
+ export declare function settleEvents(s: WorldState, now: number, events: GameEvent[], actorId?: string | null, afterDeaths?: (applied: GameEvent[]) => void): void;