-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
823 lines (745 loc) · 27.4 KB
/
Copy pathapp.js
File metadata and controls
823 lines (745 loc) · 27.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
import { Chessground } from './vendor/chessground.min.js';
import { Chess } from './vendor/chess.js';
// --- Engine (UCI over web worker) -----------------------------------------
class Engine {
constructor(url) {
this.worker = new Worker(url);
this.listeners = [];
this.queue = Promise.resolve(); // serializes searches (game moves vs hints)
this.worker.onmessage = (e) => {
const line = typeof e.data === 'string' ? e.data : '';
this.listeners = this.listeners.filter((fn) => !fn(line));
};
}
send(cmd) {
this.worker.postMessage(cmd);
}
// Resolves when a line matching `re` arrives; listener returns true to detach.
wait(re) {
return new Promise((resolve) => {
this.listeners.push((line) => {
const m = line.match(re);
if (m) resolve(m);
return !!m;
});
});
}
// Observe every line until the returned detach function is called.
listen(fn) {
let active = true;
this.listeners.push((line) => {
if (!active) return true; // lazily removed
fn(line);
return false;
});
return () => { active = false; };
}
async init() {
const ready = this.wait(/^uciok$/);
this.send('uci');
await ready;
this.send('setoption name UCI_LimitStrength value true');
}
setElo(elo) {
this.send(`setoption name UCI_Elo value ${elo}`);
}
newGame() {
this.send('stop');
this.send('ucinewgame');
}
// full=true searches at full strength (hints, evals).
// pvs>1 also collects the engine's top-N candidate moves (MultiPV).
// Returns {move, score, lines} — score is {kind: 'cp'|'mate', val} from the
// side-to-move's point of view, from the deepest info line seen; lines[i]
// is {move, score} for the (i+1)-th best candidate when pvs > 1.
search(fen, movetimeMs, { full = false, pvs = 1 } = {}) {
const run = async () => {
this.send(`setoption name UCI_LimitStrength value ${full ? 'false' : 'true'}`);
if (pvs > 1) this.send(`setoption name MultiPV value ${pvs}`);
let score = null;
const lines = [];
const detach = this.listen((line) => {
const pv = line.match(/^info .*\bmultipv (\d+) .*\bscore (cp|mate) (-?\d+).*\bpv (\S+)/);
if (pv) {
lines[Number(pv[1]) - 1] = { move: pv[4], score: { kind: pv[2], val: Number(pv[3]) } };
return;
}
const m = line.match(/^info .*\bscore (cp|mate) (-?\d+)/);
if (m) score = { kind: m[1], val: Number(m[2]) };
});
const done = this.wait(/^bestmove (\S+)/);
this.send(`position fen ${fen}`);
this.send(`go movetime ${movetimeMs}`);
const move = (await done)[1];
detach();
if (pvs > 1) this.send('setoption name MultiPV value 1');
return { move, score: lines[0] ? lines[0].score : score, lines };
};
const p = this.queue.then(run);
this.queue = p.catch(() => {});
return p;
}
}
// --- Game state -------------------------------------------------------------
const chess = new Chess();
const engine = new Engine('vendor/stockfish-18-lite-single.js');
let playerColor = 'white';
let thinking = false;
let searchId = 0; // bumped on new game to discard stale engine replies
let trainer = null; // active training position {fen, name, goal, playerSide}, or null
let positions = []; // loaded from positions.json
const statusEl = document.getElementById('status');
const movesEl = document.getElementById('moves');
const eloInput = document.getElementById('elo');
const eloLabel = document.getElementById('elo-label');
const colorSelect = document.getElementById('color-select');
const undoBtn = document.getElementById('undo');
const hintBtn = document.getElementById('hint');
const promoOverlay = document.getElementById('promo-overlay');
const trainerSelect = document.getElementById('trainer-select');
const evalFill = document.getElementById('eval-white');
const evalNum = document.getElementById('eval-num');
const pgnInput = document.getElementById('pgn-input');
const analysisEl = document.getElementById('analysis');
const graphEl = document.getElementById('graph');
const summaryEl = document.getElementById('analysis-summary');
// --- Eval bar -----------------------------------------------------------------
// score: {kind, val} from `stm`'s ('w'|'b') point of view
function setEval(score, stm) {
if (!score) return;
const sign = stm === 'w' ? 1 : -1;
let frac, label;
if (score.kind === 'mate') {
const mate = sign * score.val;
frac = mate > 0 ? 1 : 0;
label = `#${Math.abs(score.val)}`;
} else {
const cp = sign * score.val;
// cp -> win probability, same shape lichess uses
frac = 1 / (1 + Math.exp(-0.00368208 * cp));
label = (cp >= 0 ? '+' : '−') + Math.abs(cp / 100).toFixed(1);
}
evalFill.style.height = `${(frac * 100).toFixed(1)}%`;
evalNum.textContent = label;
}
function setEvalTerminal() {
if (chess.isCheckmate()) {
const whiteWon = chess.turn() === 'b';
evalFill.style.height = whiteWon ? '100%' : '0%';
evalNum.textContent = whiteWon ? '1-0' : '0-1';
} else {
evalFill.style.height = '50%';
evalNum.textContent = '½';
}
}
// quick full-strength eval of the current position (start of games/puzzles)
async function evalCurrent() {
const fenAtRequest = chess.fen();
const { score } = await engine.search(fenAtRequest, 300, { full: true });
if (chess.fen() === fenAtRequest && !chess.isGameOver()) {
setEval(score, fenAtRequest.split(' ')[1]);
}
}
// --- Post-game analysis graph -------------------------------------------------
const GRAPH_W = 560;
const GRAPH_H = 90;
// lichess-style judgements by win-probability lost on the move
const JUDGEMENTS = [
{ min: 0.3, kind: 'blunder', plural: 'blunders', glyph: '??', color: '#df5353' },
{ min: 0.2, kind: 'mistake', plural: 'mistakes', glyph: '?', color: '#e69f00' },
{ min: 0.1, kind: 'inaccuracy', plural: 'inaccuracies', glyph: '?!', color: '#56b4e9' },
];
let analysis = null; // {fens, moves, fracs, labels, marks, viewPly} while reviewing
// win probability 0..1 for the side to move (same sigmoid as the eval bar)
function moverWinFrac(score) {
if (score.kind === 'mate') return score.val > 0 ? 1 : 0;
return 1 / (1 + Math.exp(-0.00368208 * score.val));
}
// same, from White's point of view
function whiteWinFrac(score, stm) {
return stm === 'w' ? moverWinFrac(score) : 1 - moverWinFrac(score);
}
function scoreLabel(score, stm) {
const sign = stm === 'w' ? 1 : -1;
if (score.kind === 'mate') return `#${Math.abs(score.val)}`;
const cp = sign * score.val;
return (cp >= 0 ? '+' : '−') + Math.abs(cp / 100).toFixed(1);
}
async function analyseGame() {
if (analysis) return; // already reviewing this game
const moves = chess.history({ verbose: true });
if (moves.length < 2) return;
const id = searchId;
const a = analysis = {
fens: [moves[0].before, ...moves.map((m) => m.after)],
moves,
fracs: [],
labels: [],
best: [], // engine's preferred move per position (uci), null at terminal ones
marks: [],
viewPly: moves.length,
};
analysisEl.classList.remove('hidden');
ground.redrawAll(); // graph changed the layout — refresh cached board bounds
const finished = chess.isGameOver();
for (let i = 0; i < a.fens.length; i++) {
summaryEl.textContent = `Analysing… ${i + 1}/${a.fens.length}`;
// a finished game's last position carries the real result (incl.
// repetition draws the engine can't see from a lone FEN); everything
// else is engine-evaluated
const pos = finished && i === a.fens.length - 1 ? chess : new Chess(a.fens[i]);
if (pos.isCheckmate()) {
a.fracs.push(pos.turn() === 'w' ? 0 : 1);
a.labels.push(pos.turn() === 'w' ? '0-1' : '1-0');
a.best.push(null);
} else if (pos.isGameOver()) {
a.fracs.push(0.5);
a.labels.push('½');
a.best.push(null);
} else {
const { move, score } = await engine.search(a.fens[i], 180, { full: true });
// a new game started or play continued — abandon the review
if (id !== searchId || analysis !== a) return;
const stm = a.fens[i].split(' ')[1];
a.fracs.push(score ? whiteWinFrac(score, stm) : 0.5);
a.labels.push(score ? scoreLabel(score, stm) : '?');
a.best.push(move);
}
drawGraph();
}
a.marks = a.moves.map((m, i) => {
const loss = m.color === 'w'
? a.fracs[i] - a.fracs[i + 1]
: a.fracs[i + 1] - a.fracs[i];
return JUDGEMENTS.find((j) => loss >= j.min) || null;
});
drawGraph();
renderSummary();
setBarFromAnalysis(a.viewPly);
renderMoves(); // move list gains glyphs and becomes clickable
}
function moveLabel(i) {
const m = analysis.moves[i];
const num = m.before.split(' ')[5];
return `${num}${m.color === 'w' ? '.' : '…'} ${m.san}`;
}
function drawGraph() {
if (!analysis) return;
const n = analysis.fens.length - 1;
const px = (i) => ((i / n) * GRAPH_W).toFixed(1);
const py = (f) => ((1 - f) * GRAPH_H).toFixed(1);
const parts = [];
// white's share of win probability, filled from the bottom like the eval bar
if (analysis.fracs.length > 1) {
const pts = analysis.fracs.map((f, i) => `${px(i)} ${py(f)}`);
parts.push(`<path d="M 0 ${GRAPH_H} L ${pts.join(' L ')} L ${px(analysis.fracs.length - 1)} ${GRAPH_H} Z" fill="#f5f3f0"/>`);
}
parts.push(`<line x1="0" y1="${GRAPH_H / 2}" x2="${GRAPH_W}" y2="${GRAPH_H / 2}" stroke="rgba(128,128,128,0.55)" stroke-dasharray="3 3"/>`);
parts.push(`<line x1="${px(analysis.viewPly)}" y1="0" x2="${px(analysis.viewPly)}" y2="${GRAPH_H}" stroke="#629924" stroke-width="1.5"/>`);
analysis.marks.forEach((mark, i) => {
if (!mark) return;
parts.push(`<circle cx="${px(i + 1)}" cy="${py(analysis.fracs[i + 1])}" r="3.5" fill="${mark.color}" stroke="#403d39"><title>${moveLabel(i)}${mark.glyph} (${mark.kind})</title></circle>`);
});
graphEl.innerHTML = parts.join('');
}
// lichess's accuracy curve — 100 for perfect moves, decaying with win% lost
function accuracy(color) {
const accs = analysis.moves
.map((m, i) => {
if (m.color !== color) return null;
const lost = color === 'w'
? analysis.fracs[i] - analysis.fracs[i + 1]
: analysis.fracs[i + 1] - analysis.fracs[i];
const d = Math.max(0, lost * 100);
return Math.min(100, Math.max(0, 103.1668 * Math.exp(-0.04354 * d) - 3.1669));
})
.filter((v) => v !== null);
return accs.length ? Math.round(accs.reduce((x, y) => x + y, 0) / accs.length) : 100;
}
function renderSummary() {
const counts = { blunder: 0, mistake: 0, inaccuracy: 0 };
for (const m of analysis.marks) if (m) counts[m.kind]++;
const judged = JUDGEMENTS
.map((j) => `<b style="color:${j.color}">${counts[j.kind]}</b> ${counts[j.kind] === 1 ? j.kind : j.plural}`)
.join(' · ');
summaryEl.innerHTML =
`Accuracy: White <b>${accuracy('w')}%</b> · Black <b>${accuracy('b')}%</b> — ${judged}` +
' — click a move or the graph, or use ←/→';
}
// show a past position on the board without touching game state
function gotoPly(ply) {
if (!analysis) return;
analysis.viewPly = ply;
const pos = new Chess(analysis.fens[ply]);
const mv = ply > 0 ? analysis.moves[ply - 1] : null;
// at the final ply of an unfinished (loaded) game, play can continue
const atLiveEnd = ply === analysis.fens.length - 1 && !chess.isGameOver();
ground.set({
fen: analysis.fens[ply],
turnColor: fullColor(pos.turn()),
check: pos.inCheck(),
lastMove: mv ? [mv.from, mv.to] : undefined,
movable: atLiveEnd ? { color: playerColor, dests: toDests() } : { color: undefined },
});
setBarFromAnalysis(ply);
// show what the engine would have played here
const best = analysis.best[ply];
ground.setAutoShapes(best
? [{ orig: best.slice(0, 2), dest: best.slice(2, 4), brush: 'green' }]
: []);
renderMoves(); // move the highlight in the move list
drawGraph();
}
function setBarFromAnalysis(ply) {
if (analysis.fracs[ply] == null) return;
evalFill.style.height = `${(analysis.fracs[ply] * 100).toFixed(1)}%`;
evalNum.textContent = analysis.labels[ply];
}
function clearAnalysis() {
const wasShown = !analysisEl.classList.contains('hidden');
analysis = null;
analysisEl.classList.add('hidden');
graphEl.innerHTML = '';
summaryEl.textContent = '';
if (wasShown) ground.redrawAll(); // layout shifted back — refresh board bounds
}
movesEl.addEventListener('click', (e) => {
if (!analysis) return;
const s = e.target.closest('.san');
if (s && s.dataset.ply) gotoPly(Number(s.dataset.ply));
});
graphEl.addEventListener('click', (e) => {
if (!analysis) return;
const rect = graphEl.getBoundingClientRect();
const n = analysis.fens.length - 1;
const ply = Math.round(((e.clientX - rect.left) / rect.width) * n);
gotoPly(Math.min(Math.max(ply, 0), n));
});
document.addEventListener('keydown', (e) => {
if (!analysis) return;
if (e.target && /^(INPUT|SELECT|TEXTAREA)$/.test(e.target.tagName)) return;
if (e.key === 'ArrowLeft') gotoPly(Math.max(0, analysis.viewPly - 1));
else if (e.key === 'ArrowRight') gotoPly(Math.min(analysis.fens.length - 1, analysis.viewPly + 1));
else return;
e.preventDefault();
});
// --- Sounds (lichess standard set) -------------------------------------------
const sounds = {
move: new Audio('sounds/Move.mp3'),
capture: new Audio('sounds/Capture.mp3'),
gameEnd: new Audio('sounds/GenericNotify.mp3'),
};
let muted = localStorage.getItem('muted') === '1';
function playSound(name) {
if (muted) return;
const a = sounds[name];
a.currentTime = 0;
a.play().catch(() => {}); // autoplay may be blocked before first gesture
}
function soundForMove(move) {
playSound(move.captured ? 'capture' : 'move');
if (chess.isGameOver()) playSound('gameEnd');
}
const ground = Chessground(document.getElementById('board'), {
fen: chess.fen(),
orientation: playerColor,
movable: {
color: playerColor,
free: false,
dests: toDests(),
showDests: true,
events: { after: onUserMove },
},
premovable: { enabled: true },
});
// --- Helpers ----------------------------------------------------------------
function fullColor(c) {
return c === 'w' ? 'white' : 'black';
}
function toDests() {
const dests = new Map();
for (const m of chess.moves({ verbose: true })) {
const arr = dests.get(m.from) || [];
arr.push(m.to);
dests.set(m.from, arr);
}
return dests;
}
function sync(lastMove) {
ground.set({
fen: chess.fen(),
turnColor: fullColor(chess.turn()),
check: chess.inCheck(),
...(lastMove ? { lastMove } : {}),
movable: {
color: !thinking && !chess.isGameOver() ? playerColor : undefined,
dests: toDests(),
},
});
renderMoves();
renderStatus();
if (chess.isGameOver()) {
setEvalTerminal();
if (!analysis) {
updatePermalink(); // finished games are shareable straight from the URL bar
analyseGame();
}
}
undoBtn.disabled = thinking || chess.isGameOver() || chess.history().length < minHistoryForUndo;
}
function renderMoves() {
const history = chess.history();
movesEl.innerHTML = '';
if (analysis) movesEl.classList.add('analysed');
else movesEl.classList.remove('analysed');
for (let i = 0; i < history.length; i += 2) {
const li = document.createElement('li');
const num = document.createElement('span');
num.className = 'num';
num.textContent = `${i / 2 + 1}.`;
li.appendChild(num);
for (const j of [i, i + 1]) {
const san = history[j];
if (!san) continue;
const s = document.createElement('span');
s.className = 'san';
s.dataset.ply = j + 1;
const mark = analysis && analysis.marks[j];
s.textContent = mark ? san + mark.glyph : san;
if (mark) s.style.color = mark.color;
if (analysis && analysis.viewPly === j + 1) s.classList.add('current');
li.appendChild(s);
}
movesEl.appendChild(li);
}
// during play, follow the latest move; during review, stay where the user is
if (!analysis) movesEl.scrollTop = movesEl.scrollHeight;
}
function trainerGoalText() {
const side = playerColor === 'white' ? 'White' : 'Black';
return trainer.goal === 'win' ? `convert the win as ${side}` : `hold the draw as ${side}`;
}
function renderStatus() {
if (trainer && chess.isGameOver()) {
const playerWon = chess.isCheckmate() && fullColor(chess.turn()) !== playerColor;
const drawn = !chess.isCheckmate();
const success = trainer.goal === 'win' ? playerWon : playerWon || drawn;
statusEl.textContent = success
? `Success — you ${trainer.goal === 'win' ? 'converted the win' : 'held the draw'}!`
: `Failed — the goal was to ${trainerGoalText()}. "New game" retries it.`;
return;
}
if (chess.isCheckmate()) {
const winner = fullColor(chess.turn()) === playerColor ? 'Stockfish wins' : 'You win';
statusEl.textContent = `Checkmate — ${winner}!`;
} else if (chess.isStalemate()) {
statusEl.textContent = 'Draw — stalemate.';
} else if (chess.isThreefoldRepetition()) {
statusEl.textContent = 'Draw — threefold repetition.';
} else if (chess.isInsufficientMaterial()) {
statusEl.textContent = 'Draw — insufficient material.';
} else if (chess.isDraw()) {
statusEl.textContent = 'Draw.';
} else if (thinking) {
statusEl.textContent = 'Stockfish is thinking…';
} else {
const move = chess.inCheck() ? 'Your move — check!' : 'Your move.';
statusEl.textContent = trainer ? `Goal: ${trainerGoalText()}. ${move}` : move;
}
}
// --- Moves ------------------------------------------------------------------
function onUserMove(orig, dest) {
const piece = chess.get(orig);
const lastRank = piece && piece.color === 'w' ? '8' : '1';
if (piece && piece.type === 'p' && dest[1] === lastRank) {
askPromotion().then((promotion) => {
if (promotion) applyUserMove(orig, dest, promotion);
else sync(); // cancelled: snap the board back
});
return;
}
applyUserMove(orig, dest);
}
// SAN for a uci move in the current position (for hint text)
function sanFor(uci) {
const c = new Chess(chess.fen());
return c.move({
from: uci.slice(0, 2),
to: uci.slice(2, 4),
promotion: uci.length > 4 ? uci[4] : undefined,
}).san;
}
async function hint() {
if (thinking || chess.isGameOver()) return;
hintBtn.disabled = true;
hintBtn.textContent = 'Thinking…';
const fenAtRequest = chess.fen();
// MultiPV halves effective depth, so give the hint search more time
const { score, lines } = await engine.search(fenAtRequest, 1000, { full: true, pvs: 2 });
hintBtn.disabled = false;
hintBtn.textContent = 'Get a hint';
if (chess.fen() !== fenAtRequest) return; // position changed meanwhile
const stm = fenAtRequest.split(' ')[1];
setEval(score, stm);
const [best, second] = lines;
if (!best) return;
const arrow = (l, brush) => ({
orig: l.move.slice(0, 2),
dest: l.move.slice(2, 4),
brush,
label: { text: scoreLabel(l.score, stm) },
});
const shapes = [arrow(best, 'green')];
let secondNote = '';
if (second) {
// grade the runner-up by win probability given away, in the same
// colour language as the analysis graph
const gap = moverWinFrac(best.score) - moverWinFrac(second.score);
const brush = gap < 0.05 ? 'blue' : gap < 0.15 ? 'yellow' : 'red';
shapes.push(arrow(second, brush));
secondNote = ` · 2nd: ${sanFor(second.move)} ${scoreLabel(second.score, stm)} (${Math.round(gap * 100)}% worse)`;
}
ground.setAutoShapes(shapes);
statusEl.textContent = `Best: ${sanFor(best.move)} ${scoreLabel(best.score, stm)}${secondNote}`;
}
function applyUserMove(orig, dest, promotion) {
let move;
try {
move = chess.move({ from: orig, to: dest, promotion });
} catch {
sync(); // illegal (e.g. bad premove): snap back
return;
}
ground.setAutoShapes([]);
if (analysis) clearAnalysis(); // continuing a loaded game ends its review
soundForMove(move);
sync([orig, dest]);
if (!chess.isGameOver()) engineMove();
}
async function engineMove() {
thinking = true;
sync();
const id = searchId;
const fenAtSearch = chess.fen();
// trainer positions are defended at full strength — that's the exercise
const { move: uci, score } = await engine.search(fenAtSearch, 800, { full: !!trainer });
if (id !== searchId) return; // a new game started meanwhile
thinking = false;
setEval(score, fenAtSearch.split(' ')[1]);
const move = chess.move({
from: uci.slice(0, 2),
to: uci.slice(2, 4),
promotion: uci.length > 4 ? uci[4] : undefined,
});
soundForMove(move);
sync([move.from, move.to]);
ground.playPremove();
}
function askPromotion() {
promoOverlay.classList.remove('hidden');
return new Promise((resolve) => {
const done = (value) => {
promoOverlay.classList.add('hidden');
promoOverlay.onclick = null;
resolve(value);
};
promoOverlay.onclick = (e) => {
const btn = e.target.closest('button[data-piece]');
done(btn ? btn.dataset.piece : null);
};
});
}
// --- Sharing games as ?pgn= links ---------------------------------------------
// PGN for the current game with the boilerplate seven-tag roster stripped;
// SetUp/FEN headers are kept so games from custom positions round-trip
function gamePgn() {
return chess.pgn()
.split('\n')
.filter((l) => !/^\[(?!SetUp|FEN)/.test(l))
.join('\n')
.trim();
}
function updatePermalink() {
history.replaceState(null, '', `?pgn=${encodeURIComponent(gamePgn())}`);
}
// Replace the current game with a pasted/linked one and review it.
// Returns false (leaving the app untouched) if the PGN doesn't parse.
function loadGameFromPgn(text) {
const loaded = new Chess();
try {
// strip {comments}: we re-analyse anyway, and chess.js chokes on the
// consecutive comments lichess emits (draw offers, "The game is a draw.")
loaded.loadPgn(text.replace(/\{[^}]*\}/g, ' ').trim());
} catch {
return false;
}
if (loaded.history().length < 1) return false;
trainer = null;
startFen = null;
trainerSelect.value = '';
searchId++;
thinking = false;
clearAnalysis();
engine.newGame();
engine.setElo(Number(eloInput.value));
chess.loadPgn(loaded.pgn());
playerColor = fullColor(chess.turn()); // if unfinished, you continue as the side to move
ground.set({ orientation: playerColor });
ground.cancelPremove();
ground.setAutoShapes([]);
minHistoryForUndo = chess.history().length + 2; // undo only moves made after loading
const last = chess.history({ verbose: true }).at(-1);
sync([last.from, last.to]);
updatePermalink();
analyseGame(); // review even when the game isn't finished
return true;
}
const savePosBtn = document.getElementById('save-pos');
// Put the current (or currently reviewed) position in the URL and copy the
// link — the URL is the save file: bookmark it, open it later, drill it.
async function savePositionLink() {
const fen = analysis ? analysis.fens[analysis.viewPly] : chess.fen();
history.replaceState(null, '', `?fen=${encodeURIComponent(fen)}`);
let copied = false;
try {
await navigator.clipboard.writeText(location.href);
copied = true;
} catch { /* clipboard unavailable — the URL bar still has the link */ }
savePosBtn.textContent = copied ? 'Link copied ✓' : 'Link in URL bar ✓';
setTimeout(() => { savePosBtn.textContent = 'Copy position link'; }, 1500);
return fen;
}
savePosBtn.addEventListener('click', savePositionLink);
pgnInput.addEventListener('keydown', (e) => {
if (e.key !== 'Enter') return;
if (loadGameFromPgn(pgnInput.value)) {
pgnInput.value = '';
pgnInput.blur();
} else {
pgnInput.classList.add('invalid');
setTimeout(() => pgnInput.classList.remove('invalid'), 800);
}
});
// --- Controls ---------------------------------------------------------------
let minHistoryForUndo = 2; // +1 when the engine moved first in this game
let startFen = null; // set when playing from a ?fen= position link
function startFreePlay() {
trainer = null;
startFen = null;
trainerSelect.value = '';
history.replaceState(null, '', location.pathname); // fresh game, fresh URL
chess.reset();
const choice = colorSelect.value;
playerColor = choice === 'random' ? (Math.random() < 0.5 ? 'white' : 'black') : choice;
begin();
}
function startTrainer(p) {
trainer = p;
startFen = null;
history.replaceState(null, '', location.pathname);
chess.load(p.fen);
playerColor = fullColor(p.playerSide);
begin();
}
// play from a bare position (a ?fen= link); "New game" retries it
function startFromFen(fen) {
try {
new Chess(fen); // validate
} catch {
return false;
}
trainer = null;
trainerSelect.value = '';
startFen = fen;
chess.load(fen);
playerColor = fullColor(chess.turn()); // you play the side to move
begin();
history.replaceState(null, '', `?fen=${encodeURIComponent(fen)}`);
return true;
}
function begin() {
searchId++;
thinking = false;
clearAnalysis();
engine.newGame();
engine.setElo(Number(eloInput.value));
ground.set({ orientation: playerColor, lastMove: undefined });
ground.cancelPremove();
ground.setAutoShapes([]);
const engineFirst = fullColor(chess.turn()) !== playerColor;
minHistoryForUndo = (engineFirst ? 1 : 0) + 2;
sync();
if (engineFirst) engineMove();
else evalCurrent();
}
// in trainer / position-link mode "New game" retries the current position
function newGame() {
if (trainer) startTrainer(trainer);
else if (startFen) startFromFen(startFen);
else startFreePlay();
}
async function loadPositions() {
try {
positions = await (await fetch('positions.json')).json();
} catch {
return; // trainer unavailable; free play still works
}
const groups = new Map();
positions.forEach((p, i) => {
let g = groups.get(p.category);
if (!g) {
g = document.createElement('optgroup');
g.label = p.category;
trainerSelect.appendChild(g);
groups.set(p.category, g);
}
const o = document.createElement('option');
o.value = i;
o.textContent = `${p.name} (${p.goal})`;
g.appendChild(o);
});
}
trainerSelect.addEventListener('change', () => {
if (trainerSelect.value === '') startFreePlay();
else startTrainer(positions[Number(trainerSelect.value)]);
});
function undo() {
if (thinking || chess.turn() !== playerColor[0]) return;
chess.undo(); // engine's reply
chess.undo(); // player's move
const last = chess.history({ verbose: true }).at(-1);
sync(last ? [last.from, last.to] : undefined);
evalCurrent();
}
const muteBtn = document.getElementById('mute');
muteBtn.textContent = muted ? '🔇' : '🔊';
muteBtn.addEventListener('click', () => {
muted = !muted;
localStorage.setItem('muted', muted ? '1' : '0');
muteBtn.textContent = muted ? '🔇' : '🔊';
});
document.getElementById('new-game').addEventListener('click', newGame);
document.getElementById('flip').addEventListener('click', () => ground.toggleOrientation());
undoBtn.addEventListener('click', undo);
hintBtn.addEventListener('click', hint);
eloInput.addEventListener('input', () => {
eloLabel.textContent = eloInput.value;
engine.setElo(Number(eloInput.value));
});
// --- Boot -------------------------------------------------------------------
statusEl.textContent = 'Loading engine…';
loadPositions(); // in parallel with engine init
await engine.init();
const bootParams = new URLSearchParams(location.search);
const linkedPgn = bootParams.get('pgn');
const linkedFen = bootParams.get('fen');
if (linkedPgn && loadGameFromPgn(linkedPgn)) {
// reviewing a shared game
} else if (!linkedFen || !startFromFen(linkedFen)) {
newGame();
}
// Console/debug handle
window.game = {
chess, engine, move: applyUserMove, newGame, sounds, hint, startTrainer,
gotoPly, loadGame: loadGameFromPgn, startFromFen, savePosition: savePositionLink,
};