@bilkobibitkov/threewinds-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/dist/room.d.ts ADDED
@@ -0,0 +1,119 @@
1
+ import { type Action, type ClaimWindow, type GameEvent, type GameState, type HandResult, type Phase } from './game.js';
2
+ import type { Meld } from './hand.js';
3
+ import { type Tile } from './tiles.js';
4
+ import { type Seat } from './wall.js';
5
+ /** The host's interface, restated from Bilko server/rooms/runtime.ts so the engine has no host dependency. */
6
+ export interface RoomGameModule<S> {
7
+ id: string;
8
+ seats: number;
9
+ /** Most points one seat can lose in one hand (the wallet escrows this). */
10
+ maxLossPoints: number;
11
+ newHand(seed: string, dealer: number): S;
12
+ /** What one seat may see. Must not include other seats' concealed data. */
13
+ view(state: S, seat: number): unknown;
14
+ toAct(state: S): number[];
15
+ apply(state: S, seat: number, action: unknown): {
16
+ ok: true;
17
+ state: S;
18
+ } | {
19
+ ok: false;
20
+ error: string;
21
+ };
22
+ aiAction(state: S, seat: number): unknown;
23
+ isOver(state: S): boolean;
24
+ /** Per-seat points; must be integers summing to 0. */
25
+ settle(state: S): number[];
26
+ /** Seat that deals the next hand; default (this hand's dealer + 1) % seats. */
27
+ nextDealer?(state: S): number;
28
+ /** Action for a timed-out human seat (connected or not); default aiAction. */
29
+ timeoutAction?(state: S, seat: number): unknown;
30
+ /** Ms a human seat has to act now (null/undefined = turnMs); must not depend on concealed data, since every seat sees when a seat is autoplayed. */
31
+ deadlineMs?(state: S, seat: number): number | null | undefined;
32
+ }
33
+ /** Room state: a GameState without its `rules` function, so it is plain JSON data. Server-only. */
34
+ export type RoomState = Omit<GameState, 'rules'>;
35
+ /** One seat's public information. */
36
+ export interface PublicSeat {
37
+ /** How many concealed tiles the seat holds; the tiles themselves are hidden from other seats. */
38
+ concealedCount: number;
39
+ bonus: Tile[];
40
+ /** Declared melds. A concealed kong is shown too (R4.8: outer two face down, inner two face up). */
41
+ melds: Meld[];
42
+ discards: Tile[];
43
+ }
44
+ /** The event log as one seat sees it: other seats' draws carry no tile. */
45
+ export type SeatEvent = Exclude<GameEvent, {
46
+ type: 'draw';
47
+ }> | {
48
+ type: 'draw';
49
+ seat: Seat;
50
+ fromBack: boolean;
51
+ tileId?: number;
52
+ };
53
+ export type SeatResult = Extract<HandResult, {
54
+ kind: 'draw';
55
+ }> | (Extract<HandResult, {
56
+ kind: 'win';
57
+ }> & {
58
+ /** Each winner's concealed tiles, shown once the hand is over. Losers' hands stay hidden. */
59
+ hands: Partial<Record<Seat, Tile[]>>;
60
+ });
61
+ /** Everything one seat may see. Never holds the wall, the seed or another seat's concealed tiles. */
62
+ export interface SeatView {
63
+ seat: Seat;
64
+ dealer: Seat;
65
+ turn: Seat;
66
+ phase: Phase;
67
+ wallCount: number;
68
+ /** This seat's concealed tiles in engine order (a drawn tile is last). */
69
+ hand: Tile[];
70
+ /** Public information for every seat, indexed by seat. */
71
+ seats: [PublicSeat, PublicSeat, PublicSeat];
72
+ lastDiscard: {
73
+ seat: Seat;
74
+ tile: Tile;
75
+ } | null;
76
+ lastDrawOnReplacement: boolean;
77
+ mustDiscard: boolean;
78
+ /** The open claim window. Only this seat's own declaration is shown. */
79
+ claim: {
80
+ kind: ClaimWindow['kind'];
81
+ from: Seat;
82
+ tile: Tile;
83
+ declared: Action | null;
84
+ } | null;
85
+ /** Kong payments so far (§10). */
86
+ pointsDelta: [number, number, number];
87
+ /** The actions this seat may send now. */
88
+ legal: Action[];
89
+ events: SeatEvent[];
90
+ result: SeatResult | null;
91
+ }
92
+ /** Canonical Action from untrusted input (a client frame or an AI choice), or null if malformed. */
93
+ export declare function parseAction(x: unknown): Action | null;
94
+ export interface ThreeWindsRoomModule extends RoomGameModule<RoomState> {
95
+ id: 'threewinds';
96
+ seats: 3;
97
+ newHand(seed: string, dealer: number): RoomState;
98
+ view(state: RoomState, seat: number): SeatView;
99
+ toAct(state: RoomState): Seat[];
100
+ aiAction(state: RoomState, seat: number): Action;
101
+ /**
102
+ * R14.1, for the hand after this one: the dealer keeps the deal after a draw or a dealer win;
103
+ * otherwise the winner deals (the first after the thrower when two win). Throws if not over.
104
+ */
105
+ nextDealer(state: RoomState): Seat;
106
+ /**
107
+ * For a human whose deadline passed (R4.6 auto-pass): takes a legal win, otherwise passes a
108
+ * claim window or discards the tutor's pick (R15.5). Never pongs, chows or kongs for them.
109
+ */
110
+ timeoutAction(state: RoomState, seat: number): Action;
111
+ /**
112
+ * R4.6: CLAIM_WINDOW_MS (4 s) for every seat while a claim window is open (on a discard or a
113
+ * robbable added kong), else undefined: the host's own turn time. It reads only the public phase,
114
+ * so a seat's deadline never shows whether it holds a claim. Own turns keep the host's time
115
+ * although R3.5 has no own-turn timer offline: a stalled seat would hold up a live table.
116
+ */
117
+ deadlineMs(state: RoomState, seat: number): number | undefined;
118
+ }
119
+ export declare const threeWindsRoomModule: ThreeWindsRoomModule;
package/dist/room.js ADDED
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Three Winds as a Bilko authoritative-room game (~/Projects/Bilko/docs/host-contract.md,
3
+ * "Authoritative game rooms"). The host deals from a secret seed, keeps the full state, validates
4
+ * every action here, plays AI seats with aiAction, and sends each seat only view(state, seat).
5
+ */
6
+ import { chooseAction, suggestDiscard } from './ai.js';
7
+ import { apply as applyAction, CLAIM_WINDOW_MS, DEFAULT_RULES, handFromDeal, IllegalActionError, legalActions, } from './game.js';
8
+ import { HAND_LOSS_LIMIT } from './scoring.js';
9
+ import { ALL_KINDS } from './tiles.js';
10
+ import { dealFromSeed } from './wall.js';
11
+ const SEATS = [0, 1, 2];
12
+ const KINDS = new Set(ALL_KINDS);
13
+ const isSeat = (x) => x === 0 || x === 1 || x === 2;
14
+ const isTileId = (x) => Number.isInteger(x) && x >= 0 && x < 84;
15
+ const toRoom = (s) => {
16
+ const { rules: _rules, ...rest } = s;
17
+ return rest;
18
+ };
19
+ const toGame = (s) => ({ ...s, rules: DEFAULT_RULES });
20
+ const tile = (t) => ({ id: t.id, kind: t.kind });
21
+ const tiles = (ts) => ts.map(tile);
22
+ const meld = (m) => ({ ...m, tiles: tiles(m.tiles) });
23
+ const cloneAction = (a) => (a.type === 'chow' ? { type: 'chow', tileIds: [a.tileIds[0], a.tileIds[1]] } : { ...a });
24
+ /** Canonical Action from untrusted input (a client frame or an AI choice), or null if malformed. */
25
+ export function parseAction(x) {
26
+ if (typeof x !== 'object' || x === null || Array.isArray(x))
27
+ return null;
28
+ const a = x;
29
+ const type = a.type;
30
+ switch (type) {
31
+ case 'draw':
32
+ case 'selfWin':
33
+ case 'win':
34
+ case 'discardWin':
35
+ case 'pong':
36
+ case 'exposedKong':
37
+ case 'pass':
38
+ return { type };
39
+ case 'discard':
40
+ return isTileId(a.tileId) ? { type, tileId: a.tileId } : null;
41
+ case 'concealedKong':
42
+ case 'addedKong':
43
+ return typeof a.kind === 'string' && KINDS.has(a.kind) ? { type, kind: a.kind } : null;
44
+ case 'chow': {
45
+ const ids = a.tileIds;
46
+ return Array.isArray(ids) && ids.length === 2 && isTileId(ids[0]) && isTileId(ids[1])
47
+ ? { type, tileIds: [ids[0], ids[1]] }
48
+ : null;
49
+ }
50
+ default:
51
+ return null;
52
+ }
53
+ }
54
+ /** A draw is the only legal action in phase `draw`, so play it at once: no seat waits on a forced move. */
55
+ function playForcedDraws(s) {
56
+ while (s.phase === 'draw')
57
+ s = applyAction(s, s.turn, { type: 'draw' });
58
+ return s;
59
+ }
60
+ function toActOf(s) {
61
+ if (s.phase === 'over')
62
+ return [];
63
+ if (s.phase === 'claim') {
64
+ // Every seat that has not declared, even one that can only pass: listing only seats with a real
65
+ // claim would tell everyone (toAct is broadcast) that they hold two of the discarded tile.
66
+ const w = s.claim;
67
+ return SEATS.filter((x) => x !== w.from && !w.declared[x]);
68
+ }
69
+ return [s.turn];
70
+ }
71
+ function seatView(s, seat) {
72
+ const g = toGame(s);
73
+ const r = s.result;
74
+ let result = null;
75
+ if (r?.kind === 'draw')
76
+ result = { kind: 'draw', deltas: [...r.deltas] };
77
+ else if (r?.kind === 'win') {
78
+ const hands = {};
79
+ for (const w of r.winners)
80
+ hands[w] = tiles(s.hands[w]);
81
+ result = {
82
+ kind: 'win',
83
+ winners: [...r.winners],
84
+ selfDrawn: r.selfDrawn,
85
+ ...(r.discarder === undefined ? {} : { discarder: r.discarder }),
86
+ score: JSON.parse(JSON.stringify(r.score)),
87
+ deltas: [...r.deltas],
88
+ hands,
89
+ };
90
+ }
91
+ const own = s.claim?.declared[seat];
92
+ return {
93
+ seat,
94
+ dealer: s.dealer,
95
+ turn: s.turn,
96
+ phase: s.phase,
97
+ wallCount: s.wall.length,
98
+ hand: tiles(s.hands[seat]),
99
+ seats: SEATS.map((x) => ({
100
+ concealedCount: s.hands[x].length,
101
+ bonus: tiles(s.bonus[x]),
102
+ melds: s.melds[x].map(meld),
103
+ discards: tiles(s.discards[x]),
104
+ })),
105
+ lastDiscard: s.lastDiscard ? { seat: s.lastDiscard.seat, tile: tile(s.lastDiscard.tile) } : null,
106
+ lastDrawOnReplacement: s.lastDrawOnReplacement,
107
+ mustDiscard: s.mustDiscard,
108
+ claim: s.claim
109
+ ? { kind: s.claim.kind, from: s.claim.from, tile: tile(s.claim.tile), declared: own ? cloneAction(own) : null }
110
+ : null,
111
+ pointsDelta: [...s.pointsDelta],
112
+ legal: legalActions(g, seat).map(cloneAction),
113
+ events: s.events.map((e) => {
114
+ if (e.type === 'draw') {
115
+ return e.seat === seat
116
+ ? { type: 'draw', seat: e.seat, fromBack: e.fromBack, tileId: e.tileId }
117
+ : { type: 'draw', seat: e.seat, fromBack: e.fromBack };
118
+ }
119
+ return JSON.parse(JSON.stringify(e));
120
+ }),
121
+ result,
122
+ };
123
+ }
124
+ const AI_LEVEL = 'shark';
125
+ /** Shark decisions don't draw on the rng (only Steady's 50% pong does), so aiAction is deterministic. */
126
+ const NO_RNG = () => 0.5;
127
+ export const threeWindsRoomModule = {
128
+ id: 'threewinds',
129
+ seats: 3,
130
+ maxLossPoints: HAND_LOSS_LIMIT,
131
+ newHand(seed, dealer) {
132
+ if (!isSeat(dealer))
133
+ throw new RangeError(`dealer must be 0, 1 or 2, got ${String(dealer)}`);
134
+ if (typeof seed !== 'string')
135
+ throw new TypeError('seed must be a string');
136
+ // The string seed is not kept: GameState.seed only labels mulberry32 deals.
137
+ return toRoom(handFromDeal(dealFromSeed(seed, dealer), 0, dealer));
138
+ },
139
+ view(state, seat) {
140
+ if (!isSeat(seat))
141
+ throw new RangeError(`seat must be 0, 1 or 2, got ${String(seat)}`);
142
+ return seatView(state, seat);
143
+ },
144
+ toAct: toActOf,
145
+ apply(state, seat, action) {
146
+ if (!isSeat(seat))
147
+ return { ok: false, error: 'seat must be 0, 1 or 2' };
148
+ const a = parseAction(action);
149
+ if (!a)
150
+ return { ok: false, error: 'malformed action' };
151
+ try {
152
+ return { ok: true, state: toRoom(playForcedDraws(applyAction(toGame(state), seat, a))) };
153
+ }
154
+ catch (e) {
155
+ if (e instanceof IllegalActionError)
156
+ return { ok: false, error: 'illegal action' };
157
+ return { ok: false, error: `engine error: ${e instanceof Error ? e.message : String(e)}` };
158
+ }
159
+ },
160
+ aiAction(state, seat) {
161
+ if (!isSeat(seat))
162
+ throw new RangeError(`seat must be 0, 1 or 2, got ${String(seat)}`);
163
+ return cloneAction(chooseAction(toGame(state), seat, AI_LEVEL, NO_RNG));
164
+ },
165
+ isOver: (state) => state.phase === 'over',
166
+ settle(state) {
167
+ const r = state.result;
168
+ if (state.phase !== 'over' || !r)
169
+ throw new Error('settle: the hand is not over');
170
+ // Whole-hand deltas: every kong payment plus any win, after the per-hand loss limit (R9.6).
171
+ return [...r.deltas];
172
+ },
173
+ nextDealer(state) {
174
+ const r = state.result;
175
+ if (state.phase !== 'over' || !r)
176
+ throw new Error('nextDealer: the hand is not over');
177
+ if (r.kind === 'draw' || r.winners.includes(state.dealer))
178
+ return state.dealer;
179
+ // resolve() lists winners in turn order after the thrower.
180
+ return r.winners[0];
181
+ },
182
+ timeoutAction(state, seat) {
183
+ if (!isSeat(seat))
184
+ throw new RangeError(`seat must be 0, 1 or 2, got ${String(seat)}`);
185
+ const g = toGame(state);
186
+ const legal = legalActions(g, seat);
187
+ if (legal.length === 0)
188
+ throw new Error(`seat ${seat} has no legal action`);
189
+ const pick = legal.find((a) => a.type === 'win' || a.type === 'selfWin') ??
190
+ legal.find((a) => a.type === 'pass') ??
191
+ legal.find((a) => a.type === 'draw') ??
192
+ { type: 'discard', tileId: suggestDiscard(g, seat).tileId };
193
+ return cloneAction(pick);
194
+ },
195
+ deadlineMs(state, seat) {
196
+ if (!isSeat(seat))
197
+ throw new RangeError(`seat must be 0, 1 or 2, got ${String(seat)}`);
198
+ return state.phase === 'claim' ? CLAIM_WINDOW_MS : undefined;
199
+ },
200
+ };
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Fan, limit hands, points and payments (docs/RULES.md §7 Fan table, §8 Limit hands, §9 Points &
3
+ * payments, §10 Kong payments, §11 Ban rule). Pure; depends only on tiles, hand and wall types.
4
+ */
5
+ import { type Meld } from './hand.js';
6
+ import { type Tile, type TileKind } from './tiles.js';
7
+ import type { Seat } from './wall.js';
8
+ export interface WinContext {
9
+ winner: Seat;
10
+ dealer: Seat;
11
+ /** The winner's concealed tiles including the winning tile (14 − 3 × melds.length). */
12
+ concealed: Tile[];
13
+ /** Declared melds; a concealed kong has `concealed: true`. */
14
+ melds: Meld[];
15
+ /** Bonus tiles set aside during the hand. */
16
+ bonus: Tile[];
17
+ selfDrawn: boolean;
18
+ /** Thrower for a discard win; the kong declarer for a robbed kong (R4.10). */
19
+ discarder?: Seat;
20
+ onReplacement: boolean;
21
+ robbedKong: boolean;
22
+ firstOrLastTile: boolean;
23
+ /** Ban-rule liable player (R11.3), who pays the whole collection. */
24
+ liable?: Seat;
25
+ }
26
+ export interface FanItem {
27
+ key: string;
28
+ label: string;
29
+ fan: number;
30
+ }
31
+ export interface ScoreResult {
32
+ fan: FanItem[];
33
+ totalFan: number;
34
+ /** Limit-hand key (`'L1'`..`'L10'`, see LIMIT_HANDS) or null. */
35
+ limit: string | null;
36
+ points: number;
37
+ valid: boolean;
38
+ }
39
+ export declare const MIN_FAN = 5;
40
+ export declare const POINTS_PER_FAN = 20;
41
+ export declare const LIMIT_POINTS = 200;
42
+ export declare const FLY_BONUS = 50;
43
+ /**
44
+ * R9.6: no seat loses more than 400 points in one hand, counting every payment (wins, Fly bonus, ban
45
+ * rule, kongs). Without it one seat could lose 1700: two Four-kongs winners (L4) on one discard, each
46
+ * with four concealed kongs and a Fly pair, cost the thrower 8 × 100 + 2 × (2 × 200 + 50).
47
+ */
48
+ export declare const HAND_LOSS_LIMIT = 400;
49
+ /** A set as scored: a Fly-filled set scores as the tile it stands in for (R5.4); a kong is a pong. */
50
+ export interface ScoredSet {
51
+ type: 'chow' | 'pong';
52
+ kong: boolean;
53
+ /** Pong kind, or the lowest dot of a chow. */
54
+ kind: TileKind;
55
+ concealed: boolean;
56
+ }
57
+ /** One decomposition of the winning hand, flattened for the rule tables. */
58
+ export interface HandView {
59
+ ctx: WinContext;
60
+ /** Seat wind relative to the dealer: 0 East, 1 South, 2 West (R2.2). */
61
+ seatWind: 0 | 1 | 2;
62
+ sets: ScoredSet[];
63
+ /** Pair kinds; null is a two-Fly pair, which may stand in for any kind. */
64
+ pairs: (TileKind | null)[];
65
+ sevenPairs: boolean;
66
+ flies: number;
67
+ bonus: ReadonlySet<TileKind>;
68
+ }
69
+ export interface FanRule {
70
+ key: string;
71
+ label: string;
72
+ fan: (v: HandView) => number;
73
+ }
74
+ /** The 20 rows of RULES.md §7, in design order. Each returns the fan it contributes (0 = not scored). */
75
+ export declare const FAN_RULES: readonly FanRule[];
76
+ /** One display row of the RULES.md §7 fan table: what the rules drawer lists. */
77
+ export interface FanTableRow {
78
+ /** The FAN_RULES key (F1..F20). */
79
+ key: string;
80
+ /** Fan as printed in RULES.md §7 ("1", "+1", "2", "3"). */
81
+ fan: string;
82
+ /** The item name exactly as in RULES.md §7. */
83
+ item: string;
84
+ }
85
+ /**
86
+ * The fan table for display (rules drawer), one row per FAN_RULES entry in the same order, so a
87
+ * rule added to or removed from the scorer shows up here too. scoring.test.ts checks every row
88
+ * against docs/RULES.md §7.
89
+ */
90
+ export declare const FAN_TABLE: readonly FanTableRow[];
91
+ export interface LimitRule {
92
+ key: string;
93
+ label: string;
94
+ test: (v: HandView, totalFan: number) => boolean;
95
+ }
96
+ /** RULES.md §8, in design order. The first match names the limit; limits never stack. */
97
+ export declare const LIMIT_HANDS: readonly LimitRule[];
98
+ /**
99
+ * Scores a winning hand, taking the decomposition that scores most (R5.4). A hand that forms no
100
+ * winning shape returns `valid: false` with 0 points.
101
+ */
102
+ export declare function scoreWin(ctx: WinContext): ScoreResult;
103
+ /**
104
+ * Point deltas per seat for one win (R9.3, R5.5, R11.3), summing to 0. `coWinners` lists other
105
+ * players who won on the same discard (R4.4); they pay this winner nothing.
106
+ */
107
+ export declare function settle(ctx: WinContext, score: ScoreResult, coWinners?: readonly Seat[]): [number, number, number];
108
+ /**
109
+ * Kong payment deltas (§10), summing to 0. Concealed: 100 from each opponent. Exposed from a
110
+ * discard: 50 from the discarder. Added kong (exposed, no discarder): 50 from each opponent.
111
+ * A robbed added kong pays nothing, so callers must not call this for one.
112
+ */
113
+ export declare function kongPayment(kongOwner: Seat, concealed: boolean, discarder?: Seat): [number, number, number];
114
+ /**
115
+ * Applies the per-hand loss limit (R9.6) to a hand's whole-hand deltas, which sum to 0. A seat below
116
+ * −limit pays exactly `limit`; the forgiven points come off the seats that gained, in proportion to
117
+ * their gains (largest remainder, ties to the lower seat). Returns a new triple that still sums to 0.
118
+ */
119
+ export declare function capHandLoss(deltas: readonly [number, number, number], limit?: number): [number, number, number];