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/LICENSE +21 -0
- package/README.ko.md +355 -0
- package/README.md +368 -2
- package/dist/app.js +1130 -0
- package/dist/cli.js +496 -0
- package/dist/core/card.js +57 -0
- package/dist/core/deck.js +27 -0
- package/dist/core/klondike.js +364 -0
- package/dist/core/solver.js +811 -0
- package/dist/culprit-file.js +93 -0
- package/dist/saved-game.js +164 -0
- package/dist/share.js +96 -0
- package/dist/solver-client.js +125 -0
- package/dist/solver-wasm.js +47 -0
- package/dist/solver-worker.js +29 -0
- package/dist/solver.wasm +0 -0
- package/dist/stats-file.js +112 -0
- package/dist/stats.js +196 -0
- package/dist/ui/ansi.js +93 -0
- package/dist/ui/help.js +154 -0
- package/dist/ui/input.js +40 -0
- package/dist/ui/keymap.js +46 -0
- package/dist/ui/layout.js +404 -0
- package/dist/ui/screen.js +88 -0
- package/dist/ui/theme.js +155 -0
- package/package.json +50 -4
package/dist/app.js
ADDED
|
@@ -0,0 +1,1130 @@
|
|
|
1
|
+
import { cardName, sameCard } from './core/card.js';
|
|
2
|
+
import { autoComplete, autoMove, canAutoComplete, cardsIn, deal, destinations, draw, foundationFor, isWon, maxTake, move, moveTo, moveToFoundation, pile, positionKey, samePile, TABLEAU_COLUMNS, } from './core/klondike.js';
|
|
3
|
+
import { EMPTY_STATS, lossId, newGameId, pastGame, recordLoss, recordWin, statsFor, winRate, withLevel } from './stats.js';
|
|
4
|
+
import { formatTime, formatWhen } from './ui/help.js';
|
|
5
|
+
import { MAX_BATCH, SHARE_EVERY, acceptShare, declineShare, finishedGames, markShared, shareDue, unsent } from './share.js';
|
|
6
|
+
import { STOCK_KEY, keyLabel, pileForKey } from './ui/keymap.js';
|
|
7
|
+
const stallFrom = (game) => ({ waste: game.waste.length, redealt: false });
|
|
8
|
+
/** Seeds are 32-bit. */
|
|
9
|
+
const MAX_SEED = 0xffff_ffff;
|
|
10
|
+
const WELCOME = 'Press a pile key, then where it goes. Esc for the menu.';
|
|
11
|
+
const WELCOME_BACK = 'Welcome back. Your game is where you left it.';
|
|
12
|
+
const STALLED = 'This game can still be won, there is a move you have not tried. ? shows it.';
|
|
13
|
+
/**
|
|
14
|
+
* Enter or space this soon after a dialog comes up on its own was meant for
|
|
15
|
+
* the board, not the dialog. Dialogs the player opens are answered at once.
|
|
16
|
+
*/
|
|
17
|
+
export const DIALOG_GUARD_MS = 700;
|
|
18
|
+
/** Dialogs that come up without the player asking: a loss found, sharing after a win, a seed at start. */
|
|
19
|
+
const UNPROMPTED = new Set(['lost', 'share', 'seed']);
|
|
20
|
+
/**
|
|
21
|
+
* After any change: a dialog that has just come up starts on its first
|
|
22
|
+
* choice, and one that came up on its own notes when, for the guard.
|
|
23
|
+
*/
|
|
24
|
+
export function stampDialog(before, after, now) {
|
|
25
|
+
if (after.dialog === undefined || after.dialog === before.dialog)
|
|
26
|
+
return after;
|
|
27
|
+
const { dialogAt: _, ...rest } = after;
|
|
28
|
+
return UNPROMPTED.has(after.dialog) ? { ...rest, choice: 0, dialogAt: now } : { ...rest, choice: 0 };
|
|
29
|
+
}
|
|
30
|
+
/** How long the win ceremony runs before the results come up. */
|
|
31
|
+
export const CEREMONY_MS = 2_500;
|
|
32
|
+
/** How long the board shakes and fades behind the dialog when a loss is proven. */
|
|
33
|
+
export const DEFEAT_MS = 1_400;
|
|
34
|
+
export function createApp(game, options = {}) {
|
|
35
|
+
const verified = options.verified ?? false;
|
|
36
|
+
return {
|
|
37
|
+
game,
|
|
38
|
+
history: [],
|
|
39
|
+
version: 0,
|
|
40
|
+
status: verified ? 'winnable' : 'checking',
|
|
41
|
+
known: new Map(),
|
|
42
|
+
lastWinnable: verified ? { game, history: [] } : undefined,
|
|
43
|
+
verified,
|
|
44
|
+
playingOn: false,
|
|
45
|
+
culprits: new Map(),
|
|
46
|
+
culpritOutbox: [],
|
|
47
|
+
cursor: pile.tableau(0),
|
|
48
|
+
message: WELCOME,
|
|
49
|
+
stall: stallFrom(game),
|
|
50
|
+
stalled: false,
|
|
51
|
+
ascii: options.ascii ?? false,
|
|
52
|
+
compact: options.compact ?? false,
|
|
53
|
+
nextDrawMode: game.drawMode,
|
|
54
|
+
showHelp: false,
|
|
55
|
+
showStats: false,
|
|
56
|
+
pausedMs: 0,
|
|
57
|
+
redeals: options.redeals ?? game.redealsLeft,
|
|
58
|
+
stats: options.stats ?? EMPTY_STATS,
|
|
59
|
+
outbox: [],
|
|
60
|
+
canShare: options.canShare ?? false,
|
|
61
|
+
play: 'fresh',
|
|
62
|
+
gameId: options.gameId ?? newGameId(),
|
|
63
|
+
...(options.gameAt === undefined ? {} : { gameAt: options.gameAt }),
|
|
64
|
+
choice: 0,
|
|
65
|
+
celebrating: false,
|
|
66
|
+
autoQueue: [],
|
|
67
|
+
quit: false,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* A game picked up again from its positions, the deal first: undo reaches
|
|
72
|
+
* back to the deal, the clock carries on from where it stopped, and the
|
|
73
|
+
* position is judged afresh.
|
|
74
|
+
*/
|
|
75
|
+
export function resumeApp(states, options) {
|
|
76
|
+
const start = createApp(states[0], options);
|
|
77
|
+
const game = states[states.length - 1];
|
|
78
|
+
const clock = options.ms > 0 ? { startedAt: options.now - options.ms } : {};
|
|
79
|
+
if (states.length === 1)
|
|
80
|
+
return { ...start, ...clock, play: options.play, message: WELCOME_BACK };
|
|
81
|
+
let app = {
|
|
82
|
+
...start,
|
|
83
|
+
game,
|
|
84
|
+
history: states.slice(0, -1),
|
|
85
|
+
version: 1,
|
|
86
|
+
status: 'checking',
|
|
87
|
+
stall: stallFrom(game),
|
|
88
|
+
play: options.play,
|
|
89
|
+
startedAt: options.now - options.ms,
|
|
90
|
+
message: WELCOME_BACK,
|
|
91
|
+
};
|
|
92
|
+
// Where z goes back to after a loss: saved with the game, else the deal.
|
|
93
|
+
const w = options.winnable;
|
|
94
|
+
if (w !== undefined && Number.isInteger(w) && w >= 0 && w < states.length)
|
|
95
|
+
app = { ...app, lastWinnable: { game: states[w], history: states.slice(0, w) } };
|
|
96
|
+
// Quit in the middle of finishing: finish now.
|
|
97
|
+
if (canAutoComplete(game))
|
|
98
|
+
app = { ...app, status: 'winnable', autoQueue: autoComplete(game) };
|
|
99
|
+
return app;
|
|
100
|
+
}
|
|
101
|
+
const close = (app) => ({ ...app, dialog: undefined, defeat: undefined });
|
|
102
|
+
const carryOn = (app) => ({ ...close(app), message: 'Carry on.' });
|
|
103
|
+
const keepPlaying = { label: 'Keep playing', act: carryOn };
|
|
104
|
+
const quitNow = (app) => ({ ...app, quit: true });
|
|
105
|
+
/** Nothing to give up while no card has moved, or once the game is over. */
|
|
106
|
+
const untouched = (app) => app.play !== 'counted' || app.finishedAt !== undefined;
|
|
107
|
+
/** The menu that esc brings up: everything that is not a move. */
|
|
108
|
+
function menuSpec(app) {
|
|
109
|
+
const other = app.nextDrawMode === 1 ? 3 : 1;
|
|
110
|
+
return {
|
|
111
|
+
title: 'Menu',
|
|
112
|
+
lines: [],
|
|
113
|
+
choices: [
|
|
114
|
+
{ label: 'Back to the game', act: close },
|
|
115
|
+
{ label: 'New game', act: (a, now, dealer) => (untouched(a) ? newGame(close(a), dealer, now) : { ...a, held: undefined, dialog: 'new' }) },
|
|
116
|
+
{ label: 'Restart this deal', act: (a) => askRestart(close(a)) },
|
|
117
|
+
{ label: `Draw ${other} instead`, act: (a, now, dealer) => switchDraw(close(a), dealer, now) },
|
|
118
|
+
{ label: 'Hint', act: (a) => showHint(close(a)) },
|
|
119
|
+
{ label: 'Play a seed or a recent game', act: (a) => openDeals(close(a)) },
|
|
120
|
+
{ label: 'Statistics', act: (a) => ({ ...close(a), held: undefined, showStats: true }) },
|
|
121
|
+
{ label: 'Keys and rules', act: (a) => ({ ...close(a), showHelp: true }) },
|
|
122
|
+
{ label: 'Quit (your game is kept)', act: quitNow },
|
|
123
|
+
],
|
|
124
|
+
cancel: close,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
/** The results after a win: this game, then the record for its draw mode. */
|
|
128
|
+
function wonSpec(app) {
|
|
129
|
+
const win = app.lastWin;
|
|
130
|
+
const m = statsFor(app.stats, app.game.drawMode);
|
|
131
|
+
const lines = [];
|
|
132
|
+
if (win) {
|
|
133
|
+
const turns = win.redeals === 0 ? 'no redeals' : win.redeals === 1 ? '1 redeal' : `${win.redeals} redeals`;
|
|
134
|
+
lines.push(`${win.moves} moves in ${formatTime(win.ms)}, ${turns}.`);
|
|
135
|
+
const best = [win.bestTime && 'best time', win.fewestMoves && 'fewest moves'].filter(Boolean);
|
|
136
|
+
if (best.length > 0)
|
|
137
|
+
lines.push(`New record: ${best.join(' and ')}!`);
|
|
138
|
+
}
|
|
139
|
+
lines.push(`Draw ${app.game.drawMode}: won ${m.won} of ${m.played} (${winRate(m)}%).`);
|
|
140
|
+
lines.push(`Streak ${m.streak}, longest ${m.bestStreak}.`);
|
|
141
|
+
const look = (a) => ({ ...close(a), message: 'Esc for the menu: a new deal, or choose one.' });
|
|
142
|
+
return {
|
|
143
|
+
title: 'You won!',
|
|
144
|
+
lines,
|
|
145
|
+
choices: [
|
|
146
|
+
{ label: 'New deal', act: (a, now, dealer) => newGame(a, dealer, now) },
|
|
147
|
+
{ label: 'Choose a deal', act: (a) => openDeals(close(a)) },
|
|
148
|
+
{ label: 'Statistics', act: (a) => ({ ...close(a), showStats: true }) },
|
|
149
|
+
{ label: 'Look at the board', act: look },
|
|
150
|
+
// Nothing to keep: the next start deals a new game.
|
|
151
|
+
{ label: 'Quit', act: quitNow },
|
|
152
|
+
],
|
|
153
|
+
cancel: look,
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
/** The question at each hundred games. */
|
|
157
|
+
function shareSpec(app) {
|
|
158
|
+
const total = finishedGames(app.stats);
|
|
159
|
+
const n = (x) => x.toLocaleString('en-US');
|
|
160
|
+
const next = n((Math.floor(total / SHARE_EVERY) + 1) * SHARE_EVERY);
|
|
161
|
+
// Asked after a win: either answer goes on to the results.
|
|
162
|
+
const results = (a) => (a.finishedAt !== undefined ? { ...a, dialog: 'won' } : close(a));
|
|
163
|
+
const notNow = (a) => say({ ...results(a), stats: declineShare(a.stats) }, `Not sent. You will be asked again at ${next} games.`);
|
|
164
|
+
return {
|
|
165
|
+
title: `You won, and that makes ${n(total)} games!`,
|
|
166
|
+
lines: [
|
|
167
|
+
'Send your results to Klondike research?',
|
|
168
|
+
`${n(Math.min(unsent(app.stats).length, MAX_BATCH))} games: seed, mode, result, time, moves.`,
|
|
169
|
+
'Nothing about you or your computer is sent.',
|
|
170
|
+
`Not now asks again at ${next}, with all games.`,
|
|
171
|
+
],
|
|
172
|
+
choices: [
|
|
173
|
+
{ label: 'Send', act: (a) => say({ ...results(a), stats: acceptShare(a.stats) }, 'Thank you! Sending your results...') },
|
|
174
|
+
{ label: 'Not now', act: notNow },
|
|
175
|
+
],
|
|
176
|
+
cancel: notNow,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
/** The choices after a proven loss, saying how far back it may have been lost when that is more than one move. */
|
|
180
|
+
function lostSpec(app) {
|
|
181
|
+
const since = app.history.length - (app.lastWinnable?.history.length ?? 0);
|
|
182
|
+
const playOn = (a) => ({ ...close(a), playingOn: true, message: 'Playing on. This deal can no longer be won.' });
|
|
183
|
+
const culprit = culpritOf(app);
|
|
184
|
+
const proven = culprit === undefined ? undefined : app.culprits.get(culprit);
|
|
185
|
+
const blame = proven === true ? ['The move that lost it is blocked from now on.'] : proven === false ? ['Going that way again will be warned about first.'] : [];
|
|
186
|
+
return {
|
|
187
|
+
title: 'No way to win from here',
|
|
188
|
+
lines: [...(since <= 1 ? ['Win chance is now 0%. Try again?'] : [`It was lost within the last ${since} moves.`, 'Going back goes to just before them.']), ...blame],
|
|
189
|
+
choices: [
|
|
190
|
+
{ label: 'Back to the last winnable spot', act: backToWinnable },
|
|
191
|
+
{ label: 'Restart this deal', act: restart },
|
|
192
|
+
{ label: 'New deal', act: (a, now, dealer) => newGame(a, dealer, now) },
|
|
193
|
+
{ label: 'Play on', act: playOn },
|
|
194
|
+
{ label: 'Quit (your game is kept)', act: quitNow },
|
|
195
|
+
],
|
|
196
|
+
cancel: playOn,
|
|
197
|
+
danger: true,
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
/** A seed was asked for on the command line while a game was kept. */
|
|
201
|
+
function seedSpec(app) {
|
|
202
|
+
const offer = app.seedOffer;
|
|
203
|
+
const keep = (a) => ({ ...close(a), seedOffer: undefined, message: WELCOME_BACK });
|
|
204
|
+
return {
|
|
205
|
+
title: 'A game is in progress',
|
|
206
|
+
lines: offer ? [`You asked for seed ${offer.seed}, Draw ${offer.drawMode}.`, 'Giving up the kept game counts as a loss.'] : [],
|
|
207
|
+
choices: [
|
|
208
|
+
{ label: 'Carry on with the kept game', act: keep },
|
|
209
|
+
{ label: offer ? `Give up and play seed ${offer.seed}` : 'Give up', act: (a, now) => (a.seedOffer ? playSeed({ ...close(a), seedOffer: undefined }, a.seedOffer.seed, a.seedOffer.drawMode, now) : keep(a)) },
|
|
210
|
+
],
|
|
211
|
+
cancel: keep,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
function confirmSpec(kind) {
|
|
215
|
+
return kind === 'restart'
|
|
216
|
+
? {
|
|
217
|
+
title: 'Restart this deal?',
|
|
218
|
+
lines: ['Every move so far will be undone.'],
|
|
219
|
+
choices: [{ label: 'Restart', act: restart }, keepPlaying],
|
|
220
|
+
cancel: carryOn,
|
|
221
|
+
}
|
|
222
|
+
: {
|
|
223
|
+
title: 'Give up this game?',
|
|
224
|
+
lines: ['A new deal replaces this one. It counts as a loss.'],
|
|
225
|
+
choices: [{ label: 'Give up and deal a new game', act: (a, now, dealer) => newGame(a, dealer, now) }, keepPlaying],
|
|
226
|
+
cancel: carryOn,
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
/** ? when a hint is there to give: asked first, since seeing it is a choice. */
|
|
230
|
+
function hintSpec() {
|
|
231
|
+
return {
|
|
232
|
+
title: 'Show a hint?',
|
|
233
|
+
lines: ['The solver will show its next move toward a win.'],
|
|
234
|
+
choices: [{ label: 'Show the hint', act: (a) => showHint(close(a)) }, keepPlaying],
|
|
235
|
+
cancel: carryOn,
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
/** The question x asks; a finished game has nothing to keep. */
|
|
239
|
+
function quitSpec(app) {
|
|
240
|
+
return {
|
|
241
|
+
title: 'Quit soliterminal?',
|
|
242
|
+
lines: [app.finishedAt === undefined ? 'Your game is kept: run soliterminal to carry on.' : 'See you next time.'],
|
|
243
|
+
choices: [{ label: 'Quit', act: quitNow }, keepPlaying],
|
|
244
|
+
cancel: carryOn,
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
function specOf(app) {
|
|
248
|
+
switch (app.dialog) {
|
|
249
|
+
case undefined:
|
|
250
|
+
return undefined;
|
|
251
|
+
case 'quit':
|
|
252
|
+
return quitSpec(app);
|
|
253
|
+
case 'hint':
|
|
254
|
+
return hintSpec();
|
|
255
|
+
case 'menu':
|
|
256
|
+
return menuSpec(app);
|
|
257
|
+
case 'won':
|
|
258
|
+
return wonSpec(app);
|
|
259
|
+
case 'share':
|
|
260
|
+
return shareSpec(app);
|
|
261
|
+
case 'lost':
|
|
262
|
+
return lostSpec(app);
|
|
263
|
+
case 'seed':
|
|
264
|
+
return seedSpec(app);
|
|
265
|
+
case 'restart':
|
|
266
|
+
case 'new':
|
|
267
|
+
return confirmSpec(app.dialog);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
/** The dialog as the screen draws it. */
|
|
271
|
+
function dialogView(app) {
|
|
272
|
+
const spec = specOf(app);
|
|
273
|
+
if (!spec)
|
|
274
|
+
return undefined;
|
|
275
|
+
const choice = Math.min(app.choice, spec.choices.length - 1);
|
|
276
|
+
return { title: spec.title, lines: spec.lines, choices: spec.choices.map((c) => c.label), selected: choice, ...(spec.danger ? { danger: true } : {}) };
|
|
277
|
+
}
|
|
278
|
+
export function viewOf(app, now) {
|
|
279
|
+
const elapsedMs = playTime(app, now);
|
|
280
|
+
const warning = app.dialog ? undefined : heldWarning(app);
|
|
281
|
+
return {
|
|
282
|
+
danger: warning === undefined ? undefined : { message: app.message.includes(warning) },
|
|
283
|
+
tight: noSlack(app) || undefined,
|
|
284
|
+
cursor: app.cursor,
|
|
285
|
+
selected: app.selected,
|
|
286
|
+
held: app.held,
|
|
287
|
+
message: app.message,
|
|
288
|
+
elapsedMs,
|
|
289
|
+
paused: app.pausedAt !== undefined,
|
|
290
|
+
record: statsFor(app.stats, app.game.drawMode),
|
|
291
|
+
lostBefore: pastGame(app.stats, app.game.seed, app.game.drawMode, 'lost')?.at,
|
|
292
|
+
status: app.status,
|
|
293
|
+
dialog: dialogView(app),
|
|
294
|
+
// The confetti keeps falling behind the results until they are put away.
|
|
295
|
+
celebration: (app.celebrating || afterWin(app)) && app.finishedAt !== undefined ? now - app.finishedAt : undefined,
|
|
296
|
+
// Once it has run, the board stays faded behind the dialog.
|
|
297
|
+
defeat: app.defeat && app.dialog === 'lost' ? (app.defeat.done ? DEFEAT_MS : Math.min(DEFEAT_MS, Math.max(0, now - app.defeat.at))) : undefined,
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
// ---------------------------------------------------------------------------
|
|
301
|
+
// Words
|
|
302
|
+
const pileName = (p) => p.kind === 'waste' ? 'the waste' : p.kind === 'tableau' ? `column ${p.index + 1}` : keyLabel(p);
|
|
303
|
+
/** The card that leads a move from `from`: the bottom of the run being moved. */
|
|
304
|
+
function leadCard(app, from, count = 1) {
|
|
305
|
+
const cards = cardsIn(app.game, from);
|
|
306
|
+
const card = cards[cards.length - Math.max(1, count)];
|
|
307
|
+
return card ? cardName(card, app.ascii) : pileName(from);
|
|
308
|
+
}
|
|
309
|
+
function explain(app, error, from, to) {
|
|
310
|
+
const held = app.held;
|
|
311
|
+
const lead = leadCard(app, from);
|
|
312
|
+
switch (error) {
|
|
313
|
+
case 'empty-source':
|
|
314
|
+
return from.kind === 'waste' ? `The waste is empty. Press ${STOCK_KEY} to draw.` : `Nothing to move from ${pileName(from)}.`;
|
|
315
|
+
case 'stock-empty':
|
|
316
|
+
return 'The stock and the waste are both empty.';
|
|
317
|
+
case 'no-redeals':
|
|
318
|
+
return 'No redeals left: the waste cannot be turned over again.';
|
|
319
|
+
case 'bad-count':
|
|
320
|
+
return 'Those cards cannot move together.';
|
|
321
|
+
case 'same-pile':
|
|
322
|
+
case 'no-move':
|
|
323
|
+
return `${lead} has nowhere to go right now.`;
|
|
324
|
+
case 'wrong-foundation': {
|
|
325
|
+
const card = cardsIn(app.game, from).at(-1);
|
|
326
|
+
const home = card === undefined ? undefined : foundationFor(app.game, card);
|
|
327
|
+
const where = home === undefined ? 'another foundation' : keyLabel(pile.foundation(home));
|
|
328
|
+
return `${lead} goes on ${where}. Press ${keyLabel({ kind: 'auto-foundation' })} to send it there.`;
|
|
329
|
+
}
|
|
330
|
+
case 'not-allowed':
|
|
331
|
+
if (to?.kind === 'tableau' && from.kind === 'tableau' && held) {
|
|
332
|
+
return `Nothing in ${pileName(from)} fits on ${pileName(to)}.`;
|
|
333
|
+
}
|
|
334
|
+
if (to === undefined || to.kind === 'foundation')
|
|
335
|
+
return `${lead} cannot go to a foundation yet.`;
|
|
336
|
+
return `${lead} cannot go on ${pileName(to)}.`;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
// ---------------------------------------------------------------------------
|
|
340
|
+
// State changes
|
|
341
|
+
const say = (app, message) => ({ ...app, message });
|
|
342
|
+
/** On the winning move: stop the clock, count the win once, and start the ceremony. */
|
|
343
|
+
function winIfDone(app, now) {
|
|
344
|
+
if (!isWon(app.game) || app.finishedAt !== undefined)
|
|
345
|
+
return app;
|
|
346
|
+
const ms = playTime(app, now);
|
|
347
|
+
let { stats, play, lastWin, outbox } = app;
|
|
348
|
+
if (play !== 'won') {
|
|
349
|
+
const id = { id: app.gameId, seed: app.game.seed, at: app.gameAt ?? now, limit: dealLimit(app) };
|
|
350
|
+
const r = recordWin(stats, app.game.drawMode, ms, app.game.moves, { ...id, redeals: redealsUsed([...app.history, app.game]) });
|
|
351
|
+
stats = r.stats;
|
|
352
|
+
lastWin = r.record;
|
|
353
|
+
outbox = [...outbox, { game: r.game }];
|
|
354
|
+
play = 'won';
|
|
355
|
+
}
|
|
356
|
+
return {
|
|
357
|
+
...app,
|
|
358
|
+
finishedAt: now,
|
|
359
|
+
status: 'winnable',
|
|
360
|
+
stats,
|
|
361
|
+
outbox,
|
|
362
|
+
play,
|
|
363
|
+
lastWin,
|
|
364
|
+
celebrating: true,
|
|
365
|
+
held: undefined,
|
|
366
|
+
message: `You won! ${app.game.moves} moves in ${formatTime(ms)}.`,
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
/** Redeals the deal allowed: what it started with, before any were used. */
|
|
370
|
+
const dealLimit = (app) => (app.history[0] ?? app.game).redealsLeft;
|
|
371
|
+
/** The background's rating of a finished game's deal. */
|
|
372
|
+
export function applyRating(app, id, level) {
|
|
373
|
+
return { ...app, stats: withLevel(app.stats, id, level), outbox: [...app.outbox, { level: { id, level } }] };
|
|
374
|
+
}
|
|
375
|
+
/** How many times the waste was turned over along the way: undone redeals do not count. */
|
|
376
|
+
export function redealsUsed(states) {
|
|
377
|
+
let n = 0;
|
|
378
|
+
for (let i = 1; i < states.length; i++)
|
|
379
|
+
if (states[i - 1].stock.length === 0 && states[i].stock.length > 0)
|
|
380
|
+
n++;
|
|
381
|
+
return n;
|
|
382
|
+
}
|
|
383
|
+
/** Time on the clock: from the first move, less any time the terminal was out of focus. */
|
|
384
|
+
export function playTime(app, now) {
|
|
385
|
+
if (app.startedAt === undefined)
|
|
386
|
+
return 0;
|
|
387
|
+
const end = app.finishedAt ?? app.pausedAt ?? now;
|
|
388
|
+
return Math.max(0, end - app.startedAt - app.pausedMs);
|
|
389
|
+
}
|
|
390
|
+
/** The terminal lost focus: stop the clock. */
|
|
391
|
+
function blur(app, now) {
|
|
392
|
+
return app.pausedAt === undefined ? { ...app, pausedAt: now } : app;
|
|
393
|
+
}
|
|
394
|
+
/** Focus is back: start the clock again, leaving out the time away. */
|
|
395
|
+
function focus(app, now) {
|
|
396
|
+
if (app.pausedAt === undefined)
|
|
397
|
+
return app;
|
|
398
|
+
// Before the first move there is no clock running yet to make up for.
|
|
399
|
+
const away = app.startedAt === undefined ? 0 : now - Math.max(app.pausedAt, app.startedAt);
|
|
400
|
+
return { ...app, pausedAt: undefined, pausedMs: app.pausedMs + away };
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Ends the ceremony and shows the results; first, when a new hundred games
|
|
404
|
+
* is reached and a server takes them, the question about sharing them. A win
|
|
405
|
+
* is the time to ask, never the middle of a game or the start of one.
|
|
406
|
+
*/
|
|
407
|
+
function endCeremony(app) {
|
|
408
|
+
const ask = app.canShare && shareDue(app.stats);
|
|
409
|
+
return { ...app, celebrating: false, dialog: ask ? 'share' : 'won' };
|
|
410
|
+
}
|
|
411
|
+
/** Right after a win: the results, or the question before them. The confetti keeps falling behind both. */
|
|
412
|
+
const afterWin = (app) => app.finishedAt !== undefined && (app.dialog === 'won' || app.dialog === 'share');
|
|
413
|
+
/**
|
|
414
|
+
* Leaving this play of the deal unfinished ends the win streak: it goes on
|
|
415
|
+
* record as a loss. Quitting does not, since the game is kept for later.
|
|
416
|
+
*/
|
|
417
|
+
export function abandon(app, now = Date.now()) {
|
|
418
|
+
if (app.play !== 'counted')
|
|
419
|
+
return app;
|
|
420
|
+
const r = recordLoss(app.stats, app.game.drawMode, gameEnd(app, now));
|
|
421
|
+
return { ...app, stats: r.stats, outbox: [...app.outbox, { game: r.game }], play: 'fresh' };
|
|
422
|
+
}
|
|
423
|
+
/** How this play stands for the record if it ends now. */
|
|
424
|
+
function gameEnd(app, now) {
|
|
425
|
+
// A loss proven while playing says which move lost it: the one after the last winnable position.
|
|
426
|
+
const lostAt = app.status === 'lost' ? (app.lastWinnable ? app.lastWinnable.history.length + 1 : 0) : undefined;
|
|
427
|
+
return { id: app.gameId, seed: app.game.seed, ms: Math.round(playTime(app, now)), moves: app.game.moves, at: app.gameAt ?? now, limit: dealLimit(app), lostAt };
|
|
428
|
+
}
|
|
429
|
+
/** A new position: the solver's earlier answer no longer applies. */
|
|
430
|
+
function moved(app, game, history, now) {
|
|
431
|
+
return recall({
|
|
432
|
+
...app,
|
|
433
|
+
game,
|
|
434
|
+
history,
|
|
435
|
+
version: app.version + 1,
|
|
436
|
+
status: 'checking',
|
|
437
|
+
dialog: undefined,
|
|
438
|
+
defeat: undefined,
|
|
439
|
+
culpritWarned: undefined,
|
|
440
|
+
held: undefined,
|
|
441
|
+
stall: stallFrom(game),
|
|
442
|
+
stalled: false,
|
|
443
|
+
}, now);
|
|
444
|
+
}
|
|
445
|
+
/** Adds a settled answer to what is known. `unclear` settles nothing. */
|
|
446
|
+
function remember(app, game, verdict, next) {
|
|
447
|
+
if (verdict === 'unclear')
|
|
448
|
+
return app;
|
|
449
|
+
const key = positionKey(game);
|
|
450
|
+
const known = new Map(app.known);
|
|
451
|
+
known.set(key, { verdict, next });
|
|
452
|
+
// A culprit only suspected so far, now proven: from here on it is blocked.
|
|
453
|
+
if (verdict === 'lost' && app.culprits.get(key) === false)
|
|
454
|
+
return withCulprits({ ...app, known }, [{ key, proven: true }], true);
|
|
455
|
+
return { ...app, known };
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Adds culprits: found here (`fresh`, so the runner writes them out), or read
|
|
459
|
+
* from another window on the same deal. Proven wins over suspected.
|
|
460
|
+
*/
|
|
461
|
+
export function withCulprits(app, culprits, fresh = false) {
|
|
462
|
+
const added = culprits.filter((c) => {
|
|
463
|
+
const had = app.culprits.get(c.key);
|
|
464
|
+
return had === undefined || (c.proven && !had);
|
|
465
|
+
});
|
|
466
|
+
if (added.length === 0)
|
|
467
|
+
return app;
|
|
468
|
+
const map = new Map(app.culprits);
|
|
469
|
+
for (const c of added)
|
|
470
|
+
map.set(c.key, c.proven || map.get(c.key) === true);
|
|
471
|
+
return { ...app, culprits: map, culpritOutbox: fresh ? [...app.culpritOutbox, ...added] : app.culpritOutbox };
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* Where the move that lost the game led: the position right after the last
|
|
475
|
+
* winnable one (or after the deal, when none was proven). Undefined when the
|
|
476
|
+
* last winnable position is no longer on the way here.
|
|
477
|
+
*/
|
|
478
|
+
function culpritOf(app) {
|
|
479
|
+
const states = [...app.history, app.game];
|
|
480
|
+
const w = app.lastWinnable;
|
|
481
|
+
const from = w === undefined ? 0 : states[w.history.length] === w.game ? w.history.length : undefined;
|
|
482
|
+
const to = from === undefined ? undefined : states[from + 1];
|
|
483
|
+
return to && positionKey(to);
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* A move into a position a move lost the game in before: proven, it is
|
|
487
|
+
* refused; only suspected, it is refused once with a warning, then allowed.
|
|
488
|
+
* The cards stay in hand either way, so another place can be tried.
|
|
489
|
+
*/
|
|
490
|
+
function blocked(app, after) {
|
|
491
|
+
const key = positionKey(after);
|
|
492
|
+
const proven = app.culprits.get(key);
|
|
493
|
+
if (proven === true)
|
|
494
|
+
return say(app, 'This move lost the game last time, so it is blocked. Try another.');
|
|
495
|
+
if (proven === false && app.culpritWarned !== key) {
|
|
496
|
+
return { ...app, culpritWarned: key, message: 'The game was lost after this move last time. Do it again to go ahead anyway.' };
|
|
497
|
+
}
|
|
498
|
+
return undefined;
|
|
499
|
+
}
|
|
500
|
+
/** The same position with one redeal fewer: if that cannot be won, the win needs every redeal left. */
|
|
501
|
+
function oneRedealLess(game) {
|
|
502
|
+
return Number.isFinite(game.redealsLeft) && game.redealsLeft > 0 ? { ...game, redealsLeft: game.redealsLeft - 1 } : undefined;
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* The position to judge to find out whether a winnable game has any redeal to
|
|
506
|
+
* spare, while that is not known yet. Its answer goes in through `applyAhead`.
|
|
507
|
+
*/
|
|
508
|
+
export function slackCheck(app) {
|
|
509
|
+
if (app.status !== 'winnable')
|
|
510
|
+
return undefined;
|
|
511
|
+
const less = oneRedealLess(app.game);
|
|
512
|
+
return less && !app.known.has(positionKey(less)) ? less : undefined;
|
|
513
|
+
}
|
|
514
|
+
/** Winnable, but only by using every redeal left: one more wasted trip through the stock loses. */
|
|
515
|
+
function noSlack(app) {
|
|
516
|
+
const less = app.status === 'winnable' ? oneRedealLess(app.game) : undefined;
|
|
517
|
+
return less !== undefined && app.known.get(positionKey(less))?.verdict === 'lost';
|
|
518
|
+
}
|
|
519
|
+
/** A position already settled is answered at once: no solver, no wait. */
|
|
520
|
+
function recall(app, now) {
|
|
521
|
+
const k = app.known.get(positionKey(app.game));
|
|
522
|
+
if (!k)
|
|
523
|
+
return app;
|
|
524
|
+
return k.verdict === 'winnable' ? settleWinnable(app, k.next) : lose({ ...app, suspect: undefined }, now);
|
|
525
|
+
}
|
|
526
|
+
/** The current position is proven winnable. */
|
|
527
|
+
function settleWinnable(app, next) {
|
|
528
|
+
return {
|
|
529
|
+
...app,
|
|
530
|
+
status: 'winnable',
|
|
531
|
+
playingOn: false,
|
|
532
|
+
// Winnable now means winnable at every step on the way here: nothing left to suspect.
|
|
533
|
+
suspect: undefined,
|
|
534
|
+
lastWinnable: { game: app.game, history: app.history },
|
|
535
|
+
hint: next && { version: app.version, move: next },
|
|
536
|
+
message: app.stalled ? STALLED : app.message,
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* A warning when the cards in hand have a known losing place to go. Which
|
|
541
|
+
* place is not said: the choice stays the player's.
|
|
542
|
+
*/
|
|
543
|
+
function heldWarning(app) {
|
|
544
|
+
const held = app.held;
|
|
545
|
+
if (!held)
|
|
546
|
+
return undefined;
|
|
547
|
+
const results = destinations(app.game, held.from, held.count).map((to) => place(app.game, held, to));
|
|
548
|
+
const ends = results.flatMap((r) => (r.ok ? [app.known.get(positionKey(r.state))?.verdict] : []));
|
|
549
|
+
const lost = ends.filter((v) => v === 'lost').length;
|
|
550
|
+
if (lost === 0)
|
|
551
|
+
return undefined;
|
|
552
|
+
if (lost === ends.length)
|
|
553
|
+
return 'Careful: wherever it goes, the game is lost.';
|
|
554
|
+
return ends.length === 2 ? 'Careful: one of its two places loses the game.' : 'Careful: one place it can go loses the game.';
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* Applies a game result. On success the old state goes on the undo stack and
|
|
558
|
+
* the held cards are dropped. On failure the cards stay in hand so the player
|
|
559
|
+
* can try another destination straight away.
|
|
560
|
+
*/
|
|
561
|
+
function commit(app, result, now, onError, isDraw = false) {
|
|
562
|
+
if (!result.ok)
|
|
563
|
+
return say(app, onError(result.error));
|
|
564
|
+
const refused = blocked(app, result.state);
|
|
565
|
+
if (refused)
|
|
566
|
+
return refused;
|
|
567
|
+
// The first card moved makes this a played game. Drawing alone only looks through the stock,
|
|
568
|
+
// and moves in a game already lost and played on do not start a new one.
|
|
569
|
+
const counting = app.play === 'fresh' && !isDraw && !app.playingOn;
|
|
570
|
+
const base = counting ? { ...app, play: 'counted', gameAt: app.gameAt ?? now } : app;
|
|
571
|
+
// The cursor stays where the cards came from: the card turned up there, or the next one in the waste, is usually what comes next.
|
|
572
|
+
let next = {
|
|
573
|
+
...moved(base, result.state, [...app.history, app.game], now),
|
|
574
|
+
startedAt: app.startedAt ?? now,
|
|
575
|
+
};
|
|
576
|
+
// A move straight into a known loss keeps the dialog's empty line; any other clears the last message.
|
|
577
|
+
if (next.status !== 'lost')
|
|
578
|
+
next = { ...next, message: '' };
|
|
579
|
+
if (canAutoComplete(next.game)) {
|
|
580
|
+
next = {
|
|
581
|
+
...next,
|
|
582
|
+
status: 'winnable',
|
|
583
|
+
autoQueue: autoComplete(next.game),
|
|
584
|
+
message: 'Every card is face up. Finishing the game...',
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
return winIfDone(next, now);
|
|
588
|
+
}
|
|
589
|
+
/** Puts held cards on `to`: exactly `count` of them if set, otherwise the count that fits. */
|
|
590
|
+
function place(game, held, to) {
|
|
591
|
+
if (held.count === undefined || (held.count === 1 && to.kind === 'foundation'))
|
|
592
|
+
return moveTo(game, held.from, to);
|
|
593
|
+
return move(game, held.from, to, held.count);
|
|
594
|
+
}
|
|
595
|
+
/** "7♥", or "7♥ and the 2 cards on it". */
|
|
596
|
+
function runName(app, from, count) {
|
|
597
|
+
const lead = leadCard(app, from, count);
|
|
598
|
+
return count <= 1 ? lead : `${lead} and the ${count === 2 ? 'card' : `${count - 1} cards`} on it`;
|
|
599
|
+
}
|
|
600
|
+
function pick(app, from, count) {
|
|
601
|
+
const max = maxTake(app.game, from);
|
|
602
|
+
if (max === 0)
|
|
603
|
+
return say(app, explain(app, 'empty-source', from));
|
|
604
|
+
// A foundation key leaves the cursor where it is; the arrows may have put it on the foundation already.
|
|
605
|
+
const cursor = from.kind === 'foundation' ? app.cursor : from;
|
|
606
|
+
const exact = count !== undefined && from.kind === 'tableau' ? Math.min(count, max) : undefined;
|
|
607
|
+
const what = exact !== undefined ? runName(app, from, exact) : max > 1 ? pileName(from) : leadCard(app, from);
|
|
608
|
+
const next = { ...app, cursor, held: { from, count: exact } };
|
|
609
|
+
return { ...next, message: `Holding ${what}. ${heldWarning(next) ?? 'Where does it go?'}` };
|
|
610
|
+
}
|
|
611
|
+
function drop(app, to, now) {
|
|
612
|
+
const held = app.held;
|
|
613
|
+
if (samePile(held.from, to))
|
|
614
|
+
return autoFrom(app, held.from, now, held.count);
|
|
615
|
+
return commit(app, place(app.game, held, to), now, (e) => explain(app, e, held.from, to));
|
|
616
|
+
}
|
|
617
|
+
function drawCard(app, now) {
|
|
618
|
+
const cleared = { ...app, held: undefined };
|
|
619
|
+
const next = commit(cleared, draw(app.game), now, (e) => explain(cleared, e, pile.waste), true);
|
|
620
|
+
// A freshly turned card is usually the next thing to play, so the cursor follows it.
|
|
621
|
+
// Recycling the waste leaves nothing there, so the cursor stays put. Drawing
|
|
622
|
+
// with the cursor on the stock keeps it there, so space can draw again.
|
|
623
|
+
const turned = next.game !== app.game && next.game.waste.length > 0;
|
|
624
|
+
if (!turned)
|
|
625
|
+
return next;
|
|
626
|
+
const g = next.game;
|
|
627
|
+
const out = g.stock.length === 0 && Number.isFinite(g.redealsLeft);
|
|
628
|
+
const left = g.redealsLeft === 1 ? '1 redeal left' : `${g.redealsLeft} redeals left`;
|
|
629
|
+
return {
|
|
630
|
+
...next,
|
|
631
|
+
cursor: app.cursor.kind === 'stock' ? app.cursor : pile.waste,
|
|
632
|
+
message: out ? `The stock is out. ${g.redealsLeft === 0 ? 'No redeals left.' : `${left}.`}` : next.message,
|
|
633
|
+
};
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* Keeps track of drawing since the last real move. The player is stalled once
|
|
637
|
+
* the waste has been turned over and has grown back to where it was, so every
|
|
638
|
+
* talon card has been on top since, or once a draw fails: the stock is out and
|
|
639
|
+
* cannot be turned again, so it has nothing left to show.
|
|
640
|
+
*/
|
|
641
|
+
function watchStall(before, after) {
|
|
642
|
+
if (after.finishedAt !== undefined || after.autoQueue.length > 0)
|
|
643
|
+
return after;
|
|
644
|
+
const s = before.stall;
|
|
645
|
+
let stall = s;
|
|
646
|
+
let stalled = before.stalled;
|
|
647
|
+
if (after.game !== before.game) {
|
|
648
|
+
stall = { ...s, redealt: s.redealt || before.game.stock.length === 0 };
|
|
649
|
+
stalled ||= stall.redealt && after.game.waste.length >= s.waste;
|
|
650
|
+
}
|
|
651
|
+
else {
|
|
652
|
+
stalled = true;
|
|
653
|
+
}
|
|
654
|
+
const next = { ...after, stall, stalled };
|
|
655
|
+
// Said as soon as the solver agrees there is a way on; see applyVerdict.
|
|
656
|
+
if (stalled && !before.stalled && next.status === 'winnable')
|
|
657
|
+
return { ...next, message: STALLED };
|
|
658
|
+
return next;
|
|
659
|
+
}
|
|
660
|
+
/** The solver's next move toward a win, whenever the player asks for it. */
|
|
661
|
+
function showHint(app) {
|
|
662
|
+
if (app.status === 'checking')
|
|
663
|
+
return say(app, 'Still checking this position. Ask again in a moment.');
|
|
664
|
+
const move = app.hint?.version === app.version ? app.hint.move : undefined;
|
|
665
|
+
if (app.status !== 'winnable' || !move)
|
|
666
|
+
return say(app, 'No hint here: a win from this position is not confirmed.');
|
|
667
|
+
const g = app.game;
|
|
668
|
+
const card = cardName(move.card, app.ascii);
|
|
669
|
+
const to = move.to.kind === 'foundation'
|
|
670
|
+
? `its foundation (${keyLabel({ kind: 'auto-foundation' })})`
|
|
671
|
+
: `${pileName(pile.tableau(move.to.index))} (${keyLabel(pile.tableau(move.to.index))})`;
|
|
672
|
+
const base = { ...app, held: undefined };
|
|
673
|
+
switch (move.from.kind) {
|
|
674
|
+
case 'talon': {
|
|
675
|
+
const message = sameCard(g.waste.at(-1), move.card)
|
|
676
|
+
? `Hint: ${card} from the waste (${keyLabel(pile.waste)}) to ${to}.`
|
|
677
|
+
: `Hint: draw until ${card} is on the waste, then play it to ${to}.`;
|
|
678
|
+
return { ...base, cursor: pile.waste, message };
|
|
679
|
+
}
|
|
680
|
+
case 'tableau': {
|
|
681
|
+
const from = pile.tableau(move.from.index);
|
|
682
|
+
const message = `Hint: ${runName(app, from, move.count)} from ${pileName(from)} (${keyLabel(from)}) to ${to}.`;
|
|
683
|
+
// Part of a run: choose just those cards, so space picks up the right ones.
|
|
684
|
+
const part = move.count < maxTake(g, from) ? move.count : undefined;
|
|
685
|
+
return { ...base, cursor: from, selected: part, message };
|
|
686
|
+
}
|
|
687
|
+
case 'foundation': {
|
|
688
|
+
const f = g.foundations.findIndex((p) => sameCard(p.at(-1), move.card));
|
|
689
|
+
const key = f < 0 ? '' : ` (${keyLabel(pile.foundation(f))})`;
|
|
690
|
+
return { ...base, message: `Hint: take ${card} back down from its foundation${key} to ${to}.` };
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
/** ?: asks before showing a hint, when there is one to show; otherwise says why not. */
|
|
695
|
+
function askHint(app) {
|
|
696
|
+
const ready = app.status === 'winnable' && app.hint?.version === app.version;
|
|
697
|
+
return ready ? { ...app, held: undefined, dialog: 'hint' } : showHint(app);
|
|
698
|
+
}
|
|
699
|
+
/** Sends cards to the best spot: exactly `count` of them if given, else whatever fits. */
|
|
700
|
+
function autoFrom(app, from, now, count) {
|
|
701
|
+
if (count === undefined)
|
|
702
|
+
return commit(app, autoMove(app.game, from), now, (e) => explain(app, e, from));
|
|
703
|
+
const to = destinations(app.game, from, count)[0];
|
|
704
|
+
if (!to)
|
|
705
|
+
return say(app, `${runName(app, from, count)} ${count > 1 ? 'have' : 'has'} nowhere to go right now.`);
|
|
706
|
+
return commit(app, move(app.game, from, to, count), now, () => '');
|
|
707
|
+
}
|
|
708
|
+
function toFoundation(app, now) {
|
|
709
|
+
const from = app.held?.from ?? (app.cursor.kind === 'stock' ? pile.waste : app.cursor);
|
|
710
|
+
return commit(app, moveToFoundation(app.game, from), now, (e) => explain(app, e, from, pile.foundation(0)));
|
|
711
|
+
}
|
|
712
|
+
function fresh(app, game, verified, message) {
|
|
713
|
+
const next = createApp(game, { ascii: app.ascii, compact: app.compact, verified, redeals: app.redeals, stats: app.stats, canShare: app.canShare });
|
|
714
|
+
return { ...next, outbox: app.outbox, version: app.version + 1, nextDrawMode: app.nextDrawMode, message };
|
|
715
|
+
}
|
|
716
|
+
/** Another deal in place of this one, which goes on record as a loss if it was under way. `first` opens its greeting. */
|
|
717
|
+
function startDeal(app, seed, drawMode, verified, first, now) {
|
|
718
|
+
const left = abandon(app, now);
|
|
719
|
+
return { ...fresh(left, deal(seed, drawMode, app.redeals), verified, greeting(left, seed, drawMode, first)), nextDrawMode: drawMode };
|
|
720
|
+
}
|
|
721
|
+
function newGame(app, dealer, now, drawMode = app.nextDrawMode) {
|
|
722
|
+
const { seed, verified } = dealer(drawMode);
|
|
723
|
+
return startDeal(app, seed, drawMode, verified, 'New game.', now);
|
|
724
|
+
}
|
|
725
|
+
/**
|
|
726
|
+
* The same deal from the start. An unfinished game carries on as the same
|
|
727
|
+
* play in the statistics; after a win it is a new one.
|
|
728
|
+
*/
|
|
729
|
+
function restart(app, now) {
|
|
730
|
+
// The same deal goes through the same positions: what is known about them, and what lost it, still holds.
|
|
731
|
+
const start = fresh(app, deal(app.game.seed, app.game.drawMode, app.redeals), app.verified, 'Same deal, from the start.');
|
|
732
|
+
const next = recall({ ...start, known: app.known, culprits: app.culprits, culpritOutbox: app.culpritOutbox }, now);
|
|
733
|
+
return app.play === 'counted' ? { ...next, play: 'counted', gameId: app.gameId, ...(app.gameAt === undefined ? {} : { gameAt: app.gameAt }) } : next;
|
|
734
|
+
}
|
|
735
|
+
/** Restart, after asking; not before a move, and not once the deal is won. */
|
|
736
|
+
function askRestart(app) {
|
|
737
|
+
if (app.game.moves === 0 && app.history.length === 0)
|
|
738
|
+
return say(app, 'This deal is already at the start.');
|
|
739
|
+
// A deal won stays won: it is not played again.
|
|
740
|
+
if (app.play === 'won')
|
|
741
|
+
return say(app, 'This deal is won. Choose New game in the menu.');
|
|
742
|
+
return { ...app, held: undefined, dialog: 'restart' };
|
|
743
|
+
}
|
|
744
|
+
/** A deal proven winnable in one mode may not be in the other, so an untouched deal is replaced; else the next deal switches. */
|
|
745
|
+
function switchDraw(app, dealer, now) {
|
|
746
|
+
const nextDrawMode = app.nextDrawMode === 1 ? 3 : 1;
|
|
747
|
+
if (untouched(app) && app.finishedAt === undefined)
|
|
748
|
+
return { ...newGame(app, dealer, now, nextDrawMode), message: `Draw ${nextDrawMode}.` };
|
|
749
|
+
return { ...app, nextDrawMode, message: `Draw ${nextDrawMode} from the next game.` };
|
|
750
|
+
}
|
|
751
|
+
function backToWinnable(app, now) {
|
|
752
|
+
const snap = app.lastWinnable;
|
|
753
|
+
if (!snap)
|
|
754
|
+
return restart(app, now);
|
|
755
|
+
return {
|
|
756
|
+
...moved(app, snap.game, snap.history, now),
|
|
757
|
+
status: 'winnable',
|
|
758
|
+
playingOn: false,
|
|
759
|
+
message: 'Back to the last winnable position.',
|
|
760
|
+
};
|
|
761
|
+
}
|
|
762
|
+
const STOCK = { kind: 'stock' };
|
|
763
|
+
/** The top row, left to right: stock, waste, then the foundations over columns 4 to 7. */
|
|
764
|
+
const TOP_ROW = [STOCK, pile.waste, ...Array.from({ length: 4 }, (_, i) => pile.foundation(i))];
|
|
765
|
+
/** What is straight above each column. Nothing is above column 3, so it goes to the waste, the nearest. */
|
|
766
|
+
const ABOVE = [STOCK, pile.waste, pile.waste, ...TOP_ROW.slice(2)];
|
|
767
|
+
/** The column straight below each place in the top row. */
|
|
768
|
+
const BELOW = [0, 1, 3, 4, 5, 6];
|
|
769
|
+
const sameSpot = (a, b) => a.kind === 'stock' || b.kind === 'stock' ? a.kind === b.kind : samePile(a, b);
|
|
770
|
+
/**
|
|
771
|
+
* Left and right stay on their row and go round it: the seven columns, or
|
|
772
|
+
* the stock, the waste and the four foundations. Only up and down change rows.
|
|
773
|
+
*/
|
|
774
|
+
function cursorSideways(app, step) {
|
|
775
|
+
const c = app.cursor;
|
|
776
|
+
if (c.kind === 'tableau')
|
|
777
|
+
return { ...app, cursor: pile.tableau((c.index + step + TABLEAU_COLUMNS) % TABLEAU_COLUMNS) };
|
|
778
|
+
const n = TOP_ROW.length;
|
|
779
|
+
const i = TOP_ROW.findIndex((p) => sameSpot(p, c));
|
|
780
|
+
return { ...app, cursor: TOP_ROW[(i + step + n) % n] };
|
|
781
|
+
}
|
|
782
|
+
/**
|
|
783
|
+
* Up goes to whatever is straight above, as on the board. With cards chosen
|
|
784
|
+
* in a column it first walks the choice back up the run, a card at a time;
|
|
785
|
+
* past its first card it leaves the column.
|
|
786
|
+
*/
|
|
787
|
+
function cursorUp(app) {
|
|
788
|
+
const c = app.cursor;
|
|
789
|
+
if (c.kind !== 'tableau')
|
|
790
|
+
return app;
|
|
791
|
+
const max = maxTake(app.game, c);
|
|
792
|
+
if (app.selected !== undefined && app.selected < max)
|
|
793
|
+
return choose(app, c, app.selected + 1);
|
|
794
|
+
return { ...app, cursor: ABOVE[c.index], selected: undefined };
|
|
795
|
+
}
|
|
796
|
+
/** Says which cards are chosen, as down and up move through a run. */
|
|
797
|
+
function choose(app, from, n) {
|
|
798
|
+
return { ...app, selected: n, message: `${runName(app, from, n)}: space picks ${n === 1 ? 'it' : 'them'} up.` };
|
|
799
|
+
}
|
|
800
|
+
/**
|
|
801
|
+
* Down in a column chooses cards down its run: first the whole run, from its
|
|
802
|
+
* top card, then one card fewer each time. From the top row it goes to the
|
|
803
|
+
* column below, or back to the one the cursor came up from.
|
|
804
|
+
*/
|
|
805
|
+
function cursorDown(app) {
|
|
806
|
+
const c = app.cursor;
|
|
807
|
+
if (c.kind === 'tableau') {
|
|
808
|
+
const max = maxTake(app.game, c);
|
|
809
|
+
if (app.held || max <= 1)
|
|
810
|
+
return app;
|
|
811
|
+
return choose(app, c, app.selected === undefined ? max : Math.max(1, app.selected - 1));
|
|
812
|
+
}
|
|
813
|
+
const back = app.cameFrom !== undefined && sameSpot(ABOVE[app.cameFrom], c) ? app.cameFrom : undefined;
|
|
814
|
+
const index = back ?? BELOW[TOP_ROW.findIndex((p) => sameSpot(p, c))];
|
|
815
|
+
return { ...app, cursor: pile.tableau(index) };
|
|
816
|
+
}
|
|
817
|
+
/**
|
|
818
|
+
* Remembers the column whenever the cursor goes from it to the top row,
|
|
819
|
+
* however it got there. Chosen cards are let go once the cursor or the
|
|
820
|
+
* position changes, unless the key chose them afresh.
|
|
821
|
+
*/
|
|
822
|
+
function trackColumn(before, after) {
|
|
823
|
+
let next = after;
|
|
824
|
+
const moved = !sameSpot(before.cursor, after.cursor) || before.version !== after.version || after.held !== undefined;
|
|
825
|
+
if (moved && after.selected !== undefined && after.selected === before.selected)
|
|
826
|
+
next = { ...next, selected: undefined };
|
|
827
|
+
if (next.cursor.kind === 'tableau')
|
|
828
|
+
return next.cameFrom === undefined ? next : { ...next, cameFrom: undefined };
|
|
829
|
+
if (before.cursor.kind === 'tableau')
|
|
830
|
+
return { ...next, cameFrom: before.cursor.index };
|
|
831
|
+
return next;
|
|
832
|
+
}
|
|
833
|
+
/** A particular deal, chosen by seed: not checked first, so the solver judges it as play starts. */
|
|
834
|
+
function playSeed(app, seed, drawMode, now) {
|
|
835
|
+
return startDeal(app, seed, drawMode, false, `Seed ${seed}, Draw ${drawMode}.`, now);
|
|
836
|
+
}
|
|
837
|
+
/** The answer came back from the server: the games sent are marked, or the batch waits for the next start. */
|
|
838
|
+
export function applyShared(app, ids, error) {
|
|
839
|
+
if (error)
|
|
840
|
+
return say(app, `Results not sent: ${error}. Trying again next start.`);
|
|
841
|
+
const stats = markShared(app.stats, ids);
|
|
842
|
+
return say({ ...app, stats, outbox: [...app.outbox, { sent: ids }] }, `Sent ${ids.length.toLocaleString('en-US')} games. Thank you for helping research!`);
|
|
843
|
+
}
|
|
844
|
+
/** The opening line of a deal, saying when it was lost before if it was. */
|
|
845
|
+
function greeting(app, seed, drawMode, first) {
|
|
846
|
+
const lost = pastGame(app.stats, seed, drawMode, 'lost');
|
|
847
|
+
return lost ? `${first} You lost this deal on ${formatWhen(lost.at)}. Revenge?` : `${first} Good luck!`;
|
|
848
|
+
}
|
|
849
|
+
function openDeals(app) {
|
|
850
|
+
return { ...app, held: undefined, deals: { typed: '', index: 0, drawMode: app.nextDrawMode } };
|
|
851
|
+
}
|
|
852
|
+
/** Keys on the deals screen: type a seed or choose a recent game, then Enter. */
|
|
853
|
+
function handleDeals(app, screen, key, now) {
|
|
854
|
+
// Any key clears a note from the last Enter.
|
|
855
|
+
const set = (change) => ({ ...app, deals: { ...screen, note: undefined, ...change } });
|
|
856
|
+
const recent = app.stats.games;
|
|
857
|
+
if (/^[0-9]$/.test(key)) {
|
|
858
|
+
const typed = (screen.typed === '0' ? '' : screen.typed) + key;
|
|
859
|
+
return Number(typed) > MAX_SEED ? app : set({ typed });
|
|
860
|
+
}
|
|
861
|
+
switch (key) {
|
|
862
|
+
case 'backspace':
|
|
863
|
+
return set({ typed: screen.typed.slice(0, -1) });
|
|
864
|
+
case 'up':
|
|
865
|
+
case 'down': {
|
|
866
|
+
if (recent.length === 0)
|
|
867
|
+
return app;
|
|
868
|
+
const index = Math.min(recent.length - 1, Math.max(0, screen.index + (key === 'down' ? 1 : -1)));
|
|
869
|
+
return set({ typed: '', index });
|
|
870
|
+
}
|
|
871
|
+
case 'left':
|
|
872
|
+
case 'right':
|
|
873
|
+
return set({ drawMode: screen.drawMode === 1 ? 3 : 1 });
|
|
874
|
+
case 'space':
|
|
875
|
+
case 'enter': {
|
|
876
|
+
const pick = screen.typed ? { seed: Number(screen.typed), drawMode: screen.drawMode } : recent[screen.index];
|
|
877
|
+
if (!pick)
|
|
878
|
+
return app;
|
|
879
|
+
const closed = { ...app, deals: undefined };
|
|
880
|
+
const current = pick.seed === app.game.seed && pick.drawMode === app.game.drawMode && app.finishedAt === undefined && app.game.moves > 0;
|
|
881
|
+
if (current)
|
|
882
|
+
return say(closed, 'That is the game you are playing.');
|
|
883
|
+
const won = pastGame(app.stats, pick.seed, pick.drawMode, 'won');
|
|
884
|
+
if (won)
|
|
885
|
+
return set({ note: `Seed ${pick.seed} was won on ${formatWhen(won.at)}: won deals are not played again.` });
|
|
886
|
+
return playSeed(closed, pick.seed, pick.drawMode, now);
|
|
887
|
+
}
|
|
888
|
+
case 'escape':
|
|
889
|
+
return { ...app, deals: undefined };
|
|
890
|
+
default:
|
|
891
|
+
return app;
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
/** The letter that picks a choice: the first of its label. Each dialog keeps them distinct. */
|
|
895
|
+
export const choiceKey = (label) => label[0].toLowerCase();
|
|
896
|
+
/**
|
|
897
|
+
* Keys while a dialog is up: up and down choose, enter or space or the
|
|
898
|
+
* choice's letter takes it, esc backs out. Anything else is ignored.
|
|
899
|
+
*/
|
|
900
|
+
function handleDialog(app, key, dealer, now) {
|
|
901
|
+
const spec = specOf(app);
|
|
902
|
+
if (!spec)
|
|
903
|
+
return close(app);
|
|
904
|
+
const n = spec.choices.length;
|
|
905
|
+
// A key already on its way when the dialog came up was meant for the board.
|
|
906
|
+
const tooSoon = app.dialogAt !== undefined && now >= app.dialogAt && now - app.dialogAt < DIALOG_GUARD_MS;
|
|
907
|
+
const lettered = spec.choices.findIndex((c) => choiceKey(c.label) === key);
|
|
908
|
+
if (lettered >= 0)
|
|
909
|
+
return tooSoon ? app : spec.choices[lettered].act({ ...app, choice: lettered }, now, dealer);
|
|
910
|
+
switch (key) {
|
|
911
|
+
case 'up':
|
|
912
|
+
case 'down':
|
|
913
|
+
return { ...app, choice: (Math.min(app.choice, n - 1) + (key === 'down' ? 1 : n - 1)) % n };
|
|
914
|
+
case 'enter':
|
|
915
|
+
case 'space':
|
|
916
|
+
if (tooSoon)
|
|
917
|
+
return app;
|
|
918
|
+
return spec.choices[Math.min(app.choice, n - 1)].act(app, now, dealer);
|
|
919
|
+
case 'escape':
|
|
920
|
+
return spec.cancel(app, now, dealer);
|
|
921
|
+
case 'z':
|
|
922
|
+
case 'backspace':
|
|
923
|
+
// After a loss, undo still means going back.
|
|
924
|
+
return app.dialog === 'lost' ? backToWinnable(app, now) : app;
|
|
925
|
+
default:
|
|
926
|
+
return app;
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* One key press. `now` is the clock in ms and `dealer` supplies new deals;
|
|
931
|
+
* both are passed in so tests stay deterministic.
|
|
932
|
+
*/
|
|
933
|
+
export function handleKey(app, key, now, dealer) {
|
|
934
|
+
return stampDialog(app, trackColumn(app, press(app, key, now, dealer)), now);
|
|
935
|
+
}
|
|
936
|
+
function press(app, key, now, dealer) {
|
|
937
|
+
if (key === 'focus-out')
|
|
938
|
+
return blur(app, now);
|
|
939
|
+
// A key press means the player is here, even if the terminal never said focus came back.
|
|
940
|
+
app = focus(app, now);
|
|
941
|
+
if (key === 'focus-in')
|
|
942
|
+
return app;
|
|
943
|
+
if (key === 'ctrl+c' || key === 'ctrl+q')
|
|
944
|
+
return { ...app, quit: true };
|
|
945
|
+
if (app.showHelp)
|
|
946
|
+
return { ...app, showHelp: false };
|
|
947
|
+
if (app.showStats)
|
|
948
|
+
return { ...app, showStats: false };
|
|
949
|
+
// Any key cuts the ceremony short.
|
|
950
|
+
if (app.celebrating)
|
|
951
|
+
return endCeremony(app);
|
|
952
|
+
if (app.deals)
|
|
953
|
+
return handleDeals(app, app.deals, key, now);
|
|
954
|
+
if (app.dialog)
|
|
955
|
+
return handleDialog(app, key, dealer, now);
|
|
956
|
+
// Any key during auto-complete jumps straight to the end.
|
|
957
|
+
if (app.autoQueue.length > 0) {
|
|
958
|
+
const last = app.autoQueue[app.autoQueue.length - 1];
|
|
959
|
+
return winIfDone({ ...app, game: last, history: [...app.history, app.game], autoQueue: [] }, now);
|
|
960
|
+
}
|
|
961
|
+
const target = pileForKey(key);
|
|
962
|
+
if (target) {
|
|
963
|
+
if (target.kind === 'stock')
|
|
964
|
+
return watchStall(app, drawCard(app, now));
|
|
965
|
+
if (target.kind === 'auto-foundation')
|
|
966
|
+
return toFoundation(app, now);
|
|
967
|
+
return app.held ? drop(app, target, now) : pick(app, target);
|
|
968
|
+
}
|
|
969
|
+
switch (key) {
|
|
970
|
+
case 'left':
|
|
971
|
+
case 'right':
|
|
972
|
+
return cursorSideways(app, key === 'right' ? 1 : -1);
|
|
973
|
+
case 'up':
|
|
974
|
+
return cursorUp(app);
|
|
975
|
+
case 'down':
|
|
976
|
+
return cursorDown(app);
|
|
977
|
+
case 'space':
|
|
978
|
+
if (app.cursor.kind === 'stock')
|
|
979
|
+
return app.held ? say(app, 'Cards cannot go on the stock.') : watchStall(app, drawCard(app, now));
|
|
980
|
+
if (app.held)
|
|
981
|
+
return drop(app, app.cursor, now);
|
|
982
|
+
return pick(app, app.cursor, app.selected);
|
|
983
|
+
case 'enter': {
|
|
984
|
+
if (!app.held && app.cursor.kind === 'stock')
|
|
985
|
+
return watchStall(app, drawCard(app, now));
|
|
986
|
+
const from = app.held?.from ?? (app.cursor.kind === 'stock' ? pile.waste : app.cursor);
|
|
987
|
+
return autoFrom({ ...app, held: undefined }, from, now, app.held ? app.held.count : app.selected);
|
|
988
|
+
}
|
|
989
|
+
case 'escape':
|
|
990
|
+
// Esc first puts held cards back; with nothing in hand it brings up the menu.
|
|
991
|
+
if (app.held)
|
|
992
|
+
return { ...app, held: undefined, message: 'Put back.' };
|
|
993
|
+
return { ...app, dialog: 'menu' };
|
|
994
|
+
case 'tab':
|
|
995
|
+
return { ...app, compact: !app.compact, message: app.compact ? 'Large cards.' : 'Compact cards. Tab for large ones.' };
|
|
996
|
+
case 'z':
|
|
997
|
+
case 'backspace': {
|
|
998
|
+
const prev = app.history[app.history.length - 1];
|
|
999
|
+
if (!prev)
|
|
1000
|
+
return say(app, 'Nothing to undo.');
|
|
1001
|
+
const back = moved(app, prev, app.history.slice(0, -1), now);
|
|
1002
|
+
return back.status === 'lost' ? back : { ...back, finishedAt: undefined, message: 'Undone.' };
|
|
1003
|
+
}
|
|
1004
|
+
case '?':
|
|
1005
|
+
case '/':
|
|
1006
|
+
return askHint(app);
|
|
1007
|
+
case 'e':
|
|
1008
|
+
return say(app, 'e sits over the gap in the top row: nothing there. Esc for the menu.');
|
|
1009
|
+
case 'x':
|
|
1010
|
+
return { ...app, held: undefined, dialog: 'quit' };
|
|
1011
|
+
default:
|
|
1012
|
+
return app;
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
/**
|
|
1016
|
+
* The solver's answer for position `version`, with the first move of the win
|
|
1017
|
+
* it found when there is one. Answers for older positions are dropped. A
|
|
1018
|
+
* proven loss brings up the retry choices.
|
|
1019
|
+
*/
|
|
1020
|
+
export function applyVerdict(app, version, verdict, next, now = Date.now()) {
|
|
1021
|
+
if (version !== app.version || app.status !== 'checking')
|
|
1022
|
+
return app;
|
|
1023
|
+
app = remember(app, app.game, verdict, next);
|
|
1024
|
+
switch (verdict) {
|
|
1025
|
+
case 'winnable':
|
|
1026
|
+
return settleWinnable(app, next);
|
|
1027
|
+
case 'unclear': {
|
|
1028
|
+
// The first unsettled position after a winnable one is where a loss would have started.
|
|
1029
|
+
const known = liveSuspect(app);
|
|
1030
|
+
const suspect = known ?? { game: app.game, at: app.history.length };
|
|
1031
|
+
// Say so the moment it happens: this move may be the one that loses the game.
|
|
1032
|
+
const warn = !known && !app.playingOn && app.message === '';
|
|
1033
|
+
const message = warn ? 'Win ? : a win from here is not confirmed yet. Checking deeper; z undoes.' : app.message;
|
|
1034
|
+
return { ...app, status: 'unclear', suspect, message };
|
|
1035
|
+
}
|
|
1036
|
+
case 'lost':
|
|
1037
|
+
return lose({ ...app, suspect: undefined }, now);
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
/**
|
|
1041
|
+
* A loss proven: it goes on record at once, the move that lost it is kept
|
|
1042
|
+
* against the next try, and the board shakes behind the retry choices.
|
|
1043
|
+
*/
|
|
1044
|
+
function lose(app, now) {
|
|
1045
|
+
if (app.playingOn)
|
|
1046
|
+
return { ...app, status: 'lost' };
|
|
1047
|
+
const culprit = culpritOf(app);
|
|
1048
|
+
let next = { ...app, status: 'lost', dialog: 'lost', held: undefined, message: '', defeat: { at: now, done: false } };
|
|
1049
|
+
if (culprit !== undefined)
|
|
1050
|
+
next = withCulprits(next, [{ key: culprit, proven: next.known.get(culprit)?.verdict === 'lost' }], true);
|
|
1051
|
+
return recordDefeat(next, culprit ?? positionKey(app.game), now);
|
|
1052
|
+
}
|
|
1053
|
+
/**
|
|
1054
|
+
* Puts a proven loss on record. It is named after the play and where it was
|
|
1055
|
+
* lost, so the same loss found in two windows counts once, and the play
|
|
1056
|
+
* carries on under its own name: going back and winning is a win as well.
|
|
1057
|
+
* It counts again only once a card is moved after this.
|
|
1058
|
+
*/
|
|
1059
|
+
function recordDefeat(app, where, now) {
|
|
1060
|
+
if (app.play !== 'counted')
|
|
1061
|
+
return app;
|
|
1062
|
+
const end = { ...gameEnd(app, now), id: lossId(app.gameId, where) };
|
|
1063
|
+
const r = recordLoss(app.stats, app.game.drawMode, end);
|
|
1064
|
+
return { ...app, stats: r.stats, outbox: [...app.outbox, { game: r.game }], play: 'fresh' };
|
|
1065
|
+
}
|
|
1066
|
+
/** The suspect position, if this game still passes through it (undo or a restart can leave it behind). */
|
|
1067
|
+
export function liveSuspect(app) {
|
|
1068
|
+
const s = app.suspect;
|
|
1069
|
+
if (!s)
|
|
1070
|
+
return undefined;
|
|
1071
|
+
const onPath = s.at === app.history.length ? app.game === s.game : app.history[s.at] === s.game;
|
|
1072
|
+
return onPath ? s : undefined;
|
|
1073
|
+
}
|
|
1074
|
+
/**
|
|
1075
|
+
* The long look at the suspect position is back. A loss there is a loss
|
|
1076
|
+
* here too, since no move can make a lost game winnable again. A win there
|
|
1077
|
+
* moves the point to go back to forward.
|
|
1078
|
+
*/
|
|
1079
|
+
export function applyDeepVerdict(app, game, verdict, now = Date.now()) {
|
|
1080
|
+
app = remember(app, game, verdict);
|
|
1081
|
+
const s = liveSuspect(app);
|
|
1082
|
+
if (!s || s.game !== game)
|
|
1083
|
+
return app.suspect && !s ? { ...app, suspect: undefined } : app;
|
|
1084
|
+
const cleared = { ...app, suspect: undefined };
|
|
1085
|
+
switch (verdict) {
|
|
1086
|
+
case 'lost':
|
|
1087
|
+
if (app.status === 'lost')
|
|
1088
|
+
return cleared;
|
|
1089
|
+
return lose(cleared, now);
|
|
1090
|
+
case 'winnable': {
|
|
1091
|
+
const ahead = (app.lastWinnable?.history.length ?? -1) < s.at;
|
|
1092
|
+
return ahead ? { ...cleared, lastWinnable: { game: s.game, history: app.history.slice(0, s.at) } } : cleared;
|
|
1093
|
+
}
|
|
1094
|
+
case 'unclear':
|
|
1095
|
+
// Give up on this one; the next unsettled position will be looked at instead.
|
|
1096
|
+
return cleared;
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
/**
|
|
1100
|
+
* The answer for `game`, a position one move from where the player was when
|
|
1101
|
+
* it was asked. It is kept; if the player has since moved there it settles the
|
|
1102
|
+
* position now, and if it is a loss the cards in hand could make, they are warned.
|
|
1103
|
+
*/
|
|
1104
|
+
export function applyAhead(app, game, verdict, next, now = Date.now()) {
|
|
1105
|
+
if (verdict === 'unclear')
|
|
1106
|
+
return app;
|
|
1107
|
+
if (app.status === 'checking' && positionKey(app.game) === positionKey(game))
|
|
1108
|
+
return applyVerdict(app, app.version, verdict, next, now);
|
|
1109
|
+
app = remember(app, game, verdict, next);
|
|
1110
|
+
const warning = verdict === 'lost' && !app.dialog ? heldWarning(app) : undefined;
|
|
1111
|
+
return warning ? { ...app, message: warning } : app;
|
|
1112
|
+
}
|
|
1113
|
+
/** Whether the runner should keep ticking: auto-complete steps, the ceremony, or confetti behind the results. */
|
|
1114
|
+
export function animating(app) {
|
|
1115
|
+
return app.autoQueue.length > 0 || app.celebrating || afterWin(app) || (app.defeat !== undefined && !app.defeat.done);
|
|
1116
|
+
}
|
|
1117
|
+
/**
|
|
1118
|
+
* Shows the next auto-complete step, or moves the ceremony along. The runner
|
|
1119
|
+
* calls this on a short timer while `animating`.
|
|
1120
|
+
*/
|
|
1121
|
+
export function tick(app, now) {
|
|
1122
|
+
if (app.celebrating)
|
|
1123
|
+
return now - (app.finishedAt ?? now) >= CEREMONY_MS ? endCeremony(app) : app;
|
|
1124
|
+
if (app.defeat && !app.defeat.done)
|
|
1125
|
+
return now - app.defeat.at >= DEFEAT_MS ? { ...app, defeat: { ...app.defeat, done: true } } : app;
|
|
1126
|
+
const [next, ...rest] = app.autoQueue;
|
|
1127
|
+
if (!next)
|
|
1128
|
+
return app;
|
|
1129
|
+
return winIfDone({ ...app, game: next, history: [...app.history, app.game], autoQueue: rest }, now);
|
|
1130
|
+
}
|