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/stats.js
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
export const EMPTY_STATS = { games: [] };
|
|
3
|
+
/** A fresh name for a game. */
|
|
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);
|
|
12
|
+
const limitOf = (game) => game.limit === undefined ? {} : { limit: Number.isFinite(game.limit) ? game.limit : null };
|
|
13
|
+
export function statsFor(stats, drawMode) {
|
|
14
|
+
// Oldest first, so runs of wins can be counted as they happened.
|
|
15
|
+
const games = stats.games.filter((g) => g.drawMode === drawMode).reverse();
|
|
16
|
+
let won = 0;
|
|
17
|
+
let run = 0;
|
|
18
|
+
let bestStreak = 0;
|
|
19
|
+
let bestMs;
|
|
20
|
+
let fewestMoves;
|
|
21
|
+
for (const g of games) {
|
|
22
|
+
if (g.result === 'won') {
|
|
23
|
+
won++;
|
|
24
|
+
run++;
|
|
25
|
+
bestStreak = Math.max(bestStreak, run);
|
|
26
|
+
if (bestMs === undefined || g.ms < bestMs)
|
|
27
|
+
bestMs = g.ms;
|
|
28
|
+
if (fewestMoves === undefined || g.moves < fewestMoves)
|
|
29
|
+
fewestMoves = g.moves;
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
run = 0;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return {
|
|
36
|
+
played: games.length,
|
|
37
|
+
won,
|
|
38
|
+
streak: run,
|
|
39
|
+
bestStreak,
|
|
40
|
+
...(bestMs === undefined ? {} : { bestMs }),
|
|
41
|
+
...(fewestMoves === undefined ? {} : { fewestMoves }),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/** Adds a finished game, unless a game with its id is on record already. */
|
|
45
|
+
export function addGame(stats, game) {
|
|
46
|
+
if (stats.games.some((g) => g.id === game.id))
|
|
47
|
+
return stats;
|
|
48
|
+
return { ...stats, games: [game, ...stats.games] };
|
|
49
|
+
}
|
|
50
|
+
export function recordWin(stats, drawMode, ms, moves, game) {
|
|
51
|
+
const before = statsFor(stats, drawMode);
|
|
52
|
+
// Not on the very first win: there is nothing to beat yet.
|
|
53
|
+
const bestTime = before.bestMs !== undefined && ms < before.bestMs;
|
|
54
|
+
const fewestMoves = before.fewestMoves !== undefined && moves < before.fewestMoves;
|
|
55
|
+
const record = { id: game.id, seed: game.seed, drawMode, result: 'won', ms, moves, at: game.at, redeals: game.redeals, ...limitOf(game) };
|
|
56
|
+
return { stats: addGame(stats, record), record: { ms, moves, redeals: game.redeals, bestTime, fewestMoves }, game: record };
|
|
57
|
+
}
|
|
58
|
+
/** A game given up (a new deal, or the saved game replaced) is a loss: it ends the streak. */
|
|
59
|
+
export function recordLoss(stats, drawMode, end) {
|
|
60
|
+
const record = {
|
|
61
|
+
id: end.id,
|
|
62
|
+
seed: end.seed,
|
|
63
|
+
drawMode,
|
|
64
|
+
result: 'lost',
|
|
65
|
+
ms: end.ms,
|
|
66
|
+
moves: end.moves,
|
|
67
|
+
at: end.at,
|
|
68
|
+
...limitOf(end),
|
|
69
|
+
...(end.lostAt === undefined ? {} : { lostAt: end.lostAt }),
|
|
70
|
+
};
|
|
71
|
+
return { stats: addGame(stats, record), game: record };
|
|
72
|
+
}
|
|
73
|
+
/** The newest lost game not rated yet: the background rates them one at a time. */
|
|
74
|
+
export function unrated(stats) {
|
|
75
|
+
return stats.games.find((g) => g.result === 'lost' && g.level === undefined);
|
|
76
|
+
}
|
|
77
|
+
/** Sets the level of the game with this id. */
|
|
78
|
+
export function withLevel(stats, id, level) {
|
|
79
|
+
const i = stats.games.findIndex((g) => g.id === id);
|
|
80
|
+
if (i < 0)
|
|
81
|
+
return stats;
|
|
82
|
+
const games = [...stats.games];
|
|
83
|
+
games[i] = { ...games[i], level };
|
|
84
|
+
return { ...stats, games };
|
|
85
|
+
}
|
|
86
|
+
/** Marks these games sent. */
|
|
87
|
+
export function withSent(stats, ids) {
|
|
88
|
+
const done = new Set(ids);
|
|
89
|
+
return { ...stats, games: stats.games.map((g) => (done.has(g.id) && !g.sent ? { ...g, sent: true } : g)) };
|
|
90
|
+
}
|
|
91
|
+
/** The newest game with this deal that ended `result`, if any. */
|
|
92
|
+
export function pastGame(stats, seed, drawMode, result) {
|
|
93
|
+
return stats.games.find((g) => g.seed === seed && g.drawMode === drawMode && g.result === result);
|
|
94
|
+
}
|
|
95
|
+
export function winRate(m) {
|
|
96
|
+
return m.played === 0 ? 0 : Math.round((m.won / m.played) * 100);
|
|
97
|
+
}
|
|
98
|
+
// ---------------------------------------------------------------------------
|
|
99
|
+
// The log on disk
|
|
100
|
+
const count = (v) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.floor(v) : 0);
|
|
101
|
+
const isLevel = (v) => v === 0 || v === 1 || v === 2 || v === 3;
|
|
102
|
+
/** What a game's id looks like: see {@link newGameId}. */
|
|
103
|
+
export const GAME_ID = /^[0-9a-f]{8,32}$/;
|
|
104
|
+
/** One game as read back, or undefined if anything about it is off. `id` stands in for a record without one (old files). */
|
|
105
|
+
export function parseGame(x, id) {
|
|
106
|
+
if (typeof x !== 'object' || x === null)
|
|
107
|
+
return undefined;
|
|
108
|
+
const g = x;
|
|
109
|
+
const gid = typeof g.id === 'string' && GAME_ID.test(g.id) ? g.id : id;
|
|
110
|
+
if (gid === undefined)
|
|
111
|
+
return undefined;
|
|
112
|
+
if (!Number.isInteger(g.seed) || g.seed < 0 || (g.drawMode !== 1 && g.drawMode !== 3))
|
|
113
|
+
return undefined;
|
|
114
|
+
if (g.result !== 'won' && g.result !== 'lost')
|
|
115
|
+
return undefined;
|
|
116
|
+
const redeals = g.result === 'won' && typeof g.redeals === 'number' ? { redeals: count(g.redeals) } : {};
|
|
117
|
+
const limit = g.limit === null ? { limit: null } : Number.isInteger(g.limit) && g.limit >= 0 ? { limit: g.limit } : {};
|
|
118
|
+
const lostAt = g.result === 'lost' && typeof g.lostAt === 'number' ? { lostAt: count(g.lostAt) } : {};
|
|
119
|
+
const level = g.result === 'lost' && isLevel(g.level) ? { level: g.level } : {};
|
|
120
|
+
const sent = g.sent === true ? { sent: true } : {};
|
|
121
|
+
return { id: gid, seed: g.seed, drawMode: g.drawMode, result: g.result, ms: count(g.ms), moves: count(g.moves), at: count(g.at), ...redeals, ...limit, ...lostAt, ...level, ...sent };
|
|
122
|
+
}
|
|
123
|
+
/** The line written for an event. */
|
|
124
|
+
export function eventLine(e) {
|
|
125
|
+
return JSON.stringify(e) + '\n';
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Works the games out from the log, oldest line first. A game is counted
|
|
129
|
+
* once, by the first line that finished it; damaged lines (a crash halfway
|
|
130
|
+
* through a write, say) are skipped.
|
|
131
|
+
*/
|
|
132
|
+
export function foldLog(text) {
|
|
133
|
+
const games = [];
|
|
134
|
+
const at = new Map();
|
|
135
|
+
const levels = new Map();
|
|
136
|
+
const sent = new Set();
|
|
137
|
+
for (const line of text.split('\n')) {
|
|
138
|
+
if (!line.trim())
|
|
139
|
+
continue;
|
|
140
|
+
let e;
|
|
141
|
+
try {
|
|
142
|
+
e = JSON.parse(line);
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
if (typeof e !== 'object' || e === null)
|
|
148
|
+
continue;
|
|
149
|
+
if ('game' in e) {
|
|
150
|
+
const g = parseGame(e.game);
|
|
151
|
+
if (g && !at.has(g.id)) {
|
|
152
|
+
at.set(g.id, games.length);
|
|
153
|
+
games.push(g);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
else if ('level' in e && typeof e.level === 'object' && e.level !== null) {
|
|
157
|
+
const { id, level } = e.level;
|
|
158
|
+
if (typeof id === 'string' && isLevel(level))
|
|
159
|
+
levels.set(id, level);
|
|
160
|
+
}
|
|
161
|
+
else if ('sent' in e && Array.isArray(e.sent)) {
|
|
162
|
+
for (const id of e.sent)
|
|
163
|
+
if (typeof id === 'string')
|
|
164
|
+
sent.add(id);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
const done = games.map((g) => {
|
|
168
|
+
const level = levels.get(g.id);
|
|
169
|
+
return {
|
|
170
|
+
...g,
|
|
171
|
+
...(g.result === 'lost' && level !== undefined ? { level } : {}),
|
|
172
|
+
...(sent.has(g.id) ? { sent: true } : {}),
|
|
173
|
+
};
|
|
174
|
+
});
|
|
175
|
+
return { games: done.reverse() };
|
|
176
|
+
}
|
|
177
|
+
/** The share state as read back, or undefined if it is missing or odd. */
|
|
178
|
+
export function parseShare(json) {
|
|
179
|
+
const sh = typeof json === 'object' && json !== null ? json : undefined;
|
|
180
|
+
if (!sh || typeof sh.id !== 'string' || !/^[0-9a-f-]{36}$/.test(sh.id))
|
|
181
|
+
return undefined;
|
|
182
|
+
return { id: sh.id, asked: count(sh.asked), pending: sh.pending === true };
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* The statistics file from before the log (`stats.json`): games newest
|
|
186
|
+
* first, unfinished ones left out. Each game is given an id as it moves over.
|
|
187
|
+
*/
|
|
188
|
+
export function parseLegacyStats(json) {
|
|
189
|
+
const o = typeof json === 'object' && json !== null ? json : {};
|
|
190
|
+
const games = (Array.isArray(o.games) ? o.games : []).flatMap((x) => {
|
|
191
|
+
const g = parseGame(x, newGameId());
|
|
192
|
+
return g ? [g] : [];
|
|
193
|
+
});
|
|
194
|
+
const share = parseShare(o.share);
|
|
195
|
+
return { games, ...(share ? { share } : {}) };
|
|
196
|
+
}
|
package/dist/ui/ansi.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { isEmoji, sameCell } from './screen.js';
|
|
2
|
+
export const ansi = {
|
|
3
|
+
altScreenOn: '\x1b[?1049h',
|
|
4
|
+
altScreenOff: '\x1b[?1049l',
|
|
5
|
+
hideCursor: '\x1b[?25l',
|
|
6
|
+
/** Ask the terminal to report focus changes as ESC [ I and ESC [ O. */
|
|
7
|
+
focusReportingOn: '\x1b[?1004h',
|
|
8
|
+
focusReportingOff: '\x1b[?1004l',
|
|
9
|
+
showCursor: '\x1b[?25h',
|
|
10
|
+
clear: '\x1b[2J',
|
|
11
|
+
reset: '\x1b[0m',
|
|
12
|
+
/** Zero-based column and row. */
|
|
13
|
+
moveTo: (x, y) => `\x1b[${y + 1};${x + 1}H`,
|
|
14
|
+
/** Zero-based column, same row. */
|
|
15
|
+
column: (x) => `\x1b[${x + 1}G`,
|
|
16
|
+
sgr: (params) => `\x1b[${params}m`,
|
|
17
|
+
};
|
|
18
|
+
function rowText(buf, y, theme, from, to) {
|
|
19
|
+
let out = '';
|
|
20
|
+
let last = '';
|
|
21
|
+
for (let x = from; x < to; x++) {
|
|
22
|
+
const cell = buf.get(x, y);
|
|
23
|
+
if (cell.ch === '')
|
|
24
|
+
continue; // right half of a wide character
|
|
25
|
+
const sgr = theme.sgr(cell);
|
|
26
|
+
if (sgr !== last) {
|
|
27
|
+
out += ansi.sgr(sgr);
|
|
28
|
+
last = sgr;
|
|
29
|
+
}
|
|
30
|
+
if (isEmoji(cell.ch)) {
|
|
31
|
+
// Blank both cells, draw the emoji over them, then carry on from a known
|
|
32
|
+
// column, whether this terminal drew it one cell wide or two.
|
|
33
|
+
out += ' ' + ansi.column(x) + cell.ch + ansi.column(x + 2);
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
out += cell.ch;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return out + ansi.reset;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* The whole buffer as lines for normal (scrolling) output.
|
|
43
|
+
* Trailing blank cells are dropped so a narrow terminal does not wrap.
|
|
44
|
+
*/
|
|
45
|
+
export function paint(buf, theme) {
|
|
46
|
+
const lines = [];
|
|
47
|
+
for (let y = 0; y < buf.height; y++) {
|
|
48
|
+
let end = buf.width;
|
|
49
|
+
while (end > 0) {
|
|
50
|
+
const c = buf.get(end - 1, y);
|
|
51
|
+
if (c.ch !== ' ' || c.bg !== 'none')
|
|
52
|
+
break;
|
|
53
|
+
end--;
|
|
54
|
+
}
|
|
55
|
+
lines.push(end === 0 ? '' : rowText(buf, y, theme, 0, end));
|
|
56
|
+
}
|
|
57
|
+
return lines.join('\n');
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* The escape sequence that turns the screen showing `prev` into `next`, touching
|
|
61
|
+
* only cells that changed. With no `prev`, or a size change, redraws everything.
|
|
62
|
+
* Positions are absolute, so this works in raw mode without relying on newlines.
|
|
63
|
+
*/
|
|
64
|
+
export function diff(prev, next, theme) {
|
|
65
|
+
if (!prev || prev.width !== next.width || prev.height !== next.height) {
|
|
66
|
+
let out = ansi.reset + ansi.clear;
|
|
67
|
+
for (let y = 0; y < next.height; y++)
|
|
68
|
+
out += ansi.moveTo(0, y) + rowText(next, y, theme, 0, next.width);
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
let out = '';
|
|
72
|
+
for (let y = 0; y < next.height; y++) {
|
|
73
|
+
let x = 0;
|
|
74
|
+
while (x < next.width) {
|
|
75
|
+
if (sameCell(prev.get(x, y), next.get(x, y))) {
|
|
76
|
+
x++;
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
// Start a run at the beginning of a wide character, never in its right half.
|
|
80
|
+
let start = x;
|
|
81
|
+
if (next.get(start, y).ch === '' && start > 0)
|
|
82
|
+
start--;
|
|
83
|
+
let end = x + 1;
|
|
84
|
+
while (end < next.width && !sameCell(prev.get(end, y), next.get(end, y)))
|
|
85
|
+
end++;
|
|
86
|
+
if (end < next.width && next.get(end, y).ch === '')
|
|
87
|
+
end++;
|
|
88
|
+
out += ansi.moveTo(start, y) + rowText(next, y, theme, start, end);
|
|
89
|
+
x = end;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return out;
|
|
93
|
+
}
|
package/dist/ui/help.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { ScreenBuffer } from './screen.js';
|
|
2
|
+
import { statsFor, winRate } from '../stats.js';
|
|
3
|
+
const HELP = [
|
|
4
|
+
['', 'Press where cards come from, then where they go.'],
|
|
5
|
+
['', ''],
|
|
6
|
+
['q', 'draw from the stock'],
|
|
7
|
+
['w', 'the waste'],
|
|
8
|
+
['a s d f g h j', 'tableau columns 1 to 7'],
|
|
9
|
+
['i', 'send to its foundation (the usual way)'],
|
|
10
|
+
['r t y u', 'one particular foundation'],
|
|
11
|
+
['same key twice', 'move to the best spot'],
|
|
12
|
+
['', ''],
|
|
13
|
+
['arrows', 'move round the board; up and down change rows'],
|
|
14
|
+
['down in a column', 'choose cards from the top of the run, one fewer each time'],
|
|
15
|
+
['space', 'pick up / put down at the cursor; draw on the stock'],
|
|
16
|
+
['enter', "move the cursor's cards to the best spot"],
|
|
17
|
+
['z', 'undo'],
|
|
18
|
+
['? or /', 'a hint: the solver\'s next move (asks first)'],
|
|
19
|
+
['tab', 'large / compact cards'],
|
|
20
|
+
['esc', 'put held cards back; otherwise the menu:'],
|
|
21
|
+
['', ' new game, restart, Draw 1 / 3, hint, seeds, statistics, keys'],
|
|
22
|
+
['x', 'quit (asks first; the game is kept for next time)'],
|
|
23
|
+
['ctrl+q', 'quit at once (ctrl+c too); the game is still kept'],
|
|
24
|
+
['', ''],
|
|
25
|
+
['', 'Win ✓ in the header: this position can still be won.'],
|
|
26
|
+
['', 'Win 0%: it cannot. You will be offered a retry.'],
|
|
27
|
+
['', '↺3 under the stock: redeals left (turning the waste over).'],
|
|
28
|
+
['', 'A trip through the stock with no move: the game says one is there.'],
|
|
29
|
+
['', 'The cursor stays where cards came from: what turns up there is next.'],
|
|
30
|
+
];
|
|
31
|
+
export function renderHelp(width, height, ascii = false) {
|
|
32
|
+
const buf = new ScreenBuffer(width, height);
|
|
33
|
+
const sep = ascii ? '-' : '·';
|
|
34
|
+
buf.put(1, 0, `soliterminal ${sep} Help`, { fg: 'header' });
|
|
35
|
+
HELP.forEach(([key, text], i) => {
|
|
36
|
+
const y = i + 2;
|
|
37
|
+
if (!key) {
|
|
38
|
+
buf.put(3, y, ascii ? text.replace('✓', 'ok').replace('↺', 'O') : text, { fg: 'text' });
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
buf.put(3, y, key, { fg: 'key' });
|
|
42
|
+
buf.put(20, y, text, { fg: 'text' });
|
|
43
|
+
});
|
|
44
|
+
buf.put(1, Math.min(height - 1, HELP.length + 3), 'Press any key to go back to the game.', { fg: 'message' });
|
|
45
|
+
return buf;
|
|
46
|
+
}
|
|
47
|
+
/** Time on the clock, like 03:41. */
|
|
48
|
+
export function formatTime(ms) {
|
|
49
|
+
const s = Math.floor(ms / 1000);
|
|
50
|
+
return `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`;
|
|
51
|
+
}
|
|
52
|
+
/** Statistics for both draw modes, side by side. */
|
|
53
|
+
export function renderStats(width, height, stats, ascii = false) {
|
|
54
|
+
const buf = new ScreenBuffer(width, height);
|
|
55
|
+
buf.put(1, 0, `soliterminal ${ascii ? '-' : '·'} Statistics`, { fg: 'header' });
|
|
56
|
+
const rows = [
|
|
57
|
+
['Played', (m) => String(m.played)],
|
|
58
|
+
['Won', (m) => String(m.won)],
|
|
59
|
+
['Win rate', (m) => `${winRate(m)}%`],
|
|
60
|
+
['Streak', (m) => String(m.streak)],
|
|
61
|
+
['Longest streak', (m) => String(m.bestStreak)],
|
|
62
|
+
['Best time', (m) => (m.bestMs === undefined ? '-' : formatTime(m.bestMs))],
|
|
63
|
+
['Fewest moves', (m) => (m.fewestMoves === undefined ? '-' : String(m.fewestMoves))],
|
|
64
|
+
];
|
|
65
|
+
const col = [20, 32];
|
|
66
|
+
buf.put(col[0], 2, 'Draw 1', { fg: 'key', bold: true });
|
|
67
|
+
buf.put(col[1], 2, 'Draw 3', { fg: 'key', bold: true });
|
|
68
|
+
rows.forEach(([label, value], i) => {
|
|
69
|
+
const y = 4 + i;
|
|
70
|
+
buf.put(3, y, label, { fg: 'text' });
|
|
71
|
+
buf.put(col[0], y, value(statsFor(stats, 1)), { fg: 'text', bold: true });
|
|
72
|
+
buf.put(col[1], y, value(statsFor(stats, 3)), { fg: 'text', bold: true });
|
|
73
|
+
});
|
|
74
|
+
buf.put(3, 5 + rows.length, 'A game counts once it is won or given up; one kept for later waits.', { fg: 'dim' });
|
|
75
|
+
buf.put(3, 6 + rows.length, 'A new deal before this one is done is a loss: it ends the streak.', { fg: 'dim' });
|
|
76
|
+
buf.put(1, Math.min(height - 1, rows.length + 8), 'Press any key to go back to the game.', { fg: 'message' });
|
|
77
|
+
return buf;
|
|
78
|
+
}
|
|
79
|
+
/** A date and time in the player's own time zone, like 11-26 14:02. */
|
|
80
|
+
export const formatWhen = (at) => {
|
|
81
|
+
if (at <= 0)
|
|
82
|
+
return '';
|
|
83
|
+
const d = new Date(at);
|
|
84
|
+
const two = (n) => String(n).padStart(2, '0');
|
|
85
|
+
return `${two(d.getMonth() + 1)}-${two(d.getDate())} ${two(d.getHours())}:${two(d.getMinutes())}`;
|
|
86
|
+
};
|
|
87
|
+
/** The deals screen: a seed to type, and recent games to choose from. */
|
|
88
|
+
export function renderDeals(width, height, recent, screen, current, ascii = false) {
|
|
89
|
+
const buf = new ScreenBuffer(width, height);
|
|
90
|
+
buf.put(1, 0, `soliterminal ${ascii ? '-' : '·'} Deals`, { fg: 'header' });
|
|
91
|
+
let x = buf.put(3, 2, 'Seed ', { fg: 'text' });
|
|
92
|
+
x = buf.put(x, 2, screen.typed, { fg: 'key', bold: true });
|
|
93
|
+
buf.put(x, 2, ' ', { bg: 'cursor' });
|
|
94
|
+
buf.put(Math.max(x + 3, 24), 2, `Draw ${screen.drawMode} (${ascii ? 'left / right' : '← →'} switches)`, { fg: 'dim' });
|
|
95
|
+
// What became of the typed deal before.
|
|
96
|
+
if (screen.typed) {
|
|
97
|
+
const seed = Number(screen.typed);
|
|
98
|
+
const won = recent.find((g) => g.seed === seed && g.drawMode === screen.drawMode && g.result === 'won');
|
|
99
|
+
const lost = recent.find((g) => g.seed === seed && g.drawMode === screen.drawMode && g.result === 'lost');
|
|
100
|
+
if (won)
|
|
101
|
+
buf.put(9, 3, `Won on ${formatWhen(won.at)}: won deals are not played again.`, { fg: 'red' });
|
|
102
|
+
else if (lost)
|
|
103
|
+
buf.put(9, 3, `Lost on ${formatWhen(lost.at)}.`, { fg: 'message' });
|
|
104
|
+
}
|
|
105
|
+
buf.put(3, 4, 'Your games', { fg: 'key', bold: true });
|
|
106
|
+
const cols = [5, 17, 23, 34, 41, 48, 56, 64];
|
|
107
|
+
['Seed', 'Draw', 'Result', 'Time', 'Moves', 'Redeals', 'Level', 'When'].forEach((h, i) => buf.put(cols[i], 5, h, { fg: 'dim' }));
|
|
108
|
+
const room = Math.max(1, height - 11);
|
|
109
|
+
// Keep the chosen row in view.
|
|
110
|
+
const first = Math.max(0, Math.min(screen.index - room + 1, recent.length - room));
|
|
111
|
+
if (recent.length === 0)
|
|
112
|
+
buf.put(5, 6, 'None yet: games are listed once they are won or given up.', { fg: 'dim' });
|
|
113
|
+
recent.slice(first, first + room).forEach((g, k) => {
|
|
114
|
+
const i = first + k;
|
|
115
|
+
const y = 6 + k;
|
|
116
|
+
const chosen = screen.typed === '' && i === screen.index;
|
|
117
|
+
// A loss proven in play says at which move; one given up while it might still be won says so.
|
|
118
|
+
const lost = g.lostAt === undefined ? ['gave up', 'message'] : g.lostAt === 0 ? ['no win', 'red'] : [`lost @${g.lostAt}`, 'red'];
|
|
119
|
+
const [result, fg] = g.result === 'won' ? ['won', 'key'] : lost;
|
|
120
|
+
if (chosen)
|
|
121
|
+
buf.put(3, y, ascii ? '>' : '›', { fg: 'key', bold: true });
|
|
122
|
+
buf.put(cols[0], y, String(g.seed), { fg: chosen ? 'key' : 'text', bold: chosen });
|
|
123
|
+
buf.put(cols[1], y, String(g.drawMode), { fg: 'text' });
|
|
124
|
+
buf.put(cols[2], y, result, { fg });
|
|
125
|
+
buf.put(cols[3], y, formatTime(g.ms), { fg: 'text' });
|
|
126
|
+
buf.put(cols[4], y, String(g.moves).padStart(5), { fg: 'text' });
|
|
127
|
+
buf.put(cols[7], y, formatWhen(g.at), { fg: 'dim' });
|
|
128
|
+
// Lost deals are rated in the background: … until then, ? if no win was found to rate them by.
|
|
129
|
+
if (g.result === 'lost') {
|
|
130
|
+
const level = g.level === undefined ? (ascii ? '..' : '…') : ['?', 'easy', 'medium', 'hard'][g.level];
|
|
131
|
+
buf.put(cols[6], y, level, { fg: g.level === 3 ? 'red' : g.level === undefined ? 'dim' : 'text' });
|
|
132
|
+
}
|
|
133
|
+
if (g.result === 'won' && g.redeals !== undefined)
|
|
134
|
+
buf.put(cols[5], y, String(g.redeals).padStart(3), { fg: 'text' });
|
|
135
|
+
});
|
|
136
|
+
const foot = Math.min(height - 3, 7 + Math.min(room, Math.max(recent.length, 1)));
|
|
137
|
+
const arrows = ascii ? 'up / down' : '↑ ↓';
|
|
138
|
+
buf.put(1, foot, `Type a seed, or choose a game with ${arrows}. Enter plays it; esc goes back.`, { fg: 'message' });
|
|
139
|
+
if (screen.note)
|
|
140
|
+
buf.put(1, foot + 1, screen.note, { fg: 'red', bold: true });
|
|
141
|
+
else if (current.playing)
|
|
142
|
+
buf.put(1, foot + 1, `Playing another deal gives up seed ${current.seed}: it counts as a loss.`, { fg: 'dim' });
|
|
143
|
+
return buf;
|
|
144
|
+
}
|
|
145
|
+
/** A centred notice, used when the window is too small to draw the board. */
|
|
146
|
+
export function renderNotice(width, height, lines) {
|
|
147
|
+
const buf = new ScreenBuffer(Math.max(width, 1), Math.max(height, 1));
|
|
148
|
+
const top = Math.max(0, Math.floor((height - lines.length) / 2));
|
|
149
|
+
lines.forEach((line, i) => {
|
|
150
|
+
const x = Math.max(0, Math.floor((width - line.length) / 2));
|
|
151
|
+
buf.put(x, top + i, line, { fg: i === 0 ? 'message' : 'text' });
|
|
152
|
+
});
|
|
153
|
+
return buf;
|
|
154
|
+
}
|
package/dist/ui/input.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
const NAMED = {
|
|
2
|
+
return: 'enter',
|
|
3
|
+
enter: 'enter',
|
|
4
|
+
escape: 'escape',
|
|
5
|
+
space: 'space',
|
|
6
|
+
backspace: 'backspace',
|
|
7
|
+
up: 'up',
|
|
8
|
+
down: 'down',
|
|
9
|
+
left: 'left',
|
|
10
|
+
right: 'right',
|
|
11
|
+
tab: 'tab',
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Turns a Node keypress into one short name the app understands:
|
|
15
|
+
* `q`, `a`, `?`, `left`, `space`, `enter`, `escape`, `tab`, `ctrl+q`…
|
|
16
|
+
* Shifted letters count as the plain letter. Returns `undefined` for keys the
|
|
17
|
+
* game does not use.
|
|
18
|
+
*/
|
|
19
|
+
export function normalizeKey(str, key) {
|
|
20
|
+
// Focus reports (ESC [ I / ESC [ O), sent once focus reporting is turned on.
|
|
21
|
+
if (key?.code === '[I')
|
|
22
|
+
return 'focus-in';
|
|
23
|
+
if (key?.code === '[O')
|
|
24
|
+
return 'focus-out';
|
|
25
|
+
if (key?.ctrl)
|
|
26
|
+
return key.name === 'c' ? 'ctrl+c' : key.name === 'q' ? 'ctrl+q' : undefined;
|
|
27
|
+
const name = key?.name;
|
|
28
|
+
if (name) {
|
|
29
|
+
if (NAMED[name])
|
|
30
|
+
return NAMED[name];
|
|
31
|
+
if (/^f\d{1,2}$/.test(name))
|
|
32
|
+
return name;
|
|
33
|
+
if (/^[a-z0-9]$/.test(name))
|
|
34
|
+
return name;
|
|
35
|
+
}
|
|
36
|
+
// Punctuation such as ` and ? arrives with no name, only the character.
|
|
37
|
+
if (str && str.length === 1 && str >= ' ' && str <= '~')
|
|
38
|
+
return str;
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { pile } from '../core/klondike.js';
|
|
2
|
+
/**
|
|
3
|
+
* Hotkeys mirror the board on the keyboard. The top row of the board sits on
|
|
4
|
+
* the top letter row (q stock, w waste, r t y u the foundations over columns
|
|
5
|
+
* 4 to 7, with e over the gap at column 3), and the seven columns sit on the
|
|
6
|
+
* home row straight below (a s d f g h j). i, the next key over from the
|
|
7
|
+
* foundations, means "whichever foundation fits" and is the one to reach for.
|
|
8
|
+
* Keys are lower-case names as Node's keypress events report them.
|
|
9
|
+
*/
|
|
10
|
+
export const STOCK_KEY = 'q';
|
|
11
|
+
export const WASTE_KEY = 'w';
|
|
12
|
+
export const TABLEAU_KEYS = ['a', 's', 'd', 'f', 'g', 'h', 'j'];
|
|
13
|
+
export const FOUNDATION_KEYS = ['r', 't', 'y', 'u'];
|
|
14
|
+
/** Destination only: whichever foundation the card belongs on. */
|
|
15
|
+
export const AUTO_FOUNDATION_KEY = 'i';
|
|
16
|
+
export function pileForKey(key) {
|
|
17
|
+
const k = key.toLowerCase();
|
|
18
|
+
if (k === STOCK_KEY)
|
|
19
|
+
return { kind: 'stock' };
|
|
20
|
+
if (k === WASTE_KEY)
|
|
21
|
+
return pile.waste;
|
|
22
|
+
if (k === AUTO_FOUNDATION_KEY)
|
|
23
|
+
return { kind: 'auto-foundation' };
|
|
24
|
+
const t = TABLEAU_KEYS.indexOf(k);
|
|
25
|
+
if (t >= 0)
|
|
26
|
+
return pile.tableau(t);
|
|
27
|
+
const f = FOUNDATION_KEYS.indexOf(k);
|
|
28
|
+
if (f >= 0)
|
|
29
|
+
return pile.foundation(f);
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
/** The label drawn above a pile on screen. */
|
|
33
|
+
export function keyLabel(target) {
|
|
34
|
+
switch (target.kind) {
|
|
35
|
+
case 'stock':
|
|
36
|
+
return STOCK_KEY;
|
|
37
|
+
case 'waste':
|
|
38
|
+
return WASTE_KEY;
|
|
39
|
+
case 'auto-foundation':
|
|
40
|
+
return AUTO_FOUNDATION_KEY;
|
|
41
|
+
case 'tableau':
|
|
42
|
+
return TABLEAU_KEYS[target.index];
|
|
43
|
+
case 'foundation':
|
|
44
|
+
return FOUNDATION_KEYS[target.index];
|
|
45
|
+
}
|
|
46
|
+
}
|