@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/scoring.js
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
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
|
+
/** RULES.md §7 "Fan" and "Item" columns, keyed by rule; FAN_TABLE pairs them with FAN_RULES. */
|
|
79
|
+
const FAN_DISPLAY = {
|
|
80
|
+
F1: ['1', 'Each face tile'],
|
|
81
|
+
F2: ['+1', 'All four faces'],
|
|
82
|
+
F3: ['1', 'Each animal tile'],
|
|
83
|
+
F4: ['+1', 'All four animals'],
|
|
84
|
+
F5: ['1', 'All four flowers'],
|
|
85
|
+
F6: ['1', 'All four seasons'],
|
|
86
|
+
F7: ['1', 'Your own flower or season (East 1, South 2, West 3)'],
|
|
87
|
+
F8: ['1', 'Number-four flower or season'],
|
|
88
|
+
F9: ['1', 'Pong of 東 East. Dealer gets +1'],
|
|
89
|
+
F10: ['1', 'Pong of 北 North'],
|
|
90
|
+
F11: ['1', 'Pong of your own wind'],
|
|
91
|
+
F12: ['1', 'Pong of a dragon'],
|
|
92
|
+
F13: ['3', 'Two dragon pongs and a dragon pair'],
|
|
93
|
+
F14: ['1', 'Mixed one suit (dots + honours)'],
|
|
94
|
+
F15: ['3', 'Pure dots'],
|
|
95
|
+
F16: ['1', 'All chows, with a pair of dots'],
|
|
96
|
+
F17: ['2', 'All pongs'],
|
|
97
|
+
F18: ['1', 'Win on a replacement tile'],
|
|
98
|
+
F19: ['1', 'Seven pairs'],
|
|
99
|
+
F20: ['1', 'Robbing a kong'],
|
|
100
|
+
};
|
|
101
|
+
/**
|
|
102
|
+
* The fan table for display (rules drawer), one row per FAN_RULES entry in the same order, so a
|
|
103
|
+
* rule added to or removed from the scorer shows up here too. scoring.test.ts checks every row
|
|
104
|
+
* against docs/RULES.md §7.
|
|
105
|
+
*/
|
|
106
|
+
export const FAN_TABLE = FAN_RULES.map((r) => {
|
|
107
|
+
const d = FAN_DISPLAY[r.key];
|
|
108
|
+
if (!d)
|
|
109
|
+
throw new Error(`FAN_TABLE: no RULES.md §7 row for ${r.key}`);
|
|
110
|
+
return { key: r.key, fan: d[0], item: d[1] };
|
|
111
|
+
});
|
|
112
|
+
function nineGates(v) {
|
|
113
|
+
const { concealed, melds } = v.ctx;
|
|
114
|
+
if (melds.length > 0 || v.flies > 0 || !concealed.every((t) => isDot(t.kind)))
|
|
115
|
+
return false;
|
|
116
|
+
const c = new Array(10).fill(0);
|
|
117
|
+
for (const t of concealed)
|
|
118
|
+
c[dotValue(t.kind)]++;
|
|
119
|
+
return c[1] >= 3 && c[9] >= 3 && [2, 3, 4, 5, 6, 7, 8].every((n) => c[n] >= 1);
|
|
120
|
+
}
|
|
121
|
+
/** RULES.md §8, in design order. The first match names the limit; limits never stack. */
|
|
122
|
+
export const LIMIT_HANDS = [
|
|
123
|
+
{ key: 'L1', label: 'Pongs of all four winds', test: (v) => pongs(v, isWind) === 4 },
|
|
124
|
+
{ key: 'L2', label: 'Three dragon pongs', test: (v) => pongs(v, isDragon) === 3 },
|
|
125
|
+
{ key: 'L3', label: 'No bonus tiles at all', test: (v) => v.ctx.bonus.length === 0 },
|
|
126
|
+
{ key: 'L4', label: 'Four kongs', test: (v) => v.sets.filter((s) => s.kong).length === 4 },
|
|
127
|
+
{
|
|
128
|
+
key: 'L5',
|
|
129
|
+
label: 'Four concealed pongs (self-drawn)',
|
|
130
|
+
test: (v) => v.ctx.selfDrawn && standard(v) && v.sets.every((s) => s.type === 'pong' && s.concealed),
|
|
131
|
+
},
|
|
132
|
+
{ key: 'L6', label: 'Four Fly', test: (v) => v.flies === 4 },
|
|
133
|
+
{ key: 'L7', label: 'Win on the first or last tile', test: (v) => v.ctx.firstOrLastTile },
|
|
134
|
+
{ key: 'L8', label: 'All winds and dragons', test: (v) => kinds(v).every(isHonour) },
|
|
135
|
+
{ key: 'L9', label: 'Nine Gates', test: nineGates },
|
|
136
|
+
{ key: 'L10', label: '10 fan or more', test: (_v, total) => total >= 10 },
|
|
137
|
+
];
|
|
138
|
+
function meldSet(m) {
|
|
139
|
+
const ks = m.tiles.map((t) => t.kind).sort((a, b) => (dotValue(a) ?? 0) - (dotValue(b) ?? 0));
|
|
140
|
+
return { type: m.type === 'chow' ? 'chow' : 'pong', kong: m.type === 'kong', kind: ks[0], concealed: m.concealed };
|
|
141
|
+
}
|
|
142
|
+
function view(ctx, d) {
|
|
143
|
+
const pairs = (d.pairs ?? [d.pair]).map((p) => (isFly(p.kinds[0]) ? null : p.kinds[0]));
|
|
144
|
+
return {
|
|
145
|
+
ctx,
|
|
146
|
+
seatWind: ((ctx.winner - ctx.dealer + 3) % 3),
|
|
147
|
+
sets: [
|
|
148
|
+
...ctx.melds.map(meldSet),
|
|
149
|
+
...d.sets.map((s) => ({ type: s.type, kong: false, kind: s.kinds[0], concealed: true })),
|
|
150
|
+
],
|
|
151
|
+
pairs,
|
|
152
|
+
sevenPairs: d.sevenPairs,
|
|
153
|
+
flies: ctx.concealed.filter((t) => isFly(t.kind)).length,
|
|
154
|
+
bonus: new Set(ctx.bonus.map((t) => t.kind)),
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
function scoreView(v) {
|
|
158
|
+
const fan = [];
|
|
159
|
+
for (const r of FAN_RULES) {
|
|
160
|
+
const n = r.fan(v);
|
|
161
|
+
if (n > 0)
|
|
162
|
+
fan.push({ key: r.key, label: r.label, fan: n });
|
|
163
|
+
}
|
|
164
|
+
const totalFan = fan.reduce((a, f) => a + f.fan, 0);
|
|
165
|
+
const limit = LIMIT_HANDS.find((l) => l.test(v, totalFan))?.key ?? null;
|
|
166
|
+
const valid = limit !== null || totalFan >= MIN_FAN;
|
|
167
|
+
const points = limit !== null ? LIMIT_POINTS : Math.min(totalFan * POINTS_PER_FAN, LIMIT_POINTS);
|
|
168
|
+
return { fan, totalFan, limit, points, valid };
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Scores a winning hand, taking the decomposition that scores most (R5.4). A hand that forms no
|
|
172
|
+
* winning shape returns `valid: false` with 0 points.
|
|
173
|
+
*/
|
|
174
|
+
export function scoreWin(ctx) {
|
|
175
|
+
let best = null;
|
|
176
|
+
for (const d of decompose(ctx.concealed, ctx.melds)) {
|
|
177
|
+
const s = scoreView(view(ctx, d));
|
|
178
|
+
if (best === null ||
|
|
179
|
+
s.points > best.points ||
|
|
180
|
+
(s.points === best.points && (s.totalFan > best.totalFan || (s.totalFan === best.totalFan && s.limit !== null && best.limit === null)))) {
|
|
181
|
+
best = s;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return best ?? { fan: [], totalFan: 0, limit: null, points: 0, valid: false };
|
|
185
|
+
}
|
|
186
|
+
const SEATS = [0, 1, 2];
|
|
187
|
+
/**
|
|
188
|
+
* Point deltas per seat for one win (R9.3, R5.5, R11.3), summing to 0. `coWinners` lists other
|
|
189
|
+
* players who won on the same discard (R4.4); they pay this winner nothing.
|
|
190
|
+
*/
|
|
191
|
+
export function settle(ctx, score, coWinners = []) {
|
|
192
|
+
if (!score.valid)
|
|
193
|
+
throw new Error('settle: hand is below the 5-fan minimum and not a limit hand');
|
|
194
|
+
if (!ctx.selfDrawn && ctx.discarder === undefined)
|
|
195
|
+
throw new Error('settle: a discard win needs a discarder');
|
|
196
|
+
const P = score.points;
|
|
197
|
+
const flyBonus = FLY_BONUS * ctx.concealed.filter((t) => isFly(t.kind)).length;
|
|
198
|
+
const out = [0, 0, 0];
|
|
199
|
+
let total = 0;
|
|
200
|
+
for (const s of SEATS) {
|
|
201
|
+
if (s === ctx.winner || coWinners.includes(s))
|
|
202
|
+
continue;
|
|
203
|
+
const owe = (ctx.selfDrawn || s === ctx.discarder ? 2 * P : P) + flyBonus;
|
|
204
|
+
total += owe;
|
|
205
|
+
if (ctx.liable === undefined)
|
|
206
|
+
out[s] -= owe;
|
|
207
|
+
}
|
|
208
|
+
if (ctx.liable !== undefined) {
|
|
209
|
+
if (ctx.liable === ctx.winner)
|
|
210
|
+
throw new Error('settle: the winner cannot be liable');
|
|
211
|
+
out[ctx.liable] -= total;
|
|
212
|
+
}
|
|
213
|
+
out[ctx.winner] += total;
|
|
214
|
+
return out;
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Kong payment deltas (§10), summing to 0. Concealed: 100 from each opponent. Exposed from a
|
|
218
|
+
* discard: 50 from the discarder. Added kong (exposed, no discarder): 50 from each opponent.
|
|
219
|
+
* A robbed added kong pays nothing, so callers must not call this for one.
|
|
220
|
+
*/
|
|
221
|
+
export function kongPayment(kongOwner, concealed, discarder) {
|
|
222
|
+
const out = [0, 0, 0];
|
|
223
|
+
const pay = (s, n) => {
|
|
224
|
+
out[s] -= n;
|
|
225
|
+
out[kongOwner] += n;
|
|
226
|
+
};
|
|
227
|
+
if (concealed) {
|
|
228
|
+
for (const s of SEATS)
|
|
229
|
+
if (s !== kongOwner)
|
|
230
|
+
pay(s, 100);
|
|
231
|
+
}
|
|
232
|
+
else if (discarder !== undefined) {
|
|
233
|
+
if (discarder === kongOwner)
|
|
234
|
+
throw new Error('kongPayment: discarder cannot be the kong owner');
|
|
235
|
+
pay(discarder, 50);
|
|
236
|
+
}
|
|
237
|
+
else {
|
|
238
|
+
for (const s of SEATS)
|
|
239
|
+
if (s !== kongOwner)
|
|
240
|
+
pay(s, 50);
|
|
241
|
+
}
|
|
242
|
+
return out;
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Applies the per-hand loss limit (R9.6) to a hand's whole-hand deltas, which sum to 0. A seat below
|
|
246
|
+
* −limit pays exactly `limit`; the forgiven points come off the seats that gained, in proportion to
|
|
247
|
+
* their gains (largest remainder, ties to the lower seat). Returns a new triple that still sums to 0.
|
|
248
|
+
*/
|
|
249
|
+
export function capHandLoss(deltas, limit = HAND_LOSS_LIMIT) {
|
|
250
|
+
const out = [deltas[0], deltas[1], deltas[2]];
|
|
251
|
+
let forgiven = 0;
|
|
252
|
+
for (const s of SEATS) {
|
|
253
|
+
if (out[s] < -limit) {
|
|
254
|
+
forgiven += -limit - out[s];
|
|
255
|
+
out[s] = -limit;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
if (forgiven === 0)
|
|
259
|
+
return out;
|
|
260
|
+
const gainers = SEATS.filter((s) => out[s] > 0);
|
|
261
|
+
const gain = gainers.reduce((a, s) => a + out[s], 0);
|
|
262
|
+
const cuts = gainers.map((s) => ({ s, cut: Math.floor((forgiven * out[s]) / gain), rem: (forgiven * out[s]) % gain }));
|
|
263
|
+
let left = forgiven - cuts.reduce((a, c) => a + c.cut, 0);
|
|
264
|
+
for (const c of [...cuts].sort((x, y) => y.rem - x.rem || x.s - y.s)) {
|
|
265
|
+
if (left === 0)
|
|
266
|
+
break;
|
|
267
|
+
c.cut++;
|
|
268
|
+
left--;
|
|
269
|
+
}
|
|
270
|
+
for (const c of cuts)
|
|
271
|
+
out[c.s] -= c.cut;
|
|
272
|
+
return out;
|
|
273
|
+
}
|
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[];
|
package/dist/seed.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
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
|
+
const SIGMA = [0x61707865, 0x3320646e, 0x79622d32, 0x6b206574];
|
|
8
|
+
const rotl = (x, n) => ((x << n) | (x >>> (32 - n))) >>> 0;
|
|
9
|
+
function quarter(s, a, b, c, d) {
|
|
10
|
+
s[a] = s[a] + s[b];
|
|
11
|
+
s[d] = rotl(s[d] ^ s[a], 16);
|
|
12
|
+
s[c] = s[c] + s[d];
|
|
13
|
+
s[b] = rotl(s[b] ^ s[c], 12);
|
|
14
|
+
s[a] = s[a] + s[b];
|
|
15
|
+
s[d] = rotl(s[d] ^ s[a], 8);
|
|
16
|
+
s[c] = s[c] + s[d];
|
|
17
|
+
s[b] = rotl(s[b] ^ s[c], 7);
|
|
18
|
+
}
|
|
19
|
+
/** One ChaCha20 block (RFC 8439 §2.3) as 16 little-endian words. `key` is 8 words, `nonce` 3. */
|
|
20
|
+
export function chacha20Block(key, counter, nonce) {
|
|
21
|
+
const init = new Uint32Array(16);
|
|
22
|
+
init.set(SIGMA, 0);
|
|
23
|
+
init.set(key, 4);
|
|
24
|
+
init[12] = counter >>> 0;
|
|
25
|
+
init.set(nonce, 13);
|
|
26
|
+
const s = init.slice();
|
|
27
|
+
for (let i = 0; i < 10; i++) {
|
|
28
|
+
quarter(s, 0, 4, 8, 12);
|
|
29
|
+
quarter(s, 1, 5, 9, 13);
|
|
30
|
+
quarter(s, 2, 6, 10, 14);
|
|
31
|
+
quarter(s, 3, 7, 11, 15);
|
|
32
|
+
quarter(s, 0, 5, 10, 15);
|
|
33
|
+
quarter(s, 1, 6, 11, 12);
|
|
34
|
+
quarter(s, 2, 7, 8, 13);
|
|
35
|
+
quarter(s, 3, 4, 9, 14);
|
|
36
|
+
}
|
|
37
|
+
for (let i = 0; i < 16; i++)
|
|
38
|
+
s[i] = s[i] + init[i];
|
|
39
|
+
return s;
|
|
40
|
+
}
|
|
41
|
+
/** UTF-8 bytes (no TextEncoder: the engine's lib is plain ES2022). */
|
|
42
|
+
function utf8(s) {
|
|
43
|
+
const out = [];
|
|
44
|
+
for (const ch of s) {
|
|
45
|
+
const c = ch.codePointAt(0);
|
|
46
|
+
if (c < 0x80)
|
|
47
|
+
out.push(c);
|
|
48
|
+
else if (c < 0x800)
|
|
49
|
+
out.push(0xc0 | (c >> 6), 0x80 | (c & 63));
|
|
50
|
+
else if (c < 0x10000)
|
|
51
|
+
out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));
|
|
52
|
+
else
|
|
53
|
+
out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
const HEX_SEED = /^(?:[0-9a-f]{32}|[0-9a-f]{64})$/i;
|
|
58
|
+
/**
|
|
59
|
+
* Key and nonce for a seed string. 16 or 32 bytes of hex (the host sends 16) are decoded; any other
|
|
60
|
+
* string is taken as its UTF-8 bytes (1-32). The nonce holds the byte count and the hex flag, so
|
|
61
|
+
* zero-padding can't make two different seeds collide.
|
|
62
|
+
*/
|
|
63
|
+
function seedMaterial(seed) {
|
|
64
|
+
const hex = HEX_SEED.test(seed);
|
|
65
|
+
const bytes = [];
|
|
66
|
+
if (!hex && seed.length > 32)
|
|
67
|
+
throw new RangeError('seed must be 16 or 32 bytes of hex, or 1-32 bytes of text');
|
|
68
|
+
if (hex)
|
|
69
|
+
for (let i = 0; i < seed.length; i += 2)
|
|
70
|
+
bytes.push(parseInt(seed.slice(i, i + 2), 16));
|
|
71
|
+
else
|
|
72
|
+
bytes.push(...utf8(seed));
|
|
73
|
+
if (bytes.length === 0 || bytes.length > 32) {
|
|
74
|
+
throw new RangeError('seed must be 16 or 32 bytes of hex, or 1-32 bytes of text');
|
|
75
|
+
}
|
|
76
|
+
const key = new Uint32Array(8);
|
|
77
|
+
for (let i = 0; i < bytes.length; i++)
|
|
78
|
+
key[i >> 2] = key[i >> 2] | (bytes[i] << (8 * (i & 3)));
|
|
79
|
+
return { key, nonce: Uint32Array.of(bytes.length, hex ? 1 : 0, 0) };
|
|
80
|
+
}
|
|
81
|
+
/** A stream of uniform 32-bit integers from the ChaCha20 keystream for `seed`. */
|
|
82
|
+
export function seedStream(seed) {
|
|
83
|
+
const { key, nonce } = seedMaterial(seed);
|
|
84
|
+
let counter = 0;
|
|
85
|
+
let block = new Uint32Array(0);
|
|
86
|
+
let i = 0;
|
|
87
|
+
return () => {
|
|
88
|
+
if (i >= block.length) {
|
|
89
|
+
block = chacha20Block(key, counter++, nonce);
|
|
90
|
+
i = 0;
|
|
91
|
+
}
|
|
92
|
+
return block[i++];
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
const TWO_32 = 0x100000000;
|
|
96
|
+
/** A uniform integer in [0, n) from a 32-bit stream, with rejection sampling so there is no bias. */
|
|
97
|
+
export function randomBelow(next, n) {
|
|
98
|
+
if (!Number.isInteger(n) || n < 1 || n > TWO_32)
|
|
99
|
+
throw new RangeError(`randomBelow: bad bound ${n}`);
|
|
100
|
+
const limit = TWO_32 - (TWO_32 % n);
|
|
101
|
+
for (;;) {
|
|
102
|
+
const x = next();
|
|
103
|
+
if (x < limit)
|
|
104
|
+
return x % n;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** Unbiased Fisher-Yates over a 32-bit stream; returns a new array, the input is not mutated. */
|
|
108
|
+
export function shuffleWith(items, next) {
|
|
109
|
+
const out = [...items];
|
|
110
|
+
for (let i = out.length - 1; i > 0; i--) {
|
|
111
|
+
const j = randomBelow(next, i + 1);
|
|
112
|
+
[out[i], out[j]] = [out[j], out[i]];
|
|
113
|
+
}
|
|
114
|
+
return out;
|
|
115
|
+
}
|
package/dist/tiles.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tile vocabulary for Three Winds (docs/RULES.md §1). Pure data + helpers; no DOM, no deps.
|
|
3
|
+
*/
|
|
4
|
+
declare const DOT_KINDS: readonly ["d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9"];
|
|
5
|
+
declare const WIND_KINDS: readonly ["we", "ws", "ww", "wn"];
|
|
6
|
+
declare const DRAGON_KINDS: readonly ["dr", "dg", "dw"];
|
|
7
|
+
declare const FLOWER_KINDS: readonly ["f1", "f2", "f3", "f4"];
|
|
8
|
+
declare const SEASON_KINDS: readonly ["s1", "s2", "s3", "s4"];
|
|
9
|
+
declare const FACE_KINDS: readonly ["x1", "x2", "x3", "x4"];
|
|
10
|
+
declare const ANIMAL_KINDS: readonly ["acat", "arat", "arooster", "acentipede"];
|
|
11
|
+
declare const FLY_KIND: "fly";
|
|
12
|
+
export type DotKind = (typeof DOT_KINDS)[number];
|
|
13
|
+
export type WindKind = (typeof WIND_KINDS)[number];
|
|
14
|
+
export type DragonKind = (typeof DRAGON_KINDS)[number];
|
|
15
|
+
export type BonusKind = (typeof FLOWER_KINDS)[number] | (typeof SEASON_KINDS)[number] | (typeof FACE_KINDS)[number] | (typeof ANIMAL_KINDS)[number];
|
|
16
|
+
/** One of the 33 kind codes in RULES.md §1.1. */
|
|
17
|
+
export type TileKind = DotKind | WindKind | DragonKind | BonusKind | typeof FLY_KIND;
|
|
18
|
+
export interface Tile {
|
|
19
|
+
id: number;
|
|
20
|
+
kind: TileKind;
|
|
21
|
+
}
|
|
22
|
+
/** All 33 kinds, in design sort order (R1.4, then bonus tiles). */
|
|
23
|
+
export declare const ALL_KINDS: readonly TileKind[];
|
|
24
|
+
export declare const isDot: (k: TileKind) => k is DotKind;
|
|
25
|
+
export declare const isWind: (k: TileKind) => k is WindKind;
|
|
26
|
+
export declare const isDragon: (k: TileKind) => k is DragonKind;
|
|
27
|
+
/** Honours = winds + dragons (R1.3). */
|
|
28
|
+
export declare const isHonour: (k: TileKind) => k is WindKind | DragonKind;
|
|
29
|
+
/** Bonus = flowers, seasons, faces, animals. The Fly is NOT a bonus tile (R1.3). */
|
|
30
|
+
export declare const isBonus: (k: TileKind) => k is BonusKind;
|
|
31
|
+
export declare const isFly: (k: TileKind) => k is typeof FLY_KIND;
|
|
32
|
+
/** Face value 1-9 of a dot tile, or null for any other kind. */
|
|
33
|
+
export declare function dotValue(k: TileKind): number | null;
|
|
34
|
+
/** The full 84-tile set with unique ids 0-83. Returns a fresh array each call. */
|
|
35
|
+
export declare function fullSet(): Tile[];
|
|
36
|
+
/** Design order: fly, d1..d9, E S W N, Red Green White, then bonus tiles. */
|
|
37
|
+
export declare function sortKey(k: TileKind): number;
|
|
38
|
+
/** Returns a new array sorted by sortKey (ties broken by id); the input is not mutated. */
|
|
39
|
+
export declare function sortTiles(tiles: Tile[]): Tile[];
|
|
40
|
+
/**
|
|
41
|
+
* Own flower/season number for a seat wind (R2.2, F7): East 1, South 2, West 3.
|
|
42
|
+
* `seat` is the seat-wind index relative to the dealer: 0 East (dealer), 1 South, 2 West.
|
|
43
|
+
*/
|
|
44
|
+
export declare function ownBonusNumber(seat: 0 | 1 | 2): 1 | 2 | 3;
|
|
45
|
+
export {};
|
package/dist/tiles.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tile vocabulary for Three Winds (docs/RULES.md §1). Pure data + helpers; no DOM, no deps.
|
|
3
|
+
*/
|
|
4
|
+
const DOT_KINDS = ['d1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9'];
|
|
5
|
+
const WIND_KINDS = ['we', 'ws', 'ww', 'wn'];
|
|
6
|
+
const DRAGON_KINDS = ['dr', 'dg', 'dw'];
|
|
7
|
+
const FLOWER_KINDS = ['f1', 'f2', 'f3', 'f4'];
|
|
8
|
+
const SEASON_KINDS = ['s1', 's2', 's3', 's4'];
|
|
9
|
+
const FACE_KINDS = ['x1', 'x2', 'x3', 'x4'];
|
|
10
|
+
const ANIMAL_KINDS = ['acat', 'arat', 'arooster', 'acentipede'];
|
|
11
|
+
const FLY_KIND = 'fly';
|
|
12
|
+
const BONUS_KINDS = [
|
|
13
|
+
...FLOWER_KINDS,
|
|
14
|
+
...SEASON_KINDS,
|
|
15
|
+
...FACE_KINDS,
|
|
16
|
+
...ANIMAL_KINDS,
|
|
17
|
+
];
|
|
18
|
+
/** All 33 kinds, in design sort order (R1.4, then bonus tiles). */
|
|
19
|
+
export const ALL_KINDS = Object.freeze([
|
|
20
|
+
FLY_KIND,
|
|
21
|
+
...DOT_KINDS,
|
|
22
|
+
...WIND_KINDS,
|
|
23
|
+
...DRAGON_KINDS,
|
|
24
|
+
...BONUS_KINDS,
|
|
25
|
+
]);
|
|
26
|
+
const DOT_SET = new Set(DOT_KINDS);
|
|
27
|
+
const WIND_SET = new Set(WIND_KINDS);
|
|
28
|
+
const DRAGON_SET = new Set(DRAGON_KINDS);
|
|
29
|
+
const BONUS_SET = new Set(BONUS_KINDS);
|
|
30
|
+
const SORT_KEY = new Map(ALL_KINDS.map((k, i) => [k, i]));
|
|
31
|
+
export const isDot = (k) => DOT_SET.has(k);
|
|
32
|
+
export const isWind = (k) => WIND_SET.has(k);
|
|
33
|
+
export const isDragon = (k) => DRAGON_SET.has(k);
|
|
34
|
+
/** Honours = winds + dragons (R1.3). */
|
|
35
|
+
export const isHonour = (k) => isWind(k) || isDragon(k);
|
|
36
|
+
/** Bonus = flowers, seasons, faces, animals. The Fly is NOT a bonus tile (R1.3). */
|
|
37
|
+
export const isBonus = (k) => BONUS_SET.has(k);
|
|
38
|
+
export const isFly = (k) => k === FLY_KIND;
|
|
39
|
+
/** Face value 1-9 of a dot tile, or null for any other kind. */
|
|
40
|
+
export function dotValue(k) {
|
|
41
|
+
return isDot(k) ? Number(k.slice(1)) : null;
|
|
42
|
+
}
|
|
43
|
+
/** Copies per kind (R1.2): 4 for dots, honours and the Fly; 1 for bonus tiles. */
|
|
44
|
+
function copiesOf(k) {
|
|
45
|
+
return isBonus(k) ? 1 : 4;
|
|
46
|
+
}
|
|
47
|
+
/** The full 84-tile set with unique ids 0-83. Returns a fresh array each call. */
|
|
48
|
+
export function fullSet() {
|
|
49
|
+
const tiles = [];
|
|
50
|
+
for (const kind of ALL_KINDS) {
|
|
51
|
+
for (let c = 0; c < copiesOf(kind); c++)
|
|
52
|
+
tiles.push({ id: tiles.length, kind });
|
|
53
|
+
}
|
|
54
|
+
return tiles;
|
|
55
|
+
}
|
|
56
|
+
/** Design order: fly, d1..d9, E S W N, Red Green White, then bonus tiles. */
|
|
57
|
+
export function sortKey(k) {
|
|
58
|
+
return SORT_KEY.get(k);
|
|
59
|
+
}
|
|
60
|
+
/** Returns a new array sorted by sortKey (ties broken by id); the input is not mutated. */
|
|
61
|
+
export function sortTiles(tiles) {
|
|
62
|
+
return [...tiles].sort((a, b) => sortKey(a.kind) - sortKey(b.kind) || a.id - b.id);
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Own flower/season number for a seat wind (R2.2, F7): East 1, South 2, West 3.
|
|
66
|
+
* `seat` is the seat-wind index relative to the dealer: 0 East (dealer), 1 South, 2 West.
|
|
67
|
+
*/
|
|
68
|
+
export function ownBonusNumber(seat) {
|
|
69
|
+
return (seat + 1);
|
|
70
|
+
}
|
package/dist/wall.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type Tile } from './tiles.js';
|
|
2
|
+
export type Seat = 0 | 1 | 2;
|
|
3
|
+
export interface DealResult {
|
|
4
|
+
wall: Tile[];
|
|
5
|
+
hands: [Tile[], Tile[], Tile[]];
|
|
6
|
+
bonus: [Tile[], Tile[], Tile[]];
|
|
7
|
+
}
|
|
8
|
+
export interface DrawResult {
|
|
9
|
+
tile: Tile | undefined;
|
|
10
|
+
wall: Tile[];
|
|
11
|
+
}
|
|
12
|
+
/** Mulberry32 PRNG: returns a function yielding floats in [0, 1). */
|
|
13
|
+
export declare function mulberry32(seed: number): () => number;
|
|
14
|
+
/** Fisher-Yates shuffle; returns a new array, the input is not mutated. */
|
|
15
|
+
export declare function shuffle<T>(items: readonly T[], rng: () => number): T[];
|
|
16
|
+
/** Draw from the front of the wall (normal draw). */
|
|
17
|
+
export declare function drawFront(wall: readonly Tile[]): DrawResult;
|
|
18
|
+
/** Draw from the back of the wall (bonus / kong replacement). */
|
|
19
|
+
export declare function drawBack(wall: readonly Tile[]): DrawResult;
|
|
20
|
+
/**
|
|
21
|
+
* Deal from a given wall order (internal; exported for tests and scripted deals).
|
|
22
|
+
* Dealer takes 14 from the front, then the next two seats in turn order take 13 each (R2.5).
|
|
23
|
+
* Then, from the dealer in turn order, each bonus tile is set aside and replaced from the
|
|
24
|
+
* back, repeating while the replacement is also a bonus tile (R2.6).
|
|
25
|
+
*/
|
|
26
|
+
export declare function dealFromOrder(order: readonly Tile[], dealer: Seat): DealResult;
|
|
27
|
+
/** Shuffle the 84-tile set with mulberry32(seed) and deal it (R2.4–R2.6). */
|
|
28
|
+
export declare function deal(seed: number, dealer: Seat): DealResult;
|
|
29
|
+
/**
|
|
30
|
+
* Shuffle with the ChaCha20 stream for a string seed and deal it (R2.4–R2.6). Used for staked room
|
|
31
|
+
* hands, where the 32-bit mulberry32 seed of `deal` could be brute-forced from one seat's tiles.
|
|
32
|
+
*/
|
|
33
|
+
export declare function dealFromSeed(seed: string, dealer: Seat): DealResult;
|
package/dist/wall.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wall + opening deal (docs/RULES.md §2, R2.4–R2.6). Deterministic from a seed.
|
|
3
|
+
* One live wall: normal draws from the front, replacement draws from the back.
|
|
4
|
+
*/
|
|
5
|
+
import { seedStream, shuffleWith } from './seed.js';
|
|
6
|
+
import { fullSet, isBonus } from './tiles.js';
|
|
7
|
+
/** Mulberry32 PRNG: returns a function yielding floats in [0, 1). */
|
|
8
|
+
export function mulberry32(seed) {
|
|
9
|
+
let a = seed >>> 0;
|
|
10
|
+
return () => {
|
|
11
|
+
a = (a + 0x6d2b79f5) >>> 0;
|
|
12
|
+
let t = a;
|
|
13
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
14
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
15
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/** Fisher-Yates shuffle; returns a new array, the input is not mutated. */
|
|
19
|
+
export function shuffle(items, rng) {
|
|
20
|
+
const out = [...items];
|
|
21
|
+
for (let i = out.length - 1; i > 0; i--) {
|
|
22
|
+
const j = Math.floor(rng() * (i + 1));
|
|
23
|
+
[out[i], out[j]] = [out[j], out[i]];
|
|
24
|
+
}
|
|
25
|
+
return out;
|
|
26
|
+
}
|
|
27
|
+
/** Draw from the front of the wall (normal draw). */
|
|
28
|
+
export function drawFront(wall) {
|
|
29
|
+
return { tile: wall[0], wall: wall.slice(1) };
|
|
30
|
+
}
|
|
31
|
+
/** Draw from the back of the wall (bonus / kong replacement). */
|
|
32
|
+
export function drawBack(wall) {
|
|
33
|
+
return { tile: wall[wall.length - 1], wall: wall.slice(0, -1) };
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Deal from a given wall order (internal; exported for tests and scripted deals).
|
|
37
|
+
* Dealer takes 14 from the front, then the next two seats in turn order take 13 each (R2.5).
|
|
38
|
+
* Then, from the dealer in turn order, each bonus tile is set aside and replaced from the
|
|
39
|
+
* back, repeating while the replacement is also a bonus tile (R2.6).
|
|
40
|
+
*/
|
|
41
|
+
export function dealFromOrder(order, dealer) {
|
|
42
|
+
let wall = [...order];
|
|
43
|
+
const hands = [[], [], []];
|
|
44
|
+
const bonus = [[], [], []];
|
|
45
|
+
const turnOrder = [0, 1, 2].map((k) => ((dealer + k) % 3));
|
|
46
|
+
for (const seat of turnOrder) {
|
|
47
|
+
const n = seat === dealer ? 14 : 13;
|
|
48
|
+
hands[seat] = wall.slice(0, n);
|
|
49
|
+
wall = wall.slice(n);
|
|
50
|
+
}
|
|
51
|
+
for (const seat of turnOrder) {
|
|
52
|
+
const hand = hands[seat];
|
|
53
|
+
for (let i = 0; i < hand.length; i++) {
|
|
54
|
+
while (isBonus(hand[i].kind)) {
|
|
55
|
+
const r = drawBack(wall);
|
|
56
|
+
if (!r.tile)
|
|
57
|
+
throw new Error('wall exhausted during bonus replacement');
|
|
58
|
+
bonus[seat].push(hand[i]);
|
|
59
|
+
hand[i] = r.tile;
|
|
60
|
+
wall = r.wall;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return { wall, hands, bonus };
|
|
65
|
+
}
|
|
66
|
+
/** Shuffle the 84-tile set with mulberry32(seed) and deal it (R2.4–R2.6). */
|
|
67
|
+
export function deal(seed, dealer) {
|
|
68
|
+
return dealFromOrder(shuffle(fullSet(), mulberry32(seed)), dealer);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Shuffle with the ChaCha20 stream for a string seed and deal it (R2.4–R2.6). Used for staked room
|
|
72
|
+
* hands, where the 32-bit mulberry32 seed of `deal` could be brute-forced from one seat's tiles.
|
|
73
|
+
*/
|
|
74
|
+
export function dealFromSeed(seed, dealer) {
|
|
75
|
+
return dealFromOrder(shuffleWith(fullSet(), seedStream(seed)), dealer);
|
|
76
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,33 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bilkobibitkov/threewinds-engine",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Rules engine for Three Winds, Malaysian 3-player mahjong, plus its Bilko authoritative-room module (threeWindsRoomModule). Imported as @threewinds/engine via an alias.",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"files": [
|
|
10
|
+
"dist",
|
|
11
|
+
"README.md"
|
|
12
|
+
],
|
|
13
|
+
"sideEffects": false,
|
|
14
|
+
"publishConfig": {
|
|
15
|
+
"access": "public"
|
|
16
|
+
},
|
|
17
|
+
"devDependencies": {
|
|
18
|
+
"typescript": "^5.9.3",
|
|
19
|
+
"vitest": "^4.0.0"
|
|
20
|
+
},
|
|
21
|
+
"scripts": {
|
|
22
|
+
"build": "node scripts/build.mjs",
|
|
23
|
+
"test": "vitest run",
|
|
24
|
+
"typecheck": "tsc --noEmit"
|
|
25
|
+
},
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"default": "./dist/index.js"
|
|
30
|
+
},
|
|
31
|
+
"./package.json": "./package.json"
|
|
32
|
+
}
|
|
6
33
|
}
|