@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/README.md +32 -2
- package/dist/ai.d.ts +21 -0
- package/dist/ai.js +445 -0
- package/dist/game.d.ts +186 -0
- package/dist/game.js +434 -0
- package/dist/hand.d.ts +39 -0
- package/dist/hand.js +175 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +13 -0
- package/dist/room.d.ts +119 -0
- package/dist/room.js +200 -0
- package/dist/scoring.d.ts +119 -0
- package/dist/scoring.js +273 -0
- package/dist/seed.d.ts +14 -0
- package/dist/seed.js +115 -0
- package/dist/tiles.d.ts +45 -0
- package/dist/tiles.js +70 -0
- package/dist/wall.d.ts +33 -0
- package/dist/wall.js +76 -0
- package/package.json +30 -3
package/dist/game.js
ADDED
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
import { capHandLoss, kongPayment, scoreWin, settle } from './scoring.js';
|
|
2
|
+
import { dotValue, isBonus, isDot, isDragon, isFly, isWind } from './tiles.js';
|
|
3
|
+
import { deal, drawBack, drawFront } from './wall.js';
|
|
4
|
+
/** Real rules: a win needs scoreWin(...).valid (≥ 5 fan or a limit hand, R6.3); paid by settle. */
|
|
5
|
+
export const DEFAULT_RULES = {
|
|
6
|
+
canWin: (ctx, coWinners = []) => {
|
|
7
|
+
const score = scoreWin(ctx);
|
|
8
|
+
return { valid: score.valid, deltas: score.valid ? settle(ctx, score, coWinners) : [0, 0, 0], score };
|
|
9
|
+
},
|
|
10
|
+
};
|
|
11
|
+
/** R4.6: a human has this many ms to declare in any claim window, then auto-passes. AIs decide within it. */
|
|
12
|
+
export const CLAIM_WINDOW_MS = 4000;
|
|
13
|
+
export class IllegalActionError extends Error {
|
|
14
|
+
seat;
|
|
15
|
+
action;
|
|
16
|
+
constructor(seat, action) {
|
|
17
|
+
super(`illegal action for seat ${seat}: ${JSON.stringify(action)}`);
|
|
18
|
+
this.seat = seat;
|
|
19
|
+
this.action = action;
|
|
20
|
+
this.name = 'IllegalActionError';
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
const SEATS = [0, 1, 2];
|
|
24
|
+
const next = (s) => ((s + 1) % 3);
|
|
25
|
+
const addDeltas = (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
|
|
26
|
+
/** Deal a fresh hand (R2.4–R2.6). The dealer holds 14 and acts first, with no draw (R3.1). */
|
|
27
|
+
export function newHand(seed, dealer, rules = DEFAULT_RULES) {
|
|
28
|
+
return handFromDeal(deal(seed, dealer), seed, dealer, rules);
|
|
29
|
+
}
|
|
30
|
+
/** A fresh hand from an existing deal (room deals from a string seed, scripted deals). */
|
|
31
|
+
export function handFromDeal(d, seed, dealer, rules = DEFAULT_RULES) {
|
|
32
|
+
return {
|
|
33
|
+
seed,
|
|
34
|
+
dealer,
|
|
35
|
+
turn: dealer,
|
|
36
|
+
phase: 'act',
|
|
37
|
+
wall: d.wall,
|
|
38
|
+
hands: d.hands,
|
|
39
|
+
bonus: d.bonus,
|
|
40
|
+
melds: [[], [], []],
|
|
41
|
+
discards: [[], [], []],
|
|
42
|
+
lastDiscard: null,
|
|
43
|
+
lastDrawOnReplacement: false,
|
|
44
|
+
claim: null,
|
|
45
|
+
mustDiscard: false,
|
|
46
|
+
pointsDelta: [0, 0, 0],
|
|
47
|
+
events: [],
|
|
48
|
+
result: null,
|
|
49
|
+
rules,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function kindCounts(tiles) {
|
|
53
|
+
const m = new Map();
|
|
54
|
+
for (const t of tiles)
|
|
55
|
+
m.set(t.kind, (m.get(t.kind) ?? 0) + 1);
|
|
56
|
+
return m;
|
|
57
|
+
}
|
|
58
|
+
const copyMelds = (ms) => ms.map((m) => ({ ...m, tiles: [...m.tiles] }));
|
|
59
|
+
/** Nothing but the deal (draws and bonus replacements) has happened yet. */
|
|
60
|
+
const noPlayYet = (s) => s.events.every((e) => e.type === 'draw' || e.type === 'bonus');
|
|
61
|
+
function selfWinContext(s, seat) {
|
|
62
|
+
return {
|
|
63
|
+
winner: seat,
|
|
64
|
+
dealer: s.dealer,
|
|
65
|
+
concealed: [...s.hands[seat]],
|
|
66
|
+
melds: copyMelds(s.melds[seat]),
|
|
67
|
+
bonus: [...s.bonus[seat]],
|
|
68
|
+
selfDrawn: true,
|
|
69
|
+
onReplacement: s.lastDrawOnReplacement,
|
|
70
|
+
robbedKong: false,
|
|
71
|
+
firstOrLastTile: s.wall.length === 0 || noPlayYet(s),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Ban rule (R11.2): `seat` has exposed pongs/kongs of two dragons and `kind` is the third, or of
|
|
76
|
+
* three winds and `kind` is the fourth.
|
|
77
|
+
*/
|
|
78
|
+
function banApplies(melds, kind) {
|
|
79
|
+
const exposed = new Set(melds.filter((m) => m.type !== 'chow' && !m.concealed).map((m) => m.tiles[0].kind));
|
|
80
|
+
if (exposed.has(kind))
|
|
81
|
+
return false;
|
|
82
|
+
const count = (pred) => [...exposed].filter(pred).length;
|
|
83
|
+
return (isDragon(kind) && count(isDragon) === 2) || (isWind(kind) && count(isWind) === 3);
|
|
84
|
+
}
|
|
85
|
+
/** Win context for `seat` claiming the open window's tile (discard win or robbed kong). */
|
|
86
|
+
function claimWinContext(s, w, seat) {
|
|
87
|
+
// First tile (R8.2): the dealer's first discard, with nothing else played; last: wall empty.
|
|
88
|
+
const firstDiscard = w.kind === 'discard' &&
|
|
89
|
+
w.from === s.dealer &&
|
|
90
|
+
s.events.filter((e) => e.type !== 'draw' && e.type !== 'bonus').length === 1;
|
|
91
|
+
const ctx = {
|
|
92
|
+
winner: seat,
|
|
93
|
+
dealer: s.dealer,
|
|
94
|
+
concealed: [...s.hands[seat], w.tile],
|
|
95
|
+
melds: copyMelds(s.melds[seat]),
|
|
96
|
+
bonus: [...s.bonus[seat]],
|
|
97
|
+
selfDrawn: false,
|
|
98
|
+
discarder: w.from,
|
|
99
|
+
onReplacement: false,
|
|
100
|
+
robbedKong: w.kind === 'robKong',
|
|
101
|
+
firstOrLastTile: s.wall.length === 0 || firstDiscard,
|
|
102
|
+
};
|
|
103
|
+
if (banApplies(s.melds[seat], w.tile.kind))
|
|
104
|
+
ctx.liable = w.from;
|
|
105
|
+
return ctx;
|
|
106
|
+
}
|
|
107
|
+
/** Chow options for `seat` on `tile`: one canonical [lower, higher] tile-id pair per run shape. */
|
|
108
|
+
function chowOptions(hand, tile) {
|
|
109
|
+
const v = dotValue(tile.kind);
|
|
110
|
+
if (v === null)
|
|
111
|
+
return [];
|
|
112
|
+
const byValue = (n) => hand.find((t) => isDot(t.kind) && dotValue(t.kind) === n);
|
|
113
|
+
const out = [];
|
|
114
|
+
for (const [a, b] of [
|
|
115
|
+
[v - 2, v - 1],
|
|
116
|
+
[v - 1, v + 1],
|
|
117
|
+
[v + 1, v + 2],
|
|
118
|
+
]) {
|
|
119
|
+
const ta = byValue(a);
|
|
120
|
+
const tb = byValue(b);
|
|
121
|
+
if (ta && tb)
|
|
122
|
+
out.push([ta.id, tb.id]);
|
|
123
|
+
}
|
|
124
|
+
return out;
|
|
125
|
+
}
|
|
126
|
+
/** Structural chow check, so any copies of the right kinds are accepted, not only the canonical ids. */
|
|
127
|
+
function isLegalChow(hand, tile, ids) {
|
|
128
|
+
const v = dotValue(tile.kind);
|
|
129
|
+
if (v === null || ids.length !== 2 || ids[0] === ids[1])
|
|
130
|
+
return false;
|
|
131
|
+
const ts = ids.map((id) => hand.find((t) => t.id === id));
|
|
132
|
+
if (ts.some((t) => !t || !isDot(t.kind)))
|
|
133
|
+
return false;
|
|
134
|
+
const vals = [v, ...ts.map((t) => dotValue(t.kind))].sort((x, y) => x - y);
|
|
135
|
+
return vals[1] === vals[0] + 1 && vals[2] === vals[0] + 2;
|
|
136
|
+
}
|
|
137
|
+
function claimActions(state, seat) {
|
|
138
|
+
const w = state.claim;
|
|
139
|
+
if (seat === w.from || state.result)
|
|
140
|
+
return [];
|
|
141
|
+
const out = [{ type: 'pass' }];
|
|
142
|
+
if (state.rules.canWin(claimWinContext(state, w, seat)).valid)
|
|
143
|
+
out.push({ type: 'win' });
|
|
144
|
+
// R13.2: after the last tile is drawn a discard can be claimed for a win only. Robbing = win only.
|
|
145
|
+
if (w.kind === 'robKong' || state.wall.length === 0)
|
|
146
|
+
return out;
|
|
147
|
+
const hand = state.hands[seat];
|
|
148
|
+
const n = hand.filter((t) => t.kind === w.tile.kind).length;
|
|
149
|
+
if (n >= 2)
|
|
150
|
+
out.push({ type: 'pong' });
|
|
151
|
+
if (n >= 3)
|
|
152
|
+
out.push({ type: 'exposedKong' });
|
|
153
|
+
if (seat === next(w.from))
|
|
154
|
+
for (const tileIds of chowOptions(hand, w.tile))
|
|
155
|
+
out.push({ type: 'chow', tileIds });
|
|
156
|
+
return out;
|
|
157
|
+
}
|
|
158
|
+
export function legalActions(state, seat) {
|
|
159
|
+
if (state.phase === 'over')
|
|
160
|
+
return [];
|
|
161
|
+
if (state.phase === 'claim')
|
|
162
|
+
return state.claim.declared[seat] ? [] : claimActions(state, seat);
|
|
163
|
+
if (seat !== state.turn)
|
|
164
|
+
return [];
|
|
165
|
+
if (state.phase === 'draw')
|
|
166
|
+
return [{ type: 'draw' }];
|
|
167
|
+
const hand = state.hands[seat];
|
|
168
|
+
const out = [];
|
|
169
|
+
if (!state.mustDiscard) {
|
|
170
|
+
if (state.rules.canWin(selfWinContext(state, seat)).valid)
|
|
171
|
+
out.push({ type: 'selfWin' });
|
|
172
|
+
for (const [kind, n] of kindCounts(hand)) {
|
|
173
|
+
if (n === 4 && !isFly(kind) && !isBonus(kind))
|
|
174
|
+
out.push({ type: 'concealedKong', kind });
|
|
175
|
+
}
|
|
176
|
+
for (const m of state.melds[seat]) {
|
|
177
|
+
const kind = m.tiles[0].kind;
|
|
178
|
+
if (m.type === 'pong' && !m.concealed && hand.some((t) => t.kind === kind))
|
|
179
|
+
out.push({ type: 'addedKong', kind });
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
for (const t of hand)
|
|
183
|
+
out.push({ type: 'discard', tileId: t.id });
|
|
184
|
+
return out;
|
|
185
|
+
}
|
|
186
|
+
const normalize = (a) => (a.type === 'discardWin' ? { type: 'win' } : a);
|
|
187
|
+
function sameAction(a, b) {
|
|
188
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
189
|
+
}
|
|
190
|
+
function isLegal(state, seat, action) {
|
|
191
|
+
const a = normalize(action);
|
|
192
|
+
if (state.phase === 'claim' && a.type === 'chow') {
|
|
193
|
+
const w = state.claim;
|
|
194
|
+
return (!w.declared[seat] &&
|
|
195
|
+
claimActions(state, seat).some((x) => x.type === 'chow') &&
|
|
196
|
+
isLegalChow(state.hands[seat], w.tile, a.tileIds));
|
|
197
|
+
}
|
|
198
|
+
return legalActions(state, seat).some((x) => sameAction(x, a));
|
|
199
|
+
}
|
|
200
|
+
/** Working copy: fresh outer arrays per seat so the input state is never touched. */
|
|
201
|
+
function copy(s) {
|
|
202
|
+
const per = (x) => [[...x[0]], [...x[1]], [...x[2]]];
|
|
203
|
+
return {
|
|
204
|
+
...s,
|
|
205
|
+
wall: [...s.wall],
|
|
206
|
+
hands: per(s.hands),
|
|
207
|
+
bonus: per(s.bonus),
|
|
208
|
+
melds: per(s.melds),
|
|
209
|
+
discards: per(s.discards),
|
|
210
|
+
pointsDelta: [...s.pointsDelta],
|
|
211
|
+
claim: s.claim ? { ...s.claim, declared: { ...s.claim.declared } } : null,
|
|
212
|
+
events: [...s.events],
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
function endDraw(s) {
|
|
216
|
+
s.phase = 'over';
|
|
217
|
+
s.claim = null;
|
|
218
|
+
s.result = { kind: 'draw', deltas: capHandLoss(s.pointsDelta) };
|
|
219
|
+
s.events.push({ type: 'drawGame' });
|
|
220
|
+
return s;
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Draw for `seat` (front or back), setting aside bonus tiles and replacing them from the back
|
|
224
|
+
* while they keep coming (R3.2, R12.1). An empty wall ends the hand as a draw (R13.1).
|
|
225
|
+
*/
|
|
226
|
+
function drawInto(s, seat, fromBack) {
|
|
227
|
+
s.turn = seat;
|
|
228
|
+
s.mustDiscard = false;
|
|
229
|
+
let back = fromBack;
|
|
230
|
+
for (;;) {
|
|
231
|
+
const r = back ? drawBack(s.wall) : drawFront(s.wall);
|
|
232
|
+
if (!r.tile)
|
|
233
|
+
return endDraw(s);
|
|
234
|
+
s.wall = r.wall;
|
|
235
|
+
s.events.push({ type: 'draw', seat, tileId: r.tile.id, fromBack: back });
|
|
236
|
+
if (isBonus(r.tile.kind)) {
|
|
237
|
+
s.bonus[seat].push(r.tile);
|
|
238
|
+
s.events.push({ type: 'bonus', seat, tileId: r.tile.id });
|
|
239
|
+
back = true;
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
242
|
+
s.hands[seat].push(r.tile);
|
|
243
|
+
s.lastDrawOnReplacement = back;
|
|
244
|
+
s.phase = 'act';
|
|
245
|
+
return s;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
function payKong(s, owner, concealed, discarder) {
|
|
249
|
+
s.pointsDelta = addDeltas(s.pointsDelta, kongPayment(owner, concealed, discarder));
|
|
250
|
+
}
|
|
251
|
+
function takeFromHand(s, seat, pred, n) {
|
|
252
|
+
const out = [];
|
|
253
|
+
s.hands[seat] = s.hands[seat].filter((t) => {
|
|
254
|
+
if (out.length < n && pred(t)) {
|
|
255
|
+
out.push(t);
|
|
256
|
+
return false;
|
|
257
|
+
}
|
|
258
|
+
return true;
|
|
259
|
+
});
|
|
260
|
+
return out;
|
|
261
|
+
}
|
|
262
|
+
/** Remove the claimed tile from where it sits during the window (discard pile, or declarer's hand). */
|
|
263
|
+
function takeClaimTile(s, w) {
|
|
264
|
+
if (w.kind === 'discard') {
|
|
265
|
+
const pile = s.discards[w.from];
|
|
266
|
+
pile.splice(pile.findIndex((t) => t.id === w.tile.id), 1);
|
|
267
|
+
}
|
|
268
|
+
else {
|
|
269
|
+
takeFromHand(s, w.from, (t) => t.id === w.tile.id, 1);
|
|
270
|
+
}
|
|
271
|
+
return w.tile;
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Close the open claim window with every seat's claim (missing seats pass) and resolve by R4.3
|
|
275
|
+
* priority: win > pong = kong > chow. Every winning claim wins (R4.4, R4.10). Claims already
|
|
276
|
+
* declared through apply() are kept unless overridden here. Throws IllegalActionError for an
|
|
277
|
+
* illegal claim.
|
|
278
|
+
*/
|
|
279
|
+
export function resolveClaims(state, claims) {
|
|
280
|
+
if (state.phase !== 'claim' || !state.claim) {
|
|
281
|
+
const [seat, action] = (Object.entries(claims)[0] ?? [state.turn, { type: 'pass' }]);
|
|
282
|
+
throw new IllegalActionError(Number(seat), action);
|
|
283
|
+
}
|
|
284
|
+
const w = state.claim;
|
|
285
|
+
const all = { ...w.declared };
|
|
286
|
+
const open = { ...state, claim: { ...w, declared: {} } };
|
|
287
|
+
for (const seat of SEATS) {
|
|
288
|
+
const a = claims[seat];
|
|
289
|
+
if (a === undefined)
|
|
290
|
+
continue;
|
|
291
|
+
if (!isLegal(open, seat, a))
|
|
292
|
+
throw new IllegalActionError(seat, a);
|
|
293
|
+
all[seat] = normalize(a);
|
|
294
|
+
}
|
|
295
|
+
return resolve(copy(state), w, all);
|
|
296
|
+
}
|
|
297
|
+
function resolve(s, w, claims) {
|
|
298
|
+
s.claim = null;
|
|
299
|
+
// Seats in turn order after the claimed-from seat.
|
|
300
|
+
const order = [next(w.from), next(next(w.from))];
|
|
301
|
+
const winners = order.filter((seat) => claims[seat]?.type === 'win');
|
|
302
|
+
if (winners.length > 0) {
|
|
303
|
+
let deltas = [...s.pointsDelta];
|
|
304
|
+
const score = {};
|
|
305
|
+
for (const seat of winners) {
|
|
306
|
+
const ctx = claimWinContext(s, w, seat);
|
|
307
|
+
const r = s.rules.canWin(ctx, winners.filter((x) => x !== seat));
|
|
308
|
+
score[seat] = r.score ?? scoreWin(ctx);
|
|
309
|
+
deltas = addDeltas(deltas, r.deltas);
|
|
310
|
+
}
|
|
311
|
+
deltas = capHandLoss(deltas);
|
|
312
|
+
const tile = takeClaimTile(s, w);
|
|
313
|
+
s.hands[winners[0]].push(tile);
|
|
314
|
+
s.phase = 'over';
|
|
315
|
+
s.result = { kind: 'win', winners, selfDrawn: false, discarder: w.from, score, deltas };
|
|
316
|
+
s.events.push({
|
|
317
|
+
type: 'win',
|
|
318
|
+
seats: [...winners],
|
|
319
|
+
from: w.from,
|
|
320
|
+
tileId: tile.id,
|
|
321
|
+
robbedKong: w.kind === 'robKong',
|
|
322
|
+
deltas: [...deltas],
|
|
323
|
+
});
|
|
324
|
+
return s;
|
|
325
|
+
}
|
|
326
|
+
if (w.kind === 'robKong') {
|
|
327
|
+
// Nobody robbed: the added kong stands and is paid (R10.2–R10.3).
|
|
328
|
+
const tile = takeClaimTile(s, w);
|
|
329
|
+
const melds = s.melds[w.from];
|
|
330
|
+
const mi = melds.findIndex((m) => m.type === 'pong' && !m.concealed && m.tiles[0].kind === tile.kind);
|
|
331
|
+
const old = melds[mi];
|
|
332
|
+
melds[mi] = { ...old, type: 'kong', tiles: [...old.tiles, tile] };
|
|
333
|
+
s.events.push({ type: 'kong', seat: w.from, kind: tile.kind, concealed: false, added: true });
|
|
334
|
+
payKong(s, w.from, false);
|
|
335
|
+
return drawInto(s, w.from, true);
|
|
336
|
+
}
|
|
337
|
+
const meldClaim = order.find((seat) => claims[seat]?.type === 'pong' || claims[seat]?.type === 'exposedKong');
|
|
338
|
+
if (meldClaim !== undefined) {
|
|
339
|
+
const kong = claims[meldClaim].type === 'exposedKong';
|
|
340
|
+
const tile = takeClaimTile(s, w);
|
|
341
|
+
const own = takeFromHand(s, meldClaim, (t) => t.kind === tile.kind, kong ? 3 : 2);
|
|
342
|
+
s.melds[meldClaim].push({ type: kong ? 'kong' : 'pong', tiles: [...own, tile], concealed: false, from: w.from });
|
|
343
|
+
s.events.push({ type: 'claim', seat: meldClaim, claim: kong ? 'exposedKong' : 'pong', tileId: tile.id, from: w.from });
|
|
344
|
+
if (kong) {
|
|
345
|
+
s.events.push({ type: 'kong', seat: meldClaim, kind: tile.kind, concealed: false, added: false });
|
|
346
|
+
payKong(s, meldClaim, false, w.from);
|
|
347
|
+
return drawInto(s, meldClaim, true);
|
|
348
|
+
}
|
|
349
|
+
return claimedTurn(s, meldClaim);
|
|
350
|
+
}
|
|
351
|
+
const chowSeat = next(w.from);
|
|
352
|
+
const chow = claims[chowSeat];
|
|
353
|
+
if (chow?.type === 'chow') {
|
|
354
|
+
const tile = takeClaimTile(s, w);
|
|
355
|
+
const own = takeFromHand(s, chowSeat, (t) => chow.tileIds.includes(t.id), 2);
|
|
356
|
+
const run = [...own, tile].sort((a, b) => dotValue(a.kind) - dotValue(b.kind));
|
|
357
|
+
s.melds[chowSeat].push({ type: 'chow', tiles: run, concealed: false, from: w.from });
|
|
358
|
+
s.events.push({ type: 'claim', seat: chowSeat, claim: 'chow', tileId: tile.id, from: w.from });
|
|
359
|
+
return claimedTurn(s, chowSeat);
|
|
360
|
+
}
|
|
361
|
+
// Everyone passed: the seat after the discarder draws.
|
|
362
|
+
s.turn = next(w.from);
|
|
363
|
+
s.phase = 'draw';
|
|
364
|
+
return s;
|
|
365
|
+
}
|
|
366
|
+
/** After a pong or chow the claimer takes the turn and must discard (R4.5); seats between are skipped. */
|
|
367
|
+
function claimedTurn(s, seat) {
|
|
368
|
+
s.turn = seat;
|
|
369
|
+
s.phase = 'act';
|
|
370
|
+
s.mustDiscard = true;
|
|
371
|
+
s.lastDrawOnReplacement = false;
|
|
372
|
+
return s;
|
|
373
|
+
}
|
|
374
|
+
function openWindow(s, kind, from, tile) {
|
|
375
|
+
s.phase = 'claim';
|
|
376
|
+
s.turn = from;
|
|
377
|
+
s.claim = { kind, from, tile, declared: {} };
|
|
378
|
+
return s;
|
|
379
|
+
}
|
|
380
|
+
export function apply(state, seat, action) {
|
|
381
|
+
if (!isLegal(state, seat, action))
|
|
382
|
+
throw new IllegalActionError(seat, action);
|
|
383
|
+
const s = copy(state);
|
|
384
|
+
if (state.phase === 'claim') {
|
|
385
|
+
const w = s.claim;
|
|
386
|
+
w.declared[seat] = normalize(action);
|
|
387
|
+
const waiting = SEATS.some((x) => x !== w.from && !w.declared[x]);
|
|
388
|
+
return waiting ? s : resolve(s, w, w.declared);
|
|
389
|
+
}
|
|
390
|
+
switch (action.type) {
|
|
391
|
+
case 'draw':
|
|
392
|
+
return drawInto(s, seat, false);
|
|
393
|
+
case 'discard': {
|
|
394
|
+
const hand = s.hands[seat];
|
|
395
|
+
const i = hand.findIndex((t) => t.id === action.tileId);
|
|
396
|
+
const [tile] = hand.splice(i, 1);
|
|
397
|
+
s.discards[seat].push(tile);
|
|
398
|
+
s.lastDiscard = { seat, tile: tile };
|
|
399
|
+
s.events.push({ type: 'discard', seat, tileId: tile.id });
|
|
400
|
+
s.lastDrawOnReplacement = false;
|
|
401
|
+
s.mustDiscard = false;
|
|
402
|
+
// A Fly discard can't be claimed (R3.4), so no window opens.
|
|
403
|
+
if (isFly(tile.kind)) {
|
|
404
|
+
s.turn = next(seat);
|
|
405
|
+
s.phase = 'draw';
|
|
406
|
+
return s;
|
|
407
|
+
}
|
|
408
|
+
return openWindow(s, 'discard', seat, tile);
|
|
409
|
+
}
|
|
410
|
+
case 'concealedKong': {
|
|
411
|
+
const tiles = takeFromHand(s, seat, (t) => t.kind === action.kind, 4);
|
|
412
|
+
s.melds[seat].push({ type: 'kong', tiles, concealed: true });
|
|
413
|
+
s.events.push({ type: 'kong', seat, kind: action.kind, concealed: true, added: false });
|
|
414
|
+
payKong(s, seat, true);
|
|
415
|
+
return drawInto(s, seat, true);
|
|
416
|
+
}
|
|
417
|
+
case 'addedKong': {
|
|
418
|
+
// The tile stays in the declarer's hand while others may rob it (R4.10); resolve() completes it.
|
|
419
|
+
const tile = s.hands[seat].find((t) => t.kind === action.kind);
|
|
420
|
+
return openWindow(s, 'robKong', seat, tile);
|
|
421
|
+
}
|
|
422
|
+
case 'selfWin': {
|
|
423
|
+
const ctx = selfWinContext(state, seat);
|
|
424
|
+
const r = s.rules.canWin(ctx);
|
|
425
|
+
const deltas = capHandLoss(addDeltas(s.pointsDelta, r.deltas));
|
|
426
|
+
s.phase = 'over';
|
|
427
|
+
s.result = { kind: 'win', winners: [seat], selfDrawn: true, score: { [seat]: r.score ?? scoreWin(ctx) }, deltas };
|
|
428
|
+
s.events.push({ type: 'selfWin', seat, deltas: [...deltas] });
|
|
429
|
+
return s;
|
|
430
|
+
}
|
|
431
|
+
default:
|
|
432
|
+
throw new IllegalActionError(seat, action);
|
|
433
|
+
}
|
|
434
|
+
}
|
package/dist/hand.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Winning-shape enumeration (docs/RULES.md §5 The Fly, §6 Winning shapes). Pure; no deps beyond tiles.
|
|
3
|
+
*/
|
|
4
|
+
import { type Tile, type TileKind } from './tiles.js';
|
|
5
|
+
type Seat = 0 | 1 | 2;
|
|
6
|
+
export interface Meld {
|
|
7
|
+
type: 'chow' | 'pong' | 'kong';
|
|
8
|
+
tiles: Tile[];
|
|
9
|
+
concealed: boolean;
|
|
10
|
+
from?: Seat;
|
|
11
|
+
}
|
|
12
|
+
export interface DecompPair {
|
|
13
|
+
/** Kinds the pair scores as; a two-Fly pair is `['fly', 'fly']`. */
|
|
14
|
+
kinds: TileKind[];
|
|
15
|
+
flies: number;
|
|
16
|
+
}
|
|
17
|
+
export interface DecompSet {
|
|
18
|
+
type: 'chow' | 'pong';
|
|
19
|
+
/** Kinds the set scores as, ascending — a Fly is listed as the tile it stands in for (R5.4). */
|
|
20
|
+
kinds: TileKind[];
|
|
21
|
+
flies: number;
|
|
22
|
+
}
|
|
23
|
+
export interface Decomposition {
|
|
24
|
+
/** Sets formed from the concealed tiles only; melds are fixed and not repeated here. */
|
|
25
|
+
sets: DecompSet[];
|
|
26
|
+
/** The pair. For seven pairs this is `pairs[0]`. */
|
|
27
|
+
pair: DecompPair;
|
|
28
|
+
sevenPairs: boolean;
|
|
29
|
+
/** All seven pairs, present only when `sevenPairs` is true. */
|
|
30
|
+
pairs?: DecompPair[];
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Every distinct way `concealed` (plus fixed `melds`) forms a winning shape: four sets and a pair,
|
|
34
|
+
* or seven pairs. Returns [] if the tile count is wrong, a meld is malformed or holds a Fly (R4.2,
|
|
35
|
+
* R5.2), or no shape exists.
|
|
36
|
+
*/
|
|
37
|
+
export declare function decompose(concealed: Tile[], melds: Meld[]): Decomposition[];
|
|
38
|
+
export declare function isWinningShape(concealed: Tile[], melds: Meld[]): boolean;
|
|
39
|
+
export {};
|
package/dist/hand.js
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Winning-shape enumeration (docs/RULES.md §5 The Fly, §6 Winning shapes). Pure; no deps beyond tiles.
|
|
3
|
+
*/
|
|
4
|
+
import { ALL_KINDS, isBonus, isDot, isFly, sortKey } from './tiles.js';
|
|
5
|
+
/** Playing kinds (d1..d9, winds, dragons) in sortKey order; index = sortKey - 1. */
|
|
6
|
+
const PLAY_KINDS = ALL_KINDS.filter((k) => !isFly(k) && !isBonus(k));
|
|
7
|
+
const N = PLAY_KINDS.length; // 16
|
|
8
|
+
const DOTS = 9; // indices 0..8 are d1..d9
|
|
9
|
+
const MELD_SIZE = { chow: 3, pong: 3, kong: 4 };
|
|
10
|
+
/** Counts per playing kind plus Fly count, or null if any bonus tile is present. */
|
|
11
|
+
function count(tiles) {
|
|
12
|
+
const c = new Array(N).fill(0);
|
|
13
|
+
let f = 0;
|
|
14
|
+
for (const { kind } of tiles) {
|
|
15
|
+
if (isFly(kind))
|
|
16
|
+
f++;
|
|
17
|
+
else if (isBonus(kind))
|
|
18
|
+
return null;
|
|
19
|
+
else
|
|
20
|
+
c[sortKey(kind) - 1]++;
|
|
21
|
+
}
|
|
22
|
+
return { c, f };
|
|
23
|
+
}
|
|
24
|
+
function key(d) {
|
|
25
|
+
const sets = d.sets.map((s) => `${s.type}${s.kinds.join(',')}/${s.flies}`).sort();
|
|
26
|
+
const pairs = (d.pairs ?? [d.pair]).map((p) => `${p.kinds.join(',')}/${p.flies}`).sort();
|
|
27
|
+
return `${d.sevenPairs ? 'S' : 'N'}|${sets.join(' ')}|${pairs.join(' ')}`;
|
|
28
|
+
}
|
|
29
|
+
function standard(c, f, out) {
|
|
30
|
+
const sets = [];
|
|
31
|
+
let pair = null;
|
|
32
|
+
const rec = (fl) => {
|
|
33
|
+
let i = 0;
|
|
34
|
+
while (i < N && c[i] === 0)
|
|
35
|
+
i++;
|
|
36
|
+
if (i === N) {
|
|
37
|
+
if (pair === null) {
|
|
38
|
+
if (fl === 2)
|
|
39
|
+
out.push({ sets: [...sets], pair: { kinds: ['fly', 'fly'], flies: 2 }, sevenPairs: false });
|
|
40
|
+
}
|
|
41
|
+
else if (fl === 0) {
|
|
42
|
+
out.push({ sets: [...sets], pair, sevenPairs: false });
|
|
43
|
+
}
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
const k = PLAY_KINDS[i];
|
|
47
|
+
// Pair on kind i: two naturals, or one natural + one Fly.
|
|
48
|
+
if (pair === null) {
|
|
49
|
+
for (let u = 0; u <= 1; u++) {
|
|
50
|
+
const need = 2 - u;
|
|
51
|
+
if (c[i] >= need && fl >= u) {
|
|
52
|
+
c[i] -= need;
|
|
53
|
+
pair = { kinds: [k, k], flies: u };
|
|
54
|
+
rec(fl - u);
|
|
55
|
+
pair = null;
|
|
56
|
+
c[i] += need;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
// Pong on kind i with 0-2 Flies (always >= 1 natural).
|
|
61
|
+
for (let u = 0; u <= 2; u++) {
|
|
62
|
+
const need = 3 - u;
|
|
63
|
+
if (c[i] >= need && fl >= u) {
|
|
64
|
+
c[i] -= need;
|
|
65
|
+
sets.push({ type: 'pong', kinds: [k, k, k], flies: u });
|
|
66
|
+
rec(fl - u);
|
|
67
|
+
sets.pop();
|
|
68
|
+
c[i] += need;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
// Chow containing kind i (the lowest remaining natural), at most one Fly.
|
|
72
|
+
if (i < DOTS) {
|
|
73
|
+
for (let s = Math.max(0, i - 2); s <= i && s + 2 < DOTS; s++) {
|
|
74
|
+
// Members below i have no naturals left, so they must be Flies.
|
|
75
|
+
const below = i - s;
|
|
76
|
+
if (below > 1 || below > fl)
|
|
77
|
+
continue;
|
|
78
|
+
// For members above i, choose natural or (if budget allows) Fly.
|
|
79
|
+
const above = [];
|
|
80
|
+
for (let m = i + 1; m <= s + 2; m++)
|
|
81
|
+
above.push(m);
|
|
82
|
+
const opts = 1 << above.length;
|
|
83
|
+
for (let mask = 0; mask < opts; mask++) {
|
|
84
|
+
let flies = below;
|
|
85
|
+
let ok = true;
|
|
86
|
+
for (let b = 0; b < above.length; b++) {
|
|
87
|
+
if (mask & (1 << b))
|
|
88
|
+
flies++;
|
|
89
|
+
else if (c[above[b]] === 0)
|
|
90
|
+
ok = false;
|
|
91
|
+
}
|
|
92
|
+
if (!ok || flies > 1 || flies > fl)
|
|
93
|
+
continue;
|
|
94
|
+
c[i]--;
|
|
95
|
+
for (let b = 0; b < above.length; b++)
|
|
96
|
+
if (!(mask & (1 << b)))
|
|
97
|
+
c[above[b]]--;
|
|
98
|
+
sets.push({ type: 'chow', kinds: [PLAY_KINDS[s], PLAY_KINDS[s + 1], PLAY_KINDS[s + 2]], flies });
|
|
99
|
+
rec(fl - flies);
|
|
100
|
+
sets.pop();
|
|
101
|
+
for (let b = 0; b < above.length; b++)
|
|
102
|
+
if (!(mask & (1 << b)))
|
|
103
|
+
c[above[b]]++;
|
|
104
|
+
c[i]++;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
rec(f);
|
|
110
|
+
}
|
|
111
|
+
/** Seven pairs of seven different kinds (R6.2); Flies pair per R5.2. At most one result. */
|
|
112
|
+
function sevenPairs(c, f) {
|
|
113
|
+
const pairs = [];
|
|
114
|
+
let singles = 0;
|
|
115
|
+
for (let i = 0; i < N; i++) {
|
|
116
|
+
const n = c[i];
|
|
117
|
+
if (n === 0)
|
|
118
|
+
continue;
|
|
119
|
+
if (n > 2)
|
|
120
|
+
return null;
|
|
121
|
+
const k = PLAY_KINDS[i];
|
|
122
|
+
pairs.push({ kinds: [k, k], flies: 2 - n });
|
|
123
|
+
if (n === 1)
|
|
124
|
+
singles++;
|
|
125
|
+
}
|
|
126
|
+
const spare = f - singles;
|
|
127
|
+
if (spare !== 0 && spare !== 2)
|
|
128
|
+
return null;
|
|
129
|
+
if (spare === 2)
|
|
130
|
+
pairs.push({ kinds: ['fly', 'fly'], flies: 2 });
|
|
131
|
+
if (pairs.length !== 7)
|
|
132
|
+
return null;
|
|
133
|
+
return { sets: [], pair: pairs[0], sevenPairs: true, pairs };
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Every distinct way `concealed` (plus fixed `melds`) forms a winning shape: four sets and a pair,
|
|
137
|
+
* or seven pairs. Returns [] if the tile count is wrong, a meld is malformed or holds a Fly (R4.2,
|
|
138
|
+
* R5.2), or no shape exists.
|
|
139
|
+
*/
|
|
140
|
+
export function decompose(concealed, melds) {
|
|
141
|
+
for (const m of melds) {
|
|
142
|
+
if (m.tiles.length !== MELD_SIZE[m.type])
|
|
143
|
+
return [];
|
|
144
|
+
if (m.tiles.some((t) => isFly(t.kind) || isBonus(t.kind)))
|
|
145
|
+
return [];
|
|
146
|
+
if (m.type === 'chow' && !m.tiles.every((t) => isDot(t.kind)))
|
|
147
|
+
return [];
|
|
148
|
+
}
|
|
149
|
+
if (melds.length > 4 || concealed.length !== 14 - 3 * melds.length)
|
|
150
|
+
return [];
|
|
151
|
+
const counted = count(concealed);
|
|
152
|
+
if (counted === null)
|
|
153
|
+
return [];
|
|
154
|
+
const { c, f } = counted;
|
|
155
|
+
const raw = [];
|
|
156
|
+
standard(c, f, raw);
|
|
157
|
+
if (melds.length === 0) {
|
|
158
|
+
const sp = sevenPairs(c, f);
|
|
159
|
+
if (sp)
|
|
160
|
+
raw.push(sp);
|
|
161
|
+
}
|
|
162
|
+
const seen = new Set();
|
|
163
|
+
const out = [];
|
|
164
|
+
for (const d of raw) {
|
|
165
|
+
const k = key(d);
|
|
166
|
+
if (!seen.has(k)) {
|
|
167
|
+
seen.add(k);
|
|
168
|
+
out.push(d);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return out;
|
|
172
|
+
}
|
|
173
|
+
export function isWinningShape(concealed, melds) {
|
|
174
|
+
return decompose(concealed, melds).length > 0;
|
|
175
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @threewinds/engine — platform-agnostic rules engine for Three Winds
|
|
3
|
+
* (Malaysian 3-player mahjong). Must never import DOM, React or React Native.
|
|
4
|
+
*/
|
|
5
|
+
export declare const ENGINE_VERSION = "0.1.1";
|
|
6
|
+
export * from './tiles.js';
|
|
7
|
+
export * from './wall.js';
|
|
8
|
+
export * from './seed.js';
|
|
9
|
+
export * from './hand.js';
|
|
10
|
+
export * from './scoring.js';
|
|
11
|
+
export * from './game.js';
|
|
12
|
+
export * from './ai.js';
|
|
13
|
+
export * from './room.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @threewinds/engine — platform-agnostic rules engine for Three Winds
|
|
3
|
+
* (Malaysian 3-player mahjong). Must never import DOM, React or React Native.
|
|
4
|
+
*/
|
|
5
|
+
export const ENGINE_VERSION = '0.1.1';
|
|
6
|
+
export * from './tiles.js';
|
|
7
|
+
export * from './wall.js';
|
|
8
|
+
export * from './seed.js';
|
|
9
|
+
export * from './hand.js';
|
|
10
|
+
export * from './scoring.js';
|
|
11
|
+
export * from './game.js';
|
|
12
|
+
export * from './ai.js';
|
|
13
|
+
export * from './room.js';
|