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.
@@ -0,0 +1,811 @@
1
+ /**
2
+ * Klondike solver. It sees every card, face-down ones included, so "solved"
3
+ * means the deal can be won with perfect play.
4
+ *
5
+ * Search is best-first with a transposition table. The game's own immutable
6
+ * state is too slow to copy millions of times, so the solver keeps a compact
7
+ * mutable copy with cards as integers.
8
+ *
9
+ * Stock handling: the stock and waste form one sequence ("talon") with a
10
+ * pointer to how many cards are turned. Drawing on its own never helps, so the
11
+ * solver instead plays any talon card it could reach by drawing, as one move.
12
+ */
13
+ import { SUITS, sameCard } from './card.js';
14
+ import { deal as dealFor, draw, isWon, move, moveToFoundation, pile, positionKey, successors, } from './klondike.js';
15
+ /**
16
+ * A last guard on memory, checked with the clock: a search stops, unanswered,
17
+ * once this says there is no room left. Node caps a worker's heap by itself;
18
+ * Bun does not, so its workers set this (see solver-worker.ts).
19
+ */
20
+ let outOfRoom = () => false;
21
+ export function limitMemory(check) {
22
+ outOfRoom = check;
23
+ }
24
+ // ---------------------------------------------------------------------------
25
+ // Compact state
26
+ /** Cards are 0..51: suit index × 13 + rank − 1, with suits in `SUITS` order. */
27
+ const suitOf = (c) => (c / 13) | 0;
28
+ const rankOf = (c) => (c % 13) + 1;
29
+ const isRed = (c) => {
30
+ const s = suitOf(c);
31
+ return s === 1 || s === 2;
32
+ };
33
+ const toInt = (card) => SUITS.indexOf(card.suit) * 13 + card.rank - 1;
34
+ const toCard = (c) => ({ suit: SUITS[suitOf(c)], rank: rankOf(c) });
35
+ /** Marks a game with no redeal limit. Fits the byte the queue stores it in. */
36
+ const UNLIMITED = 255;
37
+ function fromGame(state) {
38
+ const found = [0, 0, 0, 0];
39
+ for (const f of state.foundations)
40
+ if (f.length > 0)
41
+ found[SUITS.indexOf(f[0].suit)] = f.length;
42
+ return {
43
+ cols: state.tableau.map((c) => [...c.down, ...c.up].map(toInt)),
44
+ down: state.tableau.map((c) => c.down.length),
45
+ found,
46
+ talon: [...state.waste, ...[...state.stock].reverse()].map(toInt),
47
+ pos: state.waste.length,
48
+ left: Number.isFinite(state.redealsLeft) ? Math.min(Math.max(0, state.redealsLeft), UNLIMITED - 1) : UNLIMITED,
49
+ };
50
+ }
51
+ const clone = (s) => ({
52
+ cols: s.cols.map((c) => c.slice()),
53
+ down: s.down.slice(),
54
+ found: s.found.slice(),
55
+ talon: s.talon.slice(),
56
+ pos: s.pos,
57
+ left: s.left,
58
+ });
59
+ const canStack = (card, onto) => rankOf(onto) === rankOf(card) + 1 && isRed(onto) !== isRed(card);
60
+ const fitsFoundation = (s, c) => s.found[suitOf(c)] === rankOf(c) - 1;
61
+ const faceUp = (s, i) => s.cols[i].length - s.down[i];
62
+ /**
63
+ * Every talon position reachable by drawing from `pos`, as the number of
64
+ * turned cards (≥ 1), with how many redeals reaching it takes. Mirrors the
65
+ * game: draw `n`, and once the stock is out, redeal if any are `left`.
66
+ */
67
+ function reach(length, pos, n, left) {
68
+ const at = [];
69
+ const redeals = [];
70
+ if (length === 0)
71
+ return { at, redeals };
72
+ const seen = new Set();
73
+ let p = pos;
74
+ let used = 0;
75
+ for (let guard = 0; guard < 2 * length + 4; guard++) {
76
+ if (p >= 1 && !seen.has(p)) {
77
+ seen.add(p);
78
+ at.push(p);
79
+ redeals.push(used);
80
+ }
81
+ if (p === length) {
82
+ if (used >= left)
83
+ break;
84
+ p = 0;
85
+ used++;
86
+ }
87
+ else {
88
+ p = Math.min(p + n, length);
89
+ }
90
+ if (p === pos)
91
+ break; // round the whole talon: nothing new from here
92
+ }
93
+ return { at, redeals };
94
+ }
95
+ /** The talon positions reachable from `pos`; see {@link reach}. */
96
+ export function reachablePositions(length, pos, n, redealsLeft = Infinity) {
97
+ return reach(length, pos, n, redealsLeft).at;
98
+ }
99
+ /**
100
+ * Moving a card home can never lose the game when nothing still on the
101
+ * tableau could need it: both opposite-color cards one rank lower are home,
102
+ * and so is the other same-color card two ranks lower.
103
+ */
104
+ function safeToFoundation(s, c) {
105
+ const r = rankOf(c);
106
+ if (r <= 2)
107
+ return true;
108
+ const suit = suitOf(c);
109
+ const [oppA, oppB] = isRed(c) ? [0, 3] : [1, 2];
110
+ const sameOther = suit === 1 ? 2 : suit === 2 ? 1 : suit === 0 ? 3 : 0;
111
+ return s.found[oppA] >= r - 1 && s.found[oppB] >= r - 1 && s.found[sameOther] >= r - 2;
112
+ }
113
+ function flip(s, i) {
114
+ if (s.down[i] > 0 && s.down[i] >= s.cols[i].length)
115
+ s.down[i] = s.cols[i].length - 1;
116
+ }
117
+ function describe(s, m) {
118
+ switch (m.t) {
119
+ case 'tf':
120
+ return { from: { kind: 'tableau', index: m.from }, to: { kind: 'foundation' }, card: toCard(s.cols[m.from].at(-1)), count: 1 };
121
+ case 'xf':
122
+ return { from: { kind: 'talon' }, to: { kind: 'foundation' }, card: toCard(s.talon[m.p - 1]), count: 1 };
123
+ case 'xt':
124
+ return { from: { kind: 'talon' }, to: { kind: 'tableau', index: m.to }, card: toCard(s.talon[m.p - 1]), count: 1 };
125
+ case 'tt': {
126
+ const col = s.cols[m.from];
127
+ return { from: { kind: 'tableau', index: m.from }, to: { kind: 'tableau', index: m.to }, card: toCard(col[col.length - m.count]), count: m.count };
128
+ }
129
+ case 'ft':
130
+ return { from: { kind: 'foundation' }, to: { kind: 'tableau', index: m.to }, card: toCard(m.suit * 13 + s.found[m.suit] - 1), count: 1 };
131
+ }
132
+ }
133
+ function apply(s, m) {
134
+ switch (m.t) {
135
+ case 'tf': {
136
+ const c = s.cols[m.from].pop();
137
+ s.found[suitOf(c)]++;
138
+ flip(s, m.from);
139
+ return;
140
+ }
141
+ case 'xf':
142
+ case 'xt': {
143
+ const [c] = s.talon.splice(m.p - 1, 1);
144
+ s.pos = m.p - 1;
145
+ if (s.left !== UNLIMITED)
146
+ s.left -= m.r;
147
+ if (m.t === 'xf')
148
+ s.found[suitOf(c)]++;
149
+ else
150
+ s.cols[m.to].push(c);
151
+ return;
152
+ }
153
+ case 'tt': {
154
+ const col = s.cols[m.from];
155
+ const run = col.splice(col.length - m.count, m.count);
156
+ s.cols[m.to].push(...run);
157
+ flip(s, m.from);
158
+ return;
159
+ }
160
+ case 'ft': {
161
+ s.found[m.suit]--;
162
+ s.cols[m.to].push(m.suit * 13 + s.found[m.suit]);
163
+ return;
164
+ }
165
+ }
166
+ }
167
+ /**
168
+ * Candidate moves, most promising first.
169
+ *
170
+ * Some moves are always left out because a game that can be won can be won
171
+ * without them: a second empty column, a king already at the bottom moving to
172
+ * an empty column, an ace leaving its foundation, drawing without playing,
173
+ * emptying a column no king is waiting for, and splitting a run when nothing
174
+ * can make use of the card uncovered. Unless `exhaustive`, moves that merely
175
+ * look pointless are dropped too; that costs coverage but never correctness,
176
+ * since every solution is replayed.
177
+ */
178
+ function generate(s, drawMode, exhaustive) {
179
+ const scored = [];
180
+ const add = (m, score) => scored.push({ m, score });
181
+ const talon = reach(s.talon.length, s.pos, drawMode, s.left === UNLIMITED ? Infinity : s.left);
182
+ const reachable = talon.at;
183
+ // Redeals a move costs. Without a limit they are free, but solutions that
184
+ // spend few still replay under one, so they are tried first either way.
185
+ const redeals = (i) => talon.redeals[i];
186
+ const n = s.cols.length;
187
+ // Cards that could be picked up and moved somewhere: face-up tableau cards and reachable talon cards.
188
+ const usable = new Array(52).fill(false);
189
+ let kingWaiting = false; // a king that would like an empty column
190
+ for (let i = 0; i < n; i++) {
191
+ const col = s.cols[i];
192
+ for (let k = s.down[i]; k < col.length; k++) {
193
+ usable[col[k]] = true;
194
+ if (rankOf(col[k]) === 13 && k > 0)
195
+ kingWaiting = true;
196
+ }
197
+ }
198
+ for (const p of reachable) {
199
+ usable[s.talon[p - 1]] = true;
200
+ if (rankOf(s.talon[p - 1]) === 13)
201
+ kingWaiting = true;
202
+ }
203
+ // A king can come back from a finished foundation too; rarely the way to win, so only a proof looks at it.
204
+ if (exhaustive && s.found.includes(13))
205
+ kingWaiting = true;
206
+ // Only the first empty column is offered: empty columns are interchangeable.
207
+ const firstEmpty = s.cols.findIndex((c) => c.length === 0);
208
+ for (let i = 0; i < n; i++) {
209
+ const top = s.cols[i].at(-1);
210
+ if (top !== undefined && faceUp(s, i) > 0 && fitsFoundation(s, top))
211
+ add({ t: 'tf', from: i }, 100 + s.down[i]);
212
+ }
213
+ reachable.forEach((p, i) => {
214
+ // Reaching a card by redealing spends something scarce, so those moves come later.
215
+ if (fitsFoundation(s, s.talon[p - 1]))
216
+ add({ t: 'xf', p, r: redeals(i) }, 90 - 30 * redeals(i));
217
+ });
218
+ for (let i = 0; i < n; i++) {
219
+ const col = s.cols[i];
220
+ const up = faceUp(s, i);
221
+ for (let k = 1; k <= up; k++) {
222
+ const lead = col[col.length - k];
223
+ const whole = k === up;
224
+ for (let j = 0; j < n; j++) {
225
+ if (j === i)
226
+ continue;
227
+ const dest = s.cols[j];
228
+ if (dest.length === 0) {
229
+ // A king run already at the bottom of its column gains nothing from moving.
230
+ if (j !== firstEmpty || rankOf(lead) !== 13 || (whole && s.down[i] === 0))
231
+ continue;
232
+ }
233
+ else if (!canStack(lead, dest.at(-1)))
234
+ continue;
235
+ if (!whole) {
236
+ // Splitting a run uncovers a card, which helps only once that card goes home or the
237
+ // lead's twin (same rank and color) is put on it; until then the run could as well
238
+ // have stayed. So the twin has to be at hand, and unless `exhaustive`, the card must
239
+ // be able to go home.
240
+ if (!fitsFoundation(s, col[col.length - k - 1])) {
241
+ if (!exhaustive)
242
+ continue;
243
+ const twin = (3 - suitOf(lead)) * 13 + (lead % 13);
244
+ if (!usable[twin] && !(s.found[suitOf(twin)] === rankOf(twin) && rankOf(twin) >= 2))
245
+ continue;
246
+ }
247
+ }
248
+ else if (s.down[i] === 0 && dest.length > 0 && !kingWaiting) {
249
+ // Emptying a column gains only the space, and only a king can use it: the move can
250
+ // wait until one is there to take it.
251
+ continue;
252
+ }
253
+ const score = whole ? (s.down[i] > 0 ? 60 + s.down[i] : 20) : 10;
254
+ add({ t: 'tt', from: i, to: j, count: k }, score);
255
+ }
256
+ }
257
+ }
258
+ reachable.forEach((p, i) => {
259
+ const c = s.talon[p - 1];
260
+ for (let j = 0; j < n; j++) {
261
+ const dest = s.cols[j];
262
+ if (dest.length === 0 ? j === firstEmpty && rankOf(c) === 13 : canStack(c, dest.at(-1))) {
263
+ add({ t: 'xt', p, r: redeals(i), to: j }, 40 - 30 * redeals(i));
264
+ }
265
+ }
266
+ });
267
+ for (let suit = 0; suit < 4; suit++) {
268
+ if (s.found[suit] < 2)
269
+ continue; // an ace back on the tableau never helps
270
+ const c = suit * 13 + s.found[suit] - 1;
271
+ // Worth bringing back only if a card that could sit on it is in play.
272
+ const below = (isRed(c) ? [0, 3] : [1, 2]).map((t) => t * 13 + (c % 13) - 1);
273
+ if (!exhaustive && !below.some((x) => usable[x]))
274
+ continue;
275
+ for (let j = 0; j < n; j++) {
276
+ const top = s.cols[j].at(-1);
277
+ if (top === undefined ? exhaustive && j === firstEmpty && rankOf(c) === 13 : canStack(c, top))
278
+ add({ t: 'ft', suit, to: j }, 0);
279
+ }
280
+ }
281
+ scored.sort((a, b) => b.score - a.score);
282
+ return scored.map((x) => x.m);
283
+ }
284
+ function key(s, drawMode) {
285
+ // Column order does not matter for whether a position can be won.
286
+ const cols = s.cols.map((c, i) => String.fromCharCode(65 + s.down[i], ...c.map((x) => 48 + x))).sort();
287
+ // In Draw 3 the pointer decides which talon cards can be reached. In Draw 1 it only decides
288
+ // what they cost in redeals, which like the redeals left is not part of the key: see `reserve`.
289
+ const pos = drawMode === 1 ? '' : String.fromCharCode(48 + s.pos);
290
+ return String.fromCharCode(...s.found.map((f) => 48 + f)) + pos + String.fromCharCode(...s.talon.map((x) => 48 + x)) + '|' + cols.join('|');
291
+ }
292
+ // ---------------------------------------------------------------------------
293
+ // Search
294
+ /** Positions waiting in the queue are packed into bytes to keep memory small. */
295
+ function pack(s) {
296
+ const size = 7 + s.talon.length + s.cols.reduce((n, c) => n + 2 + c.length, 0);
297
+ const b = new Uint8Array(size);
298
+ let i = 0;
299
+ for (const f of s.found)
300
+ b[i++] = f;
301
+ b[i++] = s.pos;
302
+ b[i++] = s.left;
303
+ b[i++] = s.talon.length;
304
+ for (const c of s.talon)
305
+ b[i++] = c;
306
+ s.cols.forEach((col, k) => {
307
+ b[i++] = s.down[k];
308
+ b[i++] = col.length;
309
+ for (const c of col)
310
+ b[i++] = c;
311
+ });
312
+ return b;
313
+ }
314
+ function unpack(b, columns) {
315
+ let i = 0;
316
+ const found = [b[i++], b[i++], b[i++], b[i++]];
317
+ const pos = b[i++];
318
+ const left = b[i++];
319
+ const talonLength = b[i++];
320
+ const talon = Array.from(b.subarray(i, i + talonLength));
321
+ i += talonLength;
322
+ const cols = [];
323
+ const down = [];
324
+ for (let k = 0; k < columns; k++) {
325
+ down.push(b[i++]);
326
+ const len = b[i++];
327
+ cols.push(Array.from(b.subarray(i, i + len)));
328
+ i += len;
329
+ }
330
+ return { cols, down, found, talon, pos, left };
331
+ }
332
+ /** Moves are stored as small integers until a solution is rebuilt. */
333
+ function encode(m) {
334
+ const fk = m.from.kind === 'talon' ? 0 : m.from.kind === 'tableau' ? 1 : 2;
335
+ const fi = m.from.kind === 'tableau' ? m.from.index : 0;
336
+ const tk = m.to.kind === 'foundation' ? 0 : 1;
337
+ const ti = m.to.kind === 'tableau' ? m.to.index : 0;
338
+ return fk | (fi << 2) | (tk << 5) | (ti << 6) | (toInt(m.card) << 9) | (m.count << 15);
339
+ }
340
+ function decode(x) {
341
+ const fk = x & 3;
342
+ const fi = (x >> 2) & 7;
343
+ const ti = (x >> 6) & 7;
344
+ const from = fk === 0 ? { kind: 'talon' } : fk === 1 ? { kind: 'tableau', index: fi } : { kind: 'foundation' };
345
+ const to = (x >> 5) & 1 ? { kind: 'tableau', index: ti } : { kind: 'foundation' };
346
+ return { from, to, card: toCard((x >> 9) & 63), count: x >> 15 };
347
+ }
348
+ /**
349
+ * What a position has in hand to reach its talon cards with, as a number that
350
+ * is larger when it has more. Of two positions with the same cards in the same
351
+ * places, the one with more can do everything the other can: more redeals left
352
+ * always, and in Draw 1 with the same redeals, fewer cards turned, because
353
+ * turning cards is free and gets it to where the other is.
354
+ */
355
+ function reserve(s, drawMode) {
356
+ return drawMode === 1 && s.left !== UNLIMITED ? s.left * 64 + 63 - s.pos : s.left;
357
+ }
358
+ /** How promising a position looks. Hidden cards are the main obstacle. */
359
+ function score(s) {
360
+ let home = 0;
361
+ let hidden = 0;
362
+ for (const f of s.found)
363
+ home += f;
364
+ for (const d of s.down)
365
+ hidden += d;
366
+ // Redeals still in hand are worth keeping.
367
+ const spare = s.left === UNLIMITED ? 0 : s.left * 3;
368
+ return home * 2 - hidden * 6 - s.talon.length + spare;
369
+ }
370
+ /**
371
+ * True when the position can be shown lost without searching: some card can
372
+ * never reach its foundation, whatever is played.
373
+ *
374
+ * It works out which things can ever happen, erring on the side of "can":
375
+ * `home[c]`, card c reaches its foundation, and `top[c]`, c lies face up on
376
+ * the tableau with nothing on it. A talon card counts as always in hand. Each
377
+ * event needs earlier ones:
378
+ *
379
+ * - c goes home once the card below it in suit has, and c is on top (or in the talon);
380
+ * - a card is uncovered once the card lying on it leaves, and that one leaves
381
+ * only by going home, onto another card that is on top, or as a king to an
382
+ * empty column;
383
+ * - a card from the talon or a foundation lands on a card that is on top, or as a king on an
384
+ * empty column, and one from a foundation only after the cards above it there have come down;
385
+ * - a column empties once its bottom card leaves.
386
+ *
387
+ * Whatever does happen in a real game happens for one of these reasons, by
388
+ * something that happened before it, so everything possible is found by
389
+ * applying the rules until nothing new comes out. A card left without `home`
390
+ * is stuck for good: typically cards that wait for one another in a circle,
391
+ * which a search would otherwise have to play every other card around to see.
392
+ */
393
+ function dead(s) {
394
+ const HOME = 0, TALON = 1, UP = 2, DOWN = 3, MISSING = 4;
395
+ const where = new Uint8Array(52).fill(MISSING);
396
+ const above = new Int8Array(52).fill(-1); // the card lying on each tableau card
397
+ const home = new Uint8Array(52);
398
+ const top = new Uint8Array(52);
399
+ let empty = false;
400
+ for (let suit = 0; suit < 4; suit++) {
401
+ for (let r = 0; r < s.found[suit]; r++) {
402
+ where[suit * 13 + r] = HOME;
403
+ home[suit * 13 + r] = 1;
404
+ }
405
+ }
406
+ for (const c of s.talon)
407
+ where[c] = TALON;
408
+ for (let i = 0; i < s.cols.length; i++) {
409
+ const col = s.cols[i];
410
+ if (col.length === 0)
411
+ empty = true;
412
+ for (let k = 0; k < col.length; k++) {
413
+ where[col[k]] = k < s.down[i] ? DOWN : UP;
414
+ if (k + 1 < col.length)
415
+ above[col[k]] = col[k + 1];
416
+ else
417
+ top[col[k]] = 1;
418
+ }
419
+ }
420
+ /** Whether a card that `c` can be put on is ever on top. */
421
+ const landing = (c) => {
422
+ const r = c % 13;
423
+ if (r === 12)
424
+ return false;
425
+ return isRed(c) ? top[r + 1] === 1 || top[39 + r + 1] === 1 : top[13 + r + 1] === 1 || top[26 + r + 1] === 1;
426
+ };
427
+ /** Whether a tableau card that is turned, or ever will be, has somewhere to go from where it lies. */
428
+ const leaves = (x, onACard) => (where[x] === UP || top[x] === 1) && (home[x] === 1 || landing(x) || (x % 13 === 12 && empty && onACard));
429
+ for (let changed = true; changed;) {
430
+ changed = false;
431
+ for (let c = 0; c < 52; c++) {
432
+ const w = where[c];
433
+ if (w === MISSING)
434
+ return true;
435
+ const lands = () => (landing(c) || (c % 13 === 12 && empty)) && (w === TALON || (c % 13) + 1 === s.found[suitOf(c)] || top[c + 1] === 1);
436
+ if (top[c] === 0 && (w === TALON || w === HOME ? lands() : leaves(above[c], true))) {
437
+ top[c] = 1;
438
+ changed = true;
439
+ }
440
+ if (home[c] === 0 && (c % 13 === 0 || home[c - 1] === 1) && (w === TALON || top[c] === 1)) {
441
+ home[c] = 1;
442
+ changed = true;
443
+ }
444
+ }
445
+ if (!empty && s.cols.some((col) => leaves(col[0], false))) {
446
+ empty = true;
447
+ changed = true;
448
+ }
449
+ }
450
+ return home.includes(0);
451
+ }
452
+ /** Whether a game is lost for a reason that shows without searching; see {@link dead}. */
453
+ export function isDeadEnd(state) {
454
+ return dead(fromGame(state));
455
+ }
456
+ /** Max-heap on score; among equals the newest position wins, which keeps lines of play going. */
457
+ class Queue {
458
+ #ids = [];
459
+ #scores = [];
460
+ get size() {
461
+ return this.#ids.length;
462
+ }
463
+ #above(a, b) {
464
+ const sa = this.#scores[a];
465
+ const sb = this.#scores[b];
466
+ return sa > sb || (sa === sb && this.#ids[a] > this.#ids[b]);
467
+ }
468
+ #swap(a, b) {
469
+ [this.#ids[a], this.#ids[b]] = [this.#ids[b], this.#ids[a]];
470
+ [this.#scores[a], this.#scores[b]] = [this.#scores[b], this.#scores[a]];
471
+ }
472
+ push(id, sc) {
473
+ this.#ids.push(id);
474
+ this.#scores.push(sc);
475
+ for (let i = this.#ids.length - 1; i > 0;) {
476
+ const parent = (i - 1) >> 1;
477
+ if (!this.#above(i, parent))
478
+ break;
479
+ this.#swap(i, parent);
480
+ i = parent;
481
+ }
482
+ }
483
+ pop() {
484
+ const top = this.#ids[0];
485
+ const lastId = this.#ids.pop();
486
+ const lastScore = this.#scores.pop();
487
+ if (this.#ids.length > 0) {
488
+ this.#ids[0] = lastId;
489
+ this.#scores[0] = lastScore;
490
+ for (let i = 0;;) {
491
+ const l = 2 * i + 1;
492
+ const r = l + 1;
493
+ let best = i;
494
+ if (l < this.#ids.length && this.#above(l, best))
495
+ best = l;
496
+ if (r < this.#ids.length && this.#above(r, best))
497
+ best = r;
498
+ if (best === i)
499
+ break;
500
+ this.#swap(i, best);
501
+ i = best;
502
+ }
503
+ }
504
+ return top;
505
+ }
506
+ }
507
+ /** The budget of a search that is not given one. */
508
+ const MAX_NODES = 300_000;
509
+ const TIME_LIMIT_MS = 5_000;
510
+ /**
511
+ * Solves a position.
512
+ *
513
+ * With a redeal limit and `exhaustive` set (proving a loss), the game is also
514
+ * searched as if there were no limit, which late in the stock is the larger
515
+ * search and early on by far the smaller: if it cannot be won even then, it
516
+ * cannot be won with the limit either. Solutions found that way are not used,
517
+ * since they typically turn the deck over many times; only a search that
518
+ * counts redeals can find one that stays within the limit. So: a short look
519
+ * with the limit, then most of the budget without it, then the rest with it.
520
+ */
521
+ export function solve(state, options = {}) {
522
+ if (!Number.isFinite(state.redealsLeft) || !options.exhaustive)
523
+ return search(state, options);
524
+ const start = Date.now();
525
+ const maxNodes = options.maxNodes ?? MAX_NODES;
526
+ const timeLimitMs = options.timeLimitMs ?? TIME_LIMIT_MS;
527
+ let nodes = 0;
528
+ /** A search with this share of the budget that is left. */
529
+ const look = (game, share) => {
530
+ const r = search(game, {
531
+ ...options,
532
+ maxNodes: Math.max(1, Math.floor((maxNodes - nodes) * share)),
533
+ timeLimitMs: Math.max(1, (timeLimitMs - (Date.now() - start)) * share),
534
+ });
535
+ nodes += r.nodes;
536
+ return { ...r, nodes, ms: Date.now() - start };
537
+ };
538
+ const glance = look(state, 1 / 8);
539
+ if (glance.status !== 'unknown')
540
+ return glance;
541
+ const relaxed = look({ ...state, redealsLeft: Infinity }, 3 / 4);
542
+ if (relaxed.status === 'unsolvable')
543
+ return relaxed;
544
+ return look(state, 1);
545
+ }
546
+ /** What an engine is built to hold; anything larger (only hand-built boards are) is searched here. */
547
+ export const ENGINE_LIMITS = { columns: 7, column: 20, talon: 24 };
548
+ let engine;
549
+ /** Sets the engine every search from now on uses, or with `undefined` goes back to the search in this file. */
550
+ export function useEngine(e) {
551
+ engine = e;
552
+ }
553
+ function fitsEngine(s) {
554
+ return s.cols.length <= ENGINE_LIMITS.columns && s.talon.length <= ENGINE_LIMITS.talon && s.cols.every((c) => c.length <= ENGINE_LIMITS.column);
555
+ }
556
+ /**
557
+ * Best-first search: always expands the most promising position seen so far,
558
+ * so one bad early choice cannot swallow the whole budget the way it can in a
559
+ * plain depth-first search.
560
+ *
561
+ * This is the reference. The engine, when one is set, is the same search
562
+ * written for speed, and a test holds the two to the same answers.
563
+ */
564
+ function search(state, options) {
565
+ const maxNodes = options.maxNodes ?? MAX_NODES;
566
+ const start = Date.now();
567
+ const deadline = start + (options.timeLimitMs ?? TIME_LIMIT_MS);
568
+ const drawMode = state.drawMode;
569
+ const columns = state.tableau.length;
570
+ if (engine) {
571
+ const position = fromGame(state);
572
+ if (fitsEngine(position)) {
573
+ const r = engine(pack(position), columns, drawMode, maxNodes, options.timeLimitMs ?? TIME_LIMIT_MS, options.exhaustive ?? false);
574
+ const ms = Date.now() - start;
575
+ return r.status === 'solved' ? { status: 'solved', moves: r.moves.map(decode), nodes: r.nodes, ms } : { status: r.status, nodes: r.nodes, ms };
576
+ }
577
+ }
578
+ /**
579
+ * Positions already queued, with the largest `reserve` any of them had: the
580
+ * same position is only worth another look with more.
581
+ */
582
+ const seen = new Map();
583
+ const better = (k, has) => {
584
+ const had = seen.get(k);
585
+ if (had !== undefined && had >= has)
586
+ return false;
587
+ seen.set(k, has);
588
+ return true;
589
+ };
590
+ const parents = [];
591
+ const steps = [];
592
+ const packed = [];
593
+ const queue = new Queue();
594
+ const step = (s, m, out) => {
595
+ out.push(encode(describe(s, m)));
596
+ apply(s, m);
597
+ };
598
+ /** Plays every safe tableau card home. Talon cards are left alone: in Draw 3 they shift the pointer. */
599
+ const playSafe = (s, out) => {
600
+ for (let changed = true; changed;) {
601
+ changed = false;
602
+ for (let i = 0; i < s.cols.length; i++) {
603
+ const top = s.cols[i].at(-1);
604
+ if (top !== undefined && faceUp(s, i) > 0 && fitsFoundation(s, top) && safeToFoundation(s, top)) {
605
+ step(s, { t: 'tf', from: i }, out);
606
+ changed = true;
607
+ }
608
+ }
609
+ }
610
+ };
611
+ /** True once the game is won or trivially winnable; in the latter case plays it out. */
612
+ const finished = (s, out) => {
613
+ if (s.found.every((f) => f === 13))
614
+ return true;
615
+ if (s.talon.length > 0 || s.down.some((d) => d > 0))
616
+ return false;
617
+ // Only a full deck plays itself out; hand-built test boards may hold fewer cards.
618
+ if (s.found.reduce((a, b) => a + b, 0) + s.cols.reduce((n, c) => n + c.length, 0) !== 52)
619
+ return false;
620
+ // Everything is face up in valid runs: the lowest top card always goes home next.
621
+ while (s.found.some((f) => f < 13)) {
622
+ let best = -1;
623
+ for (let i = 0; i < s.cols.length; i++) {
624
+ const top = s.cols[i].at(-1);
625
+ if (top !== undefined && (best < 0 || rankOf(top) < rankOf(s.cols[best].at(-1))))
626
+ best = i;
627
+ }
628
+ step(s, { t: 'tf', from: best }, out);
629
+ }
630
+ return true;
631
+ };
632
+ const solution = (id, last) => {
633
+ const chain = [last];
634
+ for (let n = id; n >= 0; n = parents[n])
635
+ chain.push(steps[n]);
636
+ return chain.reverse().flat().map(decode);
637
+ };
638
+ const done = (status) => ({ status, nodes: parents.length, ms: Date.now() - start });
639
+ const root = fromGame(state);
640
+ const rootSteps = [];
641
+ playSafe(root, rootSteps);
642
+ if (finished(root, rootSteps))
643
+ return { status: 'solved', moves: rootSteps.map(decode), nodes: 1, ms: Date.now() - start };
644
+ if (dead(root))
645
+ return { status: 'unsolvable', nodes: 1, ms: Date.now() - start };
646
+ better(key(root, drawMode), reserve(root, drawMode));
647
+ parents.push(-1);
648
+ steps.push(rootSteps);
649
+ packed.push(pack(root));
650
+ queue.push(0, score(root));
651
+ while (queue.size > 0) {
652
+ const id = queue.pop();
653
+ const s = unpack(packed[id], columns);
654
+ packed[id] = undefined; // expanded positions are only needed for their path
655
+ for (const m of generate(s, drawMode, options.exhaustive ?? false)) {
656
+ const child = clone(s);
657
+ const out = [];
658
+ step(child, m, out);
659
+ playSafe(child, out);
660
+ if (finished(child, out)) {
661
+ return { status: 'solved', moves: solution(id, out), nodes: parents.length, ms: Date.now() - start };
662
+ }
663
+ if (!better(key(child, drawMode), reserve(child, drawMode)))
664
+ continue;
665
+ if (dead(child))
666
+ continue;
667
+ if (parents.length >= maxNodes || ((parents.length & 1023) === 0 && (Date.now() > deadline || outOfRoom())))
668
+ return done('unknown');
669
+ parents.push(id);
670
+ steps.push(out);
671
+ packed.push(pack(child));
672
+ queue.push(parents.length - 1, score(child));
673
+ }
674
+ }
675
+ return done('unsolvable');
676
+ }
677
+ // ---------------------------------------------------------------------------
678
+ // Replay through the real rules
679
+ /**
680
+ * Plays a solution with the game's own `draw` and `move` and returns the final
681
+ * state. Throws if any step is illegal, so a buggy solution can never pass.
682
+ */
683
+ export function replay(state, moves) {
684
+ let s = state;
685
+ const step = (r, what) => {
686
+ if (!r.ok)
687
+ throw new Error(`Solution step failed (${r.error}): ${what}`);
688
+ s = r.state;
689
+ };
690
+ moves.forEach((m, i) => {
691
+ const what = `#${i} ${m.card.rank}${m.card.suit} ${m.from.kind} → ${m.to.kind}`;
692
+ let from;
693
+ if (m.from.kind === 'talon') {
694
+ for (let guard = 0; !sameCard(s.waste.at(-1), m.card); guard++) {
695
+ if (guard > 4 * 52)
696
+ throw new Error(`Talon card never turned up: ${what}`);
697
+ step(draw(s), what);
698
+ }
699
+ from = pile.waste;
700
+ }
701
+ else if (m.from.kind === 'tableau') {
702
+ from = pile.tableau(m.from.index);
703
+ }
704
+ else {
705
+ const f = s.foundations.findIndex((p) => sameCard(p.at(-1), m.card));
706
+ if (f < 0)
707
+ throw new Error(`Card not on a foundation: ${what}`);
708
+ from = pile.foundation(f);
709
+ }
710
+ if (m.to.kind === 'foundation')
711
+ step(moveToFoundation(s, from), what);
712
+ else
713
+ step(move(s, from, pile.tableau(m.to.index), m.count), what);
714
+ });
715
+ return s;
716
+ }
717
+ /** Solves and double-checks the answer against the real rules. */
718
+ export function isSolvable(state, options) {
719
+ const result = solve(state, options);
720
+ if (result.status === 'solved' && !isWon(replay(state, result.moves))) {
721
+ throw new Error('Solver produced a solution that does not win');
722
+ }
723
+ return result;
724
+ }
725
+ /**
726
+ * Whether a position can still be won. `lost` is only returned when an
727
+ * exhaustive search proves it, so the player is never told they lost when
728
+ * they have not. `winnable` is backed by a replayed solution.
729
+ *
730
+ * The node budgets are sized for the WebAssembly engine, which gets through
731
+ * them in about the time allowed. The search in this file is several times
732
+ * slower and simply stops at the time limit, having seen what it used to.
733
+ */
734
+ export function judge(state, options = {}) {
735
+ const start = Date.now();
736
+ const quick = isSolvable(state, { maxNodes: 300_000, timeLimitMs: 1_000, ...options.quick });
737
+ if (quick.status === 'solved')
738
+ return { verdict: 'winnable', ms: Date.now() - start, next: quick.moves[0] };
739
+ if (quick.status === 'unknown' && !options.thorough)
740
+ return { verdict: 'unclear', ms: Date.now() - start };
741
+ const sure = isSolvable(state, { maxNodes: 1_500_000, timeLimitMs: 3_000, ...options.confirm, exhaustive: true });
742
+ if (sure.status === 'solved')
743
+ return { verdict: 'winnable', ms: Date.now() - start, next: sure.moves[0] };
744
+ return { verdict: sure.status === 'unsolvable' ? 'lost' : 'unclear', ms: Date.now() - start };
745
+ }
746
+ /**
747
+ * A much longer look at a position live judging could not settle. Run in the
748
+ * background: a loss found here also holds for every position played since.
749
+ */
750
+ export function judgeDeeply(state) {
751
+ return judge(state, {
752
+ quick: { maxNodes: 2_000_000, timeLimitMs: 6_000 },
753
+ confirm: { maxNodes: 4_000_000, timeLimitMs: 12_000 },
754
+ thorough: true,
755
+ });
756
+ }
757
+ /**
758
+ * Draws seeds until one deals a game the solver can win, or `maxTries` runs
759
+ * out. Each try uses a small budget: most winnable deals solve in a few ms,
760
+ * and an undecided one is simply skipped.
761
+ */
762
+ export function findWinnableSeed(drawMode, nextSeed, options = {}) {
763
+ const tries = options.maxTries ?? 40;
764
+ for (let i = 0; i < tries; i++) {
765
+ const seed = nextSeed();
766
+ const r = isSolvable(dealFor(seed, drawMode, options.redeals), { maxNodes: 20_000, timeLimitMs: 500, ...options.perTry });
767
+ if (r.status === 'solved')
768
+ return seed;
769
+ }
770
+ return undefined;
771
+ }
772
+ /**
773
+ * Rates a deal the way a player meets it: follows a winning line and counts
774
+ * the places along it where a move goes wrong, and the places with just one
775
+ * way on. Search effort says little, since the solver sees the face-down
776
+ * cards; traps are what make a deal hard for someone who does not. Each move
777
+ * gets a short look, so a move counted as a trap may only be hard to win
778
+ * from. Deterministic: only node budgets limit the looks, with time limits as
779
+ * a backstop. Takes a few seconds.
780
+ */
781
+ export function rateDeal(state) {
782
+ const sol = isSolvable(state, { maxNodes: 300_000, timeLimitMs: 30_000 });
783
+ if (sol.status !== 'solved')
784
+ return { level: 0, traps: 0, forced: 0 };
785
+ const looked = new Map();
786
+ const wins = (g) => {
787
+ const k = positionKey(g);
788
+ let w = looked.get(k);
789
+ if (w === undefined)
790
+ looked.set(k, (w = isSolvable(g, { maxNodes: 8_000, timeLimitMs: 2_000 }).status === 'solved'));
791
+ return w;
792
+ };
793
+ let traps = 0;
794
+ let forced = 0;
795
+ let s = state;
796
+ for (let i = 0; i <= sol.moves.length; i++) {
797
+ const options = successors(s);
798
+ if (options.length >= 2) {
799
+ const good = options.filter(wins).length;
800
+ if (good < options.length)
801
+ traps++;
802
+ if (good <= 1)
803
+ forced++;
804
+ }
805
+ if (i < sol.moves.length)
806
+ s = replay(s, [sol.moves[i]]);
807
+ }
808
+ // Tuned on real deals: ordinary dealt ones score about 0 to 17, ones players found hard 11 to 72.
809
+ const score = traps + 3 * forced;
810
+ return { level: score >= 30 ? 3 : score >= 10 ? 2 : 1, traps, forced };
811
+ }