soliterminal 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,496 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Play Klondike in the terminal.
4
+ *
5
+ * node src/cli.ts [--seed N] [--draw 1|3] [--redeals N|unlimited] [--compact] [--theme NAME] [--ascii] [--any-deal]
6
+ */
7
+ import { readFileSync } from 'node:fs';
8
+ import { emitKeypressEvents } from 'node:readline';
9
+ import { parseArgs } from 'node:util';
10
+ import { animating, applyAhead, applyDeepVerdict, applyRating, applyShared, applyVerdict, createApp, handleKey, liveSuspect, playTime, resumeApp, slackCheck, stampDialog, tick, viewOf, withCulprits, } from './app.js';
11
+ import { appendCulprits, culpritPath, readCulpritsIfChanged, removeCulprits, removeOldCulprits } from './culprit-file.js';
12
+ import { randomSeed } from './core/deck.js';
13
+ import { DEFAULT_REDEALS, deal, positionKey, successors } from './core/klondike.js';
14
+ import { findWinnableSeed } from './core/solver.js';
15
+ import { SolverClient } from './solver-client.js';
16
+ import { installWasmEngine } from './solver-wasm.js';
17
+ import { ansi, diff } from './ui/ansi.js';
18
+ import { loadSavedGame, removeSavedGame, replaySaved, savedGamePath, snapshot, writeSavedGame } from './saved-game.js';
19
+ import { pastGame, unrated } from './stats.js';
20
+ import { postShare, sharePayload, shareUrl } from './share.js';
21
+ import { appendStats, loadStats, saveShare, statsPath } from './stats-file.js';
22
+ import { renderDeals, renderHelp, renderNotice, renderStats } from './ui/help.js';
23
+ import { normalizeKey } from './ui/input.js';
24
+ import { MIN_WIDTH, minScreenHeight, renderKlondike } from './ui/layout.js';
25
+ import { ACCENTS, isAccent, pickTheme } from './ui/theme.js';
26
+ const AUTO_STEP_MS = 60;
27
+ /** The first deal is searched for on this thread; the workers load the engine themselves. */
28
+ installWasmEngine();
29
+ /** Winnable deals kept ready per draw mode, so a new game never has to wait. */
30
+ const DEALS_AHEAD = 2;
31
+ function version() {
32
+ if (typeof SOLITERMINAL_VERSION === 'string')
33
+ return SOLITERMINAL_VERSION;
34
+ try {
35
+ return JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
36
+ }
37
+ catch {
38
+ return undefined;
39
+ }
40
+ }
41
+ /** The options; a mistyped one gets a line of help rather than a stack trace. */
42
+ const { values } = (() => {
43
+ try {
44
+ return parseArgs({
45
+ options: {
46
+ seed: { type: 'string' },
47
+ draw: { type: 'string', default: '1' },
48
+ redeals: { type: 'string' },
49
+ ascii: { type: 'boolean', default: false },
50
+ compact: { type: 'boolean', default: false },
51
+ theme: { type: 'string' },
52
+ 'any-deal': { type: 'boolean', default: false },
53
+ help: { type: 'boolean', short: 'h', default: false },
54
+ version: { type: 'boolean', short: 'v', default: false },
55
+ },
56
+ });
57
+ }
58
+ catch (e) {
59
+ process.stderr.write(`${e.message}. See soliterminal --help.\n`);
60
+ process.exit(2);
61
+ }
62
+ })();
63
+ if (values.version) {
64
+ process.stdout.write(`soliterminal ${version() ?? '(unknown version)'}\n`);
65
+ process.exit(0);
66
+ }
67
+ if (values.help) {
68
+ process.stdout.write('Usage: soliterminal [--seed N] [--draw 1|3] [--redeals N|unlimited] [--compact] [--theme NAME] [--ascii] [--any-deal]\n' +
69
+ ` --redeals N times the waste can be turned over (default ${DEFAULT_REDEALS}; 'unlimited' for no limit)\n` +
70
+ ' --seed N play deal N (0 to 4294967295); asks first if a game is kept\n' +
71
+ ' --compact start with small cards (tab switches while playing)\n' +
72
+ ` --theme NAME colors from your terminal palette: ${Object.keys(ACCENTS).join(', ')} (default green)\n` +
73
+ ' --any-deal deal any shuffle, not only ones proven winnable\n' +
74
+ ' --version print the version\n' +
75
+ '\n' +
76
+ 'Environment:\n' +
77
+ ' SOLITERMINAL_CARD=ddd|fff card face: soft grey-white (default) or pure white\n' +
78
+ ' SOLITERMINAL_THEME=NAME same as --theme\n' +
79
+ ' SOLITERMINAL_STATS=PATH where statistics are kept (a log, one line per game)\n' +
80
+ ' SOLITERMINAL_GAME=PATH where the game in progress is kept (default: next to the statistics)\n' +
81
+ ' SOLITERMINAL_SHARE_URL=URL where shared results go (for testing a share server)\n' +
82
+ ' COLORTERM=truecolor exact card colors (otherwise 256-color matches)\n' +
83
+ ' NO_COLOR=1 no color at all\n');
84
+ process.exit(0);
85
+ }
86
+ const themeName = values.theme?.trim().toLowerCase();
87
+ if (themeName !== undefined && !isAccent(themeName)) {
88
+ process.stderr.write(`Unknown theme "${values.theme}". Choose one of: ${Object.keys(ACCENTS).join(', ')}.\n`);
89
+ process.exit(2);
90
+ }
91
+ function parseRedeals(text) {
92
+ if (text === undefined)
93
+ return DEFAULT_REDEALS;
94
+ const t = text.trim().toLowerCase();
95
+ if (t === 'unlimited' || t === 'inf' || t === 'infinity')
96
+ return Infinity;
97
+ const n = Number(t);
98
+ if (Number.isInteger(n) && n >= 0 && n <= 99)
99
+ return n;
100
+ process.stderr.write(`--redeals takes a number from 0 to 99, or 'unlimited'; got "${text}".\n`);
101
+ process.exit(2);
102
+ }
103
+ const redeals = parseRedeals(values.redeals);
104
+ function parseSeed(text) {
105
+ if (text === undefined)
106
+ return undefined;
107
+ const t = text.trim();
108
+ if (/^\d{1,10}$/.test(t) && Number(t) <= 0xffff_ffff)
109
+ return Number(t);
110
+ process.stderr.write(`--seed takes a whole number from 0 to 4294967295; got "${text}".\n`);
111
+ process.exit(2);
112
+ }
113
+ const seedAsked = parseSeed(values.seed);
114
+ if (values.draw !== '1' && values.draw !== '3') {
115
+ process.stderr.write(`--draw takes 1 or 3; got "${values.draw}".\n`);
116
+ process.exit(2);
117
+ }
118
+ const { stdin, stdout } = process;
119
+ if (!stdin.isTTY || !stdout.isTTY) {
120
+ process.stderr.write('soliterminal needs an interactive terminal.\n');
121
+ process.exit(1);
122
+ }
123
+ const ascii = values.ascii;
124
+ const anyDeal = values['any-deal'];
125
+ const theme = pickTheme(process.env, true, themeName);
126
+ const solver = new SolverClient();
127
+ // --- deals ---------------------------------------------------------------------
128
+ const ready = { 1: [], 3: [] };
129
+ const filling = { 1: false, 3: false };
130
+ /** Keeps a couple of proven-winnable seeds in stock, found in the background. */
131
+ function refill(drawMode) {
132
+ if (anyDeal || filling[drawMode] || ready[drawMode].length >= DEALS_AHEAD)
133
+ return;
134
+ filling[drawMode] = true;
135
+ solver.deal(drawMode, redeals, (seed) => {
136
+ filling[drawMode] = false;
137
+ if (seed !== undefined)
138
+ ready[drawMode].push(seed);
139
+ refill(drawMode);
140
+ });
141
+ }
142
+ /** The statistics as they stand; the app's once it exists. */
143
+ let currentStats = () => stats;
144
+ /** A deal won is not dealt again in the same draw mode. */
145
+ const wonAlready = (seed, drawMode) => pastGame(currentStats(), seed, drawMode, 'won') !== undefined;
146
+ const dealer = (drawMode) => {
147
+ const fresh = () => {
148
+ let seed = randomSeed();
149
+ while (wonAlready(seed, drawMode))
150
+ seed = randomSeed();
151
+ return seed;
152
+ };
153
+ if (anyDeal)
154
+ return { seed: fresh(), verified: false };
155
+ // Normally a seed is waiting. If not, finding one here takes well under a second.
156
+ let seed = ready[drawMode].shift();
157
+ while (seed !== undefined && wonAlready(seed, drawMode))
158
+ seed = ready[drawMode].shift();
159
+ seed ??= findWinnableSeed(drawMode, fresh, { redeals });
160
+ refill(drawMode);
161
+ return seed === undefined ? { seed: fresh(), verified: false } : { seed, verified: true };
162
+ };
163
+ const drawMode = values.draw === '3' ? 3 : 1;
164
+ const statsFile = statsPath(process.env);
165
+ const gameFile = savedGamePath(process.env, statsFile);
166
+ /**
167
+ * The game in progress is kept on disk and picked up again on the next start.
168
+ * --seed asks for a particular deal: if a game under way is kept, the player
169
+ * is asked first whether to give it up (a loss) or carry on with it.
170
+ */
171
+ const saved = loadSavedGame(gameFile);
172
+ const resumed = saved ? replaySaved(saved) : undefined;
173
+ const stats = loadStats(statsFile);
174
+ const shareTo = shareUrl(process.env);
175
+ const options = { ascii, compact: values.compact, redeals, stats, canShare: shareTo !== undefined };
176
+ let app;
177
+ if (resumed && saved && (seedAsked === undefined || saved.play === 'counted')) {
178
+ app = resumeApp(resumed, {
179
+ ...options,
180
+ verified: saved.verified,
181
+ play: saved.play,
182
+ ms: saved.ms,
183
+ now: Date.now(),
184
+ winnable: saved.winnable,
185
+ gameId: saved.id,
186
+ ...(saved.at === undefined ? {} : { gameAt: saved.at }),
187
+ });
188
+ if (seedAsked !== undefined)
189
+ app = { ...app, dialog: 'seed', choice: 0, seedOffer: { seed: seedAsked, drawMode } };
190
+ }
191
+ else {
192
+ const first = seedAsked === undefined ? dealer(drawMode) : { seed: seedAsked, verified: false };
193
+ app = createApp(deal(first.seed, drawMode, redeals), { ...options, verified: first.verified });
194
+ }
195
+ refill(app.game.drawMode);
196
+ currentStats = () => app.stats;
197
+ let savedShare = app.stats.share;
198
+ /**
199
+ * Writes what changed: new lines for the statistics log (then reads the log
200
+ * back, so games finished in other windows count too), the share state, and
201
+ * the game whenever it moves. A failed save is not worth interrupting a game for.
202
+ */
203
+ function saveIfChanged() {
204
+ if (app.outbox.length > 0) {
205
+ const ended = app.outbox.some((e) => 'game' in e);
206
+ const written = appendStats(statsFile, app.outbox);
207
+ app = { ...app, outbox: [] };
208
+ if (written && ended) {
209
+ const share = app.stats.share;
210
+ app = { ...app, stats: { ...loadStats(statsFile), ...(share ? { share } : {}) } };
211
+ }
212
+ rateIfNeeded();
213
+ shareIfAgreed();
214
+ }
215
+ syncCulprits();
216
+ if (app.stats.share !== savedShare) {
217
+ savedShare = app.stats.share;
218
+ if (savedShare)
219
+ saveShare(statsFile, savedShare);
220
+ shareIfAgreed();
221
+ }
222
+ saveGame();
223
+ }
224
+ /**
225
+ * Rates lost deals in the background, one at a time, newest first: a few
226
+ * seconds each on a worker of its own. One left unrated when soliterminal
227
+ * quit is rated on a later run.
228
+ */
229
+ let rating;
230
+ function rateIfNeeded() {
231
+ if (rating)
232
+ return;
233
+ const game = unrated(app.stats);
234
+ if (!game)
235
+ return;
236
+ rating = game;
237
+ const limit = game.limit === null ? Infinity : (game.limit ?? DEFAULT_REDEALS);
238
+ solver.rate(deal(game.seed, game.drawMode, limit), (level) => {
239
+ rating = undefined;
240
+ app = applyRating(app, game.id, level);
241
+ saveIfChanged();
242
+ render();
243
+ });
244
+ }
245
+ /** What this program calls itself to the share server: its name and version, nothing more. */
246
+ function clientName() {
247
+ const v = version();
248
+ return v ? `soliterminal/${v}` : 'soliterminal';
249
+ }
250
+ /**
251
+ * Sends the batch the player agreed to share. One try per run: a failure
252
+ * waits for the next start rather than retrying against a struggling server.
253
+ */
254
+ let shareTried = false;
255
+ function shareIfAgreed() {
256
+ if (!shareTo || shareTried)
257
+ return;
258
+ const batch = sharePayload(app.stats, clientName());
259
+ if (!batch)
260
+ return;
261
+ shareTried = true;
262
+ void postShare(shareTo, batch.payload).then((error) => {
263
+ app = applyShared(app, batch.games.map((g) => g.id), error);
264
+ saveIfChanged();
265
+ render();
266
+ });
267
+ }
268
+ /**
269
+ * The moves that lost this deal, shared with every window playing it through
270
+ * a file per deal: new ones are written out, ones other windows found are
271
+ * read in, and the file goes once the deal is won or left for another.
272
+ */
273
+ let culpritFile;
274
+ let culpritSeen = -1;
275
+ function syncCulprits() {
276
+ const first = app.history[0] ?? app.game;
277
+ const path = culpritPath(statsFile, { seed: first.seed, drawMode: first.drawMode, limit: first.redealsLeft });
278
+ if (path !== culpritFile) {
279
+ // Another deal now: the last one is over in this window.
280
+ if (culpritFile !== undefined)
281
+ removeCulprits(culpritFile);
282
+ culpritFile = path;
283
+ culpritSeen = -1;
284
+ }
285
+ if (app.culpritOutbox.length > 0) {
286
+ appendCulprits(path, app.culpritOutbox);
287
+ app = { ...app, culpritOutbox: [] };
288
+ }
289
+ if (app.play === 'won') {
290
+ removeCulprits(path);
291
+ culpritSeen = -1;
292
+ return;
293
+ }
294
+ const read = readCulpritsIfChanged(path, culpritSeen);
295
+ if (read) {
296
+ culpritSeen = read.size;
297
+ app = withCulprits(app, read.culprits);
298
+ }
299
+ }
300
+ let keptGame;
301
+ let keptHistory;
302
+ let keptPlay;
303
+ let kept = false;
304
+ /**
305
+ * Writes the game in progress when it changed, or `always` (to bring the
306
+ * clock up to date); a finished game is removed. Says whether a game is kept.
307
+ */
308
+ function saveGame(always = false) {
309
+ if (!always && app.game === keptGame && app.history === keptHistory && app.play === keptPlay)
310
+ return kept;
311
+ keptGame = app.game;
312
+ keptHistory = app.history;
313
+ keptPlay = app.play;
314
+ const snap = snapshot(app, Date.now());
315
+ kept = snap !== undefined && writeSavedGame(gameFile, snap);
316
+ if (!snap)
317
+ removeSavedGame(gameFile);
318
+ return kept;
319
+ }
320
+ // --- terminal setup and teardown -------------------------------------------
321
+ let restored = false;
322
+ function restore() {
323
+ if (restored)
324
+ return;
325
+ restored = true;
326
+ stdout.write(ansi.reset + ansi.focusReportingOff + ansi.showCursor + ansi.altScreenOff);
327
+ if (stdin.isTTY)
328
+ stdin.setRawMode(false);
329
+ }
330
+ function quit(code = 0) {
331
+ // A kept game is only paused: run soliterminal again to carry on.
332
+ saveIfChanged();
333
+ const kept = saveGame(true);
334
+ restore();
335
+ void solver.close();
336
+ const after = kept ? ' Your game is saved: run soliterminal to carry on.' : '';
337
+ stdout.write(`Thanks for playing. This deal was seed ${app.game.seed}.${after}\n`);
338
+ process.exit(code);
339
+ }
340
+ process.on('exit', restore);
341
+ for (const signal of ['SIGTERM', 'SIGHUP', 'SIGINT'])
342
+ process.on(signal, () => quit(130));
343
+ process.on('uncaughtException', (err) => {
344
+ restore();
345
+ process.stderr.write(`${err.stack ?? err}\n`);
346
+ process.exit(1);
347
+ });
348
+ // --- drawing -----------------------------------------------------------------
349
+ let shown;
350
+ let autoTimer;
351
+ function frame() {
352
+ const cols = stdout.columns;
353
+ const rows = stdout.rows;
354
+ if (app.showHelp)
355
+ return renderHelp(cols, rows, ascii);
356
+ if (app.showStats)
357
+ return renderStats(cols, rows, app.stats, ascii);
358
+ if (app.deals) {
359
+ const playing = app.finishedAt === undefined && app.game.moves > 0;
360
+ const current = { seed: app.game.seed, drawMode: app.game.drawMode, ms: playTime(app, Date.now()), moves: app.game.moves, playing };
361
+ return renderDeals(cols, rows, app.stats.games, app.deals, current, ascii);
362
+ }
363
+ const needRows = minScreenHeight(app.game);
364
+ if (cols < MIN_WIDTH || rows < needRows) {
365
+ return renderNotice(cols, rows, ['Window too small', `Needs ${MIN_WIDTH}x${needRows}, now ${cols}x${rows}.`]);
366
+ }
367
+ return renderKlondike(app.game, viewOf(app, Date.now()), { ascii, compact: app.compact, width: cols, height: rows });
368
+ }
369
+ function render() {
370
+ const next = frame();
371
+ const out = diff(shown, next, theme);
372
+ if (out)
373
+ stdout.write(out);
374
+ shown = next;
375
+ }
376
+ /** Steps auto-complete and the win ceremony while either is running. */
377
+ function scheduleAuto() {
378
+ if (autoTimer || !animating(app))
379
+ return;
380
+ autoTimer = setTimeout(() => {
381
+ autoTimer = undefined;
382
+ app = stampDialog(app, tick(app, Date.now()), Date.now());
383
+ saveIfChanged();
384
+ render();
385
+ scheduleAuto();
386
+ }, AUTO_STEP_MS);
387
+ }
388
+ /** Asks the solver about the current position whenever it is new. */
389
+ let judgedVersion = -1;
390
+ function judgeIfNeeded() {
391
+ if (app.status !== 'checking' || judgedVersion === app.version)
392
+ return;
393
+ const version = app.version;
394
+ judgedVersion = version;
395
+ solver.judge(app.game, (verdict, next) => {
396
+ app = stampDialog(app, applyVerdict(app, version, verdict, next, Date.now()), Date.now());
397
+ // A loss proven goes on record at once, and shakes the board.
398
+ saveIfChanged();
399
+ render();
400
+ scheduleAuto();
401
+ deepIfNeeded();
402
+ lookAheadIfNeeded();
403
+ });
404
+ }
405
+ /**
406
+ * While the player thinks, settles every position one move away that is not
407
+ * known yet: a quick look at each, then a long one at those it left open. A
408
+ * move into a loss found here ends the game at once instead of seconds later.
409
+ * Only a winnable position is worth it; a move makes it all moot.
410
+ */
411
+ let aheadVersion = -1;
412
+ function lookAheadIfNeeded() {
413
+ if (aheadVersion === app.version)
414
+ return;
415
+ solver.cancelAhead();
416
+ if (app.status !== 'winnable' || app.dialog || animating(app))
417
+ return;
418
+ aheadVersion = app.version;
419
+ const ask = (child, deep) =>
420
+ // Answers only arrive while the position is unchanged: a move cancels them.
421
+ solver.lookAhead(child, deep, (verdict, next) => {
422
+ if (!deep && verdict === 'unclear')
423
+ ask(child, true);
424
+ app = stampDialog(app, applyAhead(app, child, verdict, next, Date.now()), Date.now());
425
+ saveIfChanged();
426
+ render();
427
+ scheduleAuto();
428
+ });
429
+ // First whether any redeal is to spare, then each move.
430
+ const spare = slackCheck(app);
431
+ if (spare)
432
+ ask(spare, false);
433
+ for (const child of successors(app.game))
434
+ if (!app.known.has(positionKey(child)))
435
+ ask(child, false);
436
+ }
437
+ /**
438
+ * Gives the suspect position, the first one quick judging could not settle,
439
+ * a long look on the second worker. Stops that look once it no longer matters.
440
+ */
441
+ let deepOn;
442
+ function deepIfNeeded() {
443
+ const suspect = liveSuspect(app)?.game;
444
+ if (suspect === deepOn)
445
+ return;
446
+ deepOn = suspect;
447
+ if (!suspect) {
448
+ solver.cancelDeep();
449
+ return;
450
+ }
451
+ solver.judgeDeeply(suspect, (verdict) => {
452
+ deepOn = undefined;
453
+ app = stampDialog(app, applyDeepVerdict(app, suspect, verdict, Date.now()), Date.now());
454
+ saveIfChanged();
455
+ render();
456
+ scheduleAuto();
457
+ deepIfNeeded();
458
+ });
459
+ }
460
+ // --- go ----------------------------------------------------------------------
461
+ // Focus reporting lets the clock stop while the player is in another window.
462
+ stdout.write(ansi.altScreenOn + ansi.hideCursor + ansi.focusReportingOn + ansi.clear);
463
+ emitKeypressEvents(stdin);
464
+ stdin.setRawMode(true);
465
+ stdin.resume();
466
+ stdin.on('keypress', (str, key) => {
467
+ const name = normalizeKey(str, key);
468
+ if (!name)
469
+ return;
470
+ // Another window may have found a losing move in this deal since.
471
+ syncCulprits();
472
+ app = handleKey(app, name, Date.now(), dealer);
473
+ if (app.quit)
474
+ quit();
475
+ saveIfChanged();
476
+ render();
477
+ scheduleAuto();
478
+ judgeIfNeeded();
479
+ deepIfNeeded();
480
+ lookAheadIfNeeded();
481
+ });
482
+ stdout.on('resize', () => {
483
+ shown = undefined;
484
+ render();
485
+ });
486
+ // The clock in the header only changes once a second, and diff sends just those cells.
487
+ setInterval(render, 1000).unref();
488
+ // Write the game straight away, so a tool looking at the file sees the game on screen.
489
+ saveGame(true);
490
+ syncCulprits();
491
+ removeOldCulprits(statsFile, culpritFile);
492
+ render();
493
+ scheduleAuto();
494
+ rateIfNeeded();
495
+ shareIfAgreed();
496
+ judgeIfNeeded();
@@ -0,0 +1,57 @@
1
+ export const SUITS = ['S', 'H', 'D', 'C'];
2
+ export const RANKS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
3
+ export function colorOf(card) {
4
+ return card.suit === 'H' || card.suit === 'D' ? 'red' : 'black';
5
+ }
6
+ /** Compact notation, ten as `X`, so every label is two characters (used in tests and parsing). */
7
+ const RANK_LABELS = ['', 'A', '2', '3', '4', '5', '6', '7', '8', '9', 'X', 'J', 'Q', 'K'];
8
+ const SUIT_SYMBOLS = { S: '♠', H: '♥', D: '♦', C: '♣' };
9
+ export function rankLabel(rank) {
10
+ return RANK_LABELS[rank];
11
+ }
12
+ export function suitLabel(suit, ascii = false) {
13
+ return ascii ? suit : SUIT_SYMBOLS[suit];
14
+ }
15
+ /**
16
+ * Suits as emoji (`♠` + U+FE0F). Plain ♠♥♦♣ are "ambiguous width" and most
17
+ * fonts draw them in one narrow cell; the emoji form is drawn two cells wide
18
+ * by terminals that support it (kitty, WezTerm, Ghostty, iTerm2, Windows Terminal).
19
+ */
20
+ export function suitGlyph(suit) {
21
+ return SUIT_SYMBOLS[suit] + '\uFE0F';
22
+ }
23
+ /**
24
+ * Ranks for drawing large cards, all two cells wide: fullwidth `A`…`9`,
25
+ * `J` `Q` `K`, and ten as plain `10`, which is already two characters.
26
+ */
27
+ const RANK_GLYPHS = ['', 'A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
28
+ const RANK_ASCII = ['', 'A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
29
+ /** The rank as drawn on a card face. With `ascii`, plain `A`…`10`…`K`. */
30
+ export function rankGlyph(rank, ascii = false) {
31
+ return (ascii ? RANK_ASCII : RANK_GLYPHS)[rank];
32
+ }
33
+ /** `K♠`, `X♥`, or with `ascii` set, `KS`, `XH`. */
34
+ export function cardLabel(card, ascii = false) {
35
+ return rankLabel(card.rank) + suitLabel(card.suit, ascii);
36
+ }
37
+ /** How messages name a card: `K♠`, `10♥`, or with `ascii` set, `KS`, `10H`. */
38
+ export function cardName(card, ascii = false) {
39
+ return rankGlyph(card.rank, true) + suitLabel(card.suit, ascii);
40
+ }
41
+ export function sameCard(a, b) {
42
+ return a !== undefined && a.suit === b.suit && a.rank === b.rank;
43
+ }
44
+ /**
45
+ * Parses `KS`, `K♠`, `XH`, `10H` and the like. Mostly for tests and debugging.
46
+ * Throws on anything else.
47
+ */
48
+ export function parseCard(text) {
49
+ const match = /^(10|[A2-9XJQK])([SHDC♠♥♦♣])$/i.exec(text.trim());
50
+ if (!match)
51
+ throw new Error(`Not a card: "${text}"`);
52
+ const rankText = match[1].toUpperCase();
53
+ const rank = (rankText === '10' ? 10 : RANK_LABELS.indexOf(rankText));
54
+ const suitText = match[2].toUpperCase();
55
+ const suit = (Object.entries(SUIT_SYMBOLS).find(([, sym]) => sym === suitText)?.[0] ?? suitText);
56
+ return { suit, rank };
57
+ }
@@ -0,0 +1,27 @@
1
+ import { RANKS, SUITS } from './card.js';
2
+ /** Small, fast, seedable PRNG. The same seed always deals the same game. */
3
+ export function mulberry32(seed) {
4
+ let a = seed >>> 0;
5
+ return () => {
6
+ a = (a + 0x6d2b79f5) >>> 0;
7
+ let t = a;
8
+ t = Math.imul(t ^ (t >>> 15), t | 1);
9
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
10
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
11
+ };
12
+ }
13
+ export function randomSeed() {
14
+ return Math.floor(Math.random() * 0x1_0000_0000) >>> 0;
15
+ }
16
+ export function createDeck() {
17
+ return SUITS.flatMap((suit) => RANKS.map((rank) => ({ suit, rank })));
18
+ }
19
+ /** Fisher–Yates. Returns a new array and leaves the input untouched. */
20
+ export function shuffle(items, rng) {
21
+ const out = [...items];
22
+ for (let i = out.length - 1; i > 0; i--) {
23
+ const j = Math.floor(rng() * (i + 1));
24
+ [out[i], out[j]] = [out[j], out[i]];
25
+ }
26
+ return out;
27
+ }