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 function supports_html5_storage() {
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 function get_unique() {
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 function request_update() {
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 function process_update_response(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 function possibly_play_sound(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 function sync_server_clock(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 function clear_arrows() {
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 function redraw_arrows() {
396 for (let i = 0; i < arrows.length; ++i) {
397 position_arrow(arrows[i]);
401 /** @param {!number} 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 function interfering_arrow(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 function point_from_start(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 function point_from_end(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 function position_arrow(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 // We always draw as if the board is 400x400, the viewBox will adjust that for us
508 let line_width = arrow.line_width;
509 let arrow_size = arrow.arrow_size;
511 let square_width = 400 / 8;
512 let from_y, to_y, from_x, to_x;
513 if (board.orientation() === 'black') {
514 from_y = (arrow.from_row + 0.5)*square_width;
515 to_y = (arrow.to_row + 0.5)*square_width;
516 from_x = (7 - arrow.from_col + 0.5)*square_width;
517 to_x = (7 - arrow.to_col + 0.5)*square_width;
519 from_y = (7 - arrow.from_row + 0.5)*square_width;
520 to_y = (7 - arrow.to_row + 0.5)*square_width;
521 from_x = (arrow.from_col + 0.5)*square_width;
522 to_x = (arrow.to_col + 0.5)*square_width;
525 let SVG_NS = "http://www.w3.org/2000/svg";
526 let XHTML_NS = "http://www.w3.org/1999/xhtml";
527 let svg = document.createElementNS(SVG_NS, "svg");
528 svg.setAttribute("width", "100%");
529 svg.setAttribute("height", "100%");
530 svg.setAttribute("viewBox", "0 0 400 400");
531 svg.setAttribute("version", "1.1");
532 svg.setAttribute("class", "c1");
533 svg.setAttribute("xmlns", XHTML_NS);
541 let outline = document.createElementNS(SVG_NS, "path");
542 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));
543 outline.setAttribute("xmlns", XHTML_NS);
544 outline.setAttribute("stroke", "#666");
545 outline.setAttribute("stroke-width", line_width + 2);
546 outline.setAttribute("fill", "none");
547 svg.appendChild(outline);
549 let path = document.createElementNS(SVG_NS, "path");
550 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));
551 path.setAttribute("xmlns", XHTML_NS);
552 path.setAttribute("stroke", arrow.fg_color);
553 path.setAttribute("stroke-width", line_width);
554 path.setAttribute("fill", "none");
555 svg.appendChild(path);
557 // Then the arrow head.
558 let head = document.createElementNS(SVG_NS, "path");
559 head.setAttribute("d",
560 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
561 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
562 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 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, 0, 0));
565 head.setAttribute("xmlns", XHTML_NS);
566 head.setAttribute("stroke", "#000");
567 head.setAttribute("stroke-width", "1");
568 head.setAttribute("fill", arrow.fg_color);
569 svg.appendChild(head);
571 svg.style.position = 'absolute';
572 svg.style.top = '0px'; /* Border for .board-b72b1. */
573 svg.style.left = '0px';
574 svg.style.pointerEvents = 'none';
575 document.getElementById('board').appendChild(svg);
580 * @param {!string} from_square
581 * @param {!string} to_square
582 * @param {!string} fg_color
583 * @param {number} line_width
584 * @param {number} arrow_size
586 function create_arrow(from_square, to_square, fg_color, line_width, arrow_size) {
587 let from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
588 let from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
589 let to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
590 let to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
598 line_width: line_width,
599 arrow_size: arrow_size,
603 position_arrow(arrow);
607 function compare_by_score(refutation_lines, invert, a, b) {
608 let sa = compute_score_sort_key(refutation_lines[b]['score'], refutation_lines[b]['depth'], invert);
609 let sb = compute_score_sort_key(refutation_lines[a]['score'], refutation_lines[a]['depth'], invert);
614 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
615 * sorted by quality, descending.
617 * @param {!Object} data
618 * @param {number} margin The maximum number of centipawns worse than the
619 * best move can be and still be included.
620 * @param {boolean} invert Whether black is to play.
621 * @return {Array.<string>} The FEN representation (e.g. Ne4) of all
622 * moves, in score order.
624 function find_nonstupid_moves(data, margin, invert) {
625 // First of all, if there are any moves that are more than 0.5 ahead of
626 // the primary move, the refutation lines are probably bunk, so just
628 let best_score = undefined;
629 let pv_score = undefined;
630 for (let move in data['refutation_lines']) {
631 let line = data['refutation_lines'][move];
632 let score = compute_score_sort_key(line['score'], line['depth'], invert);
633 if (move == data['pv'][0]) {
636 if (best_score === undefined || score > best_score) {
639 if (line['depth'] < 8) {
644 if (best_score - pv_score > 50) {
648 // Now find all moves that are within “margin” of the best score.
649 // The PV move will always be first.
651 for (let move in data['refutation_lines']) {
652 let line = data['refutation_lines'][move];
653 let score = compute_score_sort_key(line['score'], line['depth'], invert);
654 if (move != data['pv'][0] && best_score - score <= margin) {
658 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], data['position']['toplay'] === 'B', a, b) });
659 moves.unshift(data['pv'][0]);
668 function thousands(x) {
669 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
673 * @param {!string} start_fen
674 * @param {Array.<string>} pv
675 * @param {number} move_num
676 * @param {!string} toplay
677 * @param {Array<{ first_move: integer, score: Object }>} scores
678 * @param {number} start_display_move_num
679 * @param {number=} opt_limit
680 * @param {boolean=} opt_showlast
682 function add_pv(start_fen, pv, move_num, toplay, scores, start_display_move_num, opt_limit, opt_showlast) {
684 start_fen: start_fen,
686 move_num: parseInt(move_num),
689 start_display_move_num: start_display_move_num
691 let splicepos = null;
692 if (scores !== null && scores.length >= 1 &&
693 scores[scores.length - 1].score !== undefined &&
694 scores[scores.length - 1].score !== null &&
695 (scores[scores.length - 1].score[0] === 'T' ||
696 scores[scores.length - 1].score[0] === 't')) {
697 splicepos = scores[scores.length - 1].score[1];
699 return print_pv(display_lines.length - 1, splicepos, opt_limit, opt_showlast);
703 * @param {number} line_num
704 * @param {?number} splicepos If non-null, where the tablebase-spliced portion of the TB starts.
705 * @param {number=} opt_limit If set, show at most this number of moves.
706 * @param {boolean=} opt_showlast If limit is set, show the last moves instead of the first ones.
708 function print_pv(line_num, splicepos, opt_limit, opt_showlast) {
709 let display_line = display_lines[line_num];
710 let pv = display_line.pv;
711 let move_num = display_line.move_num;
712 let toplay = display_line.toplay;
714 // Truncate PV at the start if needed.
715 let start_display_move_num = display_line.start_display_move_num;
716 if (start_display_move_num > 0) {
717 pv = pv.slice(start_display_move_num);
718 let to_add = start_display_move_num;
719 if (toplay === 'B') {
724 if (to_add % 2 == 1) {
728 move_num += to_add / 2;
729 if (splicepos !== null && splicepos > 0) {
734 let ret = document.createDocumentFragment();
737 if (opt_limit && opt_showlast && pv.length > opt_limit) {
738 // Truncate the PV at the beginning (instead of at the end).
739 // We assume here that toplay is 'W'. We also assume that if
740 // opt_showlast is set, then it is the history, and thus,
741 // the UI should be to expand the history.
742 ret.appendChild(document.createTextNode('('));
743 let link = document.createElement('a');
744 link.className = 'move';
745 link.href = 'javascript:collapse_history(false)';
746 link.textContent = '…';
747 ret.appendChild(link);
748 ret.appendChild(document.createTextNode(') '));
749 i = pv.length - opt_limit;
754 } else if (toplay == 'B' && pv.length > 0) {
755 ret.appendChild(document.createTextNode(move_num + '. … '));
757 for (; i < pv.length; ++i) {
759 if (splicepos === i) {
764 if (toplay == 'B' && i == 0) {
767 } else if (toplay == 'W') {
768 if (i > opt_limit && !opt_showlast) {
772 ret.appendChild(document.createTextNode(prefix + ' (…)'));
775 prefix += ' ' + move_num + '. ';
782 ret.appendChild(document.createTextNode(prefix));
784 let link = document.createElement('a');
785 link.className = 'move';
786 link.setAttribute('id', 'automove' + line_num + '-' + i);
787 link.textContent = pv[i];
788 link.href = 'javascript:show_line(' + line_num + ', ' + i + ');';
789 ret.appendChild(link);
792 ret.appendChild(document.createTextNode(')'));
797 /** Update the highlighted to/from squares on the board.
798 * Based on the global "highlight_from" and "highlight_to" letiables.
800 function update_board_highlight() {
801 document.getElementById("board").querySelectorAll('.square-55d63').forEach((square) => square.classList.remove('nonuglyhighlight'));
802 if ((current_display_line === null || current_display_line_is_history) &&
803 highlight_from !== undefined && highlight_to !== undefined) {
804 document.getElementById("board").querySelector('.square-' + highlight_from).classList.add('nonuglyhighlight');
805 document.getElementById("board").querySelector('.square-' + highlight_to).classList.add('nonuglyhighlight');
809 function update_history() {
810 let history = document.getElementById('history');
811 if (display_lines[0] === null || display_lines[0].pv.length == 0) {
812 history.textContent = 'No history';
813 } else if (truncate_display_history) {
814 history.replaceChildren(print_pv(0, null, 8, true));
816 history.textContent = '(';
817 let link = document.createElement('a');
818 link.className = 'move';
819 link.href = 'javascript:collapse_history(true)';
820 link.textContent = 'collapse';
821 history.appendChild(link);
822 history.appendChild(document.createTextNode(') '));
823 history.append(print_pv(0, null));
828 * @param {!boolean} truncate_history
830 function collapse_history(truncate_history) {
831 truncate_display_history = truncate_history;
834 window['collapse_history'] = collapse_history;
836 /** Update the HTML display of multi-PV from the global "refutation_lines".
838 * Also recreates the global "display_lines".
840 function update_refutation_lines() {
841 if (base_fen === null) {
844 if (display_lines.length > 2) {
845 // Truncate so that only the history and PV is left.
846 display_lines = [ display_lines[0], display_lines[1] ];
848 let tbl = document.getElementById("refutationlines");
849 tbl.replaceChildren();
851 if (display_lines.length < 2) {
852 // Update the move highlight, as we've rewritten all the HTML.
853 update_move_highlight();
857 // Find out where the lines start from.
859 let base_scores = display_lines[1].scores;
860 let start_display_move_num = 0;
861 if (hash_refutation_lines) {
862 base_line = current_display_line.pv.slice(0, current_display_move + 1);
863 base_scores = current_display_line.scores;
864 start_display_move_num = base_line.length;
868 for (let move in refutation_lines) {
872 let invert = (toplay === 'B');
873 if (current_display_line && current_display_move % 2 == 0 && !current_display_line_is_history) {
876 moves = moves.sort(function(a, b) { return compare_by_score(refutation_lines, invert, a, b) });
877 for (let i = 0; i < moves.length; ++i) {
878 let line = refutation_lines[moves[i]];
880 let tr = document.createElement("tr");
882 let move_td = document.createElement("td");
883 tr.appendChild(move_td);
884 move_td.classList.add("move");
886 let scores = base_scores.concat([{ first_move: start_display_move_num, score: line['score'] }]);
888 if (line['pv'].length == 0) {
889 // Not found, so just make a one-move PV.
890 let link = document.createElement('a');
891 link.className = 'move';
892 link.href = 'javascript:show_line(' + display_lines.length + ', ' + 0 + ')';
893 link.textContent = line['move'];
894 move_td.replaceChildren(link);
896 let score_td = document.createElement("td");
897 score_td.classList.add("score");
898 score_td.textContent = "—";
899 tr.appendChild(score_td);
901 let depth_td = document.createElement("td");
902 tr.appendChild(depth_td);
903 depth_td.classList.add("depth");
904 depth_td.textContent = "—";
906 let pv_td = document.createElement("td");
907 tr.appendChild(pv_td);
908 pv_td.classList.add("pv");
909 pv_td.append(add_pv(base_fen, base_line.concat([ line['move'] ]), move_num, toplay, scores, start_display_move_num));
915 let move_link = document.createElement("a");
916 move_link.classList.add("move");
917 move_link.setAttribute("href", "javascript:show_line(" + display_lines.length + ", 0)");
918 move_link.textContent = line['move'];
919 move_td.appendChild(move_link);
921 let score_td = document.createElement("td");
922 tr.appendChild(score_td);
923 score_td.classList.add("score");
924 score_td.textContent = format_short_score(line['score']);
926 let depth_td = document.createElement("td");
927 tr.appendChild(depth_td);
928 depth_td.classList.add("depth");
929 if (line['depth'] && line['depth'] >= 0) {
930 depth_td.textContent = "d" + line['depth'];
932 depth_td.textContent = "—";
935 let pv_td = document.createElement("td");
936 tr.appendChild(pv_td);
937 pv_td.classList.add("pv");
938 pv_td.append(add_pv(base_fen, base_line.concat(line['pv']), move_num, toplay, scores, start_display_move_num, 10));
943 // Update the move highlight, as we've rewritten all the HTML.
944 update_move_highlight();
948 * Create a Chess.js board object, containing the given position plus the given moves,
949 * up to the given limit.
951 * @param {?string} fen
952 * @param {Array.<string>} moves
953 * @param {number} last_move
955 function chess_from(fen, moves, last_move) {
956 let hiddenboard = new Chess();
957 if (fen !== null && fen !== undefined) {
958 hiddenboard.load(fen);
960 for (let i = 0; i <= last_move; ++i) {
961 if (moves[i] === '0-0') {
962 hiddenboard.move('O-O');
963 } else if (moves[i] === '0-0-0') {
964 hiddenboard.move('O-O-O');
966 hiddenboard.move(moves[i]);
972 function update_game_list(games) {
973 document.getElementById("games").textContent = "";
974 if (games === null) {
978 let games_div = document.getElementById('games');
979 for (let game_num = 0; game_num < games.length; ++game_num) {
980 let game = games[game_num];
981 let game_span = document.createElement("span");
982 game_span.setAttribute("class", "game");
984 let game_name = document.createTextNode(game['name']);
985 if (game['url'] === backend_url) {
987 game_span.appendChild(game_name);
989 if (current_analysis_data && current_analysis_data['position']) {
991 if (current_analysis_data['position']['result']) {
992 score = " (" + current_analysis_data['position']['result'] + ")";
994 score = " (" + format_short_score(current_analysis_data['score']) + ")";
996 game_span.appendChild(document.createTextNode(score));
1000 let game_a = document.createElement("a");
1001 game_a.setAttribute("href", "#" + game['id']);
1002 game_a.appendChild(game_name);
1003 game_span.appendChild(game_a);
1006 if (game['result']) {
1007 score = " (" + game['result'] + ")";
1009 score = " (" + format_short_score(game['score']) + ")";
1011 game_span.appendChild(document.createTextNode(score));
1014 games_div.appendChild(game_span);
1019 * Try to find a running game that matches with the current hash,
1020 * and switch to it if we're not already displaying it.
1022 function possibly_switch_game_from_hash() {
1023 let history_match = window.location.hash.match(/^#history=([a-zA-Z0-9_-]+)/);
1024 if (history_match !== null) {
1025 let game_id = history_match[1];
1027 url: '/history/' + game_id + '.json',
1029 id: 'history=' + game_id
1031 switch_backend(fake_game);
1035 if (current_games === null) {
1039 let hash = window.location.hash.replace(/^#/,'');
1040 for (let i = 0; i < current_games.length; ++i) {
1041 if (current_games[i]['id'] === hash) {
1042 if (backend_url !== current_games[i]['url']) {
1043 switch_backend(current_games[i]);
1051 * If this is a Chess960 castling which doesn't move the king,
1052 * move the rook instead.
1054 function patch_move(move) {
1055 if (move === null) return null;
1056 if (move.from !== move.to) return move;
1058 let f = move.rook_sq & 15;
1059 let r = move.rook_sq >> 4;
1060 let from = ('abcdefgh'.substring(f,f+1) + '87654321'.substring(r,r+1));
1063 if (move.to === 'g1') {
1065 } else if (move.to === 'g8') {
1067 } else if (move.to === 'b1') {
1069 } else if (move.to === 'b8') {
1073 return { from: from, to: to };
1076 /** Update all the HTML on the page, based on current global state.
1078 function update_board() {
1079 document.body.style.opacity = null;
1081 let data = displayed_analysis_data || current_analysis_data;
1082 let current_data = current_analysis_data; // Convenience alias.
1086 // Print the history. This is pretty much the only thing that's
1087 // unconditionally taken from current_data (we're not interested in
1088 // historic history).
1089 if (current_data['position']['history']) {
1090 let start = (current_data['position'] && current_data['position']['start_fen']) ? current_data['position']['start_fen'] : 'start';
1091 add_pv(start, current_data['position']['history'], 1, 'W', null, 0, 8, true);
1093 display_lines.push(null);
1097 // Games currently in progress, if any.
1098 if (current_data['games']) {
1099 current_games = current_data['games'];
1100 possibly_switch_game_from_hash();
1102 current_games = null;
1104 update_game_list(current_games);
1106 // The headline. Names are always fetched from current_data;
1107 // the rest can depend a bit.
1110 current_data['position']['player_w'] && current_data['position']['player_b']) {
1111 headline = current_data['position']['player_w'] + '–' +
1112 current_data['position']['player_b'] + ', analysis';
1114 headline = 'Analysis';
1117 // Credits, where applicable. Note that we don't want the footer to change a lot
1118 // when e.g. viewing history, so if any of these changed during the game,
1119 // use the current one still.
1120 if (current_data['using_lomonosov']) {
1121 document.getElementById("lomonosov").style.display = null;
1123 document.getElementById("lomonosov").style.display = 'none';
1126 // Credits: The engine name/version.
1127 if (current_data['engine'] && current_data['engine']['name'] !== null) {
1128 document.getElementById("engineid").textContent = current_data['engine']['name'];
1131 // Credits: The engine URL.
1132 if (current_data['engine'] && current_data['engine']['url']) {
1133 document.getElementById("engineid").setAttribute("href", current_data['engine']['url']);
1135 document.getElementById("engineid").removeAttribute("href");
1138 // Credits: Engine details.
1139 if (current_data['engine'] && current_data['engine']['details']) {
1140 document.getElementById("enginedetails").textContent = " (" + current_data['engine']['details'] + ")";
1142 document.getElementById("enginedetails").textContent = "";
1145 // Credits: Move source, possibly with URL.
1146 if (current_data['move_source'] && current_data['move_source_url']) {
1147 document.getElementById("movesource").textContent = "Moves provided by ";
1148 let movesource_a = document.createElement("a");
1149 movesource_a.setAttribute("href", current_data['move_source_url']);
1150 let movesource_text = document.createTextNode(current_data['move_source']);
1151 movesource_a.appendChild(movesource_text);
1152 let movesource_period = document.createTextNode(".");
1153 document.getElementById("movesource").appendChild(movesource_a);
1154 document.getElementById("movesource").appendChild(movesource_period);
1155 } else if (current_data['move_source']) {
1156 document.getElementById("movesource").textContent = "Moves provided by " + current_data['move_source'] + ".";
1158 document.getElementById("movesource").textContent = "";
1162 if (displayed_analysis_data) {
1163 // Displaying some non-current position, pick out the last move
1164 // from the history. This will work even if the fetch failed.
1165 if (current_display_move !== -1) {
1166 last_move = format_halfmove_with_number(
1167 current_display_line.pv[current_display_move],
1168 current_display_move);
1169 headline += ' after ' + last_move;
1171 } else if (data['position']['last_move'] !== 'none') {
1172 // Find the previous move.
1173 let previous_move_num, previous_toplay;
1174 if (data['position']['toplay'] == 'B') {
1175 previous_move_num = data['position']['move_num'];
1176 previous_toplay = 'W';
1178 previous_move_num = data['position']['move_num'] - 1;
1179 previous_toplay = 'B';
1182 last_move = format_move_with_number(
1183 data['position']['last_move'],
1185 previous_toplay == 'W');
1186 headline += ' after ' + last_move;
1190 document.getElementById("headline").textContent = headline;
1192 // The <title> contains a very brief headline.
1193 let title_elems = [];
1194 if (data['position'] && data['position']['result']) {
1195 title_elems.push(data['position']['result']);
1196 } else if (data['score']) {
1197 title_elems.push(format_short_score(data['score']));
1199 if (last_move !== null) {
1200 title_elems.push(last_move);
1203 if (title_elems.length != 0) {
1204 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
1206 document.title = 'analysis.sesse.net';
1209 // The last move (shown by highlighting the from and to squares).
1210 if (data['position'] && data['position']['last_move_uci']) {
1211 highlight_from = data['position']['last_move_uci'].substr(0, 2);
1212 highlight_to = data['position']['last_move_uci'].substr(2, 2);
1213 } else if (current_display_line_is_history && current_display_line && current_display_move >= 0) {
1214 // We don't have historic analysis for this position, but we
1215 // can reconstruct what the last move was by just replaying
1217 let position = (data['position'] && data['position']['start_fen']) ? data['position']['start_fen'] : null;
1218 let hiddenboard = chess_from(position, current_display_line.pv, current_display_move);
1219 let moves = hiddenboard.history({ verbose: true });
1220 last_move = moves.pop();
1221 highlight_from = last_move.from;
1222 highlight_to = last_move.to;
1224 highlight_from = highlight_to = undefined;
1226 update_board_highlight();
1228 if (data['failed']) {
1229 document.getElementById("score").textContent = "No analysis for this move";
1230 document.getElementById("pvtitle").textContent = "PV:";
1231 document.getElementById("pv").replaceChildren();
1232 document.getElementById("searchstats").innerHTML = " ";
1233 document.getElementById("refutationlines").replaceChildren();
1234 document.getElementById("whiteclock").replaceChildren();
1235 document.getElementById("blackclock").replaceChildren();
1236 refutation_lines = [];
1237 update_refutation_lines();
1239 update_displayed_line();
1240 update_move_highlight();
1244 if (clock_timer !== null) {
1245 clearTimeout(clock_timer);
1250 if (current_display_line && !current_display_line_is_history) {
1252 if (current_display_line.scores && current_display_line.scores.length > 0) {
1253 for (let i = 0; i < current_display_line.scores.length; ++i) {
1254 if (current_display_move < current_display_line.scores[i].first_move) {
1257 score = current_display_line.scores[i].score;
1261 document.getElementById("score").textContent = format_long_score(score);
1263 document.getElementById("score").textContent = "No score for this line";
1265 } else if (data['score']) {
1266 document.getElementById("score").textContent = format_long_score(data['score']);
1269 // The search stats.
1270 if (data['searchstats']) {
1271 document.getElementById("searchstats").textContent = data['searchstats'];
1272 } else if (data['tablebase'] == 1) {
1273 document.getElementById("searchstats").textContent = "Tablebase result";
1274 } else if (data['nodes'] && data['nps'] && data['depth']) {
1275 let stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
1276 if (data['seldepth']) {
1277 stats += ' (' + data['seldepth'] + ' selective)';
1279 if (data['tbhits'] && data['tbhits'] > 0) {
1280 if (data['tbhits'] == 1) {
1281 stats += ', one Syzygy hit';
1283 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
1287 document.getElementById("searchstats").textContent = stats;
1289 document.getElementById("searchstats").textContent = "";
1292 // Update the board itself.
1293 base_fen = data['position']['fen'];
1294 update_displayed_line();
1297 document.getElementById("pvtitle").textContent = "PV:";
1299 let scores = [{ first_move: -1, score: data['score'] }];
1300 document.getElementById("pv").replaceChildren(add_pv(data['position']['fen'], data['pv'], data['position']['move_num'], data['position']['toplay'], scores, 0));
1302 // Update the PV arrow.
1304 if (data['pv'].length >= 1) {
1305 let hiddenboard = new Chess(base_fen);
1307 // draw a continuation arrow as long as it's the same piece
1309 for (let i = 0; i < data['pv'].length; i += 2) {
1310 let move = patch_move(hiddenboard.move(data['pv'][i]));
1312 if ((i >= 2 && move.from != last_to) ||
1313 interfering_arrow(move.from, move.to)) {
1316 create_arrow(move.from, move.to, '#f66', 6, 20);
1318 hiddenboard.move(data['pv'][i + 1]); // To keep continuity.
1321 let alt_moves = find_nonstupid_moves(data, 30, data['position']['toplay'] === 'B');
1322 for (let i = 1; i < alt_moves.length && i < 3; ++i) {
1323 hiddenboard = new Chess(base_fen);
1324 let move = patch_move(hiddenboard.move(alt_moves[i]));
1325 if (move !== null) {
1326 create_arrow(move.from, move.to, '#f66', 1, 10);
1331 // See if all semi-reasonable moves have only one possible response.
1332 if (data['pv'].length >= 2) {
1333 let nonstupid_moves = find_nonstupid_moves(data, 300, data['position']['toplay'] === 'B');
1334 let hiddenboard = new Chess(base_fen);
1335 hiddenboard.move(data['pv'][0]);
1336 let response = hiddenboard.move(data['pv'][1]);
1337 for (let i = 0; i < nonstupid_moves.length; ++i) {
1338 if (nonstupid_moves[i] == data['pv'][0]) {
1339 // ignore the PV move for refutation lines.
1342 if (!data['refutation_lines'] ||
1343 !data['refutation_lines'][nonstupid_moves[i]] ||
1344 !data['refutation_lines'][nonstupid_moves[i]]['pv'] ||
1345 data['refutation_lines'][nonstupid_moves[i]]['pv'].length < 2) {
1346 // Incomplete PV, abort.
1347 response = undefined;
1350 let line = data['refutation_lines'][nonstupid_moves[i]];
1351 hiddenboard = new Chess(base_fen);
1352 hiddenboard.move(line['pv'][0]);
1353 let this_response = hiddenboard.move(line['pv'][1]);
1354 if (this_response === null) {
1355 console.log("BUG: ", i);
1357 console.log(line['pv']);
1359 if (response.from !== this_response.from || response.to !== this_response.to) {
1360 // Different response depending on lines, abort.
1361 response = undefined;
1366 if (nonstupid_moves.length > 0 && response !== undefined) {
1367 create_arrow(response.from, response.to, '#66f', 6, 20);
1371 // Update the refutation lines.
1372 base_fen = data['position']['fen'];
1373 move_num = parseInt(data['position']['move_num']);
1374 toplay = data['position']['toplay'];
1375 refutation_lines = hash_refutation_lines || data['refutation_lines'];
1376 update_refutation_lines();
1378 // Update the sparkline last, since its size depends on how everything else reflowed.
1379 update_sparkline(data);
1382 function update_sparkline(data) {
1383 let scorespark = document.getElementById('scoresparkcontainer');
1384 scorespark.textContent = '';
1385 if (data && data['score_history']) {
1386 let first_move_num = undefined;
1387 for (let halfmove_num in data['score_history']) {
1388 halfmove_num = parseInt(halfmove_num);
1389 if (first_move_num === undefined || halfmove_num < first_move_num) {
1390 first_move_num = halfmove_num;
1393 if (first_move_num !== undefined) {
1394 let last_move_num = data['position']['move_num'] * 2 - 3;
1395 if (data['position']['toplay'] === 'B') {
1399 // Possibly truncate some moves if we don't have enough width.
1400 let max_moves = Math.floor(scorespark.getBoundingClientRect().width / 5) - 3;
1401 if (last_move_num - first_move_num > max_moves) {
1402 first_move_num = last_move_num - max_moves;
1407 let last_score = null;
1409 for (let halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1410 if (data['score_history'][halfmove_num]) {
1411 let score = compute_plot_score(data['score_history'][halfmove_num]);
1413 if (score < min_score) min_score = score;
1414 if (score > max_score) max_score = score;
1416 scores.push(last_score);
1418 if (data['score']) {
1419 let score = compute_plot_score(data['score']);
1421 if (score < min_score) min_score = score;
1422 if (score > max_score) max_score = score;
1424 if (max_score - min_score < 100) {
1425 if (Math.abs(max_score) >= Math.abs(min_score)) {
1426 max_score = min_score + 100;
1428 min_score = max_score - 100;
1432 const h = scorespark.getBoundingClientRect().height;
1434 let base_y = h - h * min_score / (min_score - max_score);
1435 for (let i = 0; i < scores.length; ++i) {
1436 let rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
1437 //rect.setAttributeNS(null, 'stroke', "#000000");
1438 rect.setAttributeNS(null, 'x', i * 5)
1439 rect.setAttributeNS(null, 'width', 4);
1440 let extent = scores[i] * h / (max_score - min_score);
1441 if (extent > 0 && extent < 1) {
1443 } else if (extent < 0 && extent > -1) {
1448 if (scores[i] === 0) {
1449 color = [0.5, 0.5, 0.5];
1450 rect.setAttributeNS(null, 'y', base_y);
1451 rect.setAttributeNS(null, 'height', 1);
1452 } else if (scores[i] > 0) {
1453 color = [0.2, 0.4, 0.8];
1454 rect.setAttributeNS(null, 'y', base_y - extent);
1455 rect.setAttributeNS(null, 'height', extent + 1);
1457 color = [1.0, 0.267, 0.267];
1458 rect.setAttributeNS(null, 'y', base_y);
1459 rect.setAttributeNS(null, 'height', -extent + 1);
1461 let hlcolor = [color[0], color[1], color[2]];
1462 if (scores[i] !== 0) {
1463 hlcolor[0] = Math.min(hlcolor[0] * 1.4, 1.0);
1464 hlcolor[1] = Math.min(hlcolor[1] * 1.4, 1.0);
1465 hlcolor[2] = Math.min(hlcolor[2] * 1.4, 1.0);
1467 rect.style.fill = 'rgb(' + color[0]*100.0 + '%, ' + color[1]*100.0 + '%, ' + color[2]*100.0 + '%)';
1469 // score_history contains the Nth _position_, but format_tooltip
1470 // wants to format the Nth _move_; thus the -1.
1471 const tooltip = format_tooltip(data, i + first_move_num - 1);
1472 rect.addEventListener('mouseenter', (e) => draw_hover(e, hlcolor, tooltip));
1473 rect.addEventListener('mousemove', (e) => draw_hover(e, hlcolor, tooltip));
1474 rect.addEventListener('mouseleave', (e) => hide_hover(e, color));
1475 rect.addEventListener('click', (e) => { hide_hover(e, color); show_line(0, i + first_move_num - 1) });
1476 scorespark.appendChild(rect);
1482 function draw_hover(e, color, tooltip) {
1483 e.target.style.fill = 'rgb(' + color[0]*100.0 + '%, ' + color[1]*100.0 + '%, ' + color[2]*100.0 + '%)';
1485 let hover = document.getElementById('sparklinehover');
1486 hover.textContent = tooltip;
1487 hover.style.display = 'initial';
1489 let left = Math.max(e.pageX + 10, window.pageXOffset);
1490 let top = Math.max(e.pageY - hover.getBoundingClientRect().height, window.pageYOffset);
1491 left = Math.min(left, window.pageXOffset + document.documentElement.clientWidth - hover.getBoundingClientRect().width);
1493 hover.style.left = left + 'px';
1494 hover.style.top = top + 'px';
1497 function hide_hover(e, color) {
1498 e.target.style.fill = 'rgb(' + color[0]*100.0 + '%, ' + color[1]*100.0 + '%, ' + color[2]*100.0 + '%)';
1499 document.getElementById('sparklinehover').style.display = 'none';
1503 * @param {number} num_viewers
1505 function update_num_viewers(num_viewers) {
1507 if (num_viewers === null) {
1509 } else if (num_viewers == 1) {
1510 text = "You are the only current viewer";
1512 text = num_viewers + " current viewers";
1514 if (display_fen !== null) {
1515 let counter = Math.floor(display_fen.split(" ")[4] / 2);
1516 if (counter >= 20) {
1517 text = text.replace("current ", "");
1518 text += " | 50-move rule: " + counter;
1521 document.getElementById("numviewers").textContent = text;
1524 function update_clock() {
1527 let data = displayed_analysis_data || current_analysis_data;
1530 if (data['position']) {
1531 let result = data['position']['result'];
1532 if (result === '1-0') {
1533 document.getElementById("whiteclock").textContent = "1";
1534 document.getElementById("blackclock").textContent = "0";
1535 document.getElementById("whiteclock").classList.remove("running-clock");
1536 document.getElementById("blackclock").classList.remove("running-clock");
1539 if (result === '1/2-1/2') {
1540 document.getElementById("whiteclock").textContent = "1/2";
1541 document.getElementById("blackclock").textContent = "1/2";
1542 document.getElementById("whiteclock").classList.remove("running-clock");
1543 document.getElementById("blackclock").classList.remove("running-clock");
1546 if (result === '0-1') {
1547 document.getElementById("whiteclock").textContent = "0";
1548 document.getElementById("blackclock").textContent = "1";
1549 document.getElementById("whiteclock").classList.remove("running-clock");
1550 document.getElementById("blackclock").classList.remove("running-clock");
1555 let white_clock_ms = null;
1556 let black_clock_ms = null;
1559 if (data['position'] &&
1560 data['position']['white_clock'] &&
1561 data['position']['black_clock']) {
1562 white_clock_ms = data['position']['white_clock'] * 1000;
1563 black_clock_ms = data['position']['black_clock'] * 1000;
1566 // Dynamic clock (only one, obviously).
1568 if (data['position']['white_clock_target']) {
1570 document.getElementById("whiteclock").classList.add("running-clock");
1571 document.getElementById("blackclock").classList.remove("running-clock");
1572 } else if (data['position']['black_clock_target']) {
1574 document.getElementById("whiteclock").classList.remove("running-clock");
1575 document.getElementById("blackclock").classList.add("running-clock");
1577 document.getElementById("whiteclock").classList.remove("running-clock");
1578 document.getElementById("blackclock").classList.remove("running-clock");
1582 let now = new Date().getTime() + client_clock_offset_ms;
1583 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1584 if (color === "white") {
1585 white_clock_ms = remaining_ms;
1587 black_clock_ms = remaining_ms;
1591 if (white_clock_ms === null || black_clock_ms === null) {
1592 document.getElementById("whiteclock").replaceChildren();
1593 document.getElementById("blackclock").replaceChildren();
1597 // If either player has twenty minutes or less left, add the second counters.
1598 // This matches what DGT clocks do.
1599 let show_seconds = (white_clock_ms < 60 * 20 * 1000 || black_clock_ms < 60 * 20 * 1000);
1601 if (color && remaining_ms > 0) {
1602 // See when the clock will change next, and update right after that.
1605 next_update_ms = remaining_ms % 1000 + 100;
1607 next_update_ms = remaining_ms % 60000 + 100;
1609 clock_timer = setTimeout(update_clock, next_update_ms);
1612 document.getElementById("whiteclock").textContent = format_clock(white_clock_ms, show_seconds);
1613 document.getElementById("blackclock").textContent = format_clock(black_clock_ms, show_seconds);
1617 * @param {Number} remaining_ms
1618 * @param {boolean} show_seconds
1620 function format_clock(remaining_ms, show_seconds) {
1621 if (remaining_ms <= 0) {
1629 let remaining = Math.floor(remaining_ms / 1000);
1630 let seconds = remaining % 60;
1631 remaining = (remaining - seconds) / 60;
1632 let minutes = remaining % 60;
1633 remaining = (remaining - minutes) / 60;
1634 let hours = remaining;
1636 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1638 return format_2d(hours) + ":" + format_2d(minutes);
1645 function format_2d(x) {
1654 * @param {string} move
1655 * @param {Number} move_num Move number of this move.
1656 * @param {boolean} white_to_play Whether white is to play this move.
1658 function format_move_with_number(move, move_num, white_to_play) {
1660 if (white_to_play) {
1661 ret = move_num + '. ';
1663 ret = move_num + '… ';
1670 * @param {string} move
1671 * @param {Number} halfmove_num Half-move number that is to be played,
1674 function format_halfmove_with_number(move, halfmove_num) {
1675 return format_move_with_number(
1677 Math.floor(halfmove_num / 2) + 1,
1678 halfmove_num % 2 == 0);
1682 * @param {Object} data
1683 * @param {Number} halfmove_num
1685 function format_tooltip(data, halfmove_num) {
1686 if (data['score_history'][halfmove_num + 1] ||
1687 (halfmove_num + 1) === data['position']['history'].length) {
1688 // Position is in the history, or it is the current position
1689 // (which is implicitly tacked onto the history).
1692 if ((halfmove_num + 1) === data['position']['history'].length) {
1693 move = data['position']['last_move'];
1694 short_score = format_short_score(data['score']);
1696 move = data['position']['history'][halfmove_num];
1697 short_score = format_short_score(data['score_history'][halfmove_num + 1]);
1699 if (halfmove_num === -1) {
1700 return "Start position: " + short_score;
1702 let move_with_number = format_halfmove_with_number(move, halfmove_num);
1703 return "After " + move_with_number + ": " + short_score;
1706 for (let i = halfmove_num; i --> -1; ) {
1707 if (data['score_history'][i]) {
1708 let move = data['position']['history'][i];
1710 return "[Analysis kept from start position]";
1712 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1720 * @param {boolean} truncate_history
1722 function set_truncate_history(truncate_history) {
1723 truncate_display_history = truncate_history;
1724 update_refutation_lines();
1726 window['set_truncate_history'] = set_truncate_history;
1729 * @param {number} line_num
1730 * @param {number} move_num
1732 function show_line(line_num, move_num) {
1733 if (line_num == -1) {
1734 current_display_line = null;
1735 current_display_move = null;
1736 hash_refutation_lines = null;
1737 if (displayed_analysis_data) {
1738 // TODO: Support exiting to history position if we are in an
1739 // analysis line of a history position.
1740 displayed_analysis_data = null;
1745 current_display_line = {...display_lines[line_num]}; // Shallow clone.
1746 current_display_move = move_num + current_display_line.start_display_move_num;
1748 current_display_line_is_history = (line_num == 0);
1750 update_historic_analysis();
1751 update_displayed_line();
1752 update_board_highlight();
1753 update_move_highlight();
1756 window['show_line'] = show_line;
1758 function prev_move() {
1759 if (current_display_line &&
1760 current_display_move >= current_display_line.start_display_move_num) {
1761 --current_display_move;
1763 update_historic_analysis();
1764 update_displayed_line();
1765 update_move_highlight();
1767 window['prev_move'] = prev_move;
1769 function next_move() {
1770 if (current_display_line &&
1771 current_display_move < current_display_line.pv.length - 1) {
1772 ++current_display_move;
1774 update_historic_analysis();
1775 update_displayed_line();
1776 update_move_highlight();
1778 window['next_move'] = next_move;
1780 function next_game() {
1781 if (current_games === null) {
1785 // Try to find the game we are currently looking at.
1786 for (let game_num = 0; game_num < current_games.length; ++game_num) {
1787 let game = current_games[game_num];
1788 if (game['url'] === backend_url) {
1789 let next_game_num = (game_num + 1) % current_games.length;
1790 switch_backend(current_games[next_game_num]);
1795 // Couldn't find it; give up.
1798 function update_historic_analysis() {
1799 if (!current_display_line_is_history) {
1802 if (current_display_move == current_display_line.pv.length - 1) {
1803 displayed_analysis_data = null;
1807 // Fetch old analysis for this line if it exists.
1808 let hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pv, current_display_move);
1809 let filename = "/history/move" + (current_display_move + 1) + "-" +
1810 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1812 let handle_err = () => {
1813 displayed_analysis_data = {'failed': true};
1817 current_historic_xhr = new AbortController();
1818 const signal = current_analysis_xhr.signal;
1819 fetch(filename, { signal })
1820 .then((response) => response.json().then(data => ({ok: response.ok, json: data}))) // ick
1826 displayed_analysis_data = obj.json;
1830 if (err.name === 'AbortError') {
1831 // Aborted because we are switching backends. Abandon and don't retry,
1832 // because another one is already started for us.
1841 * @param {string} fen
1843 function update_imbalance(fen) {
1844 let imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1845 for (const c of fen) {
1850 if (c != c.toUpperCase()) {
1852 } else if (c != c.toLowerCase()) {
1853 ++imbalance[c.toLowerCase()];
1857 let white_imbalance = document.getElementById('whiteimbalance');
1858 let black_imbalance = document.getElementById('blackimbalance');
1859 white_imbalance.textContent = '';
1860 black_imbalance.textContent = '';
1861 for (let piece in imbalance) {
1862 for (let i = 0; i < imbalance[piece]; ++i) {
1863 let i1 = document.createElement('img');
1864 i1.src = svg_pieces['w' + piece.toUpperCase()];
1865 i1.setAttribute('alt', piece.toUpperCase());
1866 i1.classList.add('imbalance-piece');
1867 white_imbalance.appendChild(i1);
1869 let i2 = document.createElement('img');
1870 i2.src = svg_pieces['b' + piece.toUpperCase()];
1871 i2.setAttribute('alt', piece.toUpperCase());
1872 i2.classList.add('imbalance-inverted-piece');
1873 white_imbalance.appendChild(i2);
1875 for (let i = 0; i < -imbalance[piece]; ++i) {
1876 let i1 = document.createElement('img');
1877 i1.src = svg_pieces['b' + piece.toUpperCase()];
1878 i1.setAttribute('alt', piece.toUpperCase());
1879 i1.classList.add('imbalance-piece');
1880 black_imbalance.appendChild(i1);
1882 let i2 = document.createElement('img');
1883 i2.src = svg_pieces['w' + piece.toUpperCase()];
1884 i2.setAttribute('alt', piece.toUpperCase());
1885 i2.classList.add('imbalance-inverted-piece');
1886 black_imbalance.appendChild(i2);
1891 /** Mark the currently selected move in red.
1892 * Also replaces the PV with the current displayed line if it's not shown
1893 * anywhere else on the screen.
1895 function update_move_highlight() {
1896 if (highlighted_move !== null) {
1897 highlighted_move.classList.remove('highlight');
1899 if (current_display_line) {
1900 let display_line_num = find_display_line_matching_num();
1901 if (display_line_num === null) {
1902 // Replace the PV with the (complete) line.
1903 document.getElementById("pvtitle").textContent = "Exploring:";
1904 current_display_line.start_display_move_num = 0;
1905 display_lines.push(current_display_line);
1906 document.getElementById("pv").append(print_pv(display_lines.length - 1, null)); // FIXME
1907 display_line_num = display_lines.length - 1;
1909 // Clear out the PV, so it's not selected by anything later.
1910 display_lines[1].pv = [];
1913 highlighted_move = document.getElementById("automove" + display_line_num + "-" + (current_display_move - current_display_line.start_display_move_num));
1914 if (highlighted_move !== null) {
1915 highlighted_move.classList.add('highlight');
1921 * See if the current displayed line is identical to any of the ones
1922 * we have on screen. (It might not be if e.g. the analysis reloaded
1923 * since we started looking.)
1927 function find_display_line_matching_num() {
1928 for (let i = 0; i < display_lines.length; ++i) {
1929 let line = display_lines[i];
1930 if (line.start_display_move_num > 0) continue;
1931 if (current_display_line.start_fen !== line.start_fen) continue;
1932 if (current_display_line.pv.length !== line.pv.length) continue;
1934 for (let j = 0; j < line.pv.length; ++j) {
1935 if (current_display_line.pv[j] !== line.pv[j]) {
1947 /** Update the board based on the currently displayed line.
1949 * TODO: This should really be called only whenever something changes,
1950 * instead of all the time.
1952 function update_displayed_line() {
1953 if (current_display_line === null) {
1954 document.getElementById("linenav").style.display = 'none';
1955 document.getElementById("linemsg").style.display = 'revert';
1956 display_fen = base_fen;
1957 set_board_position(base_fen);
1958 update_imbalance(base_fen);
1962 document.getElementById("linenav").style.display = 'revert';
1963 document.getElementById("linemsg").style.display = 'none';
1965 if (current_display_move <= 0) {
1966 document.getElementById("prevmove").textContent = "Previous";
1968 document.getElementById("prevmove").innerHTML = "<a href=\"javascript:prev_move();\">Previous</a></span>";
1970 if (current_display_move == current_display_line.pv.length - 1) {
1971 document.getElementById("nextmove").textContent = "Next";
1973 document.getElementById("nextmove").innerHTML = "<a href=\"javascript:next_move();\">Next</a></span>";
1976 let hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pv, current_display_move);
1977 set_board_position(hiddenboard.fen());
1978 if (display_fen !== hiddenboard.fen() && !current_display_line_is_history) {
1979 // Fire off a hash request, since we're now off the main position
1980 // and it just changed.
1981 explore_hash(hiddenboard.fen());
1983 display_fen = hiddenboard.fen();
1984 update_imbalance(hiddenboard.fen());
1987 function set_board_position(new_fen) {
1988 board_is_animating = true;
1989 let old_fen = board.fen();
1990 board.position(new_fen);
1991 if (board.fen() === old_fen) {
1992 board_is_animating = false;
1997 * @param {boolean} param_enable_sound
1999 function set_sound(param_enable_sound) {
2000 enable_sound = param_enable_sound;
2002 document.getElementById("soundon").innerHTML = "<strong>On</strong>";
2003 document.getElementById("soundoff").innerHTML = "<a href=\"javascript:set_sound(false)\">Off</a>";
2005 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
2006 // and also preload the file since the user has selected audio.
2007 let ding = document.getElementById('ding');
2008 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
2009 ding.src = 'ding.opus';
2013 document.getElementById("soundon").innerHTML = "<a href=\"javascript:set_sound(true)\">On</a>";
2014 document.getElementById("soundoff").innerHTML = "<strong>Off</strong>";
2016 if (supports_html5_storage()) {
2017 window['localStorage']['enable_sound'] = enable_sound ? 1 : 0;
2020 window['set_sound'] = set_sound;
2022 /** Send off a hash probe request to the backend.
2023 * @param {string} fen
2025 function explore_hash(fen) {
2026 // If we already have a backend response going, abort it.
2027 if (current_hash_xhr) {
2028 current_hash_xhr.abort();
2030 if (current_hash_display_timer) {
2031 clearTimeout(current_hash_display_timer);
2032 current_hash_display_timer = null;
2034 document.getElementById("refutationlines").replaceChildren();
2036 current_hash_xhr = new AbortController();
2037 const signal = current_analysis_xhr.signal;
2038 fetch(backend_hash_url + "?fen=" + fen, { signal })
2039 .then((response) => response.json())
2040 .then((data) => { show_explore_hash_results(data, fen); })
2042 // Truncate the lines, since we already cleared the display.
2043 display_lines = [ display_lines[0], display_lines[1] ];
2044 update_move_highlight();
2048 /** Process the JSON response from a hash probe request.
2049 * @param {!Object} data
2050 * @param {string} fen
2052 function show_explore_hash_results(data, fen) {
2053 if (board_is_animating) {
2054 // Updating while the animation is still going causes
2055 // the animation to jerk. This is pretty crude, but it will do.
2056 current_hash_display_timer = setTimeout(function() { show_explore_hash_results(data, fen); }, 100);
2059 current_hash_display_timer = null;
2060 hash_refutation_lines = data['lines'];
2064 // almost all of this stuff comes from the chessboard.js example page
2065 function onDragStart(source, piece, position, orientation) {
2066 let pseudogame = new Chess(display_fen);
2067 if (pseudogame.game_over() === true ||
2068 (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
2069 (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
2073 recommended_move = get_best_move(pseudogame, source, null, pseudogame.turn() === 'b');
2074 if (recommended_move) {
2075 let squareEl = document.querySelector('#board .square-' + recommended_move.to);
2076 squareEl.classList.add('highlight1-32417');
2081 function mousedownSquare(e) {
2082 if (!e.target || !e.target.getAttribute('data-square')) {
2086 reverse_dragging_from = null;
2087 let square = e.target.getAttribute('data-square');
2089 let pseudogame = new Chess(display_fen);
2090 if (pseudogame.game_over() === true) {
2094 // If the square is empty, or has a piece of the side not to move,
2095 // we handle it. If not, normal piece dragging will take it.
2096 let position = board.position();
2097 if (!position.hasOwnProperty(square) ||
2098 (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
2099 (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
2100 reverse_dragging_from = square;
2101 recommended_move = get_best_move(pseudogame, null, square, pseudogame.turn() === 'b');
2102 if (recommended_move) {
2103 let squareEl = document.querySelector('#board .square-' + recommended_move.from);
2104 squareEl.classList.add('highlight1-32417');
2105 squareEl = document.querySelector('#board .square-' + recommended_move.to);
2106 squareEl.classList.add('highlight1-32417');
2111 function mouseupSquare(e) {
2112 if (!e.target || !e.target.getAttribute('data-square')) {
2115 if (reverse_dragging_from === null) {
2118 let source = e.target.getAttribute('data-square');
2119 let target = reverse_dragging_from;
2120 reverse_dragging_from = null;
2121 if (onDrop(source, target) !== 'snapback') {
2122 onSnapEnd(source, target);
2124 document.getElementById("board").querySelectorAll('.square-55d63.highlight1-32417').forEach((square) => {
2125 square.classList.remove('highlight1-32417');
2129 function get_best_move(game, source, target, invert) {
2130 let moves = game.moves({ verbose: true });
2131 if (source !== null) {
2132 moves = moves.filter(function(move) { return move.from == source; });
2134 if (target !== null) {
2135 moves = moves.filter(function(move) { return move.to == target; });
2137 if (moves.length == 0) {
2140 if (moves.length == 1) {
2144 // More than one move. Use the display lines (if we have them)
2145 // to disambiguate; otherwise, we have no information.
2147 for (let i = 0; i < moves.length; ++i) {
2148 move_hash[moves[i].san] = moves[i];
2151 // See if we're already exploring some line.
2152 if (current_display_line &&
2153 current_display_move < current_display_line.pv.length - 1) {
2154 let first_move = current_display_line.pv[current_display_move + 1];
2155 if (move_hash[first_move]) {
2156 return move_hash[first_move];
2160 // History and PV take priority over the display lines.
2161 for (let i = 0; i < 2; ++i) {
2162 let line = display_lines[i];
2163 let first_move = line.pv[line.start_display_move_num];
2164 if (move_hash[first_move]) {
2165 return move_hash[first_move];
2169 let best_move = null;
2170 let best_move_score = null;
2172 for (let move in refutation_lines) {
2173 let line = refutation_lines[move];
2174 if (!line['score']) {
2177 let first_move = line['pv'][0];
2178 if (move_hash[first_move]) {
2179 let score = compute_score_sort_key(line['score'], line['depth'], invert);
2180 if (best_move_score === null || score > best_move_score) {
2181 best_move = move_hash[first_move];
2182 best_move_score = score;
2189 function onDrop(source, target) {
2190 if (source === target) {
2191 if (recommended_move === null) {
2194 // Accept the move. It will be changed in onSnapEnd.
2198 // Suggestion not asked for.
2199 recommended_move = null;
2202 // see if the move is legal
2203 let pseudogame = new Chess(display_fen);
2204 let move = pseudogame.move({
2207 promotion: 'q' // NOTE: always promote to a queen for example simplicity
2211 if (move === null) return 'snapback';
2214 function onSnapEnd(source, target) {
2215 if (source === target && recommended_move !== null) {
2216 source = recommended_move.from;
2217 target = recommended_move.to;
2219 recommended_move = null;
2220 let pseudogame = new Chess(display_fen);
2221 let move = pseudogame.move({
2224 promotion: 'q' // NOTE: always promote to a queen for example simplicity
2227 // Move ahead on the line we're on -- this includes history if we've
2229 if (current_display_line &&
2230 current_display_move < current_display_line.pv.length - 1 &&
2231 current_display_line.pv[current_display_move + 1] === move.san) {
2236 // Walk down the displayed lines until we find one that starts with
2237 // this move, then select that. Note that this gives us a good priority
2238 // order (PV, then multi-PV lines; history was already dealt with above,
2239 // as it's the only line that originates backwards).
2240 for (let i = 1; i < display_lines.length; ++i) {
2241 if (i == 1 && current_display_line) {
2242 // Do not choose PV if not on it.
2245 let line = display_lines[i];
2246 if (line.pv[line.start_display_move_num] === move.san) {
2252 // Shouldn't really be here if we have hash probes, but there's really
2253 // nothing we can do.
2254 // FIXME: Just make a new line, probably (even if we don't have hash moves).
2255 // As it is, we can actually drag (but not click) such a move in the UI,
2256 // but it has no effect on what we're probing.
2258 // End of dragging-related code.
2260 function fmt_cp(v) {
2264 return "+" + (v / 100).toFixed(2);
2267 return "-" + (v / 100).toFixed(2);
2271 function format_short_score(score) {
2275 if (score[0] === 'T' || score[0] === 't') {
2276 let ret = "TB\u00a0";
2277 if (score[2]) { // Is a bound.
2278 ret = score[2] + "\u00a0TB\u00a0";
2280 if (score[0] === 'T') {
2281 return ret + Math.ceil(score[1] / 2);
2283 return ret + "-" + Math.ceil(score[1] / 2);
2285 } else if (score[0] === 'M' || score[0] === 'm') {
2286 let sign = (score[0] === 'm') ? '-' : '';
2287 if (score[2]) { // Is a bound.
2288 return score[2] + "\u00a0M " + sign + score[1];
2290 return "M " + sign + score[1];
2292 } else if (score[0] === 'd') {
2294 } else if (score[0] === 'cp') {
2295 if (score[2]) { // Is a bound.
2296 return score[2] + "\u00a0" + fmt_cp(score[1]);
2298 return fmt_cp(score[1]);
2304 function format_long_score(score) {
2308 if (score[0] === 'T') {
2309 if (score[1] == 0) {
2310 return "Won for white (tablebase)";
2312 return "White wins in " + Math.ceil(score[1] / 2);
2314 } else if (score[0] === 't') {
2315 if (score[1] == -1) {
2316 return "Won for black (tablebase)";
2318 return "Black wins in " + Math.ceil(score[1] / 2);
2320 } else if (score[0] === 'M') {
2321 if (score[1] == 0) {
2322 return "White wins by checkmate";
2324 return "White mates in " + score[1];
2326 } else if (score[0] === 'm') {
2327 if (score[1] == 0) {
2328 return "Black wins by checkmate";
2330 return "Black mates in " + score[1];
2332 } else if (score[0] === 'd') {
2333 return "Theoretical draw";
2334 } else if (score[0] === 'cp') {
2335 return "Score: " + format_short_score(score);
2340 function compute_plot_score(score) {
2341 if (score[0] === 'M' || score[0] === 'T') {
2343 } else if (score[0] === 'm' || score[0] === 't') {
2345 } else if (score[0] === 'd') {
2347 } else if (score[0] === 'cp') {
2348 if (score[1] > 500) {
2350 } else if (score[1] < -500) {
2360 * @param score The score digest tuple.
2361 * @param {?number} depth Depth the move has been computed to, or null.
2362 * @param {boolean} invert Whether black is to play.
2365 function compute_score_sort_key(score, depth, invert) {
2370 if (score[0] === 'T') {
2371 // White reaches TB win.
2372 s = 89999 - score[1];
2373 } else if (score[0] === 't') {
2374 // Black reaches TB win.
2375 s = -(89999 - score[1]);
2376 } else if (score[0] === 'M') {
2378 s = 99999 - score[1];
2379 } else if (score[0] === 'm') {
2381 s = -(99999 - score[1]);
2382 } else if (score[0] === 'd') {
2384 } else if (score[0] === 'cp') {
2396 * @param {Object} game
2398 function switch_backend(game) {
2399 // Stop looking at historic data.
2400 current_display_line = null;
2401 current_display_move = null;
2402 displayed_analysis_data = null;
2403 if (current_historic_xhr) {
2404 current_historic_xhr.abort();
2407 // If we already have a backend response going, abort it.
2408 if (current_analysis_xhr) {
2409 current_analysis_xhr.abort();
2411 if (current_hash_xhr) {
2412 current_hash_xhr.abort();
2415 // Otherwise, we should have a timer going to start a new one.
2417 if (current_analysis_request_timer) {
2418 clearTimeout(current_analysis_request_timer);
2419 current_analysis_request_timer = null;
2421 if (current_hash_display_timer) {
2422 clearTimeout(current_hash_display_timer);
2423 current_hash_display_timer = null;
2426 // Request an immediate fetch with the new backend.
2427 backend_url = game['url'];
2428 backend_hash_url = game['hashurl'];
2429 window.location.hash = '#' + game['id'];
2430 current_analysis_data = null;
2434 window['switch_backend'] = switch_backend;
2436 window['flip'] = function() { board.flip(); redraw_arrows(); };
2437 window['set_delay_ms'] = function(ms) { delay_ms = ms; console.log('Delay is now ' + ms + ' ms.'); };
2439 // Mostly from Wikipedia's chess set as of October 2022, but some pieces are from
2440 // the 2013 version, as I like those better (and it matches the 2014 PNGs; nobody
2441 // really likes change, do they?). That is wK, bK, bQ. wQ is also slightly different,
2442 // but not enough to notice.
2443 const svg_pieces = {
2444 '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>',
2445 '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>',
2446 '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>',
2447 '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>',
2448 '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>',
2449 '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>',
2450 '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>',
2451 '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>',
2452 '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>',
2453 '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>',
2454 '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>',
2455 '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>',
2458 function svg_piece_theme(piece) {
2459 return svg_pieces[piece];
2463 unique = get_unique();
2465 // Load settings from HTML5 local storage if available.
2466 if (supports_html5_storage() && window['localStorage']['enable_sound']) {
2467 set_sound(parseInt(window['localStorage']['enable_sound']));
2473 board = new window.ChessBoard('board', {
2474 onMoveEnd: function() { board_is_animating = false; },
2477 pieceTheme: svg_piece_theme,
2478 onDragStart: onDragStart,
2480 onSnapEnd: onSnapEnd
2482 document.getElementById("board").addEventListener('mousedown', mousedownSquare);
2483 document.getElementById("board").addEventListener('mouseup', mouseupSquare);
2486 window.addEventListener('resize', function() {
2488 update_sparkline(displayed_analysis_data || current_analysis_data);
2489 update_board_highlight();
2492 new ResizeObserver(() => update_sparkline(displayed_analysis_data || current_analysis_data)).observe(document.getElementById('scoresparkcontainer'));
2493 window.addEventListener('keyup', function(event) {
2494 if (event.which == 39) { // Left arrow.
2496 } else if (event.which == 37) { // Right arrow.
2498 } else if (event.which >= 49 && event.which <= 57) { // 1-9.
2499 let num = event.which - 49;
2500 if (current_games && current_games.length >= num) {
2501 switch_backend(current_games[num]);
2503 } else if (event.which == 78) { // N.
2507 window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
2508 possibly_switch_game_from_hash();
2510 document.addEventListener('DOMContentLoaded', init);