5 * Version of this script. If the server returns a version larger than
6 * this, it is a sign we should reload to upgrade ourselves.
11 let SCRIPT_VERSION = 2021021300;
14 * The current backend URL.
19 let backend_url = "/analysis.pl";
20 let backend_hash_url = "/hash";
22 /** @type {window.ChessBoard} @private */
25 /** @type {boolean} @private */
26 let board_is_animating = false;
29 * The most recent analysis data we have from the server
30 * (about the most recent position).
34 let current_analysis_data = null;
37 * If we are displaying previous analysis or from hash, this is non-null,
38 * and will override most of current_analysis_data.
43 let displayed_analysis_data = null;
46 * Games currently in progress, if any.
58 let current_games = null;
73 /** @type {Array.<Array.<boolean>>} */
74 let occupied_by_arrows = [];
76 /** Currently displayed refutation lines (on-screen).
77 * Can either come from the current_analysis_data, displayed_analysis_data,
78 * or hash_refutation_lines.
80 let refutation_lines = [];
82 /** Refutation lines from current hash probe.
84 * If non-null, will override refutation lines from the base position.
85 * Note that these are relative to display_fen, not base_fen.
87 let hash_refutation_lines = null;
89 /** @type {!number} @private */
92 /** @type {!string} @private */
95 /** @type {number} @private */
98 /** @type {boolean} @private */
99 let truncate_display_history = true;
101 /** @type {!string|undefined} @private */
102 let highlight_from = undefined;
104 /** @type {!string|undefined} @private */
105 let highlight_to = undefined;
107 /** The HTML object of the move currently being highlighted (in red).
110 let highlighted_move = null;
112 /** Currently suggested/recommended move when dragging.
113 * @type {?{from: !string, to: !string}}
116 let recommended_move = null;
118 /** If reverse-dragging (dragging from the destination square to the
119 * source square), the destination square.
123 let reverse_dragging_from = null;
125 /** @type {?number} @private */
128 /** @type {boolean} @private */
129 let enable_sound = false;
131 /** @type {!number} @private */
135 * Our best estimate of how many milliseconds we need to add to
136 * new Date() to get the true UTC time. Calibrated against the
142 let client_clock_offset_ms = null;
144 let clock_timer = null;
146 /** The current position being analyzed, represented as a FEN string.
147 * Note that this is not necessarily the same as display_fen.
153 /** The current position on the board, represented as a FEN string.
154 * Note that board.fen() does not contain e.g. who is to play.
158 let display_fen = null;
162 * pv: Array.<string>,
165 * scores: Array<{first_move: number, score: Object}>,
166 * start_display_move_num: number
169 * "start_display_move_num" is the (half-)move number to start displaying the PV at.
170 * "score" is also evaluated at this point.
173 /** All PVs that we currently know of.
175 * Element 0 is history (or null if no history).
176 * Element 1 is current main PV, or explored line if nowhere else on the screen.
177 * All remaining elements are refutation lines (multi-PV).
179 * @type {Array.<DisplayLine>}
182 let display_lines = [];
184 /** @type {?DisplayLine} @private */
185 let current_display_line = null;
187 /** @type {boolean} @private */
188 let current_display_line_is_history = false;
190 /** @type {?number} @private */
191 let current_display_move = null;
194 * The current backend request to get main analysis (not history), if any,
195 * so that we can abort it.
197 * @type {?AbortController}
200 let current_analysis_xhr = null;
203 * The current timer to fire off a request to get main analysis (not history),
204 * if any, so that we can abort it.
209 let current_analysis_request_timer = null;
212 * The current backend request to get historic data, if any.
214 * @type {?AbortController}
217 let current_historic_xhr = null;
220 * The current backend request to get hash probes, if any, so that we can abort it.
222 * @type {?AbortController}
225 let current_hash_xhr = null;
228 * The current timer to display hash probe information (it could be waiting on the
229 * board to stop animating), if any, so that we can abort it.
234 let current_hash_display_timer = null;
236 let supports_html5_storage = function() {
238 return 'localStorage' in window && window['localStorage'] !== null;
244 // Make the unique token persistent so people refreshing the page won't count twice.
245 // Of course, you can never fully protect against people deliberately wanting to spam.
246 let get_unique = function() {
247 let use_local_storage = supports_html5_storage();
248 if (use_local_storage && window['localStorage']['unique']) {
249 return window['localStorage']['unique'];
251 let unique = Math.random();
252 if (use_local_storage) {
253 window['localStorage']['unique'] = unique;
258 let request_update = function() {
259 current_analysis_request_timer = null;
261 let handle_err = () => {
262 // Backend error or similar. Wait ten seconds, then try again.
263 current_analysis_request_timer = setTimeout(function() { request_update(); }, 10000);
266 current_analysis_xhr = new AbortController();
267 const signal = current_analysis_xhr.signal;
268 fetch(backend_url + "?ims=" + ims + "&unique=" + unique, { signal })
269 .then((response) => response.json().then(data => ({ok: response.ok, headers: response.headers, json: data}))) // ick
276 if (delay_ms === 0) {
277 process_update_response(obj.json, obj.headers);
279 setTimeout(function() { process_update_response(obj.json, obj.headers); }, delay_ms);
283 if (!backend_url.match(/history/)) {
285 current_analysis_request_timer = setTimeout(function() { request_update(); }, timeout);
289 if (err.name === 'AbortError') {
290 // Aborted because we are switching backends. Abandon and don't retry,
291 // because another one is already started for us.
299 document.body.style.opacity = null;
304 let process_update_response = function(data, headers) {
305 sync_server_clock(headers.get('Date'));
306 ims = headers.get('X-RGLM');
307 let num_viewers = headers.get('X-RGNV');
309 if (Array.isArray(data)) {
310 new_data = JSON.parse(JSON.stringify(current_analysis_data));
311 JSON_delta.patch(new_data, data);
316 let minimum_version = headers.get('X-RGMV');
317 if (minimum_version && minimum_version > SCRIPT_VERSION) {
318 // Upgrade to latest version with a force-reload.
319 location.reload(true);
322 // Verify that the PV makes sense.
324 if (new_data['pv']) {
325 let hiddenboard = new Chess(new_data['position']['fen']);
326 for (let i = 0; i < new_data['pv'].length; ++i) {
327 if (hiddenboard.move(new_data['pv'][i]) === null) {
335 possibly_play_sound(current_analysis_data, new_data);
336 current_analysis_data = new_data;
338 update_num_viewers(num_viewers);
340 console.log("Received invalid update, waiting five seconds and trying again.");
341 setTimeout(function() { location.reload(true); }, 5000);
345 let possibly_play_sound = function(old_data, new_data) {
349 if (old_data === null) {
352 let ding = document.getElementById('ding');
353 if (ding && ding.play) {
354 if (old_data['position'] && old_data['position']['fen'] &&
355 new_data['position'] && new_data['position']['fen'] &&
356 (old_data['position']['fen'] !== new_data['position']['fen'] ||
357 old_data['position']['move_num'] !== new_data['position']['move_num'])) {
364 * @type {!string} server_date_string
366 let sync_server_clock = function(server_date_string) {
367 let server_time_ms = new Date(server_date_string).getTime();
368 let client_time_ms = new Date().getTime();
369 let estimated_offset_ms = server_time_ms - client_time_ms;
371 // In order not to let the noise move us too much back and forth
372 // (the server only has one-second resolution anyway), we only
373 // change an existing skew if we are at least five seconds off.
374 if (client_clock_offset_ms === null ||
375 Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
376 client_clock_offset_ms = estimated_offset_ms;
380 let clear_arrows = function() {
381 for (let i = 0; i < arrows.length; ++i) {
383 arrows[i].svg.remove();
384 delete arrows[i].svg;
389 occupied_by_arrows = [];
390 for (let y = 0; y < 8; ++y) {
391 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
395 let redraw_arrows = function() {
396 for (let i = 0; i < arrows.length; ++i) {
397 position_arrow(arrows[i]);
401 /** @param {!number} x
404 let sign = function(x) {
414 /** See if drawing this arrow on the board would cause unduly amount of confusion.
415 * @param {!string} from The square the arrow is from (e.g. e4).
416 * @param {!string} to The square the arrow is to (e.g. e4).
419 let interfering_arrow = function(from, to) {
420 let from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
421 let from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
422 let to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
423 let to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
425 occupied_by_arrows[from_row][from_col] = true;
427 // Knight move: Just check that we haven't been at the destination before.
428 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
429 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
430 return occupied_by_arrows[to_row][to_col];
433 // Sliding piece: Check if anything except the from-square is seen before.
434 let dx = sign(to_col - from_col);
435 let dy = sign(to_row - from_row);
441 if (occupied_by_arrows[y][x]) {
444 occupied_by_arrows[y][x] = true;
445 } while (x != to_col || y != to_row);
450 /** Find a point along the coordinate system given by the given line,
451 * <t> units forward from the start of the line, <u> units to the right of it.
452 * @param {!number} x1
453 * @param {!number} x2
454 * @param {!number} y1
455 * @param {!number} y2
458 * @return {!string} The point in "x y" form, suitable for SVG paths.
460 let point_from_start = function(x1, y1, x2, y2, t, u) {
464 let norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
468 let x = x1 + dx * t + dy * u;
469 let y = y1 + dy * t - dx * u;
473 /** Find a point along the coordinate system given by the given line,
474 * <t> units forward from the end of the line, <u> units to the right of it.
475 * @param {!number} x1
476 * @param {!number} x2
477 * @param {!number} y1
478 * @param {!number} y2
481 * @return {!string} The point in "x y" form, suitable for SVG paths.
483 let point_from_end = function(x1, y1, x2, y2, t, u) {
487 let norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
491 let x = x2 + dx * t + dy * u;
492 let y = y2 + dy * t - dx * u;
496 let position_arrow = function(arrow) {
498 if (arrow.svg.parentElement) {
499 arrow.svg.parentElement.removeChild(arrow.svg);
503 if (current_display_line !== null && !current_display_line_is_history) {
507 let board_width = parseInt(document.querySelector(".board-b72b1").style.width, 10);
508 let zoom_factor = board_width / 400.0;
509 let line_width = arrow.line_width * zoom_factor;
510 let arrow_size = arrow.arrow_size * zoom_factor;
512 let square_width = board_width / 8;
513 let from_y, to_y, from_x, to_x;
514 if (board.orientation() === 'black') {
515 from_y = (arrow.from_row + 0.5)*square_width;
516 to_y = (arrow.to_row + 0.5)*square_width;
517 from_x = (7 - arrow.from_col + 0.5)*square_width;
518 to_x = (7 - arrow.to_col + 0.5)*square_width;
520 from_y = (7 - arrow.from_row + 0.5)*square_width;
521 to_y = (7 - arrow.to_row + 0.5)*square_width;
522 from_x = (arrow.from_col + 0.5)*square_width;
523 to_x = (arrow.to_col + 0.5)*square_width;
526 let SVG_NS = "http://www.w3.org/2000/svg";
527 let XHTML_NS = "http://www.w3.org/1999/xhtml";
528 let svg = document.createElementNS(SVG_NS, "svg");
529 svg.setAttribute("width", board_width);
530 svg.setAttribute("height", board_width);
531 svg.setAttribute("style", "position: absolute");
532 svg.setAttribute("position", "absolute");
533 svg.setAttribute("version", "1.1");
534 svg.setAttribute("class", "c1");
535 svg.setAttribute("xmlns", XHTML_NS);
543 let outline = document.createElementNS(SVG_NS, "path");
544 outline.setAttribute("d", "M " + point_from_start(x1, y1, x2, y2, arrow_size / 2, 0) + " L " + point_from_end(x1, y1, x2, y2, -arrow_size / 2, 0));
545 outline.setAttribute("xmlns", XHTML_NS);
546 outline.setAttribute("stroke", "#666");
547 outline.setAttribute("stroke-width", line_width + 2);
548 outline.setAttribute("fill", "none");
549 svg.appendChild(outline);
551 let path = document.createElementNS(SVG_NS, "path");
552 path.setAttribute("d", "M " + point_from_start(x1, y1, x2, y2, arrow_size / 2, 0) + " L " + point_from_end(x1, y1, x2, y2, -arrow_size / 2, 0));
553 path.setAttribute("xmlns", XHTML_NS);
554 path.setAttribute("stroke", arrow.fg_color);
555 path.setAttribute("stroke-width", line_width);
556 path.setAttribute("fill", "none");
557 svg.appendChild(path);
559 // Then the arrow head.
560 let head = document.createElementNS(SVG_NS, "path");
561 head.setAttribute("d",
562 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
563 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
564 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
565 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
566 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
567 head.setAttribute("xmlns", XHTML_NS);
568 head.setAttribute("stroke", "#000");
569 head.setAttribute("stroke-width", "1");
570 head.setAttribute("fill", arrow.fg_color);
571 svg.appendChild(head);
573 svg.style.top = '2px'; /* Border for .board-b72b1. */
574 svg.style.left = '2px';
575 svg.style.pointerEvents = 'none';
576 document.getElementById('board').appendChild(svg);
581 * @param {!string} from_square
582 * @param {!string} to_square
583 * @param {!string} fg_color
584 * @param {number} line_width
585 * @param {number} arrow_size
587 let create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
588 let from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
589 let from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
590 let to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
591 let to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
599 line_width: line_width,
600 arrow_size: arrow_size,
604 position_arrow(arrow);
608 let compare_by_score = function(refutation_lines, invert, a, b) {
609 let sa = compute_score_sort_key(refutation_lines[b]['score'], refutation_lines[b]['depth'], invert);
610 let sb = compute_score_sort_key(refutation_lines[a]['score'], refutation_lines[a]['depth'], invert);
615 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
616 * sorted by quality, descending.
618 * @param {!Object} data
619 * @param {number} margin The maximum number of centipawns worse than the
620 * best move can be and still be included.
621 * @param {boolean} invert Whether black is to play.
622 * @return {Array.<string>} The FEN representation (e.g. Ne4) of all
623 * moves, in score order.
625 let find_nonstupid_moves = function(data, margin, invert) {
626 // First of all, if there are any moves that are more than 0.5 ahead of
627 // the primary move, the refutation lines are probably bunk, so just
629 let best_score = undefined;
630 let pv_score = undefined;
631 for (let move in data['refutation_lines']) {
632 let line = data['refutation_lines'][move];
633 let score = compute_score_sort_key(line['score'], line['depth'], invert);
634 if (move == data['pv'][0]) {
637 if (best_score === undefined || score > best_score) {
640 if (line['depth'] < 8) {
645 if (best_score - pv_score > 50) {
649 // Now find all moves that are within “margin” of the best score.
650 // The PV move will always be first.
652 for (let move in data['refutation_lines']) {
653 let line = data['refutation_lines'][move];
654 let score = compute_score_sort_key(line['score'], line['depth'], invert);
655 if (move != data['pv'][0] && best_score - score <= margin) {
659 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], data['position']['toplay'] === 'B', a, b) });
660 moves.unshift(data['pv'][0]);
669 let thousands = function(x) {
670 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
674 * @param {!string} start_fen
675 * @param {Array.<string>} pv
676 * @param {number} move_num
677 * @param {!string} toplay
678 * @param {Array<{ first_move: integer, score: Object }>} scores
679 * @param {number} start_display_move_num
680 * @param {number=} opt_limit
681 * @param {boolean=} opt_showlast
683 let add_pv = function(start_fen, pv, move_num, toplay, scores, start_display_move_num, opt_limit, opt_showlast) {
685 start_fen: start_fen,
687 move_num: parseInt(move_num),
690 start_display_move_num: start_display_move_num
692 let splicepos = null;
693 if (scores !== null && scores.length >= 1 &&
694 scores[scores.length - 1].score !== undefined &&
695 scores[scores.length - 1].score !== null &&
696 (scores[scores.length - 1].score[0] === 'T' ||
697 scores[scores.length - 1].score[0] === 't')) {
698 splicepos = scores[scores.length - 1].score[1];
700 return print_pv(display_lines.length - 1, splicepos, opt_limit, opt_showlast);
704 * @param {number} line_num
705 * @param {?number} splicepos If non-null, where the tablebase-spliced portion of the TB starts.
706 * @param {number=} opt_limit If set, show at most this number of moves.
707 * @param {boolean=} opt_showlast If limit is set, show the last moves instead of the first ones.
709 let print_pv = function(line_num, splicepos, opt_limit, opt_showlast) {
710 let display_line = display_lines[line_num];
711 let pv = display_line.pv;
712 let move_num = display_line.move_num;
713 let toplay = display_line.toplay;
715 // Truncate PV at the start if needed.
716 let start_display_move_num = display_line.start_display_move_num;
717 if (start_display_move_num > 0) {
718 pv = pv.slice(start_display_move_num);
719 let to_add = start_display_move_num;
720 if (toplay === 'B') {
725 if (to_add % 2 == 1) {
729 move_num += to_add / 2;
730 if (splicepos !== null && splicepos > 0) {
735 let ret = document.createDocumentFragment();
738 let link = document.createElement('a');
739 link.className = 'move';
740 if (opt_limit && opt_showlast && pv.length > opt_limit) {
741 // Truncate the PV at the beginning (instead of at the end).
742 // We assume here that toplay is 'W'. We also assume that if
743 // opt_showlast is set, then it is the history, and thus,
744 // the UI should be to expand the history.
745 ret.appendChild(document.createTextNode('('));
746 link.href = 'javascript:collapse_history(false)';
747 link.textContent = '…';
748 ret.appendChild(link);
749 ret.appendChild(document.createTextNode(') '));
750 i = pv.length - opt_limit;
755 } else if (toplay == 'B' && pv.length > 0) {
756 ret.appendChild(document.createTextNode(move_num + '. … '));
758 if (splicepos === 0) {
759 ret.appendChild(document.createTextNode('(TB: '));
762 link.setAttribute('id', 'automove' + line_num + '-0');
763 link.href = 'javascript:show_line(' + line_num + ', ' + 0 + ');';
764 link.textContent = pv[0];
765 ret.appendChild(link);
770 for ( ; i < pv.length; ++i) {
771 link = document.createElement('a');
772 link.className = 'move';
773 link.setAttribute('id', 'automove' + line_num + '-' + i);
774 link.textContent = pv[i];
775 link.href = 'javascript:show_line(' + line_num + ', ' + i + ');';
776 if (splicepos === i) {
777 ret.appendChild(document.createTextNode('(TB: '));
782 if (i > opt_limit && !opt_showlast) {
784 ret.appendChild(document.createTextNode(')'));
786 ret.appendChild(document.createTextNode(' (…)'));
790 ret.appendChild(document.createTextNode(' '));
792 ret.appendChild(document.createTextNode(move_num + '. '));
796 ret.appendChild(document.createTextNode(' '));
799 ret.appendChild(link);
802 ret.appendChild(document.createTextNode(')'));
807 /** Update the highlighted to/from squares on the board.
808 * Based on the global "highlight_from" and "highlight_to" letiables.
810 let update_board_highlight = function() {
811 document.getElementById("board").querySelectorAll('.square-55d63').forEach((square) => square.classList.remove('nonuglyhighlight'));
812 if ((current_display_line === null || current_display_line_is_history) &&
813 highlight_from !== undefined && highlight_to !== undefined) {
814 document.getElementById("board").querySelector('.square-' + highlight_from).classList.add('nonuglyhighlight');
815 document.getElementById("board").querySelector('.square-' + highlight_to).classList.add('nonuglyhighlight');
819 let update_history = function() {
820 let history = document.getElementById('history');
821 if (display_lines[0] === null || display_lines[0].pv.length == 0) {
822 history.textContent = 'No history';
823 } else if (truncate_display_history) {
824 history.replaceChildren(print_pv(0, null, 8, true));
826 history.textContent = '(';
827 let link = document.createElement('a');
828 link.className = 'move';
829 link.href = 'javascript:collapse_history(true)';
830 link.textContent = 'collapse';
831 history.appendChild(link);
832 history.appendChild(document.createTextNode(') '));
833 history.append(print_pv(0, null));
838 * @param {!boolean} truncate_history
840 let collapse_history = function(truncate_history) {
841 truncate_display_history = truncate_history;
844 window['collapse_history'] = collapse_history;
846 /** Update the HTML display of multi-PV from the global "refutation_lines".
848 * Also recreates the global "display_lines".
850 let update_refutation_lines = function() {
851 if (base_fen === null) {
854 if (display_lines.length > 2) {
855 // Truncate so that only the history and PV is left.
856 display_lines = [ display_lines[0], display_lines[1] ];
858 let tbl = document.getElementById("refutationlines");
859 tbl.replaceChildren();
861 if (display_lines.length < 2) {
862 // Update the move highlight, as we've rewritten all the HTML.
863 update_move_highlight();
867 // Find out where the lines start from.
869 let base_scores = display_lines[1].scores;
870 let start_display_move_num = 0;
871 if (hash_refutation_lines) {
872 base_line = current_display_line.pv.slice(0, current_display_move + 1);
873 base_scores = current_display_line.scores;
874 start_display_move_num = base_line.length;
878 for (let move in refutation_lines) {
882 let invert = (toplay === 'B');
883 if (current_display_line && current_display_move % 2 == 0 && !current_display_line_is_history) {
886 moves = moves.sort(function(a, b) { return compare_by_score(refutation_lines, invert, a, b) });
887 for (let i = 0; i < moves.length; ++i) {
888 let line = refutation_lines[moves[i]];
890 let tr = document.createElement("tr");
892 let move_td = document.createElement("td");
893 tr.appendChild(move_td);
894 move_td.classList.add("move");
896 let scores = base_scores.concat([{ first_move: start_display_move_num, score: line['score'] }]);
898 if (line['pv'].length == 0) {
899 // Not found, so just make a one-move PV.
900 let link = document.createElement('a');
901 link.className = 'move';
902 link.href = 'javascript:show_line(' + display_lines.length + ', ' + 0 + ')';
903 link.textContent = line['move'];
904 move_td.replaceChildren(link);
906 let score_td = document.createElement("td");
907 score_td.classList.add("score");
908 score_td.textContent = "—";
909 tr.appendChild(score_td);
911 let depth_td = document.createElement("td");
912 tr.appendChild(depth_td);
913 depth_td.classList.add("depth");
914 depth_td.textContent = "—";
916 let pv_td = document.createElement("td");
917 tr.appendChild(pv_td);
918 pv_td.classList.add("pv");
919 pv_td.append(add_pv(base_fen, base_line.concat([ line['move'] ]), move_num, toplay, scores, start_display_move_num));
925 let move_link = document.createElement("a");
926 move_link.classList.add("move");
927 move_link.setAttribute("href", "javascript:show_line(" + display_lines.length + ", 0)");
928 move_link.textContent = line['move'];
929 move_td.appendChild(move_link);
931 let score_td = document.createElement("td");
932 tr.appendChild(score_td);
933 score_td.classList.add("score");
934 score_td.textContent = format_short_score(line['score']);
936 let depth_td = document.createElement("td");
937 tr.appendChild(depth_td);
938 depth_td.classList.add("depth");
939 if (line['depth'] && line['depth'] >= 0) {
940 depth_td.textContent = "d" + line['depth'];
942 depth_td.textContent = "—";
945 let pv_td = document.createElement("td");
946 tr.appendChild(pv_td);
947 pv_td.classList.add("pv");
948 pv_td.append(add_pv(base_fen, base_line.concat(line['pv']), move_num, toplay, scores, start_display_move_num, 10));
953 // Update the move highlight, as we've rewritten all the HTML.
954 update_move_highlight();
958 * Create a Chess.js board object, containing the given position plus the given moves,
959 * up to the given limit.
961 * @param {?string} fen
962 * @param {Array.<string>} moves
963 * @param {number} last_move
965 let chess_from = function(fen, moves, last_move) {
966 let hiddenboard = new Chess();
967 if (fen !== null && fen !== undefined) {
968 hiddenboard.load(fen);
970 for (let i = 0; i <= last_move; ++i) {
971 if (moves[i] === '0-0') {
972 hiddenboard.move('O-O');
973 } else if (moves[i] === '0-0-0') {
974 hiddenboard.move('O-O-O');
976 hiddenboard.move(moves[i]);
982 let update_game_list = function(games) {
983 document.getElementById("games").textContent = "";
984 if (games === null) {
988 let games_div = document.getElementById('games');
989 for (let game_num = 0; game_num < games.length; ++game_num) {
990 let game = games[game_num];
991 let game_span = document.createElement("span");
992 game_span.setAttribute("class", "game");
994 let game_name = document.createTextNode(game['name']);
995 if (game['url'] === backend_url) {
997 game_span.appendChild(game_name);
999 if (current_analysis_data && current_analysis_data['position']) {
1001 if (current_analysis_data['position']['result']) {
1002 score = " (" + current_analysis_data['position']['result'] + ")";
1004 score = " (" + format_short_score(current_analysis_data['score']) + ")";
1006 game_span.appendChild(document.createTextNode(score));
1010 let game_a = document.createElement("a");
1011 game_a.setAttribute("href", "#" + game['id']);
1012 game_a.appendChild(game_name);
1013 game_span.appendChild(game_a);
1016 if (game['result']) {
1017 score = " (" + game['result'] + ")";
1019 score = " (" + format_short_score(game['score']) + ")";
1021 game_span.appendChild(document.createTextNode(score));
1024 games_div.appendChild(game_span);
1029 * Try to find a running game that matches with the current hash,
1030 * and switch to it if we're not already displaying it.
1032 let possibly_switch_game_from_hash = function() {
1033 let history_match = window.location.hash.match(/^#history=([a-zA-Z0-9_-]+)/);
1034 if (history_match !== null) {
1035 let game_id = history_match[1];
1037 url: '/history/' + game_id + '.json',
1039 id: 'history=' + game_id
1041 switch_backend(fake_game);
1045 if (current_games === null) {
1049 let hash = window.location.hash.replace(/^#/,'');
1050 for (let i = 0; i < current_games.length; ++i) {
1051 if (current_games[i]['id'] === hash) {
1052 if (backend_url !== current_games[i]['url']) {
1053 switch_backend(current_games[i]);
1061 * If this is a Chess960 castling which doesn't move the king,
1062 * move the rook instead.
1064 let patch_move = function(move) {
1065 if (move === null) return null;
1066 if (move.from !== move.to) return move;
1068 let f = move.rook_sq & 15;
1069 let r = move.rook_sq >> 4;
1070 let from = ('abcdefgh'.substring(f,f+1) + '87654321'.substring(r,r+1));
1073 if (move.to === 'g1') {
1075 } else if (move.to === 'g8') {
1077 } else if (move.to === 'b1') {
1079 } else if (move.to === 'b8') {
1083 return { from: from, to: to };
1086 /** Update all the HTML on the page, based on current global state.
1088 let update_board = function() {
1089 document.body.style.opacity = null;
1091 let data = displayed_analysis_data || current_analysis_data;
1092 let current_data = current_analysis_data; // Convenience alias.
1096 // Print the history. This is pretty much the only thing that's
1097 // unconditionally taken from current_data (we're not interested in
1098 // historic history).
1099 if (current_data['position']['history']) {
1100 let start = (current_data['position'] && current_data['position']['start_fen']) ? current_data['position']['start_fen'] : 'start';
1101 add_pv(start, current_data['position']['history'], 1, 'W', null, 0, 8, true);
1103 display_lines.push(null);
1107 // Games currently in progress, if any.
1108 if (current_data['games']) {
1109 current_games = current_data['games'];
1110 possibly_switch_game_from_hash();
1112 current_games = null;
1114 update_game_list(current_games);
1116 // The headline. Names are always fetched from current_data;
1117 // the rest can depend a bit.
1120 current_data['position']['player_w'] && current_data['position']['player_b']) {
1121 headline = current_data['position']['player_w'] + '–' +
1122 current_data['position']['player_b'] + ', analysis';
1124 headline = 'Analysis';
1127 // Credits, where applicable. Note that we don't want the footer to change a lot
1128 // when e.g. viewing history, so if any of these changed during the game,
1129 // use the current one still.
1130 if (current_data['using_lomonosov']) {
1131 document.getElementById("lomonosov").style.display = null;
1133 document.getElementById("lomonosov").style.display = 'none';
1136 // Credits: The engine name/version.
1137 if (current_data['engine'] && current_data['engine']['name'] !== null) {
1138 document.getElementById("engineid").textContent = current_data['engine']['name'];
1141 // Credits: The engine URL.
1142 if (current_data['engine'] && current_data['engine']['url']) {
1143 document.getElementById("engineid").setAttribute("href", current_data['engine']['url']);
1145 document.getElementById("engineid").removeAttribute("href");
1148 // Credits: Engine details.
1149 if (current_data['engine'] && current_data['engine']['details']) {
1150 document.getElementById("enginedetails").textContent = " (" + current_data['engine']['details'] + ")";
1152 document.getElementById("enginedetails").textContent = "";
1155 // Credits: Move source, possibly with URL.
1156 if (current_data['move_source'] && current_data['move_source_url']) {
1157 document.getElementById("movesource").textContent = "Moves provided by ";
1158 let movesource_a = document.createElement("a");
1159 movesource_a.setAttribute("href", current_data['move_source_url']);
1160 let movesource_text = document.createTextNode(current_data['move_source']);
1161 movesource_a.appendChild(movesource_text);
1162 let movesource_period = document.createTextNode(".");
1163 document.getElementById("movesource").appendChild(movesource_a);
1164 document.getElementById("movesource").appendChild(movesource_period);
1165 } else if (current_data['move_source']) {
1166 document.getElementById("movesource").textContent = "Moves provided by " + current_data['move_source'] + ".";
1168 document.getElementById("movesource").textContent = "";
1172 if (displayed_analysis_data) {
1173 // Displaying some non-current position, pick out the last move
1174 // from the history. This will work even if the fetch failed.
1175 if (current_display_move !== -1) {
1176 last_move = format_halfmove_with_number(
1177 current_display_line.pv[current_display_move],
1178 current_display_move);
1179 headline += ' after ' + last_move;
1181 } else if (data['position']['last_move'] !== 'none') {
1182 // Find the previous move.
1183 let previous_move_num, previous_toplay;
1184 if (data['position']['toplay'] == 'B') {
1185 previous_move_num = data['position']['move_num'];
1186 previous_toplay = 'W';
1188 previous_move_num = data['position']['move_num'] - 1;
1189 previous_toplay = 'B';
1192 last_move = format_move_with_number(
1193 data['position']['last_move'],
1195 previous_toplay == 'W');
1196 headline += ' after ' + last_move;
1200 document.getElementById("headline").textContent = headline;
1202 // The <title> contains a very brief headline.
1203 let title_elems = [];
1204 if (data['position'] && data['position']['result']) {
1205 title_elems.push(data['position']['result']);
1206 } else if (data['score']) {
1207 title_elems.push(format_short_score(data['score']));
1209 if (last_move !== null) {
1210 title_elems.push(last_move);
1213 if (title_elems.length != 0) {
1214 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
1216 document.title = 'analysis.sesse.net';
1219 // The last move (shown by highlighting the from and to squares).
1220 if (data['position'] && data['position']['last_move_uci']) {
1221 highlight_from = data['position']['last_move_uci'].substr(0, 2);
1222 highlight_to = data['position']['last_move_uci'].substr(2, 2);
1223 } else if (current_display_line_is_history && current_display_line && current_display_move >= 0) {
1224 // We don't have historic analysis for this position, but we
1225 // can reconstruct what the last move was by just replaying
1227 let position = (data['position'] && data['position']['start_fen']) ? data['position']['start_fen'] : null;
1228 let hiddenboard = chess_from(position, current_display_line.pv, current_display_move);
1229 let moves = hiddenboard.history({ verbose: true });
1230 last_move = moves.pop();
1231 highlight_from = last_move.from;
1232 highlight_to = last_move.to;
1234 highlight_from = highlight_to = undefined;
1236 update_board_highlight();
1238 if (data['failed']) {
1239 document.getElementById("score").textContent = "No analysis for this move";
1240 document.getElementById("pvtitle").textContent = "PV:";
1241 document.getElementById("pv").replaceChildren();
1242 document.getElementById("searchstats").textContent = " ";
1243 document.getElementById("refutationlines").replaceChildren();
1244 document.getElementById("whiteclock").replaceChildren();
1245 document.getElementById("blackclock").replaceChildren();
1246 refutation_lines = [];
1247 update_refutation_lines();
1249 update_displayed_line();
1250 update_move_highlight();
1254 if (clock_timer !== null) {
1255 clearTimeout(clock_timer);
1260 if (current_display_line && !current_display_line_is_history) {
1262 if (current_display_line.scores && current_display_line.scores.length > 0) {
1263 for (let i = 0; i < current_display_line.scores.length; ++i) {
1264 if (current_display_move < current_display_line.scores[i].first_move) {
1267 score = current_display_line.scores[i].score;
1271 document.getElementById("score").textContent = format_long_score(score);
1273 document.getElementById("score").textContent = "No score for this line";
1275 } else if (data['score']) {
1276 document.getElementById("score").textContent = format_long_score(data['score']);
1279 // The search stats.
1280 if (data['searchstats']) {
1281 document.getElementById("searchstats").textContent = data['searchstats'];
1282 } else if (data['tablebase'] == 1) {
1283 document.getElementById("searchstats").textContent = "Tablebase result";
1284 } else if (data['nodes'] && data['nps'] && data['depth']) {
1285 let stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
1286 if (data['seldepth']) {
1287 stats += ' (' + data['seldepth'] + ' selective)';
1289 if (data['tbhits'] && data['tbhits'] > 0) {
1290 if (data['tbhits'] == 1) {
1291 stats += ', one Syzygy hit';
1293 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
1297 document.getElementById("searchstats").textContent = stats;
1299 document.getElementById("searchstats").textContent = "";
1302 // Update the board itself.
1303 base_fen = data['position']['fen'];
1304 update_displayed_line();
1307 document.getElementById("pvtitle").textContent = "PV:";
1309 let scores = [{ first_move: -1, score: data['score'] }];
1310 document.getElementById("pv").replaceChildren(add_pv(data['position']['fen'], data['pv'], data['position']['move_num'], data['position']['toplay'], scores, 0));
1312 // Update the PV arrow.
1314 if (data['pv'].length >= 1) {
1315 let hiddenboard = new Chess(base_fen);
1317 // draw a continuation arrow as long as it's the same piece
1319 for (let i = 0; i < data['pv'].length; i += 2) {
1320 let move = patch_move(hiddenboard.move(data['pv'][i]));
1322 if ((i >= 2 && move.from != last_to) ||
1323 interfering_arrow(move.from, move.to)) {
1326 create_arrow(move.from, move.to, '#f66', 6, 20);
1328 hiddenboard.move(data['pv'][i + 1]); // To keep continuity.
1331 let alt_moves = find_nonstupid_moves(data, 30, data['position']['toplay'] === 'B');
1332 for (let i = 1; i < alt_moves.length && i < 3; ++i) {
1333 hiddenboard = new Chess(base_fen);
1334 let move = patch_move(hiddenboard.move(alt_moves[i]));
1335 if (move !== null) {
1336 create_arrow(move.from, move.to, '#f66', 1, 10);
1341 // See if all semi-reasonable moves have only one possible response.
1342 if (data['pv'].length >= 2) {
1343 let nonstupid_moves = find_nonstupid_moves(data, 300, data['position']['toplay'] === 'B');
1344 let hiddenboard = new Chess(base_fen);
1345 hiddenboard.move(data['pv'][0]);
1346 let response = hiddenboard.move(data['pv'][1]);
1347 for (let i = 0; i < nonstupid_moves.length; ++i) {
1348 if (nonstupid_moves[i] == data['pv'][0]) {
1349 // ignore the PV move for refutation lines.
1352 if (!data['refutation_lines'] ||
1353 !data['refutation_lines'][nonstupid_moves[i]] ||
1354 !data['refutation_lines'][nonstupid_moves[i]]['pv'] ||
1355 data['refutation_lines'][nonstupid_moves[i]]['pv'].length < 2) {
1356 // Incomplete PV, abort.
1357 response = undefined;
1360 let line = data['refutation_lines'][nonstupid_moves[i]];
1361 hiddenboard = new Chess(base_fen);
1362 hiddenboard.move(line['pv'][0]);
1363 let this_response = hiddenboard.move(line['pv'][1]);
1364 if (this_response === null) {
1365 console.log("BUG: ", i);
1367 console.log(line['pv']);
1369 if (response.from !== this_response.from || response.to !== this_response.to) {
1370 // Different response depending on lines, abort.
1371 response = undefined;
1376 if (nonstupid_moves.length > 0 && response !== undefined) {
1377 create_arrow(response.from, response.to, '#66f', 6, 20);
1381 // Update the refutation lines.
1382 base_fen = data['position']['fen'];
1383 move_num = parseInt(data['position']['move_num']);
1384 toplay = data['position']['toplay'];
1385 refutation_lines = hash_refutation_lines || data['refutation_lines'];
1386 update_refutation_lines();
1388 // Update the sparkline last, since its size depends on how everything else reflowed.
1389 update_sparkline(data);
1392 let update_sparkline = function(data) {
1393 let scorespark = document.getElementById('scoresparkcontainer');
1394 scorespark.textContent = '';
1395 if (data && data['score_history']) {
1396 let first_move_num = undefined;
1397 for (let halfmove_num in data['score_history']) {
1398 halfmove_num = parseInt(halfmove_num);
1399 if (first_move_num === undefined || halfmove_num < first_move_num) {
1400 first_move_num = halfmove_num;
1403 if (first_move_num !== undefined) {
1404 let last_move_num = data['position']['move_num'] * 2 - 3;
1405 if (data['position']['toplay'] === 'B') {
1409 // Possibly truncate some moves if we don't have enough width.
1410 let max_moves = Math.floor(scorespark.getBoundingClientRect().width / 5) - 3;
1411 if (last_move_num - first_move_num > max_moves) {
1412 first_move_num = last_move_num - max_moves;
1417 let last_score = null;
1419 for (let halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1420 if (data['score_history'][halfmove_num]) {
1421 let score = compute_plot_score(data['score_history'][halfmove_num]);
1423 if (score < min_score) min_score = score;
1424 if (score > max_score) max_score = score;
1426 scores.push(last_score);
1428 if (data['score']) {
1429 let score = compute_plot_score(data['score']);
1431 if (score < min_score) min_score = score;
1432 if (score > max_score) max_score = score;
1434 if (max_score - min_score < 100) {
1435 if (Math.abs(max_score) >= Math.abs(min_score)) {
1436 max_score = min_score + 100;
1438 min_score = max_score - 100;
1442 const h = scorespark.getBoundingClientRect().height;
1444 let base_y = h - h * min_score / (min_score - max_score);
1445 for (let i = 0; i < scores.length; ++i) {
1446 let rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
1447 //rect.setAttributeNS(null, 'stroke', "#000000");
1448 rect.setAttributeNS(null, 'x', i * 5)
1449 rect.setAttributeNS(null, 'width', 4);
1450 let extent = scores[i] * h / (max_score - min_score);
1451 if (extent > 0 && extent < 1) {
1453 } else if (extent < 0 && extent > -1) {
1458 if (scores[i] === 0) {
1459 color = [0.5, 0.5, 0.5];
1460 rect.setAttributeNS(null, 'y', base_y);
1461 rect.setAttributeNS(null, 'height', 1);
1462 } else if (scores[i] > 0) {
1463 color = [0.2, 0.4, 0.8];
1464 rect.setAttributeNS(null, 'y', base_y - extent);
1465 rect.setAttributeNS(null, 'height', extent + 1);
1467 color = [1.0, 0.267, 0.267];
1468 rect.setAttributeNS(null, 'y', base_y);
1469 rect.setAttributeNS(null, 'height', -extent + 1);
1471 let hlcolor = [color[0], color[1], color[2]];
1472 if (scores[i] !== 0) {
1473 hlcolor[0] = Math.min(hlcolor[0] * 1.4, 1.0);
1474 hlcolor[1] = Math.min(hlcolor[1] * 1.4, 1.0);
1475 hlcolor[2] = Math.min(hlcolor[2] * 1.4, 1.0);
1477 rect.style.fill = 'rgb(' + color[0]*100.0 + '%, ' + color[1]*100.0 + '%, ' + color[2]*100.0 + '%)';
1479 // score_history contains the Nth _position_, but format_tooltip
1480 // wants to format the Nth _move_; thus the -1.
1481 const tooltip = format_tooltip(data, i + first_move_num - 1);
1482 rect.addEventListener('mouseenter', (e) => draw_hover(e, hlcolor, tooltip));
1483 rect.addEventListener('mousemove', (e) => draw_hover(e, hlcolor, tooltip));
1484 rect.addEventListener('mouseleave', (e) => hide_hover(e, color));
1485 rect.addEventListener('click', (e) => { hide_hover(e, color); show_line(0, i + first_move_num - 1) });
1486 scorespark.appendChild(rect);
1492 let draw_hover = function(e, color, tooltip) {
1493 e.target.style.fill = 'rgb(' + color[0]*100.0 + '%, ' + color[1]*100.0 + '%, ' + color[2]*100.0 + '%)';
1495 let hover = document.getElementById('sparklinehover');
1496 hover.textContent = tooltip;
1497 hover.style.display = 'initial';
1499 let left = Math.max(e.pageX + 10, window.pageXOffset);
1500 let top = Math.max(e.pageY - hover.getBoundingClientRect().height, window.pageYOffset);
1501 left = Math.min(left, window.pageXOffset + document.documentElement.clientWidth - hover.getBoundingClientRect().width);
1503 hover.style.left = left + 'px';
1504 hover.style.top = top + 'px';
1507 let hide_hover = function(e, color) {
1508 e.target.style.fill = 'rgb(' + color[0]*100.0 + '%, ' + color[1]*100.0 + '%, ' + color[2]*100.0 + '%)';
1509 document.getElementById('sparklinehover').style.display = 'none';
1513 * @param {number} num_viewers
1515 let update_num_viewers = function(num_viewers) {
1517 if (num_viewers === null) {
1519 } else if (num_viewers == 1) {
1520 text = "You are the only current viewer";
1522 text = num_viewers + " current viewers";
1524 if (display_fen !== null) {
1525 let counter = Math.floor(display_fen.split(" ")[4] / 2);
1526 if (counter >= 20) {
1527 text = text.replace("current ", "");
1528 text += " | 50-move rule: " + counter;
1531 document.getElementById("numviewers").textContent = text;
1534 let update_clock = function() {
1537 let data = displayed_analysis_data || current_analysis_data;
1540 if (data['position']) {
1541 let result = data['position']['result'];
1542 if (result === '1-0') {
1543 document.getElementById("whiteclock").textContent = "1";
1544 document.getElementById("blackclock").textContent = "0";
1545 document.getElementById("whiteclock").classList.remove("running-clock");
1546 document.getElementById("blackclock").classList.remove("running-clock");
1549 if (result === '1/2-1/2') {
1550 document.getElementById("whiteclock").textContent = "1/2";
1551 document.getElementById("blackclock").textContent = "1/2";
1552 document.getElementById("whiteclock").classList.remove("running-clock");
1553 document.getElementById("blackclock").classList.remove("running-clock");
1556 if (result === '0-1') {
1557 document.getElementById("whiteclock").textContent = "0";
1558 document.getElementById("blackclock").textContent = "1";
1559 document.getElementById("whiteclock").classList.remove("running-clock");
1560 document.getElementById("blackclock").classList.remove("running-clock");
1565 let white_clock_ms = null;
1566 let black_clock_ms = null;
1569 if (data['position'] &&
1570 data['position']['white_clock'] &&
1571 data['position']['black_clock']) {
1572 white_clock_ms = data['position']['white_clock'] * 1000;
1573 black_clock_ms = data['position']['black_clock'] * 1000;
1576 // Dynamic clock (only one, obviously).
1578 if (data['position']['white_clock_target']) {
1580 document.getElementById("whiteclock").classList.add("running-clock");
1581 document.getElementById("blackclock").classList.remove("running-clock");
1582 } else if (data['position']['black_clock_target']) {
1584 document.getElementById("whiteclock").classList.remove("running-clock");
1585 document.getElementById("blackclock").classList.add("running-clock");
1587 document.getElementById("whiteclock").classList.remove("running-clock");
1588 document.getElementById("blackclock").classList.remove("running-clock");
1592 let now = new Date().getTime() + client_clock_offset_ms;
1593 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1594 if (color === "white") {
1595 white_clock_ms = remaining_ms;
1597 black_clock_ms = remaining_ms;
1601 if (white_clock_ms === null || black_clock_ms === null) {
1602 document.getElementById("whiteclock").replaceChildren();
1603 document.getElementById("blackclock").replaceChildren();
1607 // If either player has twenty minutes or less left, add the second counters.
1608 // This matches what DGT clocks do.
1609 let show_seconds = (white_clock_ms < 60 * 20 * 1000 || black_clock_ms < 60 * 20 * 1000);
1612 // See when the clock will change next, and update right after that.
1615 next_update_ms = remaining_ms % 1000 + 100;
1617 next_update_ms = remaining_ms % 60000 + 100;
1619 clock_timer = setTimeout(update_clock, next_update_ms);
1622 document.getElementById("whiteclock").textContent = format_clock(white_clock_ms, show_seconds);
1623 document.getElementById("blackclock").textContent = format_clock(black_clock_ms, show_seconds);
1627 * @param {Number} remaining_ms
1628 * @param {boolean} show_seconds
1630 let format_clock = function(remaining_ms, show_seconds) {
1631 if (remaining_ms <= 0) {
1639 let remaining = Math.floor(remaining_ms / 1000);
1640 let seconds = remaining % 60;
1641 remaining = (remaining - seconds) / 60;
1642 let minutes = remaining % 60;
1643 remaining = (remaining - minutes) / 60;
1644 let hours = remaining;
1646 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1648 return format_2d(hours) + ":" + format_2d(minutes);
1655 let format_2d = function(x) {
1664 * @param {string} move
1665 * @param {Number} move_num Move number of this move.
1666 * @param {boolean} white_to_play Whether white is to play this move.
1668 let format_move_with_number = function(move, move_num, white_to_play) {
1670 if (white_to_play) {
1671 ret = move_num + '. ';
1673 ret = move_num + '… ';
1680 * @param {string} move
1681 * @param {Number} halfmove_num Half-move number that is to be played,
1684 let format_halfmove_with_number = function(move, halfmove_num) {
1685 return format_move_with_number(
1687 Math.floor(halfmove_num / 2) + 1,
1688 halfmove_num % 2 == 0);
1692 * @param {Object} data
1693 * @param {Number} halfmove_num
1695 let format_tooltip = function(data, halfmove_num) {
1696 if (data['score_history'][halfmove_num + 1] ||
1697 (halfmove_num + 1) === data['position']['history'].length) {
1698 // Position is in the history, or it is the current position
1699 // (which is implicitly tacked onto the history).
1702 if ((halfmove_num + 1) === data['position']['history'].length) {
1703 move = data['position']['last_move'];
1704 short_score = format_short_score(data['score']);
1706 move = data['position']['history'][halfmove_num];
1707 short_score = format_short_score(data['score_history'][halfmove_num + 1]);
1709 if (halfmove_num === -1) {
1710 return "Start position: " + short_score;
1712 let move_with_number = format_halfmove_with_number(move, halfmove_num);
1713 return "After " + move_with_number + ": " + short_score;
1716 for (let i = halfmove_num; i --> -1; ) {
1717 if (data['score_history'][i]) {
1718 let move = data['position']['history'][i];
1720 return "[Analysis kept from start position]";
1722 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1730 * @param {boolean} truncate_history
1732 let set_truncate_history = function(truncate_history) {
1733 truncate_display_history = truncate_history;
1734 update_refutation_lines();
1736 window['set_truncate_history'] = set_truncate_history;
1739 * @param {number} line_num
1740 * @param {number} move_num
1742 let show_line = function(line_num, move_num) {
1743 if (line_num == -1) {
1744 current_display_line = null;
1745 current_display_move = null;
1746 hash_refutation_lines = null;
1747 if (displayed_analysis_data) {
1748 // TODO: Support exiting to history position if we are in an
1749 // analysis line of a history position.
1750 displayed_analysis_data = null;
1755 current_display_line = {...display_lines[line_num]}; // Shallow clone.
1756 current_display_move = move_num + current_display_line.start_display_move_num;
1758 current_display_line_is_history = (line_num == 0);
1760 update_historic_analysis();
1761 update_displayed_line();
1762 update_board_highlight();
1763 update_move_highlight();
1766 window['show_line'] = show_line;
1768 let prev_move = function() {
1769 if (current_display_line &&
1770 current_display_move >= current_display_line.start_display_move_num) {
1771 --current_display_move;
1773 update_historic_analysis();
1774 update_displayed_line();
1775 update_move_highlight();
1777 window['prev_move'] = prev_move;
1779 let next_move = function() {
1780 if (current_display_line &&
1781 current_display_move < current_display_line.pv.length - 1) {
1782 ++current_display_move;
1784 update_historic_analysis();
1785 update_displayed_line();
1786 update_move_highlight();
1788 window['next_move'] = next_move;
1790 let next_game = function() {
1791 if (current_games === null) {
1795 // Try to find the game we are currently looking at.
1796 for (let game_num = 0; game_num < current_games.length; ++game_num) {
1797 let game = current_games[game_num];
1798 if (game['url'] === backend_url) {
1799 let next_game_num = (game_num + 1) % current_games.length;
1800 switch_backend(current_games[next_game_num]);
1805 // Couldn't find it; give up.
1808 let update_historic_analysis = function() {
1809 if (!current_display_line_is_history) {
1812 if (current_display_move == current_display_line.pv.length - 1) {
1813 displayed_analysis_data = null;
1817 // Fetch old analysis for this line if it exists.
1818 let hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pv, current_display_move);
1819 let filename = "/history/move" + (current_display_move + 1) + "-" +
1820 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1822 let handle_err = () => {
1823 displayed_analysis_data = {'failed': true};
1827 current_historic_xhr = new AbortController();
1828 const signal = current_analysis_xhr.signal;
1829 fetch(filename, { signal })
1830 .then((response) => response.json().then(data => ({ok: response.ok, json: data}))) // ick
1836 displayed_analysis_data = obj.json;
1840 if (err.name === 'AbortError') {
1841 // Aborted because we are switching backends. Abandon and don't retry,
1842 // because another one is already started for us.
1851 * @param {string} fen
1853 let update_imbalance = function(fen) {
1854 let imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1855 for (const c of fen) {
1860 if (c != c.toUpperCase()) {
1862 } else if (c != c.toLowerCase()) {
1863 ++imbalance[c.toLowerCase()];
1867 let white_imbalance = document.getElementById('whiteimbalance');
1868 let black_imbalance = document.getElementById('blackimbalance');
1869 white_imbalance.textContent = '';
1870 black_imbalance.textContent = '';
1871 for (let piece in imbalance) {
1872 for (let i = 0; i < imbalance[piece]; ++i) {
1873 let i1 = document.createElement('img');
1874 i1.src = svg_pieces['w' + piece.toUpperCase()];
1875 i1.setAttribute('alt', piece.toUpperCase());
1876 i1.classList.add('imbalance-piece');
1877 white_imbalance.appendChild(i1);
1879 let i2 = document.createElement('img');
1880 i2.src = svg_pieces['b' + piece.toUpperCase()];
1881 i2.setAttribute('alt', piece.toUpperCase());
1882 i2.classList.add('imbalance-inverted-piece');
1883 white_imbalance.appendChild(i2);
1885 for (let i = 0; i < -imbalance[piece]; ++i) {
1886 let i1 = document.createElement('img');
1887 i1.src = svg_pieces['b' + piece.toUpperCase()];
1888 i1.setAttribute('alt', piece.toUpperCase());
1889 i1.classList.add('imbalance-piece');
1890 black_imbalance.appendChild(i1);
1892 let i2 = document.createElement('img');
1893 i2.src = svg_pieces['w' + piece.toUpperCase()];
1894 i2.setAttribute('alt', piece.toUpperCase());
1895 i2.classList.add('imbalance-inverted-piece');
1896 black_imbalance.appendChild(i2);
1901 /** Mark the currently selected move in red.
1902 * Also replaces the PV with the current displayed line if it's not shown
1903 * anywhere else on the screen.
1905 let update_move_highlight = function() {
1906 if (highlighted_move !== null) {
1907 highlighted_move.classList.remove('highlight');
1909 if (current_display_line) {
1910 let display_line_num = find_display_line_matching_num();
1911 if (display_line_num === null) {
1912 // Replace the PV with the (complete) line.
1913 document.getElementById("pvtitle").textContent = "Exploring:";
1914 current_display_line.start_display_move_num = 0;
1915 display_lines.push(current_display_line);
1916 document.getElementById("pv").append(print_pv(display_lines.length - 1, null)); // FIXME
1917 display_line_num = display_lines.length - 1;
1919 // Clear out the PV, so it's not selected by anything later.
1920 display_lines[1].pv = [];
1923 highlighted_move = document.getElementById("automove" + display_line_num + "-" + (current_display_move - current_display_line.start_display_move_num));
1924 if (highlighted_move !== null) {
1925 highlighted_move.classList.add('highlight');
1931 * See if the current displayed line is identical to any of the ones
1932 * we have on screen. (It might not be if e.g. the analysis reloaded
1933 * since we started looking.)
1937 let find_display_line_matching_num = function() {
1938 for (let i = 0; i < display_lines.length; ++i) {
1939 let line = display_lines[i];
1940 if (line.start_display_move_num > 0) continue;
1941 if (current_display_line.start_fen !== line.start_fen) continue;
1942 if (current_display_line.pv.length !== line.pv.length) continue;
1944 for (let j = 0; j < line.pv.length; ++j) {
1945 if (current_display_line.pv[j] !== line.pv[j]) {
1957 /** Update the board based on the currently displayed line.
1959 * TODO: This should really be called only whenever something changes,
1960 * instead of all the time.
1962 let update_displayed_line = function() {
1963 if (current_display_line === null) {
1964 document.getElementById("linenav").style.display = 'none';
1965 document.getElementById("linemsg").style.display = 'revert';
1966 display_fen = base_fen;
1967 set_board_position(base_fen);
1968 update_imbalance(base_fen);
1972 document.getElementById("linenav").style.display = 'revert';
1973 document.getElementById("linemsg").style.display = 'none';
1975 if (current_display_move <= 0) {
1976 document.getElementById("prevmove").textContent = "Previous";
1978 document.getElementById("prevmove").innerHTML = "<a href=\"javascript:prev_move();\">Previous</a></span>";
1980 if (current_display_move == current_display_line.pv.length - 1) {
1981 document.getElementById("nextmove").textContent = "Next";
1983 document.getElementById("nextmove").innerHTML = "<a href=\"javascript:next_move();\">Next</a></span>";
1986 let hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pv, current_display_move);
1987 set_board_position(hiddenboard.fen());
1988 if (display_fen !== hiddenboard.fen() && !current_display_line_is_history) {
1989 // Fire off a hash request, since we're now off the main position
1990 // and it just changed.
1991 explore_hash(hiddenboard.fen());
1993 display_fen = hiddenboard.fen();
1994 update_imbalance(hiddenboard.fen());
1997 let set_board_position = function(new_fen) {
1998 board_is_animating = true;
1999 let old_fen = board.fen();
2000 board.position(new_fen);
2001 if (board.fen() === old_fen) {
2002 board_is_animating = false;
2007 * @param {boolean} param_enable_sound
2009 let set_sound = function(param_enable_sound) {
2010 enable_sound = param_enable_sound;
2012 document.getElementById("soundon").innerHTML = "<strong>On</strong>";
2013 document.getElementById("soundoff").innerHTML = "<a href=\"javascript:set_sound(false)\">Off</a>";
2015 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
2016 // and also preload the file since the user has selected audio.
2017 let ding = document.getElementById('ding');
2018 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
2019 ding.src = 'ding.opus';
2023 document.getElementById("soundon").innerHTML = "<a href=\"javascript:set_sound(true)\">On</a>";
2024 document.getElementById("soundoff").innerHTML = "<strong>Off</strong>";
2026 if (supports_html5_storage()) {
2027 window['localStorage']['enable_sound'] = enable_sound ? 1 : 0;
2030 window['set_sound'] = set_sound;
2032 /** Send off a hash probe request to the backend.
2033 * @param {string} fen
2035 let explore_hash = function(fen) {
2036 // If we already have a backend response going, abort it.
2037 if (current_hash_xhr) {
2038 current_hash_xhr.abort();
2040 if (current_hash_display_timer) {
2041 clearTimeout(current_hash_display_timer);
2042 current_hash_display_timer = null;
2044 document.getElementById("refutationlines").replaceChildren();
2046 current_hash_xhr = new AbortController();
2047 const signal = current_analysis_xhr.signal;
2048 fetch(backend_hash_url + "?fen=" + fen, { signal })
2049 .then((response) => response.json())
2050 .then((data) => { show_explore_hash_results(data, fen); })
2052 // Truncate the lines, since we already cleared the display.
2053 display_lines = [ display_lines[0], display_lines[1] ];
2054 update_move_highlight();
2058 /** Process the JSON response from a hash probe request.
2059 * @param {!Object} data
2060 * @param {string} fen
2062 let show_explore_hash_results = function(data, fen) {
2063 if (board_is_animating) {
2064 // Updating while the animation is still going causes
2065 // the animation to jerk. This is pretty crude, but it will do.
2066 current_hash_display_timer = setTimeout(function() { show_explore_hash_results(data, fen); }, 100);
2069 current_hash_display_timer = null;
2070 hash_refutation_lines = data['lines'];
2074 // almost all of this stuff comes from the chessboard.js example page
2075 let onDragStart = function(source, piece, position, orientation) {
2076 let pseudogame = new Chess(display_fen);
2077 if (pseudogame.game_over() === true ||
2078 (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
2079 (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
2083 recommended_move = get_best_move(pseudogame, source, null, pseudogame.turn() === 'b');
2084 if (recommended_move) {
2085 let squareEl = document.querySelector('#board .square-' + recommended_move.to);
2086 squareEl.classList.add('highlight1-32417');
2091 let mousedownSquare = function(e) {
2092 if (!e.target || !e.target.closest('.square-55d63')) {
2096 reverse_dragging_from = null;
2097 let square = e.target.closest('.square-55d63').getAttribute('data-square');
2099 let pseudogame = new Chess(display_fen);
2100 if (pseudogame.game_over() === true) {
2104 // If the square is empty, or has a piece of the side not to move,
2105 // we handle it. If not, normal piece dragging will take it.
2106 let position = board.position();
2107 if (!position.hasOwnProperty(square) ||
2108 (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
2109 (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
2110 reverse_dragging_from = square;
2111 recommended_move = get_best_move(pseudogame, null, square, pseudogame.turn() === 'b');
2112 if (recommended_move) {
2113 let squareEl = document.querySelector('#board .square-' + recommended_move.from);
2114 squareEl.classList.add('highlight1-32417');
2115 squareEl = document.querySelector('#board .square-' + recommended_move.to);
2116 squareEl.classList.add('highlight1-32417');
2121 let mouseupSquare = function(e) {
2122 if (!e.target || !e.target.closest('.square-55d63')) {
2125 if (reverse_dragging_from === null) {
2128 let source = e.target.closest('.square-55d63').getAttribute('data-square');
2129 let target = reverse_dragging_from;
2130 reverse_dragging_from = null;
2131 if (onDrop(source, target) !== 'snapback') {
2132 onSnapEnd(source, target);
2134 document.getElementById("board").querySelectorAll('.square-55d63.highlight1-32417').forEach((square) => {
2135 square.classList.remove('highlight1-32417');
2139 let get_best_move = function(game, source, target, invert) {
2140 let moves = game.moves({ verbose: true });
2141 if (source !== null) {
2142 moves = moves.filter(function(move) { return move.from == source; });
2144 if (target !== null) {
2145 moves = moves.filter(function(move) { return move.to == target; });
2147 if (moves.length == 0) {
2150 if (moves.length == 1) {
2154 // More than one move. Use the display lines (if we have them)
2155 // to disambiguate; otherwise, we have no information.
2157 for (let i = 0; i < moves.length; ++i) {
2158 move_hash[moves[i].san] = moves[i];
2161 // See if we're already exploring some line.
2162 if (current_display_line &&
2163 current_display_move < current_display_line.pv.length - 1) {
2164 let first_move = current_display_line.pv[current_display_move + 1];
2165 if (move_hash[first_move]) {
2166 return move_hash[first_move];
2170 // History and PV take priority over the display lines.
2171 for (let i = 0; i < 2; ++i) {
2172 let line = display_lines[i];
2173 let first_move = line.pv[line.start_display_move_num];
2174 if (move_hash[first_move]) {
2175 return move_hash[first_move];
2179 let best_move = null;
2180 let best_move_score = null;
2182 for (let move in refutation_lines) {
2183 let line = refutation_lines[move];
2184 if (!line['score']) {
2187 let first_move = line['pv'][0];
2188 if (move_hash[first_move]) {
2189 let score = compute_score_sort_key(line['score'], line['depth'], invert);
2190 if (best_move_score === null || score > best_move_score) {
2191 best_move = move_hash[first_move];
2192 best_move_score = score;
2199 let onDrop = function(source, target) {
2200 if (source === target) {
2201 if (recommended_move === null) {
2204 // Accept the move. It will be changed in onSnapEnd.
2208 // Suggestion not asked for.
2209 recommended_move = null;
2212 // see if the move is legal
2213 let pseudogame = new Chess(display_fen);
2214 let move = pseudogame.move({
2217 promotion: 'q' // NOTE: always promote to a queen for example simplicity
2221 if (move === null) return 'snapback';
2224 let onSnapEnd = function(source, target) {
2225 if (source === target && recommended_move !== null) {
2226 source = recommended_move.from;
2227 target = recommended_move.to;
2229 recommended_move = null;
2230 let pseudogame = new Chess(display_fen);
2231 let move = pseudogame.move({
2234 promotion: 'q' // NOTE: always promote to a queen for example simplicity
2237 // Move ahead on the line we're on -- this includes history if we've
2239 if (current_display_line &&
2240 current_display_move < current_display_line.pv.length - 1 &&
2241 current_display_line.pv[current_display_move + 1] === move.san) {
2246 // Walk down the displayed lines until we find one that starts with
2247 // this move, then select that. Note that this gives us a good priority
2248 // order (PV, then multi-PV lines; history was already dealt with above,
2249 // as it's the only line that originates backwards).
2250 for (let i = 1; i < display_lines.length; ++i) {
2251 if (i == 1 && current_display_line) {
2252 // Do not choose PV if not on it.
2255 let line = display_lines[i];
2256 if (line.pv[line.start_display_move_num] === move.san) {
2262 // Shouldn't really be here if we have hash probes, but there's really
2263 // nothing we can do.
2264 // FIXME: Just make a new line, probably (even if we don't have hash moves).
2265 // As it is, we can actually drag (but not click) such a move in the UI,
2266 // but it has no effect on what we're probing.
2268 // End of dragging-related code.
2270 let fmt_cp = function(v) {
2274 return "+" + (v / 100).toFixed(2);
2277 return "-" + (v / 100).toFixed(2);
2281 let format_short_score = function(score) {
2285 if (score[0] === 'T' || score[0] === 't') {
2286 let ret = "TB\u00a0";
2287 if (score[2]) { // Is a bound.
2288 ret = score[2] + "\u00a0TB\u00a0";
2290 if (score[0] === 'T') {
2291 return ret + Math.ceil(score[1] / 2);
2293 return ret + "-" + Math.ceil(score[1] / 2);
2295 } else if (score[0] === 'M' || score[0] === 'm') {
2296 let sign = (score[0] === 'm') ? '-' : '';
2297 if (score[2]) { // Is a bound.
2298 return score[2] + "\u00a0M " + sign + score[1];
2300 return "M " + sign + score[1];
2302 } else if (score[0] === 'd') {
2304 } else if (score[0] === 'cp') {
2305 if (score[2]) { // Is a bound.
2306 return score[2] + "\u00a0" + fmt_cp(score[1]);
2308 return fmt_cp(score[1]);
2314 let format_long_score = function(score) {
2318 if (score[0] === 'T') {
2319 if (score[1] == 0) {
2320 return "Won for white (tablebase)";
2322 return "White wins in " + Math.ceil(score[1] / 2);
2324 } else if (score[0] === 't') {
2325 if (score[1] == -1) {
2326 return "Won for black (tablebase)";
2328 return "Black wins in " + Math.ceil(score[1] / 2);
2330 } else if (score[0] === 'M') {
2331 if (score[1] == 0) {
2332 return "White wins by checkmate";
2334 return "White mates in " + score[1];
2336 } else if (score[0] === 'm') {
2337 if (score[1] == 0) {
2338 return "Black wins by checkmate";
2340 return "Black mates in " + score[1];
2342 } else if (score[0] === 'd') {
2343 return "Theoretical draw";
2344 } else if (score[0] === 'cp') {
2345 return "Score: " + format_short_score(score);
2350 let compute_plot_score = function(score) {
2351 if (score[0] === 'M' || score[0] === 'T') {
2353 } else if (score[0] === 'm' || score[0] === 't') {
2355 } else if (score[0] === 'd') {
2357 } else if (score[0] === 'cp') {
2358 if (score[1] > 500) {
2360 } else if (score[1] < -500) {
2370 * @param score The score digest tuple.
2371 * @param {?number} depth Depth the move has been computed to, or null.
2372 * @param {boolean} invert Whether black is to play.
2375 let compute_score_sort_key = function(score, depth, invert) {
2380 if (score[0] === 'T') {
2381 // White reaches TB win.
2382 s = 89999 - score[1];
2383 } else if (score[0] === 't') {
2384 // Black reaches TB win.
2385 s = -(89999 - score[1]);
2386 } else if (score[0] === 'M') {
2388 s = 99999 - score[1];
2389 } else if (score[0] === 'm') {
2391 s = -(99999 - score[1]);
2392 } else if (score[0] === 'd') {
2394 } else if (score[0] === 'cp') {
2406 * @param {Object} game
2408 let switch_backend = function(game) {
2409 // Stop looking at historic data.
2410 current_display_line = null;
2411 current_display_move = null;
2412 displayed_analysis_data = null;
2413 if (current_historic_xhr) {
2414 current_historic_xhr.abort();
2417 // If we already have a backend response going, abort it.
2418 if (current_analysis_xhr) {
2419 current_analysis_xhr.abort();
2421 if (current_hash_xhr) {
2422 current_hash_xhr.abort();
2425 // Otherwise, we should have a timer going to start a new one.
2427 if (current_analysis_request_timer) {
2428 clearTimeout(current_analysis_request_timer);
2429 current_analysis_request_timer = null;
2431 if (current_hash_display_timer) {
2432 clearTimeout(current_hash_display_timer);
2433 current_hash_display_timer = null;
2436 // Request an immediate fetch with the new backend.
2437 backend_url = game['url'];
2438 backend_hash_url = game['hashurl'];
2439 window.location.hash = '#' + game['id'];
2440 current_analysis_data = null;
2444 window['switch_backend'] = switch_backend;
2446 window['flip'] = function() { board.flip(); redraw_arrows(); };
2447 window['set_delay_ms'] = function(ms) { delay_ms = ms; console.log('Delay is now ' + ms + ' ms.'); };
2449 // Mostly from Wikipedia's chess set as of October 2022, but some pieces are from
2450 // the 2013 version, as I like those better (and it matches the 2014 PNGs; nobody
2451 // really likes change, do they?). That is wK, bK, bQ. wQ is also slightly different,
2452 // but not enough to notice.
2453 const svg_pieces = {
2454 'wK': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22><g style=%22fill:none;fill-opacity:1;fill-rule:evenodd;stroke:%23000000;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22><path d=%22M 22.5,11.63 L 22.5,6%22 style=%22fill:none;stroke:%23000000;stroke-linejoin:miter%22/><path d=%22M 20,8 L 25,8%22 style=%22fill:none;stroke:%23000000;stroke-linejoin:miter%22/><path d=%22M 22.5,25 C 22.5,25 27,17.5 25.5,14.5 C 25.5,14.5 24.5,12 22.5,12 C 20.5,12 19.5,14.5 19.5,14.5 C 18,17.5 22.5,25 22.5,25%22 style=%22fill:%23ffffff;stroke:%23000000;stroke-linecap:butt;stroke-linejoin:miter%22/><path d=%22M 11.5,37 C 17,40.5 27,40.5 32.5,37 L 32.5,30 C 32.5,30 41.5,25.5 38.5,19.5 C 34.5,13 25,16 22.5,23.5 L 22.5,27 L 22.5,23.5 C 19,16 9.5,13 6.5,19.5 C 3.5,25.5 11.5,29.5 11.5,29.5 L 11.5,37 z %22 style=%22fill:%23ffffff;stroke:%23000000%22/><path d=%22M 11.5,30 C 17,27 27,27 32.5,30%22 style=%22fill:none;stroke:%23000000%22/><path d=%22M 11.5,33.5 C 17,30.5 27,30.5 32.5,33.5%22 style=%22fill:none;stroke:%23000000%22/><path d=%22M 11.5,37 C 17,34 27,34 32.5,37%22 style=%22fill:none;stroke:%23000000%22/></g></svg>',
2455 'wQ': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22><g style=%22fill:%23ffffff;stroke:%23000000;stroke-width:1.5;stroke-linejoin:round%22><path d=%22M 9,26 C 17.5,24.5 30,24.5 36,26 L 38.5,13.5 L 31,25 L 30.7,10.9 L 25.5,24.5 L 22.5,10 L 19.5,24.5 L 14.3,10.9 L 14,25 L 6.5,13.5 L 9,26 z%22/><path d=%22M 9,26 C 9,28 10.5,28 11.5,30 C 12.5,31.5 12.5,31 12,33.5 C 10.5,34.5 11,36 11,36 C 9.5,37.5 11,38.5 11,38.5 C 17.5,39.5 27.5,39.5 34,38.5 C 34,38.5 35.5,37.5 34,36 C 34,36 34.5,34.5 33,33.5 C 32.5,31 32.5,31.5 33.5,30 C 34.5,28 36,28 36,26 C 27.5,24.5 17.5,24.5 9,26 z%22/><path d=%22M 11.5,30 C 15,29 30,29 33.5,30%22 style=%22fill:none%22/><path d=%22M 12,33.5 C 18,32.5 27,32.5 33,33.5%22 style=%22fill:none%22/><circle cx=%226%22 cy=%2212%22 r=%222%22/><circle cx=%2214%22 cy=%229%22 r=%222%22/><circle cx=%2222.5%22 cy=%228%22 r=%222%22/><circle cx=%2231%22 cy=%229%22 r=%222%22/><circle cx=%2239%22 cy=%2212%22 r=%222%22/></g></svg>',
2456 'wR': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22><g style=%22opacity:1;fill:%23ffffff;fill-opacity:1;fill-rule:evenodd;stroke:%23000000;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22 transform=%22translate(0,0.3)%22><path d=%22M 9,39 L 36,39 L 36,36 L 9,36 L 9,39 z %22 style=%22stroke-linecap:butt%22/><path d=%22M 12,36 L 12,32 L 33,32 L 33,36 L 12,36 z %22 style=%22stroke-linecap:butt%22/><path d=%22M 11,14 L 11,9 L 15,9 L 15,11 L 20,11 L 20,9 L 25,9 L 25,11 L 30,11 L 30,9 L 34,9 L 34,14%22 style=%22stroke-linecap:butt%22/><path d=%22M 34,14 L 31,17 L 14,17 L 11,14%22/><path d=%22M 31,17 L 31,29.5 L 14,29.5 L 14,17%22 style=%22stroke-linecap:butt;stroke-linejoin:miter%22/><path d=%22M 31,29.5 L 32.5,32 L 12.5,32 L 14,29.5%22/><path d=%22M 11,14 L 34,14%22 style=%22fill:none;stroke:%23000000;stroke-linejoin:miter%22/></g></svg>',
2457 'wB': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22><g style=%22opacity:1;fill:none;fill-rule:evenodd;fill-opacity:1;stroke:%23000000;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22 transform=%22translate(0,0.6)%22><g style=%22fill:%23ffffff;stroke:%23000000;stroke-linecap:butt%22><path d=%22M 9,36 C 12.39,35.03 19.11,36.43 22.5,34 C 25.89,36.43 32.61,35.03 36,36 C 36,36 37.65,36.54 39,38 C 38.32,38.97 37.35,38.99 36,38.5 C 32.61,37.53 25.89,38.96 22.5,37.5 C 19.11,38.96 12.39,37.53 9,38.5 C 7.65,38.99 6.68,38.97 6,38 C 7.35,36.54 9,36 9,36 z%22/><path d=%22M 15,32 C 17.5,34.5 27.5,34.5 30,32 C 30.5,30.5 30,30 30,30 C 30,27.5 27.5,26 27.5,26 C 33,24.5 33.5,14.5 22.5,10.5 C 11.5,14.5 12,24.5 17.5,26 C 17.5,26 15,27.5 15,30 C 15,30 14.5,30.5 15,32 z%22/><path d=%22M 25 8 A 2.5 2.5 0 1 1 20,8 A 2.5 2.5 0 1 1 25 8 z%22/></g><path d=%22M 17.5,26 L 27.5,26 M 15,30 L 30,30 M 22.5,15.5 L 22.5,20.5 M 20,18 L 25,18%22 style=%22fill:none;stroke:%23000000;stroke-linejoin:miter%22/></g></svg>',
2458 'wN': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22><g style=%22opacity:1;fill:none;fill-opacity:1;fill-rule:evenodd;stroke:%23000000;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22 transform=%22translate(0,0.3)%22><path d=%22M 22,10 C 32.5,11 38.5,18 38,39 L 15,39 C 15,30 25,32.5 23,18%22 style=%22fill:%23ffffff;stroke:%23000000%22/><path d=%22M 24,18 C 24.38,20.91 18.45,25.37 16,27 C 13,29 13.18,31.34 11,31 C 9.958,30.06 12.41,27.96 11,28 C 10,28 11.19,29.23 10,30 C 9,30 5.997,31 6,26 C 6,24 12,14 12,14 C 12,14 13.89,12.1 14,10.5 C 13.27,9.506 13.5,8.5 13.5,7.5 C 14.5,6.5 16.5,10 16.5,10 L 18.5,10 C 18.5,10 19.28,8.008 21,7 C 22,7 22,10 22,10%22 style=%22fill:%23ffffff;stroke:%23000000%22/><path d=%22M 9.5 25.5 A 0.5 0.5 0 1 1 8.5,25.5 A 0.5 0.5 0 1 1 9.5 25.5 z%22 style=%22fill:%23000000;stroke:%23000000%22/><path d=%22M 15 15.5 A 0.5 1.5 0 1 1 14,15.5 A 0.5 1.5 0 1 1 15 15.5 z%22 transform=%22matrix(0.866,0.5,-0.5,0.866,9.693,-5.173)%22 style=%22fill:%23000000;stroke:%23000000%22/></g></svg>',
2459 'wP': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22><path d=%22m 22.5,9 c -2.21,0 -4,1.79 -4,4 0,0.89 0.29,1.71 0.78,2.38 C 17.33,16.5 16,18.59 16,21 c 0,2.03 0.94,3.84 2.41,5.03 C 15.41,27.09 11,31.58 11,39.5 H 34 C 34,31.58 29.59,27.09 26.59,26.03 28.06,24.84 29,23.03 29,21 29,18.59 27.67,16.5 25.72,15.38 26.21,14.71 26.5,13.89 26.5,13 c 0,-2.21 -1.79,-4 -4,-4 z%22 style=%22opacity:1;fill:%23ffffff;fill-opacity:1;fill-rule:nonzero;stroke:%23000000;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22/></svg>',
2460 'bK': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22><g style=%22fill:none;fill-opacity:1;fill-rule:evenodd;stroke:%23000000;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22><path d=%22M 22.5,11.63 L 22.5,6%22 style=%22fill:none;stroke:%23000000;stroke-linejoin:miter%22 id=%22path6570%22/><path d=%22M 22.5,25 C 22.5,25 27,17.5 25.5,14.5 C 25.5,14.5 24.5,12 22.5,12 C 20.5,12 19.5,14.5 19.5,14.5 C 18,17.5 22.5,25 22.5,25%22 style=%22fill:%23000000;fill-opacity:1;stroke-linecap:butt;stroke-linejoin:miter%22/><path d=%22M 11.5,37 C 17,40.5 27,40.5 32.5,37 L 32.5,30 C 32.5,30 41.5,25.5 38.5,19.5 C 34.5,13 25,16 22.5,23.5 L 22.5,27 L 22.5,23.5 C 19,16 9.5,13 6.5,19.5 C 3.5,25.5 11.5,29.5 11.5,29.5 L 11.5,37 z %22 style=%22fill:%23000000;stroke:%23000000%22/><path d=%22M 20,8 L 25,8%22 style=%22fill:none;stroke:%23000000;stroke-linejoin:miter%22/><path d=%22M 32,29.5 C 32,29.5 40.5,25.5 38.03,19.85 C 34.15,14 25,18 22.5,24.5 L 22.51,26.6 L 22.5,24.5 C 20,18 9.906,14 6.997,19.85 C 4.5,25.5 11.85,28.85 11.85,28.85%22 style=%22fill:none;stroke:%23ffffff%22/><path d=%22M 11.5,30 C 17,27 27,27 32.5,30 M 11.5,33.5 C 17,30.5 27,30.5 32.5,33.5 M 11.5,37 C 17,34 27,34 32.5,37%22 style=%22fill:none;stroke:%23ffffff%22/></g></svg>',
2461 'bQ': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns:svg=%22http://www.w3.org/2000/svg%22 xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22 id=%22svg3128%22><defs/><g id=%22layer1%22><path d=%22M 8 12 A 2 2 0 1 1 4,12 A 2 2 0 1 1 8 12 z%22 style=%22opacity:1;fill:%23000000;fill-opacity:1;stroke:%23000000;stroke-width:1;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22 id=%22path5571%22/><path d=%22M 9 13 A 2 2 0 1 1 5,13 A 2 2 0 1 1 9 13 z%22 transform=%22translate(15.5,-5.5)%22 style=%22opacity:1;fill:%23000000;fill-opacity:1;stroke:%23000000;stroke-width:1;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22 id=%22path5573%22/><path d=%22M 9 13 A 2 2 0 1 1 5,13 A 2 2 0 1 1 9 13 z%22 transform=%22translate(32,-1)%22 style=%22opacity:1;fill:%23000000;fill-opacity:1;stroke:%23000000;stroke-width:1;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22 id=%22path5575%22/><path d=%22M 9 13 A 2 2 0 1 1 5,13 A 2 2 0 1 1 9 13 z%22 transform=%22translate(7,-4.5)%22 style=%22opacity:1;fill:%23000000;fill-opacity:1;stroke:%23000000;stroke-width:1;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22 id=%22path5577%22/><path d=%22M 9 13 A 2 2 0 1 1 5,13 A 2 2 0 1 1 9 13 z%22 transform=%22translate(24,-4)%22 style=%22opacity:1;fill:%23000000;fill-opacity:1;stroke:%23000000;stroke-width:1;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22 id=%22path5579%22/><path d=%22M 9,26 C 17.5,24.5 30,24.5 36,26 L 38,14 L 31,25 L 31,11 L 25.5,24.5 L 22.5,9.5 L 19.5,24.5 L 14,10.5 L 14,25 L 7,14 L 9,26 z %22 style=%22fill:%23000000;fill-opacity:1;fill-rule:evenodd;stroke:%23000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:round;stroke-opacity:1%22 id=%22path5581%22/><path d=%22M 9,26 C 9,28 10.5,28 11.5,30 C 12.5,31.5 12.5,31 12,33.5 C 10.5,34.5 10.5,36 10.5,36 C 9,37.5 11,38.5 11,38.5 C 17.5,39.5 27.5,39.5 34,38.5 C 34,38.5 35.5,37.5 34,36 C 34,36 34.5,34.5 33,33.5 C 32.5,31 32.5,31.5 33.5,30 C 34.5,28 36,28 36,26 C 27.5,24.5 17.5,24.5 9,26 z %22 style=%22fill:%23000000;fill-opacity:1;fill-rule:evenodd;stroke:%23000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:round;stroke-opacity:1%22 id=%22path5583%22/><path d=%22M 11.5,30 C 15,29 30,29 33.5,30%22 style=%22fill:none;fill-opacity:0.75;fill-rule:evenodd;stroke:%23ffffff;stroke-width:1px;stroke-linecap:round;stroke-linejoin:round;stroke-opacity:1%22 id=%22path5585%22/><path d=%22M 12,33.5 C 18,32.5 27,32.5 33,33.5%22 style=%22fill:none;fill-opacity:0.75;fill-rule:evenodd;stroke:%23ffffff;stroke-width:1px;stroke-linecap:round;stroke-linejoin:round;stroke-opacity:1%22 id=%22path5587%22/><path d=%22M 10.5,36 C 15.5,35 29,35 34,36%22 style=%22fill:none;fill-opacity:0.75;fill-rule:evenodd;stroke:%23ffffff;stroke-width:1px;stroke-linecap:round;stroke-linejoin:round;stroke-opacity:1%22 id=%22path5589%22/></g></svg>',
2462 'bR': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22><g style=%22opacity:1;fill:%23000000;fill-opacity:1;fill-rule:evenodd;stroke:%23000000;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22 transform=%22translate(0,0.3)%22><path d=%22M 9,39 L 36,39 L 36,36 L 9,36 L 9,39 z %22 style=%22stroke-linecap:butt%22/><path d=%22M 12.5,32 L 14,29.5 L 31,29.5 L 32.5,32 L 12.5,32 z %22 style=%22stroke-linecap:butt%22/><path d=%22M 12,36 L 12,32 L 33,32 L 33,36 L 12,36 z %22 style=%22stroke-linecap:butt%22/><path d=%22M 14,29.5 L 14,16.5 L 31,16.5 L 31,29.5 L 14,29.5 z %22 style=%22stroke-linecap:butt;stroke-linejoin:miter%22/><path d=%22M 14,16.5 L 11,14 L 34,14 L 31,16.5 L 14,16.5 z %22 style=%22stroke-linecap:butt%22/><path d=%22M 11,14 L 11,9 L 15,9 L 15,11 L 20,11 L 20,9 L 25,9 L 25,11 L 30,11 L 30,9 L 34,9 L 34,14 L 11,14 z %22 style=%22stroke-linecap:butt%22/><path d=%22M 12,35.5 L 33,35.5 L 33,35.5%22 style=%22fill:none;stroke:%23ffffff;stroke-width:1;stroke-linejoin:miter%22/><path d=%22M 13,31.5 L 32,31.5%22 style=%22fill:none;stroke:%23ffffff;stroke-width:1;stroke-linejoin:miter%22/><path d=%22M 14,29.5 L 31,29.5%22 style=%22fill:none;stroke:%23ffffff;stroke-width:1;stroke-linejoin:miter%22/><path d=%22M 14,16.5 L 31,16.5%22 style=%22fill:none;stroke:%23ffffff;stroke-width:1;stroke-linejoin:miter%22/><path d=%22M 11,14 L 34,14%22 style=%22fill:none;stroke:%23ffffff;stroke-width:1;stroke-linejoin:miter%22/></g></svg>',
2463 'bB': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22><g style=%22opacity:1;fill:none;fill-rule:evenodd;fill-opacity:1;stroke:%23000000;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22 transform=%22translate(0,0.6)%22><g style=%22fill:%23000000;stroke:%23000000;stroke-linecap:butt%22><path d=%22M 9,36 C 12.39,35.03 19.11,36.43 22.5,34 C 25.89,36.43 32.61,35.03 36,36 C 36,36 37.65,36.54 39,38 C 38.32,38.97 37.35,38.99 36,38.5 C 32.61,37.53 25.89,38.96 22.5,37.5 C 19.11,38.96 12.39,37.53 9,38.5 C 7.65,38.99 6.68,38.97 6,38 C 7.35,36.54 9,36 9,36 z%22/><path d=%22M 15,32 C 17.5,34.5 27.5,34.5 30,32 C 30.5,30.5 30,30 30,30 C 30,27.5 27.5,26 27.5,26 C 33,24.5 33.5,14.5 22.5,10.5 C 11.5,14.5 12,24.5 17.5,26 C 17.5,26 15,27.5 15,30 C 15,30 14.5,30.5 15,32 z%22/><path d=%22M 25 8 A 2.5 2.5 0 1 1 20,8 A 2.5 2.5 0 1 1 25 8 z%22/></g><path d=%22M 17.5,26 L 27.5,26 M 15,30 L 30,30 M 22.5,15.5 L 22.5,20.5 M 20,18 L 25,18%22 style=%22fill:none;stroke:%23ffffff;stroke-linejoin:miter%22/></g></svg>',
2464 'bN': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22><g style=%22opacity:1;fill:none;fill-opacity:1;fill-rule:evenodd;stroke:%23000000;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22 transform=%22translate(0,0.3)%22><path d=%22M 22,10 C 32.5,11 38.5,18 38,39 L 15,39 C 15,30 25,32.5 23,18%22 style=%22fill:%23000000;stroke:%23000000%22/><path d=%22M 24,18 C 24.38,20.91 18.45,25.37 16,27 C 13,29 13.18,31.34 11,31 C 9.958,30.06 12.41,27.96 11,28 C 10,28 11.19,29.23 10,30 C 9,30 5.997,31 6,26 C 6,24 12,14 12,14 C 12,14 13.89,12.1 14,10.5 C 13.27,9.506 13.5,8.5 13.5,7.5 C 14.5,6.5 16.5,10 16.5,10 L 18.5,10 C 18.5,10 19.28,8.008 21,7 C 22,7 22,10 22,10%22 style=%22fill:%23000000;stroke:%23000000%22/><path d=%22M 9.5 25.5 A 0.5 0.5 0 1 1 8.5,25.5 A 0.5 0.5 0 1 1 9.5 25.5 z%22 style=%22fill:%23ffffff;stroke:%23ffffff%22/><path d=%22M 15 15.5 A 0.5 1.5 0 1 1 14,15.5 A 0.5 1.5 0 1 1 15 15.5 z%22 transform=%22matrix(0.866,0.5,-0.5,0.866,9.693,-5.173)%22 style=%22fill:%23ffffff;stroke:%23ffffff%22/><path d=%22M 24.55,10.4 L 24.1,11.85 L 24.6,12 C 27.75,13 30.25,14.49 32.5,18.75 C 34.75,23.01 35.75,29.06 35.25,39 L 35.2,39.5 L 37.45,39.5 L 37.5,39 C 38,28.94 36.62,22.15 34.25,17.66 C 31.88,13.17 28.46,11.02 25.06,10.5 L 24.55,10.4 z %22 style=%22fill:%23ffffff;stroke:none%22/></g></svg>',
2465 'bP': 'data:image/svg+xml,<?xml version=%221.0%22 encoding=%22UTF-8%22 standalone=%22no%22?>%0A<!DOCTYPE svg PUBLIC %22-//W3C//DTD SVG 1.1//EN%22 %22http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd%22>%0A<svg xmlns=%22http://www.w3.org/2000/svg%22 version=%221.1%22 width=%2245%22 height=%2245%22><path d=%22m 22.5,9 c -2.21,0 -4,1.79 -4,4 0,0.89 0.29,1.71 0.78,2.38 C 17.33,16.5 16,18.59 16,21 c 0,2.03 0.94,3.84 2.41,5.03 C 15.41,27.09 11,31.58 11,39.5 H 34 C 34,31.58 29.59,27.09 26.59,26.03 28.06,24.84 29,23.03 29,21 29,18.59 27.67,16.5 25.72,15.38 26.21,14.71 26.5,13.89 26.5,13 c 0,-2.21 -1.79,-4 -4,-4 z%22 style=%22opacity:1;fill:%23000000;fill-opacity:1;fill-rule:nonzero;stroke:%23000000;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1%22/></svg>',
2468 let svg_piece_theme = function(piece) {
2469 return svg_pieces[piece];
2472 let init = function() {
2473 unique = get_unique();
2475 // Load settings from HTML5 local storage if available.
2476 if (supports_html5_storage() && window['localStorage']['enable_sound']) {
2477 set_sound(parseInt(window['localStorage']['enable_sound']));
2483 board = new window.ChessBoard('board', {
2484 onMoveEnd: function() { board_is_animating = false; },
2487 pieceTheme: svg_piece_theme,
2488 onDragStart: onDragStart,
2490 onSnapEnd: onSnapEnd
2492 document.getElementById("board").addEventListener('mousedown', mousedownSquare);
2493 document.getElementById("board").addEventListener('mouseup', mouseupSquare);
2496 window.addEventListener('resize', function() {
2498 update_sparkline(displayed_analysis_data || current_analysis_data);
2499 update_board_highlight();
2502 window.addEventListener('keyup', function(event) {
2503 if (event.which == 39) { // Left arrow.
2505 } else if (event.which == 37) { // Right arrow.
2507 } else if (event.which >= 49 && event.which <= 57) { // 1-9.
2508 let num = event.which - 49;
2509 if (current_games && current_games.length >= num) {
2510 switch_backend(current_games[num]);
2512 } else if (event.which == 78) { // N.
2516 window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
2517 possibly_switch_game_from_hash();
2519 document.addEventListener('DOMContentLoaded', init);