@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/README.md +31 -2
- package/dist/ai.d.ts +21 -0
- package/dist/ai.js +445 -0
- package/dist/game.d.ts +184 -0
- package/dist/game.js +432 -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 +106 -0
- package/dist/room.js +195 -0
- package/dist/scoring.d.ts +104 -0
- package/dist/scoring.js +239 -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/README.md
CHANGED
|
@@ -1,3 +1,32 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @bilkobibitkov/threewinds-engine
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Published under the owner's npm scope; every consumer imports it as `@threewinds/engine` through an
|
|
4
|
+
alias, so moving to an `@threewinds` org later changes one line per consumer:
|
|
5
|
+
|
|
6
|
+
```json
|
|
7
|
+
"@threewinds/engine": "npm:@bilkobibitkov/threewinds-engine@^0.1.0"
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
In this monorepo the app uses `"@threewinds/engine": "workspace:@bilkobibitkov/threewinds-engine@*"`.
|
|
11
|
+
|
|
12
|
+
Pure TypeScript rules engine for Three Winds (三風), Malaysian 3-player mahjong: tiles, seeded
|
|
13
|
+
deals, winning-hand decomposition, the fan table and payments, the hand reducer and the AI. No DOM,
|
|
14
|
+
React or Node dependencies. Rules: `docs/RULES.md` in the source repo.
|
|
15
|
+
|
|
16
|
+
## Bilko room module
|
|
17
|
+
|
|
18
|
+
`threeWindsRoomModule` implements Bilko's `RoomGameModule<RoomState>`
|
|
19
|
+
(Bilko `docs/host-contract.md`, "Authoritative game rooms"):
|
|
20
|
+
|
|
21
|
+
| Member | Behaviour |
|
|
22
|
+
|---|---|
|
|
23
|
+
| `id`, `seats` | `'threewinds'`, `3` |
|
|
24
|
+
| `maxLossPoints` | `400` (`HAND_LOSS_LIMIT`): RULES.md R9.6 caps each seat's net loss for the whole hand, kongs, Fly bonus and ban rule (包) included. `settle` and `result.deltas` already apply it (`capHandLoss`). |
|
|
25
|
+
| `newHand(seed, dealer)` | Deals with ChaCha20 keyed by the seed (16 or 32 bytes of hex, or up to 32 bytes of text). The seed is not kept. |
|
|
26
|
+
| `view(state, seat)` | `SeatView`: own hand, every seat's public tiles, wall count, own legal actions, the event log without other seats' draw tiles, and only this seat's claim declaration. Never the wall, the seed or another seat's concealed tiles, except that winners' hands are shown in `result.hands` once the hand is over. |
|
|
27
|
+
| `toAct(state)` | The seat to play, or during a claim window every seat that has not declared (even one that can only pass, so `toAct` reveals nothing). |
|
|
28
|
+
| `apply(state, seat, action)` | Validates untrusted input and returns `{ ok: false }` rather than throwing. Forced draws are played at once. Pure. |
|
|
29
|
+
| `aiAction(state, seat)` | The Shark AI's choice; always legal and deterministic. |
|
|
30
|
+
| `isOver`, `settle` | `settle` returns integer per-seat points summing to 0, none below −400: the win payment plus every kong payment (or the kong payments alone after a draw game), after R9.6. |
|
|
31
|
+
| `nextDealer(state)` | Extra: the dealer for the next hand under RULES.md R14.1. |
|
|
32
|
+
| `timeoutAction(state, seat)` | Extra: play for a timed-out human (R4.6): takes a legal win, otherwise passes or discards the tutor's pick. |
|
package/dist/ai.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI decisions for opponents and the tutor (docs/RULES.md §15 AI behaviour levels, §11 Ban rule).
|
|
3
|
+
* Deterministic given `rng`; uses only what a human in the seat can see (R15.4): own hand, every
|
|
4
|
+
* discard, every exposed meld and bonus tile. No search — one shanten pass per candidate tile.
|
|
5
|
+
*/
|
|
6
|
+
import { type Action, type GameState } from './game.js';
|
|
7
|
+
import type { Seat } from './wall.js';
|
|
8
|
+
export type AiLevel = 'steady' | 'shark';
|
|
9
|
+
/**
|
|
10
|
+
* The action `seat` takes at `level`. Always an element of legalActions(state, seat); throws if
|
|
11
|
+
* the seat has nothing to do. Wins are always taken (the engine only offers ≥ 5-fan wins, R6.3).
|
|
12
|
+
*/
|
|
13
|
+
export declare function chooseAction(state: GameState, seat: Seat, level: AiLevel, rng: () => number): Action;
|
|
14
|
+
/**
|
|
15
|
+
* The tutor's suggested discard for `seat` (R15.5: the Steady heuristic), with a one-sentence
|
|
16
|
+
* plain-English reason.
|
|
17
|
+
*/
|
|
18
|
+
export declare function suggestDiscard(state: GameState, seat: Seat): {
|
|
19
|
+
tileId: number;
|
|
20
|
+
reason: string;
|
|
21
|
+
};
|
package/dist/ai.js
ADDED
|
@@ -0,0 +1,445 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI decisions for opponents and the tutor (docs/RULES.md §15 AI behaviour levels, §11 Ban rule).
|
|
3
|
+
* Deterministic given `rng`; uses only what a human in the seat can see (R15.4): own hand, every
|
|
4
|
+
* discard, every exposed meld and bonus tile. No search — one shanten pass per candidate tile.
|
|
5
|
+
*/
|
|
6
|
+
import { legalActions } from './game.js';
|
|
7
|
+
import { FAN_RULES, MIN_FAN } from './scoring.js';
|
|
8
|
+
import { dotValue, isDragon, isFly, isHonour, isWind, sortKey } from './tiles.js';
|
|
9
|
+
/** Playing kinds by index (0..8 dots, 9..12 winds E S W N, 13..15 dragons R G W) = sortKey − 1. */
|
|
10
|
+
const KINDS = ['d1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'we', 'ws', 'ww', 'wn', 'dr', 'dg', 'dw'];
|
|
11
|
+
const N = KINDS.length;
|
|
12
|
+
const idx = (k) => sortKey(k) - 1;
|
|
13
|
+
function countsOf(tiles) {
|
|
14
|
+
const c = new Array(N).fill(0);
|
|
15
|
+
let f = 0;
|
|
16
|
+
for (const t of tiles) {
|
|
17
|
+
if (isFly(t.kind))
|
|
18
|
+
f++;
|
|
19
|
+
else
|
|
20
|
+
c[idx(t.kind)]++;
|
|
21
|
+
}
|
|
22
|
+
return { c, f };
|
|
23
|
+
}
|
|
24
|
+
// ---------------------------------------------------------------------------------------------
|
|
25
|
+
// Shanten (tiles from ready): 0 = ready, −1 = complete. Fly-aware: each Fly fills one gap.
|
|
26
|
+
/**
|
|
27
|
+
* For a dots count vector, the most partial blocks reachable for each (sets, pair) combination,
|
|
28
|
+
* indexed `sets * 2 + pair`, −1 where unreachable. Cached: the vector space is small.
|
|
29
|
+
*/
|
|
30
|
+
const dotsCache = new Map();
|
|
31
|
+
function dotsTable(c) {
|
|
32
|
+
let key = 0;
|
|
33
|
+
for (let i = 8; i >= 0; i--)
|
|
34
|
+
key = key * 5 + c[i];
|
|
35
|
+
const hit = dotsCache.get(key);
|
|
36
|
+
if (hit)
|
|
37
|
+
return hit;
|
|
38
|
+
const best = new Int8Array(10).fill(-1);
|
|
39
|
+
const d = c.slice(0, 9);
|
|
40
|
+
const rec = (start, s, p, pr) => {
|
|
41
|
+
let i = start;
|
|
42
|
+
while (i < 9 && d[i] === 0)
|
|
43
|
+
i++;
|
|
44
|
+
if (i === 9) {
|
|
45
|
+
const k = Math.min(s, 4) * 2 + pr;
|
|
46
|
+
if (p > best[k])
|
|
47
|
+
best[k] = Math.min(p, 8);
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (d[i] >= 3) {
|
|
51
|
+
d[i] -= 3;
|
|
52
|
+
rec(i, s + 1, p, pr);
|
|
53
|
+
d[i] += 3;
|
|
54
|
+
}
|
|
55
|
+
if (i <= 6 && d[i + 1] > 0 && d[i + 2] > 0) {
|
|
56
|
+
d[i]--, d[i + 1]--, d[i + 2]--;
|
|
57
|
+
rec(i, s + 1, p, pr);
|
|
58
|
+
d[i]++, d[i + 1]++, d[i + 2]++;
|
|
59
|
+
}
|
|
60
|
+
if (d[i] >= 2) {
|
|
61
|
+
d[i] -= 2;
|
|
62
|
+
if (!pr)
|
|
63
|
+
rec(i, s, p, 1);
|
|
64
|
+
rec(i, s, p + 1, pr);
|
|
65
|
+
d[i] += 2;
|
|
66
|
+
}
|
|
67
|
+
if (i <= 7 && d[i + 1] > 0) {
|
|
68
|
+
d[i]--, d[i + 1]--;
|
|
69
|
+
rec(i, s, p + 1, pr);
|
|
70
|
+
d[i]++, d[i + 1]++;
|
|
71
|
+
}
|
|
72
|
+
if (i <= 6 && d[i + 2] > 0) {
|
|
73
|
+
d[i]--, d[i + 2]--;
|
|
74
|
+
rec(i, s, p + 1, pr);
|
|
75
|
+
d[i]++, d[i + 2]++;
|
|
76
|
+
}
|
|
77
|
+
d[i]--;
|
|
78
|
+
rec(i, s, p, pr);
|
|
79
|
+
d[i]++;
|
|
80
|
+
};
|
|
81
|
+
rec(0, 0, 0, 0);
|
|
82
|
+
dotsCache.set(key, best);
|
|
83
|
+
return best;
|
|
84
|
+
}
|
|
85
|
+
function standardShanten(c, meldCount) {
|
|
86
|
+
const need = 4 - meldCount;
|
|
87
|
+
const t = dotsTable(c);
|
|
88
|
+
let hs = 0;
|
|
89
|
+
let hp = 0;
|
|
90
|
+
for (let i = 9; i < N; i++) {
|
|
91
|
+
if (c[i] >= 3)
|
|
92
|
+
hs++;
|
|
93
|
+
else if (c[i] === 2)
|
|
94
|
+
hp++;
|
|
95
|
+
}
|
|
96
|
+
let best = 99;
|
|
97
|
+
for (let s = 0; s <= 4; s++) {
|
|
98
|
+
for (let pr = 0; pr <= 1; pr++) {
|
|
99
|
+
const p = t[s * 2 + pr];
|
|
100
|
+
if (p < 0)
|
|
101
|
+
continue;
|
|
102
|
+
for (let useH = 0; useH <= (pr === 0 && hp > 0 ? 1 : 0); useH++) {
|
|
103
|
+
const S = Math.min(s + hs, need);
|
|
104
|
+
const P = Math.min(p + hp - useH, need - S);
|
|
105
|
+
best = Math.min(best, 2 * need - 2 * S - P - (pr || useH));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return best;
|
|
110
|
+
}
|
|
111
|
+
function sevenPairsShanten(c) {
|
|
112
|
+
let pairs = 0;
|
|
113
|
+
let kinds = 0;
|
|
114
|
+
for (const n of c) {
|
|
115
|
+
if (n >= 1)
|
|
116
|
+
kinds++;
|
|
117
|
+
if (n >= 2)
|
|
118
|
+
pairs++;
|
|
119
|
+
}
|
|
120
|
+
return 6 - pairs + Math.max(0, 7 - kinds);
|
|
121
|
+
}
|
|
122
|
+
/** Tiles from ready for concealed counts `h` next to `meldCount` declared melds. */
|
|
123
|
+
function shanten(h, meldCount) {
|
|
124
|
+
let base = standardShanten(h.c, meldCount);
|
|
125
|
+
if (meldCount === 0)
|
|
126
|
+
base = Math.min(base, sevenPairsShanten(h.c));
|
|
127
|
+
return Math.max(-1, base - h.f);
|
|
128
|
+
}
|
|
129
|
+
// ---------------------------------------------------------------------------------------------
|
|
130
|
+
// Fan potential: an estimate of the fan a hand is heading for (RULES §7), used to gate claims and
|
|
131
|
+
// break ties. Bonus fan is exact; honour pongs and suit fan are weighted by how close they are.
|
|
132
|
+
const BONUS_RULES = FAN_RULES.filter((r) => ['F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8'].includes(r.key));
|
|
133
|
+
/** Fan a pong of honour `k` is worth to `seatWind` (F9-F12). */
|
|
134
|
+
function honourValue(k, seatWind) {
|
|
135
|
+
if (isDragon(k))
|
|
136
|
+
return 1;
|
|
137
|
+
if (k === 'we')
|
|
138
|
+
return seatWind === 0 ? 2 : 1;
|
|
139
|
+
if (k === 'wn')
|
|
140
|
+
return 1;
|
|
141
|
+
if (k === 'ws')
|
|
142
|
+
return seatWind === 1 ? 1 : 0;
|
|
143
|
+
if (k === 'ww')
|
|
144
|
+
return seatWind === 2 ? 1 : 0;
|
|
145
|
+
return 0;
|
|
146
|
+
}
|
|
147
|
+
function bonusFan(bonus, seatWind) {
|
|
148
|
+
const view = { bonus: new Set(bonus.map((t) => t.kind)), seatWind, sets: [], pairs: [], sevenPairs: false, flies: 0 };
|
|
149
|
+
return BONUS_RULES.reduce((a, r) => a + r.fan(view), 0);
|
|
150
|
+
}
|
|
151
|
+
function fanPotential(h, melds, bonus, seatWind) {
|
|
152
|
+
// L3: a win with no bonus tiles at all is a limit hand.
|
|
153
|
+
if (bonus.length === 0)
|
|
154
|
+
return 10;
|
|
155
|
+
const meldKinds = melds.filter((m) => m.type !== 'chow').map((m) => m.tiles[0].kind);
|
|
156
|
+
const hasChow = melds.some((m) => m.type === 'chow');
|
|
157
|
+
let honourFan = 0;
|
|
158
|
+
let honourTiles = 0;
|
|
159
|
+
let honourSet = 0;
|
|
160
|
+
let honourMeld = false;
|
|
161
|
+
for (let i = 9; i < N; i++) {
|
|
162
|
+
const k = KINDS[i];
|
|
163
|
+
const melded = meldKinds.includes(k);
|
|
164
|
+
if (melded)
|
|
165
|
+
honourMeld = true;
|
|
166
|
+
const n = h.c[i] + (melded ? 3 : 0);
|
|
167
|
+
honourTiles += n;
|
|
168
|
+
const w = n >= 3 ? 1 : n === 2 ? (h.f > 0 ? 0.8 : 0.5) : 0;
|
|
169
|
+
honourFan += honourValue(k, seatWind) * w;
|
|
170
|
+
honourSet = Math.max(honourSet, w);
|
|
171
|
+
}
|
|
172
|
+
const dots = h.c.slice(0, 9).some((n) => n > 0) || hasChow || meldKinds.some((k) => !isHonour(k));
|
|
173
|
+
const pure = honourMeld ? 0 : 3 * Math.max(0, 1 - honourTiles / 4);
|
|
174
|
+
const mixed = dots ? honourSet : 0;
|
|
175
|
+
let groups = meldKinds.length;
|
|
176
|
+
for (let i = 0; i < N; i++)
|
|
177
|
+
if (h.c[i] >= 2)
|
|
178
|
+
groups++;
|
|
179
|
+
const allPongs = !hasChow && groups >= 5 ? 1.5 : 0;
|
|
180
|
+
return bonusFan(bonus, seatWind) + Math.max(pure, honourFan + mixed) + allPongs;
|
|
181
|
+
}
|
|
182
|
+
function context(state, seat) {
|
|
183
|
+
const unseen = new Array(N + 1).fill(4);
|
|
184
|
+
const see = (t) => {
|
|
185
|
+
if (isFly(t.kind))
|
|
186
|
+
unseen[N]--;
|
|
187
|
+
else if (!isHonour(t.kind) && dotValue(t.kind) === null)
|
|
188
|
+
return;
|
|
189
|
+
else
|
|
190
|
+
unseen[idx(t.kind)]--;
|
|
191
|
+
};
|
|
192
|
+
state.hands[seat].forEach(see);
|
|
193
|
+
for (const s of [0, 1, 2]) {
|
|
194
|
+
state.discards[s].forEach(see);
|
|
195
|
+
for (const m of state.melds[s])
|
|
196
|
+
m.tiles.forEach(see);
|
|
197
|
+
}
|
|
198
|
+
return {
|
|
199
|
+
state,
|
|
200
|
+
seat,
|
|
201
|
+
seatWind: ((seat - state.dealer + 3) % 3),
|
|
202
|
+
melds: state.melds[seat],
|
|
203
|
+
bonus: state.bonus[seat],
|
|
204
|
+
unseen: unseen.map((n) => Math.max(0, n)),
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
/** Unseen tiles that would lower the shanten of a (13 − 3m)-tile hand. */
|
|
208
|
+
function ukeire(h, meldCount, sh, unseen) {
|
|
209
|
+
if (sh < 0)
|
|
210
|
+
return 0;
|
|
211
|
+
let n = unseen[N]; // a Fly always helps
|
|
212
|
+
for (let i = 0; i < N; i++) {
|
|
213
|
+
if (unseen[i] === 0 || h.c[i] >= 4)
|
|
214
|
+
continue;
|
|
215
|
+
h.c[i]++;
|
|
216
|
+
if (shanten(h, meldCount) < sh)
|
|
217
|
+
n += unseen[i];
|
|
218
|
+
h.c[i]--;
|
|
219
|
+
}
|
|
220
|
+
return n;
|
|
221
|
+
}
|
|
222
|
+
/** The prototype `pick` score (RULES R15.1): lower = less useful. */
|
|
223
|
+
function pickScore(c, i) {
|
|
224
|
+
let s = (c[i] - 1) * 4;
|
|
225
|
+
if (i <= 8) {
|
|
226
|
+
for (const d of [-2, -1, 1, 2]) {
|
|
227
|
+
const j = i + d;
|
|
228
|
+
if (j >= 0 && j <= 8 && c[j] > 0)
|
|
229
|
+
s += Math.abs(d) === 1 ? 2.2 : 1.1;
|
|
230
|
+
}
|
|
231
|
+
if (i === 0 || i === 8)
|
|
232
|
+
s -= 0.4;
|
|
233
|
+
}
|
|
234
|
+
else {
|
|
235
|
+
s -= 0.6;
|
|
236
|
+
if (i >= 13)
|
|
237
|
+
s += 0.3;
|
|
238
|
+
}
|
|
239
|
+
return s;
|
|
240
|
+
}
|
|
241
|
+
/** Ban rule (R11.2) from `melds`' owner's point of view: discarding `kind` would make the thrower liable. */
|
|
242
|
+
function banThreat(melds, kind) {
|
|
243
|
+
const exposed = new Set(melds.filter((m) => m.type !== 'chow' && !m.concealed).map((m) => m.tiles[0].kind));
|
|
244
|
+
if (exposed.has(kind))
|
|
245
|
+
return false;
|
|
246
|
+
const count = (pred) => [...exposed].filter(pred).length;
|
|
247
|
+
return (isDragon(kind) && count(isDragon) === 2) || (isWind(kind) && count(isWind) === 3);
|
|
248
|
+
}
|
|
249
|
+
function candidates(x, hand, melds) {
|
|
250
|
+
const h = countsOf(hand);
|
|
251
|
+
const { state, seat } = x;
|
|
252
|
+
const opponents = [0, 1, 2].filter((s) => s !== seat);
|
|
253
|
+
const threatened = opponents.some((s) => state.melds[s].length >= 2);
|
|
254
|
+
const discarded = new Set();
|
|
255
|
+
for (const s of [0, 1, 2])
|
|
256
|
+
for (const t of state.discards[s])
|
|
257
|
+
discarded.add(t.kind);
|
|
258
|
+
const out = [];
|
|
259
|
+
const seen = new Set();
|
|
260
|
+
for (const tile of hand) {
|
|
261
|
+
if (isFly(tile.kind) || seen.has(tile.kind))
|
|
262
|
+
continue;
|
|
263
|
+
seen.add(tile.kind);
|
|
264
|
+
const i = idx(tile.kind);
|
|
265
|
+
const pick = pickScore(h.c, i);
|
|
266
|
+
h.c[i]--;
|
|
267
|
+
const sh = shanten(h, melds.length);
|
|
268
|
+
const fan = fanPotential(h, melds, x.bonus, x.seatWind);
|
|
269
|
+
out.push({
|
|
270
|
+
tile,
|
|
271
|
+
shanten: sh,
|
|
272
|
+
ukeire: ukeire(h, melds.length, sh, x.unseen),
|
|
273
|
+
fan,
|
|
274
|
+
reach: fan >= MIN_FAN,
|
|
275
|
+
pick,
|
|
276
|
+
ban: opponents.some((s) => banThreat(state.melds[s], tile.kind)),
|
|
277
|
+
unsafe: threatened && !discarded.has(tile.kind),
|
|
278
|
+
});
|
|
279
|
+
h.c[i]++;
|
|
280
|
+
}
|
|
281
|
+
return out;
|
|
282
|
+
}
|
|
283
|
+
const bySortKey = (a, b) => sortKey(a.tile.kind) - sortKey(b.tile.kind);
|
|
284
|
+
/** Steady: fewest tiles from ready, then most ways to improve, then fan, then the prototype pick. */
|
|
285
|
+
const steadyOrder = (a, b) => a.shanten - b.shanten || b.ukeire - a.ukeire || b.fan - a.fan || a.pick - b.pick || bySortKey(a, b);
|
|
286
|
+
/**
|
|
287
|
+
* Shark: a hand that can no longer reach 5 fan counts one step further from ready; among equals,
|
|
288
|
+
* safe tiles first when threatened, then fan, then speed.
|
|
289
|
+
*/
|
|
290
|
+
const sharkCost = (c) => c.shanten + (c.reach ? 0 : 1);
|
|
291
|
+
const sharkOrder = (a, b) => sharkCost(a) - sharkCost(b) ||
|
|
292
|
+
Number(a.unsafe) - Number(b.unsafe) ||
|
|
293
|
+
a.shanten - b.shanten ||
|
|
294
|
+
b.fan - a.fan ||
|
|
295
|
+
b.ukeire - a.ukeire ||
|
|
296
|
+
a.pick - b.pick ||
|
|
297
|
+
bySortKey(a, b);
|
|
298
|
+
function rankDiscards(x, level) {
|
|
299
|
+
let cs = candidates(x, x.state.hands[x.seat], x.melds);
|
|
300
|
+
if (level === 'shark') {
|
|
301
|
+
// Never make a ban-rule discard while not ready, if any other tile will do.
|
|
302
|
+
const allowed = cs.filter((c) => !c.ban || c.shanten <= 0);
|
|
303
|
+
if (allowed.length > 0)
|
|
304
|
+
cs = allowed;
|
|
305
|
+
}
|
|
306
|
+
return cs.sort(level === 'shark' ? sharkOrder : steadyOrder);
|
|
307
|
+
}
|
|
308
|
+
/** Best (shanten, fan) after discarding one tile from a (14 − 3m)-tile hand. */
|
|
309
|
+
function bestAfterDiscard(x, hand, melds) {
|
|
310
|
+
const cs = candidates(x, hand, melds);
|
|
311
|
+
if (cs.length === 0)
|
|
312
|
+
return { shanten: 99, fan: 0 };
|
|
313
|
+
const sh = Math.min(...cs.map((c) => c.shanten));
|
|
314
|
+
return { shanten: sh, fan: Math.max(...cs.filter((c) => c.shanten === sh).map((c) => c.fan)) };
|
|
315
|
+
}
|
|
316
|
+
// ---------------------------------------------------------------------------------------------
|
|
317
|
+
// Policies.
|
|
318
|
+
const without = (hand, ids) => hand.filter((t) => !ids.includes(t.id));
|
|
319
|
+
const idsOfKind = (hand, kind, n) => hand.filter((t) => t.kind === kind).slice(0, n).map((t) => t.id);
|
|
320
|
+
const meldOf = (type, tiles) => ({ type, tiles, concealed: false });
|
|
321
|
+
function claimDecision(x, legal, level, rng) {
|
|
322
|
+
const w = x.state.claim;
|
|
323
|
+
const hand = x.state.hands[x.seat];
|
|
324
|
+
const shNow = shanten(countsOf(hand), x.melds.length);
|
|
325
|
+
const fanNow = fanPotential(countsOf(hand), x.melds, x.bonus, x.seatWind);
|
|
326
|
+
const has = (t) => legal.some((a) => a.type === t);
|
|
327
|
+
if (has('exposedKong')) {
|
|
328
|
+
const ids = idsOfKind(hand, w.tile.kind, 3);
|
|
329
|
+
const rest = countsOf(without(hand, ids));
|
|
330
|
+
const melds = [...x.melds, meldOf('kong', [w.tile, w.tile, w.tile, w.tile])];
|
|
331
|
+
const sh = shanten(rest, melds.length);
|
|
332
|
+
const reach = fanPotential(rest, melds, x.bonus, x.seatWind) >= MIN_FAN;
|
|
333
|
+
if (reach && (level === 'shark' || sh <= shNow))
|
|
334
|
+
return { type: 'exposedKong' };
|
|
335
|
+
}
|
|
336
|
+
if (has('pong')) {
|
|
337
|
+
const ids = idsOfKind(hand, w.tile.kind, 2);
|
|
338
|
+
const melds = [...x.melds, meldOf('pong', [w.tile, w.tile, w.tile])];
|
|
339
|
+
const after = bestAfterDiscard(x, without(hand, ids), melds);
|
|
340
|
+
const reach = after.fan >= MIN_FAN;
|
|
341
|
+
if (reach && after.shanten <= shNow) {
|
|
342
|
+
if (level === 'shark' ? after.shanten < shNow || after.fan > fanNow : rng() < 0.5)
|
|
343
|
+
return { type: 'pong' };
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
if (level === 'shark') {
|
|
347
|
+
let best = null;
|
|
348
|
+
for (const a of legal) {
|
|
349
|
+
if (a.type !== 'chow')
|
|
350
|
+
continue;
|
|
351
|
+
const melds = [...x.melds, meldOf('chow', [])];
|
|
352
|
+
const after = bestAfterDiscard(x, without(hand, a.tileIds), melds);
|
|
353
|
+
if (after.fan < MIN_FAN || after.shanten >= shNow)
|
|
354
|
+
continue;
|
|
355
|
+
if (!best || after.shanten < best.sh || (after.shanten === best.sh && after.fan > best.fan)) {
|
|
356
|
+
best = { a, sh: after.shanten, fan: after.fan };
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
if (best)
|
|
360
|
+
return best.a;
|
|
361
|
+
}
|
|
362
|
+
return { type: 'pass' };
|
|
363
|
+
}
|
|
364
|
+
function turnDecision(x, legal, level) {
|
|
365
|
+
const hand = x.state.hands[x.seat];
|
|
366
|
+
const discards = legal.filter((a) => a.type === 'discard');
|
|
367
|
+
const ranked = rankDiscards(x, level);
|
|
368
|
+
const shBest = ranked.length > 0 ? Math.min(...ranked.map((c) => c.shanten)) : 99;
|
|
369
|
+
for (const a of legal) {
|
|
370
|
+
if (a.type === 'concealedKong') {
|
|
371
|
+
const rest = countsOf(without(hand, idsOfKind(hand, a.kind, 4)));
|
|
372
|
+
if (level === 'shark' || shanten(rest, x.melds.length + 1) <= shBest)
|
|
373
|
+
return a;
|
|
374
|
+
}
|
|
375
|
+
if (a.type === 'addedKong') {
|
|
376
|
+
const rest = countsOf(without(hand, idsOfKind(hand, a.kind, 1)));
|
|
377
|
+
if (level === 'shark' || shanten(rest, x.melds.length) <= shBest)
|
|
378
|
+
return a;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
const top = ranked[0];
|
|
382
|
+
if (top)
|
|
383
|
+
return discards.find((a) => a.tileId === top.tile.id);
|
|
384
|
+
// Only Flies left (e.g. a two-Fly pair worth under 5 fan): a Fly is the only legal discard.
|
|
385
|
+
return discards[0];
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* The action `seat` takes at `level`. Always an element of legalActions(state, seat); throws if
|
|
389
|
+
* the seat has nothing to do. Wins are always taken (the engine only offers ≥ 5-fan wins, R6.3).
|
|
390
|
+
*/
|
|
391
|
+
export function chooseAction(state, seat, level, rng) {
|
|
392
|
+
const legal = legalActions(state, seat);
|
|
393
|
+
if (legal.length === 0)
|
|
394
|
+
throw new Error(`seat ${seat} has no legal action`);
|
|
395
|
+
const win = legal.find((a) => a.type === 'win' || a.type === 'selfWin');
|
|
396
|
+
if (win)
|
|
397
|
+
return win;
|
|
398
|
+
if (legal.length === 1)
|
|
399
|
+
return legal[0];
|
|
400
|
+
const x = context(state, seat);
|
|
401
|
+
const chosen = state.phase === 'claim' ? claimDecision(x, legal, level, rng) : turnDecision(x, legal, level);
|
|
402
|
+
// Return the legal list's own element.
|
|
403
|
+
return legal.find((a) => JSON.stringify(a) === JSON.stringify(chosen)) ?? legal[0];
|
|
404
|
+
}
|
|
405
|
+
// ---------------------------------------------------------------------------------------------
|
|
406
|
+
// Tutor.
|
|
407
|
+
const DRAGON_NAMES = { dr: 'Red dragon', dg: 'Green dragon', dw: 'White dragon' };
|
|
408
|
+
const WIND_NAMES = { we: 'East wind', ws: 'South wind', ww: 'West wind', wn: 'North wind' };
|
|
409
|
+
function tileName(k) {
|
|
410
|
+
const v = dotValue(k);
|
|
411
|
+
if (v !== null)
|
|
412
|
+
return `${v} of dots`;
|
|
413
|
+
return DRAGON_NAMES[k] ?? WIND_NAMES[k] ?? (isFly(k) ? 'Fly' : k);
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* The tutor's suggested discard for `seat` (R15.5: the Steady heuristic), with a one-sentence
|
|
417
|
+
* plain-English reason.
|
|
418
|
+
*/
|
|
419
|
+
export function suggestDiscard(state, seat) {
|
|
420
|
+
const hand = state.hands[seat];
|
|
421
|
+
if (hand.length === 0)
|
|
422
|
+
throw new Error(`seat ${seat} has no tiles to discard`);
|
|
423
|
+
const x = context(state, seat);
|
|
424
|
+
const top = rankDiscards(x, 'steady')[0];
|
|
425
|
+
if (!top)
|
|
426
|
+
return { tileId: hand[0].id, reason: 'Only Flies are left, so one of them has to go.' };
|
|
427
|
+
const name = tileName(top.tile.kind);
|
|
428
|
+
const h = countsOf(hand);
|
|
429
|
+
const i = idx(top.tile.kind);
|
|
430
|
+
const lone = h.c[i] === 1;
|
|
431
|
+
let reason;
|
|
432
|
+
if (top.shanten <= 0) {
|
|
433
|
+
reason = `Throwing the ${name} keeps you ready, with ${top.ukeire} unseen tiles that can finish the hand.`;
|
|
434
|
+
}
|
|
435
|
+
else if (lone && i >= 9 && honourValue(top.tile.kind, x.seatWind) === 0) {
|
|
436
|
+
reason = `The ${name} is a lone honour that scores no fan for you, so it is the least useful tile to keep.`;
|
|
437
|
+
}
|
|
438
|
+
else if (lone && i <= 8 && [-2, -1, 1, 2].every((d) => !h.c[i + d])) {
|
|
439
|
+
reason = `The ${name} has no neighbours to build a run with, so throwing it keeps you ${top.shanten} ${top.shanten === 1 ? 'tile' : 'tiles'} from ready.`;
|
|
440
|
+
}
|
|
441
|
+
else {
|
|
442
|
+
reason = `Throwing the ${name} keeps you ${top.shanten} ${top.shanten === 1 ? 'tile' : 'tiles'} from ready with the most ways (${top.ukeire} tiles) to improve.`;
|
|
443
|
+
}
|
|
444
|
+
return { tileId: top.tile.id, reason };
|
|
445
|
+
}
|
package/dist/game.d.ts
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Immutable single-hand reducer (docs/RULES.md §3 Turn, §4 Claims & priority, R4.8–R4.10 kongs,
|
|
3
|
+
* §10 Kong payments, §11 Ban rule, §12 Bonus tiles, §13 Draw games). Wins are scored with
|
|
4
|
+
* scoreWin/settle; kong payments accumulate in `pointsDelta` as soon as each kong stands. The hand's
|
|
5
|
+
* final deltas apply the per-hand loss limit (R9.6).
|
|
6
|
+
*/
|
|
7
|
+
import { type Meld } from './hand.js';
|
|
8
|
+
import { type ScoreResult } from './scoring.js';
|
|
9
|
+
import { type Tile, type TileKind } from './tiles.js';
|
|
10
|
+
import { type DealResult, type Seat } from './wall.js';
|
|
11
|
+
export type Phase = 'draw' | 'act' | 'claim' | 'over';
|
|
12
|
+
type PerSeat<T> = [T, T, T];
|
|
13
|
+
type Deltas = [number, number, number];
|
|
14
|
+
/** What `rules.canWin` sees; field-compatible with scoring's `WinContext`. */
|
|
15
|
+
export interface WinCheckContext {
|
|
16
|
+
winner: Seat;
|
|
17
|
+
dealer: Seat;
|
|
18
|
+
/** Winner's concealed tiles including the winning tile (14 − 3 × melds.length). */
|
|
19
|
+
concealed: Tile[];
|
|
20
|
+
melds: Meld[];
|
|
21
|
+
bonus: Tile[];
|
|
22
|
+
selfDrawn: boolean;
|
|
23
|
+
discarder?: Seat;
|
|
24
|
+
onReplacement: boolean;
|
|
25
|
+
robbedKong: boolean;
|
|
26
|
+
firstOrLastTile: boolean;
|
|
27
|
+
/** Ban-rule liable seat (R11.3). */
|
|
28
|
+
liable?: Seat;
|
|
29
|
+
}
|
|
30
|
+
export interface HandRules {
|
|
31
|
+
/**
|
|
32
|
+
* Whether `ctx` is a legal win, and the payment deltas for it. `coWinners` lists other seats
|
|
33
|
+
* winning on the same discard (R4.4). `score` is optional; the reducer falls back to scoreWin.
|
|
34
|
+
*/
|
|
35
|
+
canWin(ctx: WinCheckContext, coWinners?: readonly Seat[]): {
|
|
36
|
+
valid: boolean;
|
|
37
|
+
deltas: Deltas;
|
|
38
|
+
score?: ScoreResult;
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/** Real rules: a win needs scoreWin(...).valid (≥ 5 fan or a limit hand, R6.3); paid by settle. */
|
|
42
|
+
export declare const DEFAULT_RULES: HandRules;
|
|
43
|
+
export type Action = {
|
|
44
|
+
type: 'draw';
|
|
45
|
+
} | {
|
|
46
|
+
type: 'discard';
|
|
47
|
+
tileId: number;
|
|
48
|
+
} | {
|
|
49
|
+
type: 'concealedKong';
|
|
50
|
+
kind: TileKind;
|
|
51
|
+
} | {
|
|
52
|
+
type: 'addedKong';
|
|
53
|
+
kind: TileKind;
|
|
54
|
+
} | {
|
|
55
|
+
type: 'selfWin';
|
|
56
|
+
} | {
|
|
57
|
+
type: 'win';
|
|
58
|
+
} | {
|
|
59
|
+
type: 'pong';
|
|
60
|
+
} | {
|
|
61
|
+
type: 'exposedKong';
|
|
62
|
+
} | {
|
|
63
|
+
type: 'chow';
|
|
64
|
+
tileIds: [number, number];
|
|
65
|
+
}
|
|
66
|
+
/** Alias of `win`, accepted by apply/resolveClaims; legalActions offers `win`. */
|
|
67
|
+
| {
|
|
68
|
+
type: 'discardWin';
|
|
69
|
+
} | {
|
|
70
|
+
type: 'pass';
|
|
71
|
+
};
|
|
72
|
+
export type GameEvent = {
|
|
73
|
+
type: 'draw';
|
|
74
|
+
seat: Seat;
|
|
75
|
+
tileId: number;
|
|
76
|
+
fromBack: boolean;
|
|
77
|
+
} | {
|
|
78
|
+
type: 'bonus';
|
|
79
|
+
seat: Seat;
|
|
80
|
+
tileId: number;
|
|
81
|
+
} | {
|
|
82
|
+
type: 'kong';
|
|
83
|
+
seat: Seat;
|
|
84
|
+
kind: TileKind;
|
|
85
|
+
concealed: boolean;
|
|
86
|
+
added: boolean;
|
|
87
|
+
} | {
|
|
88
|
+
type: 'discard';
|
|
89
|
+
seat: Seat;
|
|
90
|
+
tileId: number;
|
|
91
|
+
} | {
|
|
92
|
+
type: 'claim';
|
|
93
|
+
seat: Seat;
|
|
94
|
+
claim: 'pong' | 'exposedKong' | 'chow';
|
|
95
|
+
tileId: number;
|
|
96
|
+
from: Seat;
|
|
97
|
+
} | {
|
|
98
|
+
type: 'selfWin';
|
|
99
|
+
seat: Seat;
|
|
100
|
+
deltas: Deltas;
|
|
101
|
+
} | {
|
|
102
|
+
type: 'win';
|
|
103
|
+
seats: Seat[];
|
|
104
|
+
from: Seat;
|
|
105
|
+
tileId: number;
|
|
106
|
+
robbedKong: boolean;
|
|
107
|
+
deltas: Deltas;
|
|
108
|
+
} | {
|
|
109
|
+
type: 'drawGame';
|
|
110
|
+
};
|
|
111
|
+
export type HandResult = {
|
|
112
|
+
kind: 'draw';
|
|
113
|
+
/** Kong payments made during the hand (R13.3), after the per-hand loss limit (R9.6). Sums to 0. */
|
|
114
|
+
deltas: Deltas;
|
|
115
|
+
} | {
|
|
116
|
+
kind: 'win';
|
|
117
|
+
winners: Seat[];
|
|
118
|
+
selfDrawn: boolean;
|
|
119
|
+
/** Thrower, or the kong declarer for a robbed kong; absent for a self-drawn win. */
|
|
120
|
+
discarder?: Seat;
|
|
121
|
+
/** Score per winning seat. */
|
|
122
|
+
score: Partial<Record<Seat, ScoreResult>>;
|
|
123
|
+
/**
|
|
124
|
+
* Whole-hand deltas: win payments plus every kong payment made during the hand, after the
|
|
125
|
+
* per-hand loss limit (R9.6). Sums to 0.
|
|
126
|
+
*/
|
|
127
|
+
deltas: Deltas;
|
|
128
|
+
};
|
|
129
|
+
/** An open claim window: on a discard (R4.1) or on an added-kong tile that may be robbed (R4.10). */
|
|
130
|
+
export interface ClaimWindow {
|
|
131
|
+
kind: 'discard' | 'robKong';
|
|
132
|
+
/** Discarder, or the added-kong declarer. */
|
|
133
|
+
from: Seat;
|
|
134
|
+
tile: Tile;
|
|
135
|
+
/** Claims declared so far via apply(); the window closes once every other seat has declared. */
|
|
136
|
+
declared: Partial<Record<Seat, Action>>;
|
|
137
|
+
}
|
|
138
|
+
export interface GameState {
|
|
139
|
+
seed: number;
|
|
140
|
+
dealer: Seat;
|
|
141
|
+
/** Seat whose turn it is (during a claim window: the discarder / kong declarer). */
|
|
142
|
+
turn: Seat;
|
|
143
|
+
phase: Phase;
|
|
144
|
+
wall: Tile[];
|
|
145
|
+
/** Concealed tiles per seat (never holds a bonus tile). */
|
|
146
|
+
hands: PerSeat<Tile[]>;
|
|
147
|
+
bonus: PerSeat<Tile[]>;
|
|
148
|
+
melds: PerSeat<Meld[]>;
|
|
149
|
+
discards: PerSeat<Tile[]>;
|
|
150
|
+
lastDiscard: {
|
|
151
|
+
seat: Seat;
|
|
152
|
+
tile: Tile;
|
|
153
|
+
} | null;
|
|
154
|
+
/** True when the turn seat's latest tile came from a back (bonus/kong) replacement draw (F18). */
|
|
155
|
+
lastDrawOnReplacement: boolean;
|
|
156
|
+
/** The open claim window in phase `claim`, else null. */
|
|
157
|
+
claim: ClaimWindow | null;
|
|
158
|
+
/** True after a pong/chow claim: the claimer may only discard (no draw happened). */
|
|
159
|
+
mustDiscard: boolean;
|
|
160
|
+
/** Running kong payments (§10) as each kong stands, before the per-hand limit (R9.6). Sums to 0. */
|
|
161
|
+
pointsDelta: Deltas;
|
|
162
|
+
events: GameEvent[];
|
|
163
|
+
result: HandResult | null;
|
|
164
|
+
rules: HandRules;
|
|
165
|
+
}
|
|
166
|
+
export declare class IllegalActionError extends Error {
|
|
167
|
+
readonly seat: Seat;
|
|
168
|
+
readonly action: Action;
|
|
169
|
+
constructor(seat: Seat, action: Action);
|
|
170
|
+
}
|
|
171
|
+
/** Deal a fresh hand (R2.4–R2.6). The dealer holds 14 and acts first, with no draw (R3.1). */
|
|
172
|
+
export declare function newHand(seed: number, dealer: Seat, rules?: HandRules): GameState;
|
|
173
|
+
/** A fresh hand from an existing deal (room deals from a string seed, scripted deals). */
|
|
174
|
+
export declare function handFromDeal(d: DealResult, seed: number, dealer: Seat, rules?: HandRules): GameState;
|
|
175
|
+
export declare function legalActions(state: GameState, seat: Seat): Action[];
|
|
176
|
+
/**
|
|
177
|
+
* Close the open claim window with every seat's claim (missing seats pass) and resolve by R4.3
|
|
178
|
+
* priority: win > pong = kong > chow. Every winning claim wins (R4.4, R4.10). Claims already
|
|
179
|
+
* declared through apply() are kept unless overridden here. Throws IllegalActionError for an
|
|
180
|
+
* illegal claim.
|
|
181
|
+
*/
|
|
182
|
+
export declare function resolveClaims(state: GameState, claims: Partial<Record<Seat, Action>>): GameState;
|
|
183
|
+
export declare function apply(state: GameState, seat: Seat, action: Action): GameState;
|
|
184
|
+
export {};
|