@bilkobibitkov/threewinds-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/room.d.ts ADDED
@@ -0,0 +1,106 @@
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
+ }
27
+ /** Room state: a GameState without its `rules` function, so it is plain JSON data. Server-only. */
28
+ export type RoomState = Omit<GameState, 'rules'>;
29
+ /** One seat's public information. */
30
+ export interface PublicSeat {
31
+ /** How many concealed tiles the seat holds; the tiles themselves are hidden from other seats. */
32
+ concealedCount: number;
33
+ bonus: Tile[];
34
+ /** Declared melds. A concealed kong is shown too (R4.8: outer two face down, inner two face up). */
35
+ melds: Meld[];
36
+ discards: Tile[];
37
+ }
38
+ /** The event log as one seat sees it: other seats' draws carry no tile. */
39
+ export type SeatEvent = Exclude<GameEvent, {
40
+ type: 'draw';
41
+ }> | {
42
+ type: 'draw';
43
+ seat: Seat;
44
+ fromBack: boolean;
45
+ tileId?: number;
46
+ };
47
+ export type SeatResult = Extract<HandResult, {
48
+ kind: 'draw';
49
+ }> | (Extract<HandResult, {
50
+ kind: 'win';
51
+ }> & {
52
+ /** Each winner's concealed tiles, shown once the hand is over. Losers' hands stay hidden. */
53
+ hands: Partial<Record<Seat, Tile[]>>;
54
+ });
55
+ /** Everything one seat may see. Never holds the wall, the seed or another seat's concealed tiles. */
56
+ export interface SeatView {
57
+ seat: Seat;
58
+ dealer: Seat;
59
+ turn: Seat;
60
+ phase: Phase;
61
+ wallCount: number;
62
+ /** This seat's concealed tiles in engine order (a drawn tile is last). */
63
+ hand: Tile[];
64
+ /** Public information for every seat, indexed by seat. */
65
+ seats: [PublicSeat, PublicSeat, PublicSeat];
66
+ lastDiscard: {
67
+ seat: Seat;
68
+ tile: Tile;
69
+ } | null;
70
+ lastDrawOnReplacement: boolean;
71
+ mustDiscard: boolean;
72
+ /** The open claim window. Only this seat's own declaration is shown. */
73
+ claim: {
74
+ kind: ClaimWindow['kind'];
75
+ from: Seat;
76
+ tile: Tile;
77
+ declared: Action | null;
78
+ } | null;
79
+ /** Kong payments so far (§10). */
80
+ pointsDelta: [number, number, number];
81
+ /** The actions this seat may send now. */
82
+ legal: Action[];
83
+ events: SeatEvent[];
84
+ result: SeatResult | null;
85
+ }
86
+ /** Canonical Action from untrusted input (a client frame or an AI choice), or null if malformed. */
87
+ export declare function parseAction(x: unknown): Action | null;
88
+ export interface ThreeWindsRoomModule extends RoomGameModule<RoomState> {
89
+ id: 'threewinds';
90
+ seats: 3;
91
+ newHand(seed: string, dealer: number): RoomState;
92
+ view(state: RoomState, seat: number): SeatView;
93
+ toAct(state: RoomState): Seat[];
94
+ aiAction(state: RoomState, seat: number): Action;
95
+ /**
96
+ * R14.1, for the hand after this one: the dealer keeps the deal after a draw or a dealer win;
97
+ * otherwise the winner deals (the first after the thrower when two win). Throws if not over.
98
+ */
99
+ nextDealer(state: RoomState): Seat;
100
+ /**
101
+ * For a human whose deadline passed (R4.6 auto-pass): takes a legal win, otherwise passes a
102
+ * claim window or discards the tutor's pick (R15.5). Never pongs, chows or kongs for them.
103
+ */
104
+ timeoutAction(state: RoomState, seat: number): Action;
105
+ }
106
+ export declare const threeWindsRoomModule: ThreeWindsRoomModule;
package/dist/room.js ADDED
@@ -0,0 +1,195 @@
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, 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
+ };
@@ -0,0 +1,104 @@
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
+ export interface LimitRule {
77
+ key: string;
78
+ label: string;
79
+ test: (v: HandView, totalFan: number) => boolean;
80
+ }
81
+ /** RULES.md §8, in design order. The first match names the limit; limits never stack. */
82
+ export declare const LIMIT_HANDS: readonly LimitRule[];
83
+ /**
84
+ * Scores a winning hand, taking the decomposition that scores most (R5.4). A hand that forms no
85
+ * winning shape returns `valid: false` with 0 points.
86
+ */
87
+ export declare function scoreWin(ctx: WinContext): ScoreResult;
88
+ /**
89
+ * Point deltas per seat for one win (R9.3, R5.5, R11.3), summing to 0. `coWinners` lists other
90
+ * players who won on the same discard (R4.4); they pay this winner nothing.
91
+ */
92
+ export declare function settle(ctx: WinContext, score: ScoreResult, coWinners?: readonly Seat[]): [number, number, number];
93
+ /**
94
+ * Kong payment deltas (§10), summing to 0. Concealed: 100 from each opponent. Exposed from a
95
+ * discard: 50 from the discarder. Added kong (exposed, no discarder): 50 from each opponent.
96
+ * A robbed added kong pays nothing, so callers must not call this for one.
97
+ */
98
+ export declare function kongPayment(kongOwner: Seat, concealed: boolean, discarder?: Seat): [number, number, number];
99
+ /**
100
+ * Applies the per-hand loss limit (R9.6) to a hand's whole-hand deltas, which sum to 0. A seat below
101
+ * −limit pays exactly `limit`; the forgiven points come off the seats that gained, in proportion to
102
+ * their gains (largest remainder, ties to the lower seat). Returns a new triple that still sums to 0.
103
+ */
104
+ export declare function capHandLoss(deltas: readonly [number, number, number], limit?: number): [number, number, number];
@@ -0,0 +1,239 @@
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 { decompose } from './hand.js';
6
+ import { dotValue, isDot, isDragon, isFly, isHonour, isWind } from './tiles.js';
7
+ export const MIN_FAN = 5;
8
+ export const POINTS_PER_FAN = 20;
9
+ export const LIMIT_POINTS = 200;
10
+ export const FLY_BONUS = 50;
11
+ /**
12
+ * R9.6: no seat loses more than 400 points in one hand, counting every payment (wins, Fly bonus, ban
13
+ * rule, kongs). Without it one seat could lose 1700: two Four-kongs winners (L4) on one discard, each
14
+ * with four concealed kongs and a Fly pair, cost the thrower 8 × 100 + 2 × (2 × 200 + 50).
15
+ */
16
+ export const HAND_LOSS_LIMIT = 400;
17
+ const has = (v, ...ks) => ks.filter((k) => v.bonus.has(k)).length;
18
+ const pongs = (v, pred) => v.sets.filter((s) => s.type === 'pong' && pred(s.kind)).length;
19
+ const pongOf = (v, k) => pongs(v, (x) => x === k);
20
+ const standard = (v) => !v.sevenPairs;
21
+ /** Every natural kind in sets and pairs (excludes the free two-Fly pair). */
22
+ const kinds = (v) => [...v.sets.map((s) => s.kind), ...v.pairs.filter((p) => p !== null)];
23
+ const OWN_FLOWER = ['f1', 'f2', 'f3'];
24
+ const OWN_SEASON = ['s1', 's2', 's3'];
25
+ const DRAGONS = ['dr', 'dg', 'dw'];
26
+ /** The 20 rows of RULES.md §7, in design order. Each returns the fan it contributes (0 = not scored). */
27
+ export const FAN_RULES = [
28
+ { key: 'F1', label: 'Each face tile', fan: (v) => has(v, 'x1', 'x2', 'x3', 'x4') },
29
+ { key: 'F2', label: 'All four faces', fan: (v) => (has(v, 'x1', 'x2', 'x3', 'x4') === 4 ? 1 : 0) },
30
+ { key: 'F3', label: 'Each animal tile', fan: (v) => has(v, 'acat', 'arat', 'arooster', 'acentipede') },
31
+ { key: 'F4', label: 'All four animals', fan: (v) => (has(v, 'acat', 'arat', 'arooster', 'acentipede') === 4 ? 1 : 0) },
32
+ { key: 'F5', label: 'All four flowers', fan: (v) => (has(v, 'f1', 'f2', 'f3', 'f4') === 4 ? 1 : 0) },
33
+ { key: 'F6', label: 'All four seasons', fan: (v) => (has(v, 's1', 's2', 's3', 's4') === 4 ? 1 : 0) },
34
+ { key: 'F7', label: 'Own flower or season', fan: (v) => has(v, OWN_FLOWER[v.seatWind], OWN_SEASON[v.seatWind]) },
35
+ { key: 'F8', label: 'Number-four flower or season', fan: (v) => has(v, 'f4', 's4') },
36
+ { key: 'F9', label: 'Pong of 東 East', fan: (v) => (pongOf(v, 'we') ? (v.seatWind === 0 ? 2 : 1) : 0) },
37
+ { key: 'F10', label: 'Pong of 北 North', fan: (v) => (pongOf(v, 'wn') ? 1 : 0) },
38
+ {
39
+ key: 'F11',
40
+ label: 'Pong of your own wind',
41
+ fan: (v) => ((v.seatWind === 1 && pongOf(v, 'ws')) || (v.seatWind === 2 && pongOf(v, 'ww')) ? 1 : 0),
42
+ },
43
+ { key: 'F12', label: 'Pong of a dragon', fan: (v) => pongs(v, isDragon) },
44
+ {
45
+ key: 'F13',
46
+ label: 'Two dragon pongs and a dragon pair',
47
+ fan: (v) => {
48
+ if (!standard(v) || pongs(v, isDragon) !== 2)
49
+ return 0;
50
+ const third = DRAGONS.find((d) => !pongOf(v, d));
51
+ const p = v.pairs[0];
52
+ return p === null || p === third ? 3 : 0;
53
+ },
54
+ },
55
+ {
56
+ key: 'F14',
57
+ label: 'Mixed one suit',
58
+ fan: (v) => {
59
+ const honourSet = v.sevenPairs ? v.pairs.some((p) => p !== null && isHonour(p)) : pongs(v, isHonour) > 0;
60
+ const ks = kinds(v);
61
+ return honourSet && ks.some(isDot) ? 1 : 0;
62
+ },
63
+ },
64
+ { key: 'F15', label: 'Pure dots', fan: (v) => (kinds(v).every(isDot) ? 3 : 0) },
65
+ {
66
+ key: 'F16',
67
+ label: 'All chows, with a pair of dots',
68
+ fan: (v) => {
69
+ const p = v.pairs[0];
70
+ return standard(v) && v.sets.every((s) => s.type === 'chow') && (p === null || isDot(p)) ? 1 : 0;
71
+ },
72
+ },
73
+ { key: 'F17', label: 'All pongs', fan: (v) => (standard(v) && v.sets.every((s) => s.type === 'pong') ? 2 : 0) },
74
+ { key: 'F18', label: 'Win on a replacement tile', fan: (v) => (v.ctx.onReplacement ? 1 : 0) },
75
+ { key: 'F19', label: 'Seven pairs', fan: (v) => (v.sevenPairs ? 1 : 0) },
76
+ { key: 'F20', label: 'Robbing a kong', fan: (v) => (v.ctx.robbedKong ? 1 : 0) },
77
+ ];
78
+ function nineGates(v) {
79
+ const { concealed, melds } = v.ctx;
80
+ if (melds.length > 0 || v.flies > 0 || !concealed.every((t) => isDot(t.kind)))
81
+ return false;
82
+ const c = new Array(10).fill(0);
83
+ for (const t of concealed)
84
+ c[dotValue(t.kind)]++;
85
+ return c[1] >= 3 && c[9] >= 3 && [2, 3, 4, 5, 6, 7, 8].every((n) => c[n] >= 1);
86
+ }
87
+ /** RULES.md §8, in design order. The first match names the limit; limits never stack. */
88
+ export const LIMIT_HANDS = [
89
+ { key: 'L1', label: 'Pongs of all four winds', test: (v) => pongs(v, isWind) === 4 },
90
+ { key: 'L2', label: 'Three dragon pongs', test: (v) => pongs(v, isDragon) === 3 },
91
+ { key: 'L3', label: 'No bonus tiles at all', test: (v) => v.ctx.bonus.length === 0 },
92
+ { key: 'L4', label: 'Four kongs', test: (v) => v.sets.filter((s) => s.kong).length === 4 },
93
+ {
94
+ key: 'L5',
95
+ label: 'Four concealed pongs (self-drawn)',
96
+ test: (v) => v.ctx.selfDrawn && standard(v) && v.sets.every((s) => s.type === 'pong' && s.concealed),
97
+ },
98
+ { key: 'L6', label: 'Four Fly', test: (v) => v.flies === 4 },
99
+ { key: 'L7', label: 'Win on the first or last tile', test: (v) => v.ctx.firstOrLastTile },
100
+ { key: 'L8', label: 'All winds and dragons', test: (v) => kinds(v).every(isHonour) },
101
+ { key: 'L9', label: 'Nine Gates', test: nineGates },
102
+ { key: 'L10', label: '10 fan or more', test: (_v, total) => total >= 10 },
103
+ ];
104
+ function meldSet(m) {
105
+ const ks = m.tiles.map((t) => t.kind).sort((a, b) => (dotValue(a) ?? 0) - (dotValue(b) ?? 0));
106
+ return { type: m.type === 'chow' ? 'chow' : 'pong', kong: m.type === 'kong', kind: ks[0], concealed: m.concealed };
107
+ }
108
+ function view(ctx, d) {
109
+ const pairs = (d.pairs ?? [d.pair]).map((p) => (isFly(p.kinds[0]) ? null : p.kinds[0]));
110
+ return {
111
+ ctx,
112
+ seatWind: ((ctx.winner - ctx.dealer + 3) % 3),
113
+ sets: [
114
+ ...ctx.melds.map(meldSet),
115
+ ...d.sets.map((s) => ({ type: s.type, kong: false, kind: s.kinds[0], concealed: true })),
116
+ ],
117
+ pairs,
118
+ sevenPairs: d.sevenPairs,
119
+ flies: ctx.concealed.filter((t) => isFly(t.kind)).length,
120
+ bonus: new Set(ctx.bonus.map((t) => t.kind)),
121
+ };
122
+ }
123
+ function scoreView(v) {
124
+ const fan = [];
125
+ for (const r of FAN_RULES) {
126
+ const n = r.fan(v);
127
+ if (n > 0)
128
+ fan.push({ key: r.key, label: r.label, fan: n });
129
+ }
130
+ const totalFan = fan.reduce((a, f) => a + f.fan, 0);
131
+ const limit = LIMIT_HANDS.find((l) => l.test(v, totalFan))?.key ?? null;
132
+ const valid = limit !== null || totalFan >= MIN_FAN;
133
+ const points = limit !== null ? LIMIT_POINTS : Math.min(totalFan * POINTS_PER_FAN, LIMIT_POINTS);
134
+ return { fan, totalFan, limit, points, valid };
135
+ }
136
+ /**
137
+ * Scores a winning hand, taking the decomposition that scores most (R5.4). A hand that forms no
138
+ * winning shape returns `valid: false` with 0 points.
139
+ */
140
+ export function scoreWin(ctx) {
141
+ let best = null;
142
+ for (const d of decompose(ctx.concealed, ctx.melds)) {
143
+ const s = scoreView(view(ctx, d));
144
+ if (best === null ||
145
+ s.points > best.points ||
146
+ (s.points === best.points && (s.totalFan > best.totalFan || (s.totalFan === best.totalFan && s.limit !== null && best.limit === null)))) {
147
+ best = s;
148
+ }
149
+ }
150
+ return best ?? { fan: [], totalFan: 0, limit: null, points: 0, valid: false };
151
+ }
152
+ const SEATS = [0, 1, 2];
153
+ /**
154
+ * Point deltas per seat for one win (R9.3, R5.5, R11.3), summing to 0. `coWinners` lists other
155
+ * players who won on the same discard (R4.4); they pay this winner nothing.
156
+ */
157
+ export function settle(ctx, score, coWinners = []) {
158
+ if (!score.valid)
159
+ throw new Error('settle: hand is below the 5-fan minimum and not a limit hand');
160
+ if (!ctx.selfDrawn && ctx.discarder === undefined)
161
+ throw new Error('settle: a discard win needs a discarder');
162
+ const P = score.points;
163
+ const flyBonus = FLY_BONUS * ctx.concealed.filter((t) => isFly(t.kind)).length;
164
+ const out = [0, 0, 0];
165
+ let total = 0;
166
+ for (const s of SEATS) {
167
+ if (s === ctx.winner || coWinners.includes(s))
168
+ continue;
169
+ const owe = (ctx.selfDrawn || s === ctx.discarder ? 2 * P : P) + flyBonus;
170
+ total += owe;
171
+ if (ctx.liable === undefined)
172
+ out[s] -= owe;
173
+ }
174
+ if (ctx.liable !== undefined) {
175
+ if (ctx.liable === ctx.winner)
176
+ throw new Error('settle: the winner cannot be liable');
177
+ out[ctx.liable] -= total;
178
+ }
179
+ out[ctx.winner] += total;
180
+ return out;
181
+ }
182
+ /**
183
+ * Kong payment deltas (§10), summing to 0. Concealed: 100 from each opponent. Exposed from a
184
+ * discard: 50 from the discarder. Added kong (exposed, no discarder): 50 from each opponent.
185
+ * A robbed added kong pays nothing, so callers must not call this for one.
186
+ */
187
+ export function kongPayment(kongOwner, concealed, discarder) {
188
+ const out = [0, 0, 0];
189
+ const pay = (s, n) => {
190
+ out[s] -= n;
191
+ out[kongOwner] += n;
192
+ };
193
+ if (concealed) {
194
+ for (const s of SEATS)
195
+ if (s !== kongOwner)
196
+ pay(s, 100);
197
+ }
198
+ else if (discarder !== undefined) {
199
+ if (discarder === kongOwner)
200
+ throw new Error('kongPayment: discarder cannot be the kong owner');
201
+ pay(discarder, 50);
202
+ }
203
+ else {
204
+ for (const s of SEATS)
205
+ if (s !== kongOwner)
206
+ pay(s, 50);
207
+ }
208
+ return out;
209
+ }
210
+ /**
211
+ * Applies the per-hand loss limit (R9.6) to a hand's whole-hand deltas, which sum to 0. A seat below
212
+ * −limit pays exactly `limit`; the forgiven points come off the seats that gained, in proportion to
213
+ * their gains (largest remainder, ties to the lower seat). Returns a new triple that still sums to 0.
214
+ */
215
+ export function capHandLoss(deltas, limit = HAND_LOSS_LIMIT) {
216
+ const out = [deltas[0], deltas[1], deltas[2]];
217
+ let forgiven = 0;
218
+ for (const s of SEATS) {
219
+ if (out[s] < -limit) {
220
+ forgiven += -limit - out[s];
221
+ out[s] = -limit;
222
+ }
223
+ }
224
+ if (forgiven === 0)
225
+ return out;
226
+ const gainers = SEATS.filter((s) => out[s] > 0);
227
+ const gain = gainers.reduce((a, s) => a + out[s], 0);
228
+ const cuts = gainers.map((s) => ({ s, cut: Math.floor((forgiven * out[s]) / gain), rem: (forgiven * out[s]) % gain }));
229
+ let left = forgiven - cuts.reduce((a, c) => a + c.cut, 0);
230
+ for (const c of [...cuts].sort((x, y) => y.rem - x.rem || x.s - y.s)) {
231
+ if (left === 0)
232
+ break;
233
+ c.cut++;
234
+ left--;
235
+ }
236
+ for (const c of cuts)
237
+ out[c.s] -= c.cut;
238
+ return out;
239
+ }
package/dist/seed.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Seeded randomness for staked deals. mulberry32 (wall.ts) has 32 bits of state, so anyone who sees
3
+ * their own tiles could brute-force every seed and rebuild the wall. Room deals instead run Fisher-Yates
4
+ * on a ChaCha20 keystream (RFC 8439 §2.3) keyed by the host's seed. Pure TS: no node:crypto, so the
5
+ * engine still runs in React Native and the browser.
6
+ */
7
+ /** One ChaCha20 block (RFC 8439 §2.3) as 16 little-endian words. `key` is 8 words, `nonce` 3. */
8
+ export declare function chacha20Block(key: ArrayLike<number>, counter: number, nonce: ArrayLike<number>): Uint32Array;
9
+ /** A stream of uniform 32-bit integers from the ChaCha20 keystream for `seed`. */
10
+ export declare function seedStream(seed: string): () => number;
11
+ /** A uniform integer in [0, n) from a 32-bit stream, with rejection sampling so there is no bias. */
12
+ export declare function randomBelow(next: () => number, n: number): number;
13
+ /** Unbiased Fisher-Yates over a 32-bit stream; returns a new array, the input is not mutated. */
14
+ export declare function shuffleWith<T>(items: readonly T[], next: () => number): T[];