soliterminal 0.1.1 → 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/README.ko.md +24 -6
- package/README.md +24 -7
- package/dist/app.js +126 -34
- package/dist/cli.js +49 -4
- package/dist/culprit-file.js +93 -0
- package/dist/stats.js +8 -1
- package/dist/ui/layout.js +34 -0
- package/package.json +1 -1
package/README.ko.md
CHANGED
|
@@ -159,9 +159,24 @@ npx soliterminal
|
|
|
159
159
|
| `Win ?` | 아직 판정하지 못함. 백그라운드에서 더 오래 살펴보는 중 |
|
|
160
160
|
| `Win 0%` | 더 이상 이길 수 없음 |
|
|
161
161
|
|
|
162
|
-
`Win 0%`가 되면
|
|
163
|
-
|
|
164
|
-
|
|
162
|
+
`Win 0%`가 되면 보드가 흔들리고 그 자리에서 진 판으로 기록됩니다. 그다음 마지막으로
|
|
163
|
+
이길 수 있던 상황으로 돌아가기(`z`로도 됨), 이 판 처음부터 다시, 새 판,
|
|
164
|
+
계속하기(`Esc`) 중에서 고릅니다. 몇 수 전에 이미 진 판이었다면 대화 상자가 몇 수
|
|
165
|
+
전인지 알려 주고, 돌아가기는 그 직전으로 갑니다.
|
|
166
|
+
|
|
167
|
+
### 지면서 이기기
|
|
168
|
+
|
|
169
|
+
판을 지게 만든 수는 그 판이 끝날 때까지 기억됩니다. 돌아가서 같은 수를 다시 두면
|
|
170
|
+
막힙니다. `This move lost the game last time, so it is blocked. Try another.`
|
|
171
|
+
질 때마다 막다른 길이 하나씩 닫히므로, 몇 번을 지더라도 이기는 길은 열려 있습니다.
|
|
172
|
+
진 판도, 그 뒤에 이긴 판도 각각 기록됩니다.
|
|
173
|
+
|
|
174
|
+
솔버가 몇 수 뒤에야 졌다는 걸 증명하고 그중 어느 수 때문인지는 확정하지 못할 때도
|
|
175
|
+
있습니다. 그때 첫 수는 의심만 되는 수라서 한 번 경고하고, 다시 두면 그대로 둡니다.
|
|
176
|
+
나중에 증명되면 그 수도 막힙니다.
|
|
177
|
+
|
|
178
|
+
막힌 수는 같은 판을 하고 있는 모든 창이 함께 쓰고, 종료해도 남으며, 그 판을
|
|
179
|
+
이기거나 다른 판으로 넘어가면 지워집니다.
|
|
165
180
|
|
|
166
181
|
### 경고
|
|
167
182
|
|
|
@@ -206,8 +221,10 @@ iTerm2, Windows Terminal, GNOME Terminal, Konsole). tmux에서는
|
|
|
206
221
|
모든 판은 시드와 함께 기록되고, 통계는 이 기록에서 Draw 1과 Draw 3을 따로
|
|
207
222
|
계산합니다. 판 수, 승리, 승률, 현재 연승과 최장 연승, 최단 시간, 최소 수가 나옵니다.
|
|
208
223
|
|
|
209
|
-
판은 끝났을 때 기록됩니다. 이겼을 때,
|
|
210
|
-
|
|
224
|
+
판은 끝났을 때 기록됩니다. 이겼을 때, 졌다는 게 증명됐을 때(진 판으로 기록되고
|
|
225
|
+
연승이 끊깁니다), 또는 끝내지 않고 다른 판으로 넘어갔을 때(역시 진 판)입니다. 졌다는
|
|
226
|
+
게 증명된 뒤 돌아가서 계속하면 새로 도전하는 판으로 칩니다. 포기하면 그것도 진
|
|
227
|
+
판이고, 이기면 이긴 판입니다. 덱만 넘겨 본 판은 판으로 치지 않습니다.
|
|
211
228
|
같은 판을 처음부터 다시 해도 같은 판이 이어지는 것으로 보고, 종료는 잠시 멈추는
|
|
212
229
|
것일 뿐입니다. 여러 창에서 동시에 해도 됩니다. 끝난 판은 기록 파일에 한 줄씩
|
|
213
230
|
덧붙여지므로 서로 덮어쓰지 않습니다.
|
|
@@ -294,7 +311,8 @@ soliterminal --draw 3 --theme blue
|
|
|
294
311
|
|
|
295
312
|
데이터는 `~/.local/state/soliterminal/`(`$XDG_STATE_HOME`이 있으면 그 아래), Windows는
|
|
296
313
|
`%LOCALAPPDATA%\soliterminal\`에 있습니다. `games.jsonl`에 판 기록이 한 줄에 한
|
|
297
|
-
판씩, `current.json`에 진행 중인 게임이, `
|
|
314
|
+
판씩, `current.json`에 진행 중인 게임이, `culprits/`에 하고 있는 판을 지게 만든 수가,
|
|
315
|
+
`share.json`에 공유 상태가 들어 있습니다.
|
|
298
316
|
예전 버전의 `stats.json`은 처음 실행할 때 `games.jsonl`로 옮겨지고, 원래 파일은 그대로
|
|
299
317
|
남습니다.
|
|
300
318
|
|
package/README.md
CHANGED
|
@@ -166,10 +166,25 @@ The header always says where you stand:
|
|
|
166
166
|
| `Win ?` | Not settled yet; a longer look carries on in the background |
|
|
167
167
|
| `Win 0%` | It can no longer be won |
|
|
168
168
|
|
|
169
|
-
At `Win 0%`
|
|
170
|
-
|
|
171
|
-
a
|
|
172
|
-
them.
|
|
169
|
+
At `Win 0%` the board shakes, the loss goes on record straight away, and you
|
|
170
|
+
choose: back to the last winnable position (`z` does this too), start the deal
|
|
171
|
+
over, a new deal, or play on (`Esc`). If the game was lost a few moves back, the
|
|
172
|
+
dialog says how many, and going back goes to just before them.
|
|
173
|
+
|
|
174
|
+
### Losing your way to a win
|
|
175
|
+
|
|
176
|
+
The move that lost the game is remembered for the rest of the deal. Go back and
|
|
177
|
+
try it again and it is refused: `This move lost the game last time, so it is
|
|
178
|
+
blocked. Try another.` Each loss shuts one more door, so however many times you
|
|
179
|
+
lose, the way to the win stays open. The loss counts, and so does the win that
|
|
180
|
+
follows.
|
|
181
|
+
|
|
182
|
+
Sometimes the solver proves a loss a few moves later without settling which of
|
|
183
|
+
those moves lost it. Then the first of them is only suspected: you are warned
|
|
184
|
+
once, and doing it again goes ahead. Once it is proven, it is blocked too.
|
|
185
|
+
|
|
186
|
+
The blocked moves are shared by every window playing the same deal, survive
|
|
187
|
+
quitting, and are forgotten once the deal is won or left for another.
|
|
173
188
|
|
|
174
189
|
### Warnings
|
|
175
190
|
|
|
@@ -215,8 +230,9 @@ Every game is kept with its seed, and the statistics are worked out from those
|
|
|
215
230
|
games, separately for Draw 1 and Draw 3: games played, won, win rate, current
|
|
216
231
|
and longest streak, best time and fewest moves.
|
|
217
232
|
|
|
218
|
-
A game goes on record when it ends: won,
|
|
219
|
-
|
|
233
|
+
A game goes on record when it ends: won, proven lost (a loss, which ends your
|
|
234
|
+
streak), or given up for another deal (also a loss). Going back after a proven
|
|
235
|
+
loss carries on as a new try: given up, it is a loss of its own, and won, a win. Drawing from the stock alone does not make it a game.
|
|
220
236
|
Starting a deal over carries on the same game, and quitting only pauses it.
|
|
221
237
|
Several windows can play at once: each finished game is added to the record as
|
|
222
238
|
a line of its own, so none overwrites another.
|
|
@@ -307,7 +323,8 @@ soliterminal --draw 3 --theme blue
|
|
|
307
323
|
|
|
308
324
|
Your data lives in `~/.local/state/soliterminal/` (`$XDG_STATE_HOME` if set), or
|
|
309
325
|
in `%LOCALAPPDATA%\soliterminal\` on Windows: `games.jsonl` holds your games,
|
|
310
|
-
one JSON line each, `current.json` the game in progress,
|
|
326
|
+
one JSON line each, `current.json` the game in progress, `culprits/` the moves that lost the deals
|
|
327
|
+
being played, and `share.json` where
|
|
311
328
|
sharing stands. A `stats.json` from an earlier version is moved into
|
|
312
329
|
`games.jsonl` on first start and left in place.
|
|
313
330
|
|
package/dist/app.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { cardName, sameCard } from './core/card.js';
|
|
2
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, newGameId, pastGame, recordLoss, recordWin, statsFor, winRate, withLevel } from './stats.js';
|
|
3
|
+
import { EMPTY_STATS, lossId, newGameId, pastGame, recordLoss, recordWin, statsFor, winRate, withLevel } from './stats.js';
|
|
4
4
|
import { formatTime, formatWhen } from './ui/help.js';
|
|
5
5
|
import { MAX_BATCH, SHARE_EVERY, acceptShare, declineShare, finishedGames, markShared, shareDue, unsent } from './share.js';
|
|
6
6
|
import { STOCK_KEY, keyLabel, pileForKey } from './ui/keymap.js';
|
|
@@ -29,6 +29,8 @@ export function stampDialog(before, after, now) {
|
|
|
29
29
|
}
|
|
30
30
|
/** How long the win ceremony runs before the results come up. */
|
|
31
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;
|
|
32
34
|
export function createApp(game, options = {}) {
|
|
33
35
|
const verified = options.verified ?? false;
|
|
34
36
|
return {
|
|
@@ -40,6 +42,8 @@ export function createApp(game, options = {}) {
|
|
|
40
42
|
lastWinnable: verified ? { game, history: [] } : undefined,
|
|
41
43
|
verified,
|
|
42
44
|
playingOn: false,
|
|
45
|
+
culprits: new Map(),
|
|
46
|
+
culpritOutbox: [],
|
|
43
47
|
cursor: pile.tableau(0),
|
|
44
48
|
message: WELCOME,
|
|
45
49
|
stall: stallFrom(game),
|
|
@@ -94,7 +98,7 @@ export function resumeApp(states, options) {
|
|
|
94
98
|
app = { ...app, status: 'winnable', autoQueue: autoComplete(game) };
|
|
95
99
|
return app;
|
|
96
100
|
}
|
|
97
|
-
const close = (app) => ({ ...app, dialog: undefined });
|
|
101
|
+
const close = (app) => ({ ...app, dialog: undefined, defeat: undefined });
|
|
98
102
|
const carryOn = (app) => ({ ...close(app), message: 'Carry on.' });
|
|
99
103
|
const keepPlaying = { label: 'Keep playing', act: carryOn };
|
|
100
104
|
const quitNow = (app) => ({ ...app, quit: true });
|
|
@@ -176,9 +180,12 @@ function shareSpec(app) {
|
|
|
176
180
|
function lostSpec(app) {
|
|
177
181
|
const since = app.history.length - (app.lastWinnable?.history.length ?? 0);
|
|
178
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.'] : [];
|
|
179
186
|
return {
|
|
180
187
|
title: 'No way to win from here',
|
|
181
|
-
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.'],
|
|
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],
|
|
182
189
|
choices: [
|
|
183
190
|
{ label: 'Back to the last winnable spot', act: backToWinnable },
|
|
184
191
|
{ label: 'Restart this deal', act: restart },
|
|
@@ -286,6 +293,8 @@ export function viewOf(app, now) {
|
|
|
286
293
|
dialog: dialogView(app),
|
|
287
294
|
// The confetti keeps falling behind the results until they are put away.
|
|
288
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,
|
|
289
298
|
};
|
|
290
299
|
}
|
|
291
300
|
// ---------------------------------------------------------------------------
|
|
@@ -408,14 +417,17 @@ const afterWin = (app) => app.finishedAt !== undefined && (app.dialog === 'won'
|
|
|
408
417
|
export function abandon(app, now = Date.now()) {
|
|
409
418
|
if (app.play !== 'counted')
|
|
410
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) {
|
|
411
425
|
// A loss proven while playing says which move lost it: the one after the last winnable position.
|
|
412
426
|
const lostAt = app.status === 'lost' ? (app.lastWinnable ? app.lastWinnable.history.length + 1 : 0) : undefined;
|
|
413
|
-
|
|
414
|
-
const r = recordLoss(app.stats, app.game.drawMode, end);
|
|
415
|
-
return { ...app, stats: r.stats, outbox: [...app.outbox, { game: r.game }], play: 'fresh' };
|
|
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 };
|
|
416
428
|
}
|
|
417
429
|
/** A new position: the solver's earlier answer no longer applies. */
|
|
418
|
-
function moved(app, game, history) {
|
|
430
|
+
function moved(app, game, history, now) {
|
|
419
431
|
return recall({
|
|
420
432
|
...app,
|
|
421
433
|
game,
|
|
@@ -423,19 +435,68 @@ function moved(app, game, history) {
|
|
|
423
435
|
version: app.version + 1,
|
|
424
436
|
status: 'checking',
|
|
425
437
|
dialog: undefined,
|
|
438
|
+
defeat: undefined,
|
|
439
|
+
culpritWarned: undefined,
|
|
426
440
|
held: undefined,
|
|
427
441
|
stall: stallFrom(game),
|
|
428
442
|
stalled: false,
|
|
429
|
-
});
|
|
443
|
+
}, now);
|
|
430
444
|
}
|
|
431
445
|
/** Adds a settled answer to what is known. `unclear` settles nothing. */
|
|
432
446
|
function remember(app, game, verdict, next) {
|
|
433
447
|
if (verdict === 'unclear')
|
|
434
448
|
return app;
|
|
449
|
+
const key = positionKey(game);
|
|
435
450
|
const known = new Map(app.known);
|
|
436
|
-
known.set(
|
|
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);
|
|
437
455
|
return { ...app, known };
|
|
438
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
|
+
}
|
|
439
500
|
/** The same position with one redeal fewer: if that cannot be won, the win needs every redeal left. */
|
|
440
501
|
function oneRedealLess(game) {
|
|
441
502
|
return Number.isFinite(game.redealsLeft) && game.redealsLeft > 0 ? { ...game, redealsLeft: game.redealsLeft - 1 } : undefined;
|
|
@@ -456,11 +517,11 @@ function noSlack(app) {
|
|
|
456
517
|
return less !== undefined && app.known.get(positionKey(less))?.verdict === 'lost';
|
|
457
518
|
}
|
|
458
519
|
/** A position already settled is answered at once: no solver, no wait. */
|
|
459
|
-
function recall(app) {
|
|
520
|
+
function recall(app, now) {
|
|
460
521
|
const k = app.known.get(positionKey(app.game));
|
|
461
522
|
if (!k)
|
|
462
523
|
return app;
|
|
463
|
-
return k.verdict === 'winnable' ? settleWinnable(app, k.next) : lose({ ...app, suspect: undefined });
|
|
524
|
+
return k.verdict === 'winnable' ? settleWinnable(app, k.next) : lose({ ...app, suspect: undefined }, now);
|
|
464
525
|
}
|
|
465
526
|
/** The current position is proven winnable. */
|
|
466
527
|
function settleWinnable(app, next) {
|
|
@@ -500,15 +561,21 @@ function heldWarning(app) {
|
|
|
500
561
|
function commit(app, result, now, onError, isDraw = false) {
|
|
501
562
|
if (!result.ok)
|
|
502
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.
|
|
503
572
|
let next = {
|
|
504
|
-
...moved(
|
|
505
|
-
message: '',
|
|
573
|
+
...moved(base, result.state, [...app.history, app.game], now),
|
|
506
574
|
startedAt: app.startedAt ?? now,
|
|
507
575
|
};
|
|
508
|
-
//
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
next = { ...next, play: 'counted', gameAt: now };
|
|
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: '' };
|
|
512
579
|
if (canAutoComplete(next.game)) {
|
|
513
580
|
next = {
|
|
514
581
|
...next,
|
|
@@ -659,9 +726,10 @@ function newGame(app, dealer, now, drawMode = app.nextDrawMode) {
|
|
|
659
726
|
* The same deal from the start. An unfinished game carries on as the same
|
|
660
727
|
* play in the statistics; after a win it is a new one.
|
|
661
728
|
*/
|
|
662
|
-
function restart(app) {
|
|
663
|
-
// The same deal goes through the same positions: what is known about them still holds.
|
|
664
|
-
const
|
|
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);
|
|
665
733
|
return app.play === 'counted' ? { ...next, play: 'counted', gameId: app.gameId, ...(app.gameAt === undefined ? {} : { gameAt: app.gameAt }) } : next;
|
|
666
734
|
}
|
|
667
735
|
/** Restart, after asking; not before a move, and not once the deal is won. */
|
|
@@ -680,12 +748,12 @@ function switchDraw(app, dealer, now) {
|
|
|
680
748
|
return { ...newGame(app, dealer, now, nextDrawMode), message: `Draw ${nextDrawMode}.` };
|
|
681
749
|
return { ...app, nextDrawMode, message: `Draw ${nextDrawMode} from the next game.` };
|
|
682
750
|
}
|
|
683
|
-
function backToWinnable(app) {
|
|
751
|
+
function backToWinnable(app, now) {
|
|
684
752
|
const snap = app.lastWinnable;
|
|
685
753
|
if (!snap)
|
|
686
|
-
return restart(app);
|
|
754
|
+
return restart(app, now);
|
|
687
755
|
return {
|
|
688
|
-
...moved(app, snap.game, snap.history),
|
|
756
|
+
...moved(app, snap.game, snap.history, now),
|
|
689
757
|
status: 'winnable',
|
|
690
758
|
playingOn: false,
|
|
691
759
|
message: 'Back to the last winnable position.',
|
|
@@ -853,7 +921,7 @@ function handleDialog(app, key, dealer, now) {
|
|
|
853
921
|
case 'z':
|
|
854
922
|
case 'backspace':
|
|
855
923
|
// After a loss, undo still means going back.
|
|
856
|
-
return app.dialog === 'lost' ? backToWinnable(app) : app;
|
|
924
|
+
return app.dialog === 'lost' ? backToWinnable(app, now) : app;
|
|
857
925
|
default:
|
|
858
926
|
return app;
|
|
859
927
|
}
|
|
@@ -930,7 +998,8 @@ function press(app, key, now, dealer) {
|
|
|
930
998
|
const prev = app.history[app.history.length - 1];
|
|
931
999
|
if (!prev)
|
|
932
1000
|
return say(app, 'Nothing to undo.');
|
|
933
|
-
|
|
1001
|
+
const back = moved(app, prev, app.history.slice(0, -1), now);
|
|
1002
|
+
return back.status === 'lost' ? back : { ...back, finishedAt: undefined, message: 'Undone.' };
|
|
934
1003
|
}
|
|
935
1004
|
case '?':
|
|
936
1005
|
case '/':
|
|
@@ -948,7 +1017,7 @@ function press(app, key, now, dealer) {
|
|
|
948
1017
|
* it found when there is one. Answers for older positions are dropped. A
|
|
949
1018
|
* proven loss brings up the retry choices.
|
|
950
1019
|
*/
|
|
951
|
-
export function applyVerdict(app, version, verdict, next) {
|
|
1020
|
+
export function applyVerdict(app, version, verdict, next, now = Date.now()) {
|
|
952
1021
|
if (version !== app.version || app.status !== 'checking')
|
|
953
1022
|
return app;
|
|
954
1023
|
app = remember(app, app.game, verdict, next);
|
|
@@ -965,13 +1034,34 @@ export function applyVerdict(app, version, verdict, next) {
|
|
|
965
1034
|
return { ...app, status: 'unclear', suspect, message };
|
|
966
1035
|
}
|
|
967
1036
|
case 'lost':
|
|
968
|
-
return lose({ ...app, suspect: undefined });
|
|
1037
|
+
return lose({ ...app, suspect: undefined }, now);
|
|
969
1038
|
}
|
|
970
1039
|
}
|
|
971
|
-
|
|
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) {
|
|
972
1045
|
if (app.playingOn)
|
|
973
1046
|
return { ...app, status: 'lost' };
|
|
974
|
-
|
|
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' };
|
|
975
1065
|
}
|
|
976
1066
|
/** The suspect position, if this game still passes through it (undo or a restart can leave it behind). */
|
|
977
1067
|
export function liveSuspect(app) {
|
|
@@ -986,7 +1076,7 @@ export function liveSuspect(app) {
|
|
|
986
1076
|
* here too, since no move can make a lost game winnable again. A win there
|
|
987
1077
|
* moves the point to go back to forward.
|
|
988
1078
|
*/
|
|
989
|
-
export function applyDeepVerdict(app, game, verdict) {
|
|
1079
|
+
export function applyDeepVerdict(app, game, verdict, now = Date.now()) {
|
|
990
1080
|
app = remember(app, game, verdict);
|
|
991
1081
|
const s = liveSuspect(app);
|
|
992
1082
|
if (!s || s.game !== game)
|
|
@@ -996,7 +1086,7 @@ export function applyDeepVerdict(app, game, verdict) {
|
|
|
996
1086
|
case 'lost':
|
|
997
1087
|
if (app.status === 'lost')
|
|
998
1088
|
return cleared;
|
|
999
|
-
return lose(cleared);
|
|
1089
|
+
return lose(cleared, now);
|
|
1000
1090
|
case 'winnable': {
|
|
1001
1091
|
const ahead = (app.lastWinnable?.history.length ?? -1) < s.at;
|
|
1002
1092
|
return ahead ? { ...cleared, lastWinnable: { game: s.game, history: app.history.slice(0, s.at) } } : cleared;
|
|
@@ -1011,18 +1101,18 @@ export function applyDeepVerdict(app, game, verdict) {
|
|
|
1011
1101
|
* it was asked. It is kept; if the player has since moved there it settles the
|
|
1012
1102
|
* position now, and if it is a loss the cards in hand could make, they are warned.
|
|
1013
1103
|
*/
|
|
1014
|
-
export function applyAhead(app, game, verdict, next) {
|
|
1104
|
+
export function applyAhead(app, game, verdict, next, now = Date.now()) {
|
|
1015
1105
|
if (verdict === 'unclear')
|
|
1016
1106
|
return app;
|
|
1017
1107
|
if (app.status === 'checking' && positionKey(app.game) === positionKey(game))
|
|
1018
|
-
return applyVerdict(app, app.version, verdict, next);
|
|
1108
|
+
return applyVerdict(app, app.version, verdict, next, now);
|
|
1019
1109
|
app = remember(app, game, verdict, next);
|
|
1020
1110
|
const warning = verdict === 'lost' && !app.dialog ? heldWarning(app) : undefined;
|
|
1021
1111
|
return warning ? { ...app, message: warning } : app;
|
|
1022
1112
|
}
|
|
1023
1113
|
/** Whether the runner should keep ticking: auto-complete steps, the ceremony, or confetti behind the results. */
|
|
1024
1114
|
export function animating(app) {
|
|
1025
|
-
return app.autoQueue.length > 0 || app.celebrating || afterWin(app);
|
|
1115
|
+
return app.autoQueue.length > 0 || app.celebrating || afterWin(app) || (app.defeat !== undefined && !app.defeat.done);
|
|
1026
1116
|
}
|
|
1027
1117
|
/**
|
|
1028
1118
|
* Shows the next auto-complete step, or moves the ceremony along. The runner
|
|
@@ -1031,6 +1121,8 @@ export function animating(app) {
|
|
|
1031
1121
|
export function tick(app, now) {
|
|
1032
1122
|
if (app.celebrating)
|
|
1033
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;
|
|
1034
1126
|
const [next, ...rest] = app.autoQueue;
|
|
1035
1127
|
if (!next)
|
|
1036
1128
|
return app;
|
package/dist/cli.js
CHANGED
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
import { readFileSync } from 'node:fs';
|
|
8
8
|
import { emitKeypressEvents } from 'node:readline';
|
|
9
9
|
import { parseArgs } from 'node:util';
|
|
10
|
-
import { animating, applyAhead, applyDeepVerdict, applyRating, applyShared, applyVerdict, createApp, handleKey, liveSuspect, playTime, resumeApp, slackCheck, stampDialog, tick, viewOf, } from './app.js';
|
|
10
|
+
import { animating, applyAhead, applyDeepVerdict, applyRating, applyShared, applyVerdict, createApp, handleKey, liveSuspect, playTime, resumeApp, slackCheck, stampDialog, tick, viewOf, withCulprits, } from './app.js';
|
|
11
|
+
import { appendCulprits, culpritPath, readCulpritsIfChanged, removeCulprits, removeOldCulprits } from './culprit-file.js';
|
|
11
12
|
import { randomSeed } from './core/deck.js';
|
|
12
13
|
import { DEFAULT_REDEALS, deal, positionKey, successors } from './core/klondike.js';
|
|
13
14
|
import { findWinnableSeed } from './core/solver.js';
|
|
@@ -211,6 +212,7 @@ function saveIfChanged() {
|
|
|
211
212
|
rateIfNeeded();
|
|
212
213
|
shareIfAgreed();
|
|
213
214
|
}
|
|
215
|
+
syncCulprits();
|
|
214
216
|
if (app.stats.share !== savedShare) {
|
|
215
217
|
savedShare = app.stats.share;
|
|
216
218
|
if (savedShare)
|
|
@@ -263,6 +265,38 @@ function shareIfAgreed() {
|
|
|
263
265
|
render();
|
|
264
266
|
});
|
|
265
267
|
}
|
|
268
|
+
/**
|
|
269
|
+
* The moves that lost this deal, shared with every window playing it through
|
|
270
|
+
* a file per deal: new ones are written out, ones other windows found are
|
|
271
|
+
* read in, and the file goes once the deal is won or left for another.
|
|
272
|
+
*/
|
|
273
|
+
let culpritFile;
|
|
274
|
+
let culpritSeen = -1;
|
|
275
|
+
function syncCulprits() {
|
|
276
|
+
const first = app.history[0] ?? app.game;
|
|
277
|
+
const path = culpritPath(statsFile, { seed: first.seed, drawMode: first.drawMode, limit: first.redealsLeft });
|
|
278
|
+
if (path !== culpritFile) {
|
|
279
|
+
// Another deal now: the last one is over in this window.
|
|
280
|
+
if (culpritFile !== undefined)
|
|
281
|
+
removeCulprits(culpritFile);
|
|
282
|
+
culpritFile = path;
|
|
283
|
+
culpritSeen = -1;
|
|
284
|
+
}
|
|
285
|
+
if (app.culpritOutbox.length > 0) {
|
|
286
|
+
appendCulprits(path, app.culpritOutbox);
|
|
287
|
+
app = { ...app, culpritOutbox: [] };
|
|
288
|
+
}
|
|
289
|
+
if (app.play === 'won') {
|
|
290
|
+
removeCulprits(path);
|
|
291
|
+
culpritSeen = -1;
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
const read = readCulpritsIfChanged(path, culpritSeen);
|
|
295
|
+
if (read) {
|
|
296
|
+
culpritSeen = read.size;
|
|
297
|
+
app = withCulprits(app, read.culprits);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
266
300
|
let keptGame;
|
|
267
301
|
let keptHistory;
|
|
268
302
|
let keptPlay;
|
|
@@ -359,8 +393,11 @@ function judgeIfNeeded() {
|
|
|
359
393
|
const version = app.version;
|
|
360
394
|
judgedVersion = version;
|
|
361
395
|
solver.judge(app.game, (verdict, next) => {
|
|
362
|
-
app = stampDialog(app, applyVerdict(app, version, verdict, next), Date.now());
|
|
396
|
+
app = stampDialog(app, applyVerdict(app, version, verdict, next, Date.now()), Date.now());
|
|
397
|
+
// A loss proven goes on record at once, and shakes the board.
|
|
398
|
+
saveIfChanged();
|
|
363
399
|
render();
|
|
400
|
+
scheduleAuto();
|
|
364
401
|
deepIfNeeded();
|
|
365
402
|
lookAheadIfNeeded();
|
|
366
403
|
});
|
|
@@ -384,8 +421,10 @@ function lookAheadIfNeeded() {
|
|
|
384
421
|
solver.lookAhead(child, deep, (verdict, next) => {
|
|
385
422
|
if (!deep && verdict === 'unclear')
|
|
386
423
|
ask(child, true);
|
|
387
|
-
app = stampDialog(app, applyAhead(app, child, verdict, next), Date.now());
|
|
424
|
+
app = stampDialog(app, applyAhead(app, child, verdict, next, Date.now()), Date.now());
|
|
425
|
+
saveIfChanged();
|
|
388
426
|
render();
|
|
427
|
+
scheduleAuto();
|
|
389
428
|
});
|
|
390
429
|
// First whether any redeal is to spare, then each move.
|
|
391
430
|
const spare = slackCheck(app);
|
|
@@ -411,8 +450,10 @@ function deepIfNeeded() {
|
|
|
411
450
|
}
|
|
412
451
|
solver.judgeDeeply(suspect, (verdict) => {
|
|
413
452
|
deepOn = undefined;
|
|
414
|
-
app = stampDialog(app, applyDeepVerdict(app, suspect, verdict), Date.now());
|
|
453
|
+
app = stampDialog(app, applyDeepVerdict(app, suspect, verdict, Date.now()), Date.now());
|
|
454
|
+
saveIfChanged();
|
|
415
455
|
render();
|
|
456
|
+
scheduleAuto();
|
|
416
457
|
deepIfNeeded();
|
|
417
458
|
});
|
|
418
459
|
}
|
|
@@ -426,6 +467,8 @@ stdin.on('keypress', (str, key) => {
|
|
|
426
467
|
const name = normalizeKey(str, key);
|
|
427
468
|
if (!name)
|
|
428
469
|
return;
|
|
470
|
+
// Another window may have found a losing move in this deal since.
|
|
471
|
+
syncCulprits();
|
|
429
472
|
app = handleKey(app, name, Date.now(), dealer);
|
|
430
473
|
if (app.quit)
|
|
431
474
|
quit();
|
|
@@ -444,6 +487,8 @@ stdout.on('resize', () => {
|
|
|
444
487
|
setInterval(render, 1000).unref();
|
|
445
488
|
// Write the game straight away, so a tool looking at the file sees the game on screen.
|
|
446
489
|
saveGame(true);
|
|
490
|
+
syncCulprits();
|
|
491
|
+
removeOldCulprits(statsFile, culpritFile);
|
|
447
492
|
render();
|
|
448
493
|
scheduleAuto();
|
|
449
494
|
rateIfNeeded();
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { appendFileSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
export const culpritDir = (statsFile) => join(dirname(statsFile), 'culprits');
|
|
4
|
+
export function culpritPath(statsFile, d) {
|
|
5
|
+
const limit = Number.isFinite(d.limit) ? String(d.limit) : 'u';
|
|
6
|
+
return join(culpritDir(statsFile), `${d.seed}-d${d.drawMode}-r${limit}.jsonl`);
|
|
7
|
+
}
|
|
8
|
+
const isCulprit = (x) => typeof x === 'object' && x !== null && typeof x.key === 'string' && typeof x.proven === 'boolean';
|
|
9
|
+
/** The culprits written so far. A missing file is none; a damaged line is skipped. */
|
|
10
|
+
export function parseCulprits(text) {
|
|
11
|
+
const out = [];
|
|
12
|
+
for (const line of text.split('\n')) {
|
|
13
|
+
if (!line.trim())
|
|
14
|
+
continue;
|
|
15
|
+
try {
|
|
16
|
+
const c = JSON.parse(line);
|
|
17
|
+
if (isCulprit(c))
|
|
18
|
+
out.push({ key: c.key, proven: c.proven });
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
// A line cut short by a crash.
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
/** Adds culprits in a single write, each on a line of its own. Never throws. */
|
|
27
|
+
export function appendCulprits(path, culprits) {
|
|
28
|
+
if (culprits.length === 0)
|
|
29
|
+
return true;
|
|
30
|
+
try {
|
|
31
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
32
|
+
// A leading newline keeps a line cut short from swallowing the first one written here.
|
|
33
|
+
appendFileSync(path, '\n' + culprits.map((c) => JSON.stringify({ key: c.key, proven: c.proven })).join('\n') + '\n');
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Reads a deal's culprits when the file changed since `seen` (its size, as
|
|
42
|
+
* it only grows). Returns undefined when nothing new is there.
|
|
43
|
+
*/
|
|
44
|
+
export function readCulpritsIfChanged(path, seen) {
|
|
45
|
+
let size;
|
|
46
|
+
try {
|
|
47
|
+
size = statSync(path).size;
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
if (size === seen)
|
|
53
|
+
return undefined;
|
|
54
|
+
try {
|
|
55
|
+
return { culprits: parseCulprits(readFileSync(path, 'utf8')), size };
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
export function removeCulprits(path) {
|
|
62
|
+
try {
|
|
63
|
+
rmSync(path, { force: true });
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
// Nothing worth stopping for.
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/** Files older than this are from deals no window is playing any more. */
|
|
70
|
+
export const CULPRIT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
|
|
71
|
+
/** Removes old files, except `keep`: the deal being played, however long ago it was lost. */
|
|
72
|
+
export function removeOldCulprits(statsFile, keep, now = Date.now()) {
|
|
73
|
+
const dir = culpritDir(statsFile);
|
|
74
|
+
let names;
|
|
75
|
+
try {
|
|
76
|
+
names = readdirSync(dir);
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
for (const name of names) {
|
|
82
|
+
const path = join(dir, name);
|
|
83
|
+
if (path === keep || !name.endsWith('.jsonl'))
|
|
84
|
+
continue;
|
|
85
|
+
try {
|
|
86
|
+
if (now - statSync(path).mtimeMs > CULPRIT_MAX_AGE_MS)
|
|
87
|
+
rmSync(path, { force: true });
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
// Removed by another window meanwhile.
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
package/dist/stats.js
CHANGED
|
@@ -1,7 +1,14 @@
|
|
|
1
|
-
import { randomBytes } from 'node:crypto';
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
2
|
export const EMPTY_STATS = { games: [] };
|
|
3
3
|
/** A fresh name for a game. */
|
|
4
4
|
export const newGameId = () => randomBytes(8).toString('hex');
|
|
5
|
+
/**
|
|
6
|
+
* The name of a loss proven while playing: worked out from the play and the
|
|
7
|
+
* position its losing move led to, so two windows playing the same game that
|
|
8
|
+
* prove the same loss record it once. The play itself keeps its own name and
|
|
9
|
+
* carries on, so a win after going back still counts.
|
|
10
|
+
*/
|
|
11
|
+
export const lossId = (gameId, position) => createHash('sha256').update(`${gameId}/${position}`).digest('hex').slice(0, 16);
|
|
5
12
|
const limitOf = (game) => game.limit === undefined ? {} : { limit: Number.isFinite(game.limit) ? game.limit : null };
|
|
6
13
|
export function statsFor(stats, drawMode) {
|
|
7
14
|
// Oldest first, so runs of wins can be counted as they happened.
|
package/dist/ui/layout.js
CHANGED
|
@@ -198,6 +198,8 @@ export function renderKlondike(state, view, options = {}) {
|
|
|
198
198
|
});
|
|
199
199
|
if (view.celebration !== undefined)
|
|
200
200
|
drawConfetti(buf, view.celebration, footer, ascii);
|
|
201
|
+
if (view.defeat !== undefined)
|
|
202
|
+
drawDefeat(buf, view.defeat, footer);
|
|
201
203
|
if (view.dialog)
|
|
202
204
|
drawDialog(buf, view.dialog, g, left, geo.board, footer);
|
|
203
205
|
return buf;
|
|
@@ -278,6 +280,38 @@ function drawConfetti(buf, ms, bottom, ascii) {
|
|
|
278
280
|
buf.put(x, y - 1, ascii ? '.' : '·', { fg: 'dim' });
|
|
279
281
|
}
|
|
280
282
|
}
|
|
283
|
+
/** Sideways offsets of the board while it shakes, one per 70 ms. */
|
|
284
|
+
const SHAKE = [2, -2, 2, -1, 1, -1, 0];
|
|
285
|
+
const SHAKE_STEP_MS = 70;
|
|
286
|
+
/** After the shake, the ink drains from the cards one column of cells at a time, left to right. */
|
|
287
|
+
const FADE_FROM_MS = SHAKE.length * SHAKE_STEP_MS;
|
|
288
|
+
const FADE_MS = 800;
|
|
289
|
+
/**
|
|
290
|
+
* A proven loss: the board shakes, then the cards lose their color from left
|
|
291
|
+
* to right and stay grey behind the dialog. Rows between the header and the
|
|
292
|
+
* footer move; the header and the footer stay put so the verdict stays readable.
|
|
293
|
+
* Purely a function of time, like the confetti.
|
|
294
|
+
*/
|
|
295
|
+
function drawDefeat(buf, ms, bottom) {
|
|
296
|
+
const shift = ms < FADE_FROM_MS ? SHAKE[Math.floor(ms / SHAKE_STEP_MS)] : 0;
|
|
297
|
+
const faded = Math.max(0, Math.min(1, (ms - FADE_FROM_MS) / FADE_MS));
|
|
298
|
+
const reach = Math.round(faded * buf.width);
|
|
299
|
+
for (let y = 1; y < bottom; y++) {
|
|
300
|
+
const row = Array.from({ length: buf.width }, (_, x) => buf.get(x, y));
|
|
301
|
+
// A wide character split by the shift would leave half of itself behind: blank the row and redraw it whole.
|
|
302
|
+
buf.put(0, y, ' '.repeat(buf.width));
|
|
303
|
+
for (let x = 0; x < buf.width; x++) {
|
|
304
|
+
const cell = row[x];
|
|
305
|
+
if (cell.ch === '')
|
|
306
|
+
continue;
|
|
307
|
+
const to = x + shift;
|
|
308
|
+
if (to < 0 || to >= buf.width)
|
|
309
|
+
continue;
|
|
310
|
+
const grey = to < reach && (cell.fg === 'red' || cell.fg === 'black' || cell.fg === 'key' || cell.fg === 'message');
|
|
311
|
+
buf.put(to, y, cell.ch, { fg: grey ? 'dim' : cell.fg, bg: cell.bg, bold: grey ? false : cell.bold, edge: cell.edge });
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
281
315
|
/** ASCII to its fullwidth form: `q` → `q`, `1` → `1`, `` ` `` → ```. */
|
|
282
316
|
function fullwidth(text) {
|
|
283
317
|
return text.replace(/[!-~]/g, (ch) => String.fromCharCode(ch.charCodeAt(0) + 0xfee0));
|
package/package.json
CHANGED