4 * Version of this script. If the server returns a version larger than
5 * this, it is a sign we should reload to upgrade ourselves.
10 var SCRIPT_VERSION = 2016032202;
13 * The current backend URL.
18 var backend_url = "/analysis.pl";
19 var backend_hash_url = "/hash";
21 /** @type {window.ChessBoard} @private */
24 /** @type {boolean} @private */
25 var board_is_animating = false;
28 * The most recent analysis data we have from the server
29 * (about the most recent position).
33 var current_analysis_data = null;
36 * If we are displaying previous analysis or from hash, this is non-null,
37 * and will override most of current_analysis_data.
42 var displayed_analysis_data = null;
45 * Games currently in progress, if any.
57 var current_games = null;
72 /** @type {Array.<Array.<boolean>>} */
73 var occupied_by_arrows = [];
75 /** Currently displayed refutation lines (on-screen).
76 * Can either come from the current_analysis_data, displayed_analysis_data,
77 * or hash_refutation_lines.
79 var refutation_lines = [];
81 /** Refutation lines from current hash probe.
83 * If non-null, will override refutation lines from the base position.
84 * Note that these are relative to display_fen, not base_fen.
86 var hash_refutation_lines = null;
88 /** @type {!number} @private */
91 /** @type {!string} @private */
94 /** @type {number} @private */
97 /** @type {boolean} @private */
98 var sort_refutation_lines_by_score = true;
100 /** @type {boolean} @private */
101 var truncate_display_history = true;
103 /** @type {!string|undefined} @private */
104 var highlight_from = undefined;
106 /** @type {!string|undefined} @private */
107 var highlight_to = undefined;
109 /** The HTML object of the move currently being highlighted (in red).
112 var highlighted_move = null;
114 /** Currently suggested/recommended move when dragging.
115 * @type {?{from: !string, to: !string}}
118 var recommended_move = null;
120 /** If reverse-dragging (dragging from the destination square to the
121 * source square), the destination square.
125 var reverse_dragging_from = null;
127 /** @type {?number} @private */
130 /** @type {boolean} @private */
131 var enable_sound = false;
134 * Our best estimate of how many milliseconds we need to add to
135 * new Date() to get the true UTC time. Calibrated against the
141 var client_clock_offset_ms = null;
143 var clock_timer = null;
145 /** The current position being analyzed, represented as a FEN string.
146 * Note that this is not necessarily the same as display_fen.
152 /** The current position on the board, represented as a FEN string.
153 * Note that board.fen() does not contain e.g. who is to play.
157 var display_fen = null;
161 * pv: Array.<string>,
164 * scores: Array<{first_move: number, score: Object}>,
165 * start_display_move_num: number
168 * "start_display_move_num" is the (half-)move number to start displaying the PV at.
169 * "score" is also evaluated at this point.
172 /** All PVs that we currently know of.
174 * Element 0 is history (or null if no history).
175 * Element 1 is current main PV, or explored line if nowhere else on the screen.
176 * All remaining elements are refutation lines (multi-PV).
178 * @type {Array.<DisplayLine>}
181 var display_lines = [];
183 /** @type {?DisplayLine} @private */
184 var current_display_line = null;
186 /** @type {boolean} @private */
187 var current_display_line_is_history = false;
189 /** @type {?number} @private */
190 var current_display_move = null;
193 * The current backend request to get main analysis (not history), if any,
194 * so that we can abort it.
199 var current_analysis_xhr = null;
202 * The current timer to fire off a request to get main analysis (not history),
203 * if any, so that we can abort it.
208 var current_analysis_request_timer = null;
211 * The current backend request to get historic data, if any.
216 var current_historic_xhr = null;
219 * The current backend request to get hash probes, if any, so that we can abort it.
224 var current_hash_xhr = null;
227 * The current timer to display hash probe information (it could be waiting on the
228 * board to stop animating), if any, so that we can abort it.
233 var current_hash_display_timer = null;
235 var supports_html5_storage = function() {
237 return 'localStorage' in window && window['localStorage'] !== null;
243 // Make the unique token persistent so people refreshing the page won't count twice.
244 // Of course, you can never fully protect against people deliberately wanting to spam.
245 var get_unique = function() {
246 var use_local_storage = supports_html5_storage();
247 if (use_local_storage && localStorage['unique']) {
248 return localStorage['unique'];
250 var unique = Math.random();
251 if (use_local_storage) {
252 localStorage['unique'] = unique;
257 var request_update = function() {
258 current_analysis_request_timer = null;
260 current_analysis_xhr = $.ajax({
261 url: backend_url + "?ims=" + ims + "&unique=" + unique
262 }).done(function(data, textstatus, xhr) {
263 sync_server_clock(xhr.getResponseHeader('Date'));
264 ims = xhr.getResponseHeader('X-RGLM');
265 var num_viewers = xhr.getResponseHeader('X-RGNV');
267 if (Array.isArray(data)) {
268 new_data = JSON.parse(JSON.stringify(current_analysis_data));
269 JSON_delta.patch(new_data, data);
274 var minimum_version = xhr.getResponseHeader('X-RGMV');
275 if (minimum_version && minimum_version > SCRIPT_VERSION) {
276 // Upgrade to latest version with a force-reload.
277 location.reload(true);
280 possibly_play_sound(current_analysis_data, new_data);
281 current_analysis_data = new_data;
283 update_num_viewers(num_viewers);
286 current_analysis_request_timer = setTimeout(function() { request_update(); }, 100);
287 }).fail(function(jqXHR, textStatus, errorThrown) {
288 if (textStatus === "abort") {
289 // Aborted because we are switching backends. Abandon and don't retry,
290 // because another one is already started for us.
292 // Backend error or similar. Wait ten seconds, then try again.
293 current_analysis_request_timer = setTimeout(function() { request_update(); }, 10000);
298 var possibly_play_sound = function(old_data, new_data) {
302 if (old_data === null) {
305 var ding = document.getElementById('ding');
306 if (ding && ding.play) {
307 if (old_data['position'] && old_data['position']['fen'] &&
308 new_data['position'] && new_data['position']['fen'] &&
309 (old_data['position']['fen'] !== new_data['position']['fen'] ||
310 old_data['position']['move_num'] !== new_data['position']['move_num'])) {
317 * @type {!string} server_date_string
319 var sync_server_clock = function(server_date_string) {
320 var server_time_ms = new Date(server_date_string).getTime();
321 var client_time_ms = new Date().getTime();
322 var estimated_offset_ms = server_time_ms - client_time_ms;
324 // In order not to let the noise move us too much back and forth
325 // (the server only has one-second resolution anyway), we only
326 // change an existing skew if we are at least five seconds off.
327 if (client_clock_offset_ms === null ||
328 Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
329 client_clock_offset_ms = estimated_offset_ms;
333 var clear_arrows = function() {
334 for (var i = 0; i < arrows.length; ++i) {
336 if (arrows[i].svg.parentElement) {
337 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
339 delete arrows[i].svg;
344 occupied_by_arrows = [];
345 for (var y = 0; y < 8; ++y) {
346 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
350 var redraw_arrows = function() {
351 for (var i = 0; i < arrows.length; ++i) {
352 position_arrow(arrows[i]);
356 /** @param {!number} x
359 var sign = function(x) {
369 /** See if drawing this arrow on the board would cause unduly amount of confusion.
370 * @param {!string} from The square the arrow is from (e.g. e4).
371 * @param {!string} to The square the arrow is to (e.g. e4).
374 var interfering_arrow = function(from, to) {
375 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
376 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
377 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
378 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
380 occupied_by_arrows[from_row][from_col] = true;
382 // Knight move: Just check that we haven't been at the destination before.
383 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
384 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
385 return occupied_by_arrows[to_row][to_col];
388 // Sliding piece: Check if anything except the from-square is seen before.
389 var dx = sign(to_col - from_col);
390 var dy = sign(to_row - from_row);
396 if (occupied_by_arrows[y][x]) {
399 occupied_by_arrows[y][x] = true;
400 } while (x != to_col || y != to_row);
405 /** Find a point along the coordinate system given by the given line,
406 * <t> units forward from the start of the line, <u> units to the right of it.
407 * @param {!number} x1
408 * @param {!number} x2
409 * @param {!number} y1
410 * @param {!number} y2
413 * @return {!string} The point in "x y" form, suitable for SVG paths.
415 var point_from_start = function(x1, y1, x2, y2, t, u) {
419 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
423 var x = x1 + dx * t + dy * u;
424 var y = y1 + dy * t - dx * u;
428 /** Find a point along the coordinate system given by the given line,
429 * <t> units forward from the end of the line, <u> units to the right of it.
430 * @param {!number} x1
431 * @param {!number} x2
432 * @param {!number} y1
433 * @param {!number} y2
436 * @return {!string} The point in "x y" form, suitable for SVG paths.
438 var point_from_end = function(x1, y1, x2, y2, t, u) {
442 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
446 var x = x2 + dx * t + dy * u;
447 var y = y2 + dy * t - dx * u;
451 var position_arrow = function(arrow) {
453 if (arrow.svg.parentElement) {
454 arrow.svg.parentElement.removeChild(arrow.svg);
458 if (current_display_line !== null && !current_display_line_is_history) {
462 var pos = $(".square-a8").position();
464 var zoom_factor = $("#board").width() / 400.0;
465 var line_width = arrow.line_width * zoom_factor;
466 var arrow_size = arrow.arrow_size * zoom_factor;
468 var square_width = $(".square-a8").width();
469 var from_y = (7 - arrow.from_row + 0.5)*square_width;
470 var to_y = (7 - arrow.to_row + 0.5)*square_width;
471 var from_x = (arrow.from_col + 0.5)*square_width;
472 var to_x = (arrow.to_col + 0.5)*square_width;
474 var SVG_NS = "http://www.w3.org/2000/svg";
475 var XHTML_NS = "http://www.w3.org/1999/xhtml";
476 var svg = document.createElementNS(SVG_NS, "svg");
477 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
478 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
479 svg.setAttribute("style", "position: absolute");
480 svg.setAttribute("position", "absolute");
481 svg.setAttribute("version", "1.1");
482 svg.setAttribute("class", "c1");
483 svg.setAttribute("xmlns", XHTML_NS);
491 var outline = document.createElementNS(SVG_NS, "path");
492 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));
493 outline.setAttribute("xmlns", XHTML_NS);
494 outline.setAttribute("stroke", "#666");
495 outline.setAttribute("stroke-width", line_width + 2);
496 outline.setAttribute("fill", "none");
497 svg.appendChild(outline);
499 var path = document.createElementNS(SVG_NS, "path");
500 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));
501 path.setAttribute("xmlns", XHTML_NS);
502 path.setAttribute("stroke", arrow.fg_color);
503 path.setAttribute("stroke-width", line_width);
504 path.setAttribute("fill", "none");
505 svg.appendChild(path);
507 // Then the arrow head.
508 var head = document.createElementNS(SVG_NS, "path");
509 head.setAttribute("d",
510 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
511 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
512 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
513 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
514 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
515 head.setAttribute("xmlns", XHTML_NS);
516 head.setAttribute("stroke", "#000");
517 head.setAttribute("stroke-width", "1");
518 head.setAttribute("fill", arrow.fg_color);
519 svg.appendChild(head);
521 $(svg).css({ top: pos.top, left: pos.left, 'pointer-events': 'none' });
522 document.body.appendChild(svg);
527 * @param {!string} from_square
528 * @param {!string} to_square
529 * @param {!string} fg_color
530 * @param {number} line_width
531 * @param {number} arrow_size
533 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
534 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
535 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
536 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
537 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
545 line_width: line_width,
546 arrow_size: arrow_size,
550 position_arrow(arrow);
554 // Note: invert is ignored.
555 var compare_by_name = function(refutation_lines, invert, a, b) {
556 var ska = refutation_lines[a]['move'];
557 var skb = refutation_lines[b]['move'];
558 if (ska < skb) return -1;
559 if (ska > skb) return 1;
563 var compare_by_score = function(refutation_lines, invert, a, b) {
564 var sa = compute_score_sort_key(refutation_lines[b]['score'], refutation_lines[b]['depth'], invert);
565 var sb = compute_score_sort_key(refutation_lines[a]['score'], refutation_lines[a]['depth'], invert);
570 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
571 * sorted by quality, descending.
573 * @param {!Object} data
574 * @param {number} margin The maximum number of centipawns worse than the
575 * best move can be and still be included.
576 * @param {boolean} invert Whether black is to play.
577 * @return {Array.<string>} The FEN representation (e.g. Ne4) of all
578 * moves, in score order.
580 var find_nonstupid_moves = function(data, margin, invert) {
581 // First of all, if there are any moves that are more than 0.5 ahead of
582 // the primary move, the refutation lines are probably bunk, so just
584 var best_score = undefined;
585 var pv_score = undefined;
586 for (var move in data['refutation_lines']) {
587 var line = data['refutation_lines'][move];
588 var score = compute_score_sort_key(line['score'], line['depth'], invert, false);
589 if (move == data['pv'][0]) {
592 if (best_score === undefined || score > best_score) {
595 if (line['depth'] < 8) {
600 if (best_score - pv_score > 50) {
604 // Now find all moves that are within “margin” of the best score.
605 // The PV move will always be first.
607 for (var move in data['refutation_lines']) {
608 var line = data['refutation_lines'][move];
609 var score = compute_score_sort_key(line['score'], line['depth'], invert);
610 if (move != data['pv'][0] && best_score - score <= margin) {
614 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], data['position']['toplay'] === 'B', a, b) });
615 moves.unshift(data['pv'][0]);
624 var thousands = function(x) {
625 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
629 * @param {!string} start_fen
630 * @param {Array.<string>} pv
631 * @param {number} move_num
632 * @param {!string} toplay
633 * @param {Array<{ first_move: integer, score: Object }>} scores
634 * @param {number} start_display_move_num
635 * @param {number=} opt_limit
636 * @param {boolean=} opt_showlast
638 var add_pv = function(start_fen, pv, move_num, toplay, scores, start_display_move_num, opt_limit, opt_showlast) {
640 start_fen: start_fen,
642 move_num: parseInt(move_num),
645 start_display_move_num: start_display_move_num
647 return print_pv(display_lines.length - 1, opt_limit, opt_showlast);
651 * @param {number} line_num
652 * @param {number=} opt_limit If set, show at most this number of moves.
653 * @param {boolean=} opt_showlast If limit is set, show the last moves instead of the first ones.
655 var print_pv = function(line_num, opt_limit, opt_showlast) {
656 var display_line = display_lines[line_num];
657 var pv = display_line.pv;
658 var move_num = display_line.move_num;
659 var toplay = display_line.toplay;
661 // Truncate PV at the start if needed.
662 var start_display_move_num = display_line.start_display_move_num;
663 if (start_display_move_num > 0) {
664 pv = pv.slice(start_display_move_num);
665 var to_add = start_display_move_num;
666 if (toplay === 'B') {
671 if (to_add % 2 == 1) {
675 move_num += to_add / 2;
680 if (opt_limit && opt_showlast && pv.length > opt_limit) {
681 // Truncate the PV at the beginning (instead of at the end).
682 // We assume here that toplay is 'W'. We also assume that if
683 // opt_showlast is set, then it is the history, and thus,
684 // the UI should be to expand the history.
685 ret = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
686 i = pv.length - opt_limit;
691 } else if (toplay == 'B' && pv.length > 0) {
692 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pv[0] + "</a>";
693 ret = move_num + '. … ' + move;
698 for ( ; i < pv.length; ++i) {
699 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pv[i] + "</a>";
702 if (i > opt_limit && !opt_showlast) {
708 ret += move_num + '. ' + move;
719 /** Update the highlighted to/from squares on the board.
720 * Based on the global "highlight_from" and "highlight_to" variables.
722 var update_board_highlight = function() {
723 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
724 if ((current_display_line === null || current_display_line_is_history) &&
725 highlight_from !== undefined && highlight_to !== undefined) {
726 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
727 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
731 var update_history = function() {
732 if (display_lines[0] === null || display_lines[0].pv.length == 0) {
733 $("#history").html("No history");
734 } else if (truncate_display_history) {
735 $("#history").html(print_pv(0, 8, true));
738 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
744 * @param {!boolean} truncate_history
746 var collapse_history = function(truncate_history) {
747 truncate_display_history = truncate_history;
750 window['collapse_history'] = collapse_history;
752 /** Update the HTML display of multi-PV from the global "refutation_lines".
754 * Also recreates the global "display_lines".
756 var update_refutation_lines = function() {
757 if (base_fen === null) {
760 if (display_lines.length > 2) {
761 // Truncate so that only the history and PV is left.
762 display_lines = [ display_lines[0], display_lines[1] ];
764 var tbl = $("#refutationlines");
767 // Find out where the lines start from.
769 var base_scores = display_lines[1].scores;
770 var start_display_move_num = 0;
771 if (hash_refutation_lines) {
772 base_line = current_display_line.pv.slice(0, current_display_move + 1);
773 base_scores = current_display_line.scores;
774 start_display_move_num = base_line.length;
778 for (var move in refutation_lines) {
782 var invert = (toplay === 'B');
783 if (current_display_line && current_display_move % 2 == 0) {
786 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_name;
787 moves = moves.sort(function(a, b) { return compare(refutation_lines, invert, a, b) });
788 for (var i = 0; i < moves.length; ++i) {
789 var line = refutation_lines[moves[i]];
791 var tr = document.createElement("tr");
793 var move_td = document.createElement("td");
794 tr.appendChild(move_td);
795 $(move_td).addClass("move");
797 var scores = base_scores.concat([{ first_move: start_display_move_num, score: line['score'] }]);
799 if (line['pv'].length == 0) {
800 // Not found, so just make a one-move PV.
801 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['move'] + "</a>";
802 $(move_td).html(move);
803 var score_td = document.createElement("td");
805 $(score_td).addClass("score");
806 $(score_td).text("—");
807 tr.appendChild(score_td);
809 var depth_td = document.createElement("td");
810 tr.appendChild(depth_td);
811 $(depth_td).addClass("depth");
812 $(depth_td).text("—");
814 var pv_td = document.createElement("td");
815 tr.appendChild(pv_td);
816 $(pv_td).addClass("pv");
817 $(pv_td).html(add_pv(base_fen, base_line.concat([ line['move'] ]), move_num, toplay, scores, start_display_move_num));
823 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['move'] + "</a>";
824 $(move_td).html(move);
826 var score_td = document.createElement("td");
827 tr.appendChild(score_td);
828 $(score_td).addClass("score");
829 $(score_td).text(format_short_score(line['score']));
831 var depth_td = document.createElement("td");
832 tr.appendChild(depth_td);
833 $(depth_td).addClass("depth");
834 if (line['depth'] && line['depth'] >= 0) {
835 $(depth_td).text("d" + line['depth']);
837 $(depth_td).text("—");
840 var pv_td = document.createElement("td");
841 tr.appendChild(pv_td);
842 $(pv_td).addClass("pv");
843 $(pv_td).html(add_pv(base_fen, base_line.concat(line['pv']), move_num, toplay, scores, start_display_move_num, 10));
848 // Make one of the links clickable and the other nonclickable.
849 if (sort_refutation_lines_by_score) {
850 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
851 $("#sortbyscore1").html("<strong>Score</strong>");
853 $("#sortbyscore0").html("<strong>Move</strong>");
854 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
857 // Update the move highlight, as we've rewritten all the HTML.
858 update_move_highlight();
862 * Create a Chess.js board object, containing the given position plus the given moves,
863 * up to the given limit.
865 * @param {?string} fen
866 * @param {Array.<string>} moves
867 * @param {number} last_move
869 var chess_from = function(fen, moves, last_move) {
870 var hiddenboard = new Chess();
872 hiddenboard.load(fen);
874 for (var i = 0; i <= last_move; ++i) {
875 if (moves[i] === '0-0') {
876 hiddenboard.move('O-O');
877 } else if (moves[i] === '0-0-0') {
878 hiddenboard.move('O-O-O');
880 hiddenboard.move(moves[i]);
886 var update_game_list = function(games) {
887 $("#games").text("");
888 if (games === null) {
892 var games_div = document.getElementById('games');
893 for (var game_num = 0; game_num < games.length; ++game_num) {
894 var game = games[game_num];
895 var game_span = document.createElement("span");
896 game_span.setAttribute("class", "game");
898 var game_name = document.createTextNode(game['name']);
899 if (game['url'] === backend_url) {
901 game_span.appendChild(game_name);
903 if (current_analysis_data && current_analysis_data['position']) {
905 if (current_analysis_data['position']['result']) {
906 score = " (" + current_analysis_data['position']['result'] + ")";
908 score = " (" + format_short_score(current_analysis_data['score']) + ")";
910 game_span.appendChild(document.createTextNode(score));
914 var game_a = document.createElement("a");
915 game_a.setAttribute("href", "#" + game['id']);
916 game_a.appendChild(game_name);
917 game_span.appendChild(game_a);
920 if (game['result']) {
921 score = " (" + game['result'] + ")";
923 score = " (" + format_short_score(game['score']) + ")";
925 game_span.appendChild(document.createTextNode(score));
928 games_div.appendChild(game_span);
933 * Try to find a running game that matches with the current hash,
934 * and switch to it if we're not already displaying it.
936 var possibly_switch_game_from_hash = function() {
937 if (current_games === null) {
941 var hash = window.location.hash.replace(/^#/,'');
942 for (var i = 0; i < current_games.length; ++i) {
943 if (current_games[i]['id'] === hash) {
944 if (backend_url !== current_games[i]['url']) {
945 switch_backend(current_games[i]);
952 /** Update all the HTML on the page, based on current global state.
954 var update_board = function() {
955 var data = displayed_analysis_data || current_analysis_data;
956 var current_data = current_analysis_data; // Convenience alias.
960 // Print the history. This is pretty much the only thing that's
961 // unconditionally taken from current_data (we're not interested in
962 // historic history).
963 if (current_data['position']['history']) {
964 add_pv('start', current_data['position']['history'], 1, 'W', null, 0, 8, true);
966 display_lines.push(null);
970 // Games currently in progress, if any.
971 if (current_data['games']) {
972 current_games = current_data['games'];
973 possibly_switch_game_from_hash();
975 current_games = null;
977 update_game_list(current_games);
979 // The headline. Names are always fetched from current_data;
980 // the rest can depend a bit.
983 current_data['position']['player_w'] && current_data['position']['player_b']) {
984 headline = current_data['position']['player_w'] + '–' +
985 current_data['position']['player_b'] + ', analysis';
987 headline = 'Analysis';
990 // Credits, where applicable. Note that we don't want the footer to change a lot
991 // when e.g. viewing history, so if any of these changed during the game,
992 // use the current one still.
993 if (current_data['using_lomonosov']) {
994 $("#lomonosov").show();
996 $("#lomonosov").hide();
999 // Credits: The engine name/version.
1000 if (current_data['engine'] && current_data['engine']['name'] !== null) {
1001 $("#engineid").text(current_data['engine']['name']);
1004 // Credits: The engine URL.
1005 if (current_data['engine'] && current_data['engine']['url']) {
1006 $("#engineid").attr("href", current_data['engine']['url']);
1008 $("#engineid").removeAttr("href");
1011 // Credits: Engine details.
1012 if (current_data['engine'] && current_data['engine']['details']) {
1013 $("#enginedetails").text(" (" + current_data['engine']['details'] + ")");
1015 $("#enginedetails").text("");
1018 // Credits: Move source, possibly with URL.
1019 if (current_data['move_source'] && current_data['move_source_url']) {
1020 $("#movesource").text("Moves provided by ");
1021 var movesource_a = document.createElement("a");
1022 movesource_a.setAttribute("href", current_data['move_source_url']);
1023 var movesource_text = document.createTextNode(current_data['move_source']);
1024 movesource_a.appendChild(movesource_text);
1025 var movesource_period = document.createTextNode(".");
1026 document.getElementById("movesource").appendChild(movesource_a);
1027 document.getElementById("movesource").appendChild(movesource_period);
1028 } else if (current_data['move_source']) {
1029 $("#movesource").text("Moves provided by " + current_data['move_source'] + ".");
1031 $("#movesource").text("");
1035 if (displayed_analysis_data) {
1036 // Displaying some non-current position, pick out the last move
1037 // from the history. This will work even if the fetch failed.
1038 last_move = format_halfmove_with_number(
1039 current_display_line.pv[current_display_move],
1040 current_display_move + 1);
1041 headline += ' after ' + last_move;
1042 } else if (data['position']['last_move'] !== 'none') {
1043 last_move = format_move_with_number(
1044 data['position']['last_move'],
1045 data['position']['move_num'],
1046 data['position']['toplay'] == 'W');
1047 headline += ' after ' + last_move;
1051 $("#headline").text(headline);
1053 // The <title> contains a very brief headline.
1054 var title_elems = [];
1055 if (data['position'] && data['position']['result']) {
1056 title_elems.push(data['position']['result']);
1057 } else if (data['score']) {
1058 title_elems.push(format_short_score(data['score']));
1060 if (last_move !== null) {
1061 title_elems.push(last_move);
1064 if (title_elems.length != 0) {
1065 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
1067 document.title = 'analysis.sesse.net';
1070 // The last move (shown by highlighting the from and to squares).
1071 if (data['position'] && data['position']['last_move_uci']) {
1072 highlight_from = data['position']['last_move_uci'].substr(0, 2);
1073 highlight_to = data['position']['last_move_uci'].substr(2, 2);
1074 } else if (current_display_line_is_history && current_display_move >= 0) {
1075 // We don't have historic analysis for this position, but we
1076 // can reconstruct what the last move was by just replaying
1078 var hiddenboard = chess_from(null, current_display_line.pv, current_display_move);
1079 var moves = hiddenboard.history({ verbose: true });
1080 last_move = moves.pop();
1081 highlight_from = last_move.from;
1082 highlight_to = last_move.to;
1084 highlight_from = highlight_to = undefined;
1086 update_board_highlight();
1088 if (data['failed']) {
1089 $("#score").text("No analysis for this move");
1090 $("#pvtitle").text("PV:");
1092 $("#searchstats").html(" ");
1093 $("#refutationlines").empty();
1094 $("#whiteclock").empty();
1095 $("#blackclock").empty();
1096 refutation_lines = [];
1097 update_refutation_lines();
1099 update_displayed_line();
1100 update_move_highlight();
1107 if (current_display_line && !current_display_line_is_history) {
1109 if (current_display_line.scores && current_display_line.scores.length > 0) {
1110 for (var i = 0; i < current_display_line.scores.length; ++i) {
1111 if (current_display_move < current_display_line.scores[i].first_move) {
1114 score = current_display_line.scores[i].score;
1118 $("#score").text(format_long_score(score));
1120 $("#score").text("No score for this line");
1122 } else if (data['score']) {
1123 $("#score").text(format_long_score(data['score']));
1126 // The search stats.
1127 if (data['searchstats']) {
1128 $("#searchstats").html(data['searchstats']);
1129 } else if (data['tablebase'] == 1) {
1130 $("#searchstats").text("Tablebase result");
1131 } else if (data['nodes'] && data['nps'] && data['depth']) {
1132 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
1133 if (data['seldepth']) {
1134 stats += ' (' + data['seldepth'] + ' selective)';
1136 if (data['tbhits'] && data['tbhits'] > 0) {
1137 if (data['tbhits'] == 1) {
1138 stats += ', one Syzygy hit';
1140 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
1144 $("#searchstats").text(stats);
1146 $("#searchstats").text("");
1149 // Update the board itself.
1150 base_fen = data['position']['fen'];
1151 update_displayed_line();
1154 $("#pvtitle").text("PV:");
1156 var scores = [{ first_move: -1, score: data['score'] }];
1157 $("#pv").html(add_pv(data['position']['fen'], data['pv'], data['position']['move_num'], data['position']['toplay'], scores, 0));
1159 // Update the PV arrow.
1161 if (data['pv'].length >= 1) {
1162 var hiddenboard = new Chess(base_fen);
1164 // draw a continuation arrow as long as it's the same piece
1166 for (var i = 0; i < data['pv'].length; i += 2) {
1167 var move = hiddenboard.move(data['pv'][i]);
1168 if ((i >= 2 && move.from != last_to) ||
1169 interfering_arrow(move.from, move.to)) {
1172 create_arrow(move.from, move.to, '#f66', 6, 20);
1173 last_to = move.from;
1174 hiddenboard.move(data['pv'][i + 1]); // To keep continuity.
1177 var alt_moves = find_nonstupid_moves(data, 30, data['position']['toplay'] === 'B');
1178 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
1179 hiddenboard = new Chess(base_fen);
1180 var move = hiddenboard.move(alt_moves[i]);
1181 create_arrow(move.from, move.to, '#f66', 1, 10);
1185 // See if all semi-reasonable moves have only one possible response.
1186 if (data['pv'].length >= 2) {
1187 var nonstupid_moves = find_nonstupid_moves(data, 300, data['position']['toplay'] === 'B');
1190 var hiddenboard = new Chess(base_fen);
1191 hiddenboard.move(data['pv'][0]);
1192 response = hiddenboard.move(data['pv'][1]);
1194 for (var i = 0; i < nonstupid_moves.length; ++i) {
1195 if (nonstupid_moves[i] == data['pv'][0]) {
1196 // ignore the PV move for refutation lines.
1199 if (!data['refutation_lines'] ||
1200 !data['refutation_lines'][nonstupid_moves[i]] ||
1201 !data['refutation_lines'][nonstupid_moves[i]]['pv'] ||
1202 data['refutation_lines'][nonstupid_moves[i]]['pv'].length < 1) {
1203 // Incomplete PV, abort.
1204 response = undefined;
1207 var line = data['refutation_lines'][nonstupid_moves[i]];
1208 hiddenboard = new Chess(base_fen);
1209 hiddenboard.move(line['pv'][0]);
1210 var this_response = hiddenboard.move(line['pv'][1]);
1211 if (response.from !== this_response.from || response.to !== this_response.to) {
1212 // Different response depending on lines, abort.
1213 response = undefined;
1218 if (nonstupid_moves.length > 0 && response !== undefined) {
1219 create_arrow(response.from, response.to, '#66f', 6, 20);
1223 // Update the refutation lines.
1224 base_fen = data['position']['fen'];
1225 move_num = parseInt(data['position']['move_num']);
1226 toplay = data['position']['toplay'];
1227 refutation_lines = hash_refutation_lines || data['refutation_lines'];
1228 update_refutation_lines();
1230 // Update the sparkline last, since its size depends on how everything else reflowed.
1231 update_sparkline(data);
1234 var update_sparkline = function(data) {
1235 if (data && data['score_history']) {
1236 var first_move_num = undefined;
1237 for (var halfmove_num in data['score_history']) {
1238 halfmove_num = parseInt(halfmove_num);
1239 if (first_move_num === undefined || halfmove_num < first_move_num) {
1240 first_move_num = halfmove_num;
1243 if (first_move_num !== undefined) {
1244 var last_move_num = data['position']['move_num'] * 2 - 3;
1245 if (data['position']['toplay'] === 'B') {
1249 // Possibly truncate some moves if we don't have enough width.
1250 // FIXME: Sometimes width() for #scorecontainer (and by extent,
1251 // #scoresparkcontainer) on Chrome for mobile seems to start off
1252 // at something very small, and then suddenly snap back into place.
1254 var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
1255 if (last_move_num - first_move_num > max_moves) {
1256 first_move_num = last_move_num - max_moves;
1259 var min_score = -100;
1260 var max_score = 100;
1261 var last_score = null;
1263 for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1264 if (data['score_history'][halfmove_num]) {
1265 var score = compute_plot_score(data['score_history'][halfmove_num]);
1267 if (score < min_score) min_score = score;
1268 if (score > max_score) max_score = score;
1270 scores.push(last_score);
1272 if (data['score']) {
1273 scores.push(compute_plot_score(data['score']));
1275 // FIXME: at some widths, calling sparkline() seems to push
1276 // #scorecontainer under the board.
1277 $("#scorespark").sparkline(scores, {
1280 chartRangeMin: min_score,
1281 chartRangeMax: max_score,
1282 tooltipFormatter: function(sparkline, options, fields) {
1283 return format_tooltip(data, fields[0].offset + first_move_num);
1287 $("#scorespark").text("");
1290 $("#scorespark").text("");
1295 * @param {number} num_viewers
1297 var update_num_viewers = function(num_viewers) {
1298 if (num_viewers === null) {
1299 $("#numviewers").text("");
1300 } else if (num_viewers == 1) {
1301 $("#numviewers").text("You are the only current viewer");
1303 $("#numviewers").text(num_viewers + " current viewers");
1307 var update_clock = function() {
1308 clearTimeout(clock_timer);
1310 var data = displayed_analysis_data || current_analysis_data;
1313 if (data['position']) {
1314 var result = data['position']['result'];
1315 if (result === '1-0') {
1316 $("#whiteclock").text("1");
1317 $("#blackclock").text("0");
1318 $("#whiteclock").removeClass("running-clock");
1319 $("#blackclock").removeClass("running-clock");
1322 if (result === '1/2-1/2') {
1323 $("#whiteclock").text("1/2");
1324 $("#blackclock").text("1/2");
1325 $("#whiteclock").removeClass("running-clock");
1326 $("#blackclock").removeClass("running-clock");
1329 if (result === '0-1') {
1330 $("#whiteclock").text("0");
1331 $("#blackclock").text("1");
1332 $("#whiteclock").removeClass("running-clock");
1333 $("#blackclock").removeClass("running-clock");
1338 var white_clock_ms = null;
1339 var black_clock_ms = null;
1342 if (data['position'] &&
1343 data['position']['white_clock'] &&
1344 data['position']['black_clock']) {
1345 white_clock_ms = data['position']['white_clock'] * 1000;
1346 black_clock_ms = data['position']['black_clock'] * 1000;
1349 // Dynamic clock (only one, obviously).
1351 if (data['position']['white_clock_target']) {
1353 $("#whiteclock").addClass("running-clock");
1354 $("#blackclock").removeClass("running-clock");
1355 } else if (data['position']['black_clock_target']) {
1357 $("#whiteclock").removeClass("running-clock");
1358 $("#blackclock").addClass("running-clock");
1360 $("#whiteclock").removeClass("running-clock");
1361 $("#blackclock").removeClass("running-clock");
1365 var now = new Date().getTime() + client_clock_offset_ms;
1366 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1367 if (color === "white") {
1368 white_clock_ms = remaining_ms;
1370 black_clock_ms = remaining_ms;
1374 if (white_clock_ms === null || black_clock_ms === null) {
1375 $("#whiteclock").empty();
1376 $("#blackclock").empty();
1380 // If either player has ten minutes or less left, add the second counters.
1381 var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
1384 // See when the clock will change next, and update right after that.
1387 next_update_ms = remaining_ms % 1000 + 100;
1389 next_update_ms = remaining_ms % 60000 + 100;
1391 clock_timer = setTimeout(update_clock, next_update_ms);
1394 $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1395 $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1399 * @param {Number} remaining_ms
1400 * @param {boolean} show_seconds
1402 var format_clock = function(remaining_ms, show_seconds) {
1403 if (remaining_ms <= 0) {
1411 var remaining = Math.floor(remaining_ms / 1000);
1412 var seconds = remaining % 60;
1413 remaining = (remaining - seconds) / 60;
1414 var minutes = remaining % 60;
1415 remaining = (remaining - minutes) / 60;
1416 var hours = remaining;
1418 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1420 return format_2d(hours) + ":" + format_2d(minutes);
1427 var format_2d = function(x) {
1436 * @param {string} move
1437 * @param {Number} move_num
1438 * @param {boolean} white_to_play
1440 var format_move_with_number = function(move, move_num, white_to_play) {
1442 if (white_to_play) {
1443 ret = (move_num - 1) + '… ';
1445 ret = move_num + '. ';
1452 * @param {string} move
1453 * @param {Number} halfmove_num
1455 var format_halfmove_with_number = function(move, halfmove_num) {
1456 return format_move_with_number(
1458 Math.floor(halfmove_num / 2) + 1,
1459 halfmove_num % 2 == 0);
1463 * @param {Object} data
1464 * @param {Number} halfmove_num
1466 var format_tooltip = function(data, halfmove_num) {
1467 if (data['score_history'][halfmove_num] ||
1468 halfmove_num === data['position']['history'].length) {
1471 if (halfmove_num === data['position']['history'].length) {
1472 move = data['position']['last_move'];
1473 short_score = format_short_score(data['score']);
1475 move = data['position']['history'][halfmove_num];
1476 short_score = format_short_score(data['score_history'][halfmove_num]);
1478 var move_with_number = format_halfmove_with_number(move, halfmove_num);
1480 return "After " + move_with_number + ": " + short_score;
1482 for (var i = halfmove_num; i --> 0; ) {
1483 if (data['score_history'][i]) {
1484 var move = data['position']['history'][i];
1485 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1492 * @param {boolean} sort_by_score
1494 var resort_refutation_lines = function(sort_by_score) {
1495 sort_refutation_lines_by_score = sort_by_score;
1496 if (supports_html5_storage()) {
1497 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1499 update_refutation_lines();
1501 window['resort_refutation_lines'] = resort_refutation_lines;
1504 * @param {boolean} truncate_history
1506 var set_truncate_history = function(truncate_history) {
1507 truncate_display_history = truncate_history;
1508 update_refutation_lines();
1510 window['set_truncate_history'] = set_truncate_history;
1513 * @param {number} line_num
1514 * @param {number} move_num
1516 var show_line = function(line_num, move_num) {
1517 if (line_num == -1) {
1518 current_display_line = null;
1519 current_display_move = null;
1520 hash_refutation_lines = null;
1521 if (displayed_analysis_data) {
1522 // TODO: Support exiting to history position if we are in an
1523 // analysis line of a history position.
1524 displayed_analysis_data = null;
1529 current_display_line = jQuery.extend({}, display_lines[line_num]); // Shallow clone.
1530 current_display_move = move_num + current_display_line.start_display_move_num;
1532 current_display_line_is_history = (line_num == 0);
1534 update_historic_analysis();
1535 update_displayed_line();
1536 update_board_highlight();
1537 update_move_highlight();
1540 window['show_line'] = show_line;
1542 var prev_move = function() {
1543 if (current_display_line &&
1544 current_display_move >= current_display_line.start_display_move_num) {
1545 --current_display_move;
1547 update_historic_analysis();
1548 update_displayed_line();
1549 update_move_highlight();
1551 window['prev_move'] = prev_move;
1553 var next_move = function() {
1554 if (current_display_line &&
1555 current_display_move < current_display_line.pv.length - 1) {
1556 ++current_display_move;
1558 update_historic_analysis();
1559 update_displayed_line();
1560 update_move_highlight();
1562 window['next_move'] = next_move;
1564 var next_game = function() {
1565 if (current_games === null) {
1569 // Try to find the game we are currently looking at.
1570 for (var game_num = 0; game_num < current_games.length; ++game_num) {
1571 var game = current_games[game_num];
1572 if (game['url'] === backend_url) {
1573 var next_game_num = (game_num + 1) % current_games.length;
1574 switch_backend(current_games[next_game_num]);
1579 // Couldn't find it; give up.
1582 var update_historic_analysis = function() {
1583 if (!current_display_line_is_history) {
1586 if (current_display_move == current_display_line.pv.length - 1) {
1587 displayed_analysis_data = null;
1591 // Fetch old analysis for this line if it exists.
1592 var hiddenboard = chess_from(null, current_display_line.pv, current_display_move);
1593 var filename = "/history/move" + (current_display_move + 1) + "-" +
1594 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1596 current_historic_xhr = $.ajax({
1598 }).done(function(data, textstatus, xhr) {
1599 displayed_analysis_data = data;
1601 }).fail(function(jqXHR, textStatus, errorThrown) {
1602 if (textStatus === "abort") {
1603 // Aborted because we are switching backends. Don't do anything;
1604 // we will already have been cleared.
1606 displayed_analysis_data = {'failed': true};
1613 * @param {string} fen
1615 var update_imbalance = function(fen) {
1616 var hiddenboard = new Chess(fen);
1617 var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1618 for (var row = 0; row < 8; ++row) {
1619 for (var col = 0; col < 8; ++col) {
1620 var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1621 var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1622 var square = col_text + row_text;
1623 var contents = hiddenboard.get(square);
1624 if (contents !== null) {
1625 if (contents.color === 'w') {
1626 ++imbalance[contents.type];
1628 --imbalance[contents.type];
1633 var white_imbalance = '';
1634 var black_imbalance = '';
1635 for (var piece in imbalance) {
1636 for (var i = 0; i < imbalance[piece]; ++i) {
1637 white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1639 for (var i = 0; i < -imbalance[piece]; ++i) {
1640 black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1643 $('#whiteimbalance').html(white_imbalance);
1644 $('#blackimbalance').html(black_imbalance);
1647 /** Mark the currently selected move in red.
1648 * Also replaces the PV with the current displayed line if it's not shown
1649 * anywhere else on the screen.
1651 var update_move_highlight = function() {
1652 if (highlighted_move !== null) {
1653 highlighted_move.removeClass('highlight');
1655 if (current_display_line) {
1656 var display_line_num = find_display_line_matching_num();
1657 if (display_line_num === null) {
1658 // Replace the PV with the (complete) line.
1659 $("#pvtitle").text("Exploring:");
1660 current_display_line.start_display_move_num = 0;
1661 display_lines.push(current_display_line);
1662 $("#pv").html(print_pv(display_lines.length - 1));
1663 display_line_num = display_lines.length - 1;
1665 // Clear out the PV, so it's not selected by anything later.
1666 display_lines[1].pv = [];
1669 highlighted_move = $("#automove" + display_line_num + "-" + (current_display_move - current_display_line.start_display_move_num));
1670 highlighted_move.addClass('highlight');
1675 * See if the current displayed line is identical to any of the ones
1676 * we have on screen. (It might not be if e.g. the analysis reloaded
1677 * since we started looking.)
1681 var find_display_line_matching_num = function() {
1682 for (var i = 0; i < display_lines.length; ++i) {
1683 var line = display_lines[i];
1684 if (line.start_display_move_num > 0) continue;
1685 if (current_display_line.start_fen !== line.start_fen) continue;
1686 if (current_display_line.pv.length !== line.pv.length) continue;
1688 for (var j = 0; j < line.pv.length; ++j) {
1689 if (current_display_line.pv[j] !== line.pv[j]) {
1701 /** Update the board based on the currently displayed line.
1703 * TODO: This should really be called only whenever something changes,
1704 * instead of all the time.
1706 var update_displayed_line = function() {
1707 if (current_display_line === null) {
1708 $("#linenav").hide();
1709 $("#linemsg").show();
1710 display_fen = base_fen;
1711 set_board_position(base_fen);
1712 update_imbalance(base_fen);
1716 $("#linenav").show();
1717 $("#linemsg").hide();
1719 if (current_display_move <= 0) {
1720 $("#prevmove").html("Previous");
1722 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1724 if (current_display_move == current_display_line.pv.length - 1) {
1725 $("#nextmove").html("Next");
1727 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1730 var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pv, current_display_move);
1731 set_board_position(hiddenboard.fen());
1732 if (display_fen !== hiddenboard.fen() && !current_display_line_is_history) {
1733 // Fire off a hash request, since we're now off the main position
1734 // and it just changed.
1735 explore_hash(hiddenboard.fen());
1737 display_fen = hiddenboard.fen();
1738 update_imbalance(hiddenboard.fen());
1741 var set_board_position = function(new_fen) {
1742 board_is_animating = true;
1743 var old_fen = board.fen();
1744 board.position(new_fen);
1745 if (board.fen() === old_fen) {
1746 board_is_animating = false;
1751 * @param {boolean} param_enable_sound
1753 var set_sound = function(param_enable_sound) {
1754 enable_sound = param_enable_sound;
1756 $("#soundon").html("<strong>On</strong>");
1757 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1759 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1760 // and also preload the file since the user has selected audio.
1761 var ding = document.getElementById('ding');
1762 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1763 ding.src = 'ding.opus';
1767 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1768 $("#soundoff").html("<strong>Off</strong>");
1770 if (supports_html5_storage()) {
1771 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1774 window['set_sound'] = set_sound;
1776 /** Send off a hash probe request to the backend.
1777 * @param {string} fen
1779 var explore_hash = function(fen) {
1780 // If we already have a backend response going, abort it.
1781 if (current_hash_xhr) {
1782 current_hash_xhr.abort();
1784 if (current_hash_display_timer) {
1785 clearTimeout(current_hash_display_timer);
1786 current_hash_display_timer = null;
1788 $("#refutationlines").empty();
1789 current_hash_xhr = $.ajax({
1790 url: backend_hash_url + "?fen=" + fen
1791 }).done(function(data, textstatus, xhr) {
1792 show_explore_hash_results(data, fen);
1796 /** Process the JSON response from a hash probe request.
1797 * @param {!Object} data
1798 * @param {string} fen
1800 var show_explore_hash_results = function(data, fen) {
1801 if (board_is_animating) {
1802 // Updating while the animation is still going causes
1803 // the animation to jerk. This is pretty crude, but it will do.
1804 current_hash_display_timer = setTimeout(function() { show_explore_hash_results(data, fen); }, 100);
1807 current_hash_display_timer = null;
1808 hash_refutation_lines = data['lines'];
1812 // almost all of this stuff comes from the chessboard.js example page
1813 var onDragStart = function(source, piece, position, orientation) {
1814 var pseudogame = new Chess(display_fen);
1815 if (pseudogame.game_over() === true ||
1816 (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
1817 (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
1821 recommended_move = get_best_move(pseudogame, source, null, pseudogame.turn() === 'b');
1822 if (recommended_move) {
1823 var squareEl = $('#board .square-' + recommended_move.to);
1824 squareEl.addClass('highlight1-32417');
1829 var mousedownSquare = function(e) {
1830 reverse_dragging_from = null;
1831 var square = $(this).attr('data-square');
1833 var pseudogame = new Chess(display_fen);
1834 if (pseudogame.game_over() === true) {
1838 // If the square is empty, or has a piece of the side not to move,
1839 // we handle it. If not, normal piece dragging will take it.
1840 var position = board.position();
1841 if (!position.hasOwnProperty(square) ||
1842 (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
1843 (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
1844 reverse_dragging_from = square;
1845 recommended_move = get_best_move(pseudogame, null, square, pseudogame.turn() === 'b');
1846 if (recommended_move) {
1847 var squareEl = $('#board .square-' + recommended_move.from);
1848 squareEl.addClass('highlight1-32417');
1849 squareEl = $('#board .square-' + recommended_move.to);
1850 squareEl.addClass('highlight1-32417');
1855 var mouseupSquare = function(e) {
1856 if (reverse_dragging_from === null) {
1859 var source = $(this).attr('data-square');
1860 var target = reverse_dragging_from;
1861 reverse_dragging_from = null;
1862 if (onDrop(source, target) !== 'snapback') {
1863 onSnapEnd(source, target);
1865 $("#board").find('.square-55d63').removeClass('highlight1-32417');
1868 var get_best_move = function(game, source, target, invert) {
1869 var moves = game.moves({ verbose: true });
1870 if (source !== null) {
1871 moves = moves.filter(function(move) { return move.from == source; });
1873 if (target !== null) {
1874 moves = moves.filter(function(move) { return move.to == target; });
1876 if (moves.length == 0) {
1879 if (moves.length == 1) {
1883 // More than one move. Use the display lines (if we have them)
1884 // to disambiguate; otherwise, we have no information.
1886 for (var i = 0; i < moves.length; ++i) {
1887 move_hash[moves[i].san] = moves[i];
1890 // See if we're already exploring some line.
1891 if (current_display_line &&
1892 current_display_move < current_display_line.pv.length - 1) {
1893 var first_move = current_display_line.pv[current_display_move + 1];
1894 if (move_hash[first_move]) {
1895 return move_hash[first_move];
1899 // History and PV take priority over the display lines.
1900 for (var i = 0; i < 2; ++i) {
1901 var line = display_lines[i];
1902 var first_move = line.pv[line.start_display_move_num];
1903 if (move_hash[first_move]) {
1904 return move_hash[first_move];
1908 var best_move = null;
1909 var best_move_score = null;
1911 for (var move in refutation_lines) {
1912 var line = refutation_lines[move];
1913 if (!line['score']) {
1916 var first_move = line['pv'][0];
1917 if (move_hash[first_move]) {
1918 var score = compute_score_sort_key(line['score'], line['depth'], invert);
1919 if (best_move_score === null || score > best_move_score) {
1920 best_move = move_hash[first_move];
1921 best_move_score = score;
1928 var onDrop = function(source, target) {
1929 if (source === target) {
1930 if (recommended_move === null) {
1933 // Accept the move. It will be changed in onSnapEnd.
1937 // Suggestion not asked for.
1938 recommended_move = null;
1941 // see if the move is legal
1942 var pseudogame = new Chess(display_fen);
1943 var move = pseudogame.move({
1946 promotion: 'q' // NOTE: always promote to a queen for example simplicity
1950 if (move === null) return 'snapback';
1953 var onSnapEnd = function(source, target) {
1954 if (source === target && recommended_move !== null) {
1955 source = recommended_move.from;
1956 target = recommended_move.to;
1958 recommended_move = null;
1959 var pseudogame = new Chess(display_fen);
1960 var move = pseudogame.move({
1963 promotion: 'q' // NOTE: always promote to a queen for example simplicity
1966 if (current_display_line &&
1967 current_display_move < current_display_line.pv.length - 1 &&
1968 current_display_line.pv[current_display_move + 1] === move.san) {
1973 // Walk down the displayed lines until we find one that starts with
1974 // this move, then select that. Note that this gives us a good priority
1975 // order (history first, then PV, then multi-PV lines).
1976 for (var i = 0; i < display_lines.length; ++i) {
1977 if (i == 1 && current_display_line) {
1978 // Do not choose PV if not on it.
1981 var line = display_lines[i];
1982 if (line.pv[line.start_display_move_num] === move.san) {
1988 // Shouldn't really be here if we have hash probes, but there's really
1989 // nothing we can do.
1991 // End of dragging-related code.
1993 var fmt_cp = function(v) {
1997 return "+" + (v / 100).toFixed(2);
2000 return "-" + (v / 100).toFixed(2);
2004 var format_short_score = function(score) {
2008 if (score[0] === 'm') {
2009 if (score[2]) { // Is a bound.
2010 return score[2] + "\u00a0M " + score[1];
2012 return "M " + score[1];
2014 } else if (score[0] === 'd') {
2016 } else if (score[0] === 'cp') {
2017 if (score[2]) { // Is a bound.
2018 return score[2] + "\u00a0" + fmt_cp(score[1]);
2020 return fmt_cp(score[1]);
2026 var format_long_score = function(score) {
2030 if (score[0] === 'm') {
2032 return "White mates in " + score[1];
2034 return "Black mates in " + (-score[1]);
2036 } else if (score[0] === 'd') {
2037 return "Theoretical draw";
2038 } else if (score[0] === 'cp') {
2039 return "Score: " + format_short_score(score);
2044 var compute_plot_score = function(score) {
2045 if (score[0] === 'm') {
2051 } else if (score[0] === 'd') {
2053 } else if (score[0] === 'cp') {
2054 if (score[1] > 500) {
2056 } else if (score[1] < -500) {
2066 * @param score The score digest tuple.
2067 * @param {?number} depth Depth the move has been computed to, or null.
2068 * @param {boolean} invert Whether black is to play.
2069 * @param {boolean=} depth_secondary_key
2072 var compute_score_sort_key = function(score, depth, invert, depth_secondary_key) {
2077 if (score[0] === 'm') {
2080 s = 99999 - score[1];
2082 // Black mates (note the double negative for score[1]).
2083 s = -99999 - score[1];
2085 } else if (score[0] === 'd') {
2087 } else if (score[0] === 'cp') {
2092 if (depth_secondary_key) {
2093 return s * 200 + (depth || 0);
2103 * @param {Object} game
2105 var switch_backend = function(game) {
2106 // Stop looking at historic data.
2107 current_display_line = null;
2108 current_display_move = null;
2109 displayed_analysis_data = null;
2110 if (current_historic_xhr) {
2111 current_historic_xhr.abort();
2114 // If we already have a backend response going, abort it.
2115 if (current_analysis_xhr) {
2116 current_analysis_xhr.abort();
2118 if (current_hash_xhr) {
2119 current_hash_xhr.abort();
2122 // Otherwise, we should have a timer going to start a new one.
2124 if (current_analysis_request_timer) {
2125 clearTimeout(current_analysis_request_timer);
2126 current_analysis_request_timer = null;
2128 if (current_hash_display_timer) {
2129 clearTimeout(current_hash_display_timer);
2130 current_hash_display_timer = null;
2133 // Request an immediate fetch with the new backend.
2134 backend_url = game['url'];
2135 backend_hash_url = game['hashurl'];
2136 window.location.hash = '#' + game['id'];
2137 current_analysis_data = null;
2141 window['switch_backend'] = switch_backend;
2143 var init = function() {
2144 unique = get_unique();
2146 // Load settings from HTML5 local storage if available.
2147 if (supports_html5_storage() && localStorage['enable_sound']) {
2148 set_sound(parseInt(localStorage['enable_sound']));
2152 if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
2153 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
2155 sort_refutation_lines_by_score = true;
2159 board = new window.ChessBoard('board', {
2160 onMoveEnd: function() { board_is_animating = false; },
2163 onDragStart: onDragStart,
2165 onSnapEnd: onSnapEnd
2167 $("#board").on('mousedown', '.square-55d63', mousedownSquare);
2168 $("#board").on('mouseup', '.square-55d63', mouseupSquare);
2171 $(window).resize(function() {
2173 update_sparkline(displayed_analysis_data || current_analysis_data);
2174 update_board_highlight();
2177 $(window).keyup(function(event) {
2178 if (event.which == 39) { // Left arrow.
2180 } else if (event.which == 37) { // Right arrow.
2182 } else if (event.which >= 49 && event.which <= 57) { // 1-9.
2183 var num = event.which - 49;
2184 if (current_games && current_games.length >= num) {
2185 switch_backend(current_games[num]);
2187 } else if (event.which == 78) { // N.
2191 window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
2193 $(document).ready(init);