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 = 2016032200;
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.
55 var current_games = null;
70 /** @type {Array.<Array.<boolean>>} */
71 var occupied_by_arrows = [];
73 /** Currently displayed refutation lines (on-screen).
74 * Can either come from the current_analysis_data, displayed_analysis_data,
75 * or hash_refutation_lines.
77 var refutation_lines = [];
79 /** Refutation lines from current hash probe.
81 * If non-null, will override refutation lines from the base position.
82 * Note that these are relative to display_fen, not base_fen.
84 var hash_refutation_lines = null;
86 /** @type {!number} @private */
89 /** @type {!string} @private */
92 /** @type {number} @private */
95 /** @type {boolean} @private */
96 var sort_refutation_lines_by_score = true;
98 /** @type {boolean} @private */
99 var truncate_display_history = true;
101 /** @type {!string|undefined} @private */
102 var highlight_from = undefined;
104 /** @type {!string|undefined} @private */
105 var highlight_to = undefined;
107 /** The HTML object of the move currently being highlighted (in red).
110 var highlighted_move = null;
112 /** Currently suggested/recommended move when dragging.
113 * @type {?{from: !string, to: !string}}
116 var recommended_move = null;
118 /** If reverse-dragging (dragging from the destination square to the
119 * source square), the destination square.
123 var reverse_dragging_from = null;
125 /** @type {?number} @private */
128 /** @type {boolean} @private */
129 var enable_sound = false;
132 * Our best estimate of how many milliseconds we need to add to
133 * new Date() to get the true UTC time. Calibrated against the
139 var client_clock_offset_ms = null;
141 var clock_timer = null;
143 /** The current position being analyzed, represented as a FEN string.
144 * Note that this is not necessarily the same as display_fen.
150 /** The current position on the board, represented as a FEN string.
151 * Note that board.fen() does not contain e.g. who is to play.
155 var display_fen = null;
159 * pretty_pv: Array.<string>,
163 * start_display_move_num: number
166 * "start_display_move_num" is the (half-)move number to start displaying the PV at.
167 * "score" is also evaluated at this point.
170 /** All PVs that we currently know of.
172 * Element 0 is history (or null if no history).
173 * Element 1 is current main PV, or explored line if nowhere else on the screen.
174 * All remaining elements are refutation lines (multi-PV).
176 * @type {Array.<DisplayLine>}
179 var display_lines = [];
181 /** @type {?DisplayLine} @private */
182 var current_display_line = null;
184 /** @type {boolean} @private */
185 var current_display_line_is_history = false;
187 /** @type {?number} @private */
188 var current_display_move = null;
191 * The current backend request to get main analysis (not history), if any,
192 * so that we can abort it.
197 var current_analysis_xhr = null;
200 * The current timer to fire off a request to get main analysis (not history),
201 * if any, so that we can abort it.
206 var current_analysis_request_timer = null;
209 * The current backend request to get historic data, if any.
214 var current_historic_xhr = null;
217 * The current backend request to get hash probes, if any, so that we can abort it.
222 var current_hash_xhr = null;
225 * The current timer to display hash probe information (it could be waiting on the
226 * board to stop animating), if any, so that we can abort it.
231 var current_hash_display_timer = null;
233 var supports_html5_storage = function() {
235 return 'localStorage' in window && window['localStorage'] !== null;
241 // Make the unique token persistent so people refreshing the page won't count twice.
242 // Of course, you can never fully protect against people deliberately wanting to spam.
243 var get_unique = function() {
244 var use_local_storage = supports_html5_storage();
245 if (use_local_storage && localStorage['unique']) {
246 return localStorage['unique'];
248 var unique = Math.random();
249 if (use_local_storage) {
250 localStorage['unique'] = unique;
255 var request_update = function() {
256 current_analysis_request_timer = null;
258 current_analysis_xhr = $.ajax({
259 url: backend_url + "?ims=" + ims + "&unique=" + unique
260 }).done(function(data, textstatus, xhr) {
261 sync_server_clock(xhr.getResponseHeader('Date'));
262 ims = xhr.getResponseHeader('X-RGLM');
263 var num_viewers = xhr.getResponseHeader('X-RGNV');
265 if (Array.isArray(data)) {
266 new_data = JSON.parse(JSON.stringify(current_analysis_data));
267 JSON_delta.patch(new_data, data);
272 var minimum_version = xhr.getResponseHeader('X-RGMV');
273 if (minimum_version && minimum_version > SCRIPT_VERSION) {
274 // Upgrade to latest version with a force-reload.
275 location.reload(true);
278 possibly_play_sound(current_analysis_data, new_data);
279 current_analysis_data = new_data;
281 update_num_viewers(num_viewers);
284 current_analysis_request_timer = setTimeout(function() { request_update(); }, 100);
285 }).fail(function(jqXHR, textStatus, errorThrown) {
286 if (textStatus === "abort") {
287 // Aborted because we are switching backends. Abandon and don't retry,
288 // because another one is already started for us.
290 // Backend error or similar. Wait ten seconds, then try again.
291 current_analysis_request_timer = setTimeout(function() { request_update(); }, 10000);
296 var possibly_play_sound = function(old_data, new_data) {
300 if (old_data === null) {
303 var ding = document.getElementById('ding');
304 if (ding && ding.play) {
305 if (old_data['position'] && old_data['position']['fen'] &&
306 new_data['position'] && new_data['position']['fen'] &&
307 (old_data['position']['fen'] !== new_data['position']['fen'] ||
308 old_data['position']['move_num'] !== new_data['position']['move_num'])) {
315 * @type {!string} server_date_string
317 var sync_server_clock = function(server_date_string) {
318 var server_time_ms = new Date(server_date_string).getTime();
319 var client_time_ms = new Date().getTime();
320 var estimated_offset_ms = server_time_ms - client_time_ms;
322 // In order not to let the noise move us too much back and forth
323 // (the server only has one-second resolution anyway), we only
324 // change an existing skew if we are at least five seconds off.
325 if (client_clock_offset_ms === null ||
326 Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
327 client_clock_offset_ms = estimated_offset_ms;
331 var clear_arrows = function() {
332 for (var i = 0; i < arrows.length; ++i) {
334 if (arrows[i].svg.parentElement) {
335 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
337 delete arrows[i].svg;
342 occupied_by_arrows = [];
343 for (var y = 0; y < 8; ++y) {
344 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
348 var redraw_arrows = function() {
349 for (var i = 0; i < arrows.length; ++i) {
350 position_arrow(arrows[i]);
354 /** @param {!number} x
357 var sign = function(x) {
367 /** See if drawing this arrow on the board would cause unduly amount of confusion.
368 * @param {!string} from The square the arrow is from (e.g. e4).
369 * @param {!string} to The square the arrow is to (e.g. e4).
372 var interfering_arrow = function(from, to) {
373 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
374 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
375 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
376 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
378 occupied_by_arrows[from_row][from_col] = true;
380 // Knight move: Just check that we haven't been at the destination before.
381 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
382 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
383 return occupied_by_arrows[to_row][to_col];
386 // Sliding piece: Check if anything except the from-square is seen before.
387 var dx = sign(to_col - from_col);
388 var dy = sign(to_row - from_row);
394 if (occupied_by_arrows[y][x]) {
397 occupied_by_arrows[y][x] = true;
398 } while (x != to_col || y != to_row);
403 /** Find a point along the coordinate system given by the given line,
404 * <t> units forward from the start of the line, <u> units to the right of it.
405 * @param {!number} x1
406 * @param {!number} x2
407 * @param {!number} y1
408 * @param {!number} y2
411 * @return {!string} The point in "x y" form, suitable for SVG paths.
413 var point_from_start = function(x1, y1, x2, y2, t, u) {
417 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
421 var x = x1 + dx * t + dy * u;
422 var y = y1 + dy * t - dx * u;
426 /** Find a point along the coordinate system given by the given line,
427 * <t> units forward from the end of the line, <u> units to the right of it.
428 * @param {!number} x1
429 * @param {!number} x2
430 * @param {!number} y1
431 * @param {!number} y2
434 * @return {!string} The point in "x y" form, suitable for SVG paths.
436 var point_from_end = function(x1, y1, x2, y2, t, u) {
440 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
444 var x = x2 + dx * t + dy * u;
445 var y = y2 + dy * t - dx * u;
449 var position_arrow = function(arrow) {
451 if (arrow.svg.parentElement) {
452 arrow.svg.parentElement.removeChild(arrow.svg);
456 if (current_display_line !== null && !current_display_line_is_history) {
460 var pos = $(".square-a8").position();
462 var zoom_factor = $("#board").width() / 400.0;
463 var line_width = arrow.line_width * zoom_factor;
464 var arrow_size = arrow.arrow_size * zoom_factor;
466 var square_width = $(".square-a8").width();
467 var from_y = (7 - arrow.from_row + 0.5)*square_width;
468 var to_y = (7 - arrow.to_row + 0.5)*square_width;
469 var from_x = (arrow.from_col + 0.5)*square_width;
470 var to_x = (arrow.to_col + 0.5)*square_width;
472 var SVG_NS = "http://www.w3.org/2000/svg";
473 var XHTML_NS = "http://www.w3.org/1999/xhtml";
474 var svg = document.createElementNS(SVG_NS, "svg");
475 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
476 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
477 svg.setAttribute("style", "position: absolute");
478 svg.setAttribute("position", "absolute");
479 svg.setAttribute("version", "1.1");
480 svg.setAttribute("class", "c1");
481 svg.setAttribute("xmlns", XHTML_NS);
489 var outline = document.createElementNS(SVG_NS, "path");
490 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));
491 outline.setAttribute("xmlns", XHTML_NS);
492 outline.setAttribute("stroke", "#666");
493 outline.setAttribute("stroke-width", line_width + 2);
494 outline.setAttribute("fill", "none");
495 svg.appendChild(outline);
497 var path = document.createElementNS(SVG_NS, "path");
498 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));
499 path.setAttribute("xmlns", XHTML_NS);
500 path.setAttribute("stroke", arrow.fg_color);
501 path.setAttribute("stroke-width", line_width);
502 path.setAttribute("fill", "none");
503 svg.appendChild(path);
505 // Then the arrow head.
506 var head = document.createElementNS(SVG_NS, "path");
507 head.setAttribute("d",
508 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
509 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
510 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 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, 0, 0));
513 head.setAttribute("xmlns", XHTML_NS);
514 head.setAttribute("stroke", "#000");
515 head.setAttribute("stroke-width", "1");
516 head.setAttribute("fill", arrow.fg_color);
517 svg.appendChild(head);
519 $(svg).css({ top: pos.top, left: pos.left, 'pointer-events': 'none' });
520 document.body.appendChild(svg);
525 * @param {!string} from_square
526 * @param {!string} to_square
527 * @param {!string} fg_color
528 * @param {number} line_width
529 * @param {number} arrow_size
531 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
532 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
533 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
534 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
535 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
543 line_width: line_width,
544 arrow_size: arrow_size,
548 position_arrow(arrow);
552 // Note: invert is ignored.
553 var compare_by_sort_key = function(refutation_lines, invert, a, b) {
554 var ska = refutation_lines[a]['sort_key'];
555 var skb = refutation_lines[b]['sort_key'];
556 if (ska < skb) return -1;
557 if (ska > skb) return 1;
561 var compare_by_score = function(refutation_lines, invert, a, b) {
562 var sa = compute_score_sort_key(refutation_lines[b]['score'], invert);
563 var sb = compute_score_sort_key(refutation_lines[a]['score'], invert);
568 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
569 * sorted by quality, descending.
571 * @param {!Object} data
572 * @param {number} margin The maximum number of centipawns worse than the
573 * best move can be and still be included.
574 * @param {boolean} margin Whether black is to play.
575 * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
576 * moves, in score order.
578 var find_nonstupid_moves = function(data, margin, invert) {
579 // First of all, if there are any moves that are more than 0.5 ahead of
580 // the primary move, the refutation lines are probably bunk, so just
582 var best_score = undefined;
583 var pv_score = undefined;
584 for (var move in data['refutation_lines']) {
585 var score = compute_score_sort_key(data['refutation_lines'][move]['score'], invert);
586 if (move == data['pv_uci'][0]) {
589 if (best_score === undefined || score > best_score) {
592 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
597 if (best_score - pv_score > 50) {
601 // Now find all moves that are within “margin” of the best score.
602 // The PV move will always be first.
604 for (var move in data['refutation_lines']) {
605 var score = compute_score_sort_key(data['refutation_lines'][move]['score'], invert);
606 if (move != data['pv_uci'][0] && best_score - score <= margin) {
610 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], data['position']['toplay'] === 'B', a, b) });
611 moves.unshift(data['pv_uci'][0]);
620 var thousands = function(x) {
621 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
625 * @param {!string} start_fen
626 * @param {Array.<string>} pretty_pv
627 * @param {number} move_num
628 * @param {!string} toplay
629 * @param {!string} score
630 * @param {number} start_display_move_num
631 * @param {number=} opt_limit
632 * @param {boolean=} opt_showlast
634 var add_pv = function(start_fen, pretty_pv, move_num, toplay, score, start_display_move_num, opt_limit, opt_showlast) {
636 start_fen: start_fen,
637 pretty_pv: pretty_pv,
638 move_num: parseInt(move_num),
641 start_display_move_num: start_display_move_num
643 return print_pv(display_lines.length - 1, opt_limit, opt_showlast);
647 * @param {number} line_num
648 * @param {number=} opt_limit If set, show at most this number of moves.
649 * @param {boolean=} opt_showlast If limit is set, show the last moves instead of the first ones.
651 var print_pv = function(line_num, opt_limit, opt_showlast) {
652 var display_line = display_lines[line_num];
653 var pretty_pv = display_line.pretty_pv;
654 var move_num = display_line.move_num;
655 var toplay = display_line.toplay;
657 // Truncate PV at the start if needed.
658 var start_display_move_num = display_line.start_display_move_num;
659 if (start_display_move_num > 0) {
660 pretty_pv = pretty_pv.slice(start_display_move_num);
661 var to_add = start_display_move_num;
662 if (toplay === 'B') {
667 if (to_add % 2 == 1) {
671 move_num += to_add / 2;
676 if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
677 // Truncate the PV at the beginning (instead of at the end).
678 // We assume here that toplay is 'W'. We also assume that if
679 // opt_showlast is set, then it is the history, and thus,
680 // the UI should be to expand the history.
681 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
682 i = pretty_pv.length - opt_limit;
687 } else if (toplay == 'B' && pretty_pv.length > 0) {
688 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
689 pv = move_num + '. … ' + move;
694 for ( ; i < pretty_pv.length; ++i) {
695 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
698 if (i > opt_limit && !opt_showlast) {
704 pv += move_num + '. ' + move;
715 /** Update the highlighted to/from squares on the board.
716 * Based on the global "highlight_from" and "highlight_to" variables.
718 var update_board_highlight = function() {
719 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
720 if ((current_display_line === null || current_display_line_is_history) &&
721 highlight_from !== undefined && highlight_to !== undefined) {
722 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
723 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
727 var update_history = function() {
728 if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
729 $("#history").html("No history");
730 } else if (truncate_display_history) {
731 $("#history").html(print_pv(0, 8, true));
734 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
740 * @param {!boolean} truncate_history
742 var collapse_history = function(truncate_history) {
743 truncate_display_history = truncate_history;
746 window['collapse_history'] = collapse_history;
748 /** Update the HTML display of multi-PV from the global "refutation_lines".
750 * Also recreates the global "display_lines".
752 var update_refutation_lines = function() {
753 if (base_fen === null) {
756 if (display_lines.length > 2) {
757 // Truncate so that only the history and PV is left.
758 display_lines = [ display_lines[0], display_lines[1] ];
760 var tbl = $("#refutationlines");
763 // Find out where the lines start from.
765 var start_display_move_num = 0;
766 if (hash_refutation_lines) {
767 base_line = current_display_line.pretty_pv.slice(0, current_display_move + 1);
768 start_display_move_num = base_line.length;
772 for (var move in refutation_lines) {
776 var invert = (toplay === 'B');
777 if (current_display_line && current_display_move % 2 == 0) {
780 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
781 moves = moves.sort(function(a, b) { return compare(refutation_lines, invert, a, b) });
782 for (var i = 0; i < moves.length; ++i) {
783 var line = refutation_lines[moves[i]];
785 var tr = document.createElement("tr");
787 var move_td = document.createElement("td");
788 tr.appendChild(move_td);
789 $(move_td).addClass("move");
791 if (line['pv_pretty'].length == 0) {
792 // Not found, so just make a one-move PV.
793 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
794 $(move_td).html(move);
795 var score_td = document.createElement("td");
797 $(score_td).addClass("score");
798 $(score_td).text("—");
799 tr.appendChild(score_td);
801 var depth_td = document.createElement("td");
802 tr.appendChild(depth_td);
803 $(depth_td).addClass("depth");
804 $(depth_td).text("—");
806 var pv_td = document.createElement("td");
807 tr.appendChild(pv_td);
808 $(pv_td).addClass("pv");
809 $(pv_td).html(add_pv(base_fen, base_line.concat([ line['pretty_move'] ]), move_num, toplay, line['score'], start_display_move_num));
815 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
816 $(move_td).html(move);
818 var score_td = document.createElement("td");
819 tr.appendChild(score_td);
820 $(score_td).addClass("score");
821 $(score_td).text(format_short_score(line['score']));
823 var depth_td = document.createElement("td");
824 tr.appendChild(depth_td);
825 $(depth_td).addClass("depth");
826 if (line['depth'] && line['depth'] >= 0) {
827 $(depth_td).text("d" + line['depth']);
829 $(depth_td).text("—");
832 var pv_td = document.createElement("td");
833 tr.appendChild(pv_td);
834 $(pv_td).addClass("pv");
835 $(pv_td).html(add_pv(base_fen, base_line.concat(line['pv_pretty']), move_num, toplay, line['score'], start_display_move_num, 10));
840 // Make one of the links clickable and the other nonclickable.
841 if (sort_refutation_lines_by_score) {
842 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
843 $("#sortbyscore1").html("<strong>Score</strong>");
845 $("#sortbyscore0").html("<strong>Move</strong>");
846 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
849 // Update the move highlight, as we've rewritten all the HTML.
850 update_move_highlight();
854 * Create a Chess.js board object, containing the given position plus the given moves,
855 * up to the given limit.
857 * @param {?string} fen
858 * @param {Array.<string>} moves
859 * @param {number} last_move
861 var chess_from = function(fen, moves, last_move) {
862 var hiddenboard = new Chess();
864 hiddenboard.load(fen);
866 for (var i = 0; i <= last_move; ++i) {
867 if (moves[i] === '0-0') {
868 hiddenboard.move('O-O');
869 } else if (moves[i] === '0-0-0') {
870 hiddenboard.move('O-O-O');
872 hiddenboard.move(moves[i]);
878 var update_game_list = function(games) {
879 $("#games").text("");
880 if (games === null) {
884 var games_div = document.getElementById('games');
885 for (var game_num = 0; game_num < games.length; ++game_num) {
886 var game = games[game_num];
887 var game_span = document.createElement("span");
888 game_span.setAttribute("class", "game");
890 var game_name = document.createTextNode(game['name']);
891 if (game['url'] === backend_url) {
892 game_span.appendChild(game_name);
894 var game_a = document.createElement("a");
895 game_a.setAttribute("href", "#" + game['id']);
896 game_a.appendChild(game_name);
897 game_span.appendChild(game_a);
900 var score = " (" + format_short_score(game['score']) + ")";
901 game_span.appendChild(document.createTextNode(score));
903 games_div.appendChild(game_span);
908 * Try to find a running game that matches with the current hash,
909 * and switch to it if we're not already displaying it.
911 var possibly_switch_game_from_hash = function() {
912 if (current_games === null) {
916 var hash = window.location.hash.replace(/^#/,'');
917 for (var i = 0; i < current_games.length; ++i) {
918 if (current_games[i]['id'] === hash) {
919 if (backend_url !== current_games[i]['url']) {
920 switch_backend(current_games[i]['url'], current_games[i]['hashurl']);
927 /** Update all the HTML on the page, based on current global state.
929 var update_board = function() {
930 var data = displayed_analysis_data || current_analysis_data;
931 var current_data = current_analysis_data; // Convenience alias.
935 // Print the history. This is pretty much the only thing that's
936 // unconditionally taken from current_data (we're not interested in
937 // historic history).
938 if (current_data['position']['pretty_history']) {
939 add_pv('start', current_data['position']['pretty_history'], 1, 'W', null, 0, 8, true);
941 display_lines.push(null);
945 // Games currently in progress, if any.
946 if (current_data['games']) {
947 current_games = current_data['games'];
948 possibly_switch_game_from_hash();
949 update_game_list(current_data['games']);
951 current_games = null;
952 update_game_list(null);
955 // The headline. Names are always fetched from current_data;
956 // the rest can depend a bit.
959 current_data['position']['player_w'] && current_data['position']['player_b']) {
960 headline = current_data['position']['player_w'] + '–' +
961 current_data['position']['player_b'] + ', analysis';
963 headline = 'Analysis';
966 // Credits, where applicable. Note that we don't want the footer to change a lot
967 // when e.g. viewing history, so if any of these changed during the game,
968 // use the current one still.
969 if (current_data['using_lomonosov']) {
970 $("#lomonosov").show();
972 $("#lomonosov").hide();
975 // Credits: The engine name/version.
976 if (current_data['engine'] && current_data['engine']['name'] !== null) {
977 $("#engineid").text(current_data['engine']['name']);
980 // Credits: The engine URL.
981 if (current_data['engine'] && current_data['engine']['url']) {
982 $("#engineid").attr("href", current_data['engine']['url']);
984 $("#engineid").removeAttr("href");
987 // Credits: Engine details.
988 if (current_data['engine'] && current_data['engine']['details']) {
989 $("#enginedetails").text(" (" + current_data['engine']['details'] + ")");
991 $("#enginedetails").text("");
994 // Credits: Move source, possibly with URL.
995 if (current_data['move_source'] && current_data['move_source_url']) {
996 $("#movesource").text("Moves provided by ");
997 var movesource_a = document.createElement("a");
998 movesource_a.setAttribute("href", current_data['move_source_url']);
999 var movesource_text = document.createTextNode(current_data['move_source']);
1000 movesource_a.appendChild(movesource_text);
1001 var movesource_period = document.createTextNode(".");
1002 document.getElementById("movesource").appendChild(movesource_a);
1003 document.getElementById("movesource").appendChild(movesource_period);
1004 } else if (current_data['move_source']) {
1005 $("#movesource").text("Moves provided by " + current_data['move_source'] + ".");
1007 $("#movesource").text("");
1011 if (displayed_analysis_data) {
1012 // Displaying some non-current position, pick out the last move
1013 // from the history. This will work even if the fetch failed.
1014 last_move = format_halfmove_with_number(
1015 current_display_line.pretty_pv[current_display_move],
1016 current_display_move + 1);
1017 headline += ' after ' + last_move;
1018 } else if (data['position']['last_move'] !== 'none') {
1019 last_move = format_move_with_number(
1020 data['position']['last_move'],
1021 data['position']['move_num'],
1022 data['position']['toplay'] == 'W');
1023 headline += ' after ' + last_move;
1027 $("#headline").text(headline);
1029 // The <title> contains a very brief headline.
1030 var title_elems = [];
1031 if (data['score']) {
1032 title_elems.push(format_short_score(data['score']).replace(/^ /, ""));
1034 if (last_move !== null) {
1035 title_elems.push(last_move);
1038 if (title_elems.length != 0) {
1039 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
1041 document.title = 'analysis.sesse.net';
1044 // The last move (shown by highlighting the from and to squares).
1045 if (data['position'] && data['position']['last_move_uci']) {
1046 highlight_from = data['position']['last_move_uci'].substr(0, 2);
1047 highlight_to = data['position']['last_move_uci'].substr(2, 2);
1048 } else if (current_display_line_is_history && current_display_move >= 0) {
1049 // We don't have historic analysis for this position, but we
1050 // can reconstruct what the last move was by just replaying
1052 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1053 var moves = hiddenboard.history({ verbose: true });
1054 var last_move = moves.pop();
1055 highlight_from = last_move.from;
1056 highlight_to = last_move.to;
1058 highlight_from = highlight_to = undefined;
1060 update_board_highlight();
1062 if (data['failed']) {
1063 $("#score").text("No analysis for this move");
1064 $("#pvtitle").text("PV:");
1066 $("#searchstats").html(" ");
1067 $("#refutationlines").empty();
1068 $("#whiteclock").empty();
1069 $("#blackclock").empty();
1070 refutation_lines = [];
1071 update_refutation_lines();
1073 update_displayed_line();
1074 update_move_highlight();
1081 if (current_display_line) {
1082 if (current_display_line.score) {
1083 $("#score").text(format_long_score(current_display_line.score));
1085 $("#score").text("No score for this move");
1087 } else if (data['score']) {
1088 $("#score").text(format_long_score(data['score']));
1091 // The search stats.
1092 if (data['searchstats']) {
1093 $("#searchstats").html(data['searchstats']);
1094 } else if (data['tablebase'] == 1) {
1095 $("#searchstats").text("Tablebase result");
1096 } else if (data['nodes'] && data['nps'] && data['depth']) {
1097 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
1098 if (data['seldepth']) {
1099 stats += ' (' + data['seldepth'] + ' selective)';
1101 if (data['tbhits'] && data['tbhits'] > 0) {
1102 if (data['tbhits'] == 1) {
1103 stats += ', one Syzygy hit';
1105 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
1109 $("#searchstats").text(stats);
1111 $("#searchstats").text("");
1114 // Update the board itself.
1115 base_fen = data['position']['fen'];
1116 update_displayed_line();
1119 $("#pvtitle").text("PV:");
1120 $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay'], data['score'], 0));
1122 // Update the PV arrow.
1124 if (data['pv_uci'].length >= 1) {
1125 // draw a continuation arrow as long as it's the same piece
1126 for (var i = 0; i < data['pv_uci'].length; i += 2) {
1127 var from = data['pv_uci'][i].substr(0, 2);
1128 var to = data['pv_uci'][i].substr(2,4);
1129 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
1130 interfering_arrow(from, to)) {
1133 create_arrow(from, to, '#f66', 6, 20);
1136 var alt_moves = find_nonstupid_moves(data, 30, data['position']['toplay'] === 'B');
1137 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
1138 create_arrow(alt_moves[i].substr(0, 2),
1139 alt_moves[i].substr(2, 2), '#f66', 1, 10);
1143 // See if all semi-reasonable moves have only one possible response.
1144 if (data['pv_uci'].length >= 2) {
1145 var nonstupid_moves = find_nonstupid_moves(data, 300, data['position']['toplay'] === 'B');
1146 var response = data['pv_uci'][1];
1147 for (var i = 0; i < nonstupid_moves.length; ++i) {
1148 if (nonstupid_moves[i] == data['pv_uci'][0]) {
1149 // ignore the PV move for refutation lines.
1152 if (!data['refutation_lines'] ||
1153 !data['refutation_lines'][nonstupid_moves[i]] ||
1154 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
1155 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
1156 // Incomplete PV, abort.
1157 response = undefined;
1160 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
1161 if (response !== this_response) {
1162 // Different response depending on lines, abort.
1163 response = undefined;
1168 if (nonstupid_moves.length > 0 && response !== undefined) {
1169 create_arrow(response.substr(0, 2),
1170 response.substr(2, 2), '#66f', 6, 20);
1174 // Update the refutation lines.
1175 base_fen = data['position']['fen'];
1176 move_num = parseInt(data['position']['move_num']);
1177 toplay = data['position']['toplay'];
1178 refutation_lines = hash_refutation_lines || data['refutation_lines'];
1179 update_refutation_lines();
1181 // Update the sparkline last, since its size depends on how everything else reflowed.
1182 update_sparkline(data);
1185 var update_sparkline = function(data) {
1186 if (data && data['score_history']) {
1187 var first_move_num = undefined;
1188 for (var halfmove_num in data['score_history']) {
1189 halfmove_num = parseInt(halfmove_num);
1190 if (first_move_num === undefined || halfmove_num < first_move_num) {
1191 first_move_num = halfmove_num;
1194 if (first_move_num !== undefined) {
1195 var last_move_num = data['position']['move_num'] * 2 - 3;
1196 if (data['position']['toplay'] === 'B') {
1200 // Possibly truncate some moves if we don't have enough width.
1201 // FIXME: Sometimes width() for #scorecontainer (and by extent,
1202 // #scoresparkcontainer) on Chrome for mobile seems to start off
1203 // at something very small, and then suddenly snap back into place.
1205 var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
1206 if (last_move_num - first_move_num > max_moves) {
1207 first_move_num = last_move_num - max_moves;
1210 var min_score = -100;
1211 var max_score = 100;
1212 var last_score = null;
1214 for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1215 if (data['score_history'][halfmove_num]) {
1216 var score = compute_plot_score(data['score_history'][halfmove_num]);
1218 if (score < min_score) min_score = score;
1219 if (score > max_score) max_score = score;
1221 scores.push(last_score);
1223 if (data['score']) {
1224 scores.push(compute_plot_score(data['score']));
1226 // FIXME: at some widths, calling sparkline() seems to push
1227 // #scorecontainer under the board.
1228 $("#scorespark").sparkline(scores, {
1231 chartRangeMin: min_score,
1232 chartRangeMax: max_score,
1233 tooltipFormatter: function(sparkline, options, fields) {
1234 return format_tooltip(data, fields[0].offset + first_move_num);
1238 $("#scorespark").text("");
1241 $("#scorespark").text("");
1246 * @param {number} num_viewers
1248 var update_num_viewers = function(num_viewers) {
1249 if (num_viewers === null) {
1250 $("#numviewers").text("");
1251 } else if (num_viewers == 1) {
1252 $("#numviewers").text("You are the only current viewer");
1254 $("#numviewers").text(num_viewers + " current viewers");
1258 var update_clock = function() {
1259 clearTimeout(clock_timer);
1261 var data = displayed_analysis_data || current_analysis_data;
1262 if (data['position']) {
1263 var result = data['position']['result'];
1264 if (result === '1-0') {
1265 $("#whiteclock").text("1");
1266 $("#blackclock").text("0");
1267 $("#whiteclock").removeClass("running-clock");
1268 $("#blackclock").removeClass("running-clock");
1271 if (result === '1/2-1/2') {
1272 $("#whiteclock").text("1/2");
1273 $("#blackclock").text("1/2");
1274 $("#whiteclock").removeClass("running-clock");
1275 $("#blackclock").removeClass("running-clock");
1278 if (result === '0-1') {
1279 $("#whiteclock").text("0");
1280 $("#blackclock").text("1");
1281 $("#whiteclock").removeClass("running-clock");
1282 $("#blackclock").removeClass("running-clock");
1287 var white_clock_ms = null;
1288 var black_clock_ms = null;
1289 var show_seconds = false;
1292 if (data['position'] &&
1293 data['position']['white_clock'] &&
1294 data['position']['black_clock']) {
1295 white_clock_ms = data['position']['white_clock'] * 1000;
1296 black_clock_ms = data['position']['black_clock'] * 1000;
1299 // Dynamic clock (only one, obviously).
1301 if (data['position']['white_clock_target']) {
1303 $("#whiteclock").addClass("running-clock");
1304 $("#blackclock").removeClass("running-clock");
1305 } else if (data['position']['black_clock_target']) {
1307 $("#whiteclock").removeClass("running-clock");
1308 $("#blackclock").addClass("running-clock");
1310 $("#whiteclock").removeClass("running-clock");
1311 $("#blackclock").removeClass("running-clock");
1315 var now = new Date().getTime() + client_clock_offset_ms;
1316 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1317 if (color === "white") {
1318 white_clock_ms = remaining_ms;
1320 black_clock_ms = remaining_ms;
1324 if (white_clock_ms === null || black_clock_ms === null) {
1325 $("#whiteclock").empty();
1326 $("#blackclock").empty();
1330 // If either player has ten minutes or less left, add the second counters.
1331 var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
1334 // See when the clock will change next, and update right after that.
1337 next_update_ms = remaining_ms % 1000 + 100;
1339 next_update_ms = remaining_ms % 60000 + 100;
1341 clock_timer = setTimeout(update_clock, next_update_ms);
1344 $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1345 $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1349 * @param {Number} remaining_ms
1350 * @param {boolean} show_seconds
1352 var format_clock = function(remaining_ms, show_seconds) {
1353 if (remaining_ms <= 0) {
1361 var remaining = Math.floor(remaining_ms / 1000);
1362 var seconds = remaining % 60;
1363 remaining = (remaining - seconds) / 60;
1364 var minutes = remaining % 60;
1365 remaining = (remaining - minutes) / 60;
1366 var hours = remaining;
1368 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1370 return format_2d(hours) + ":" + format_2d(minutes);
1377 var format_2d = function(x) {
1386 * @param {string} move
1387 * @param {Number} move_num
1388 * @param {boolean} white_to_play
1390 var format_move_with_number = function(move, move_num, white_to_play) {
1392 if (white_to_play) {
1393 ret = (move_num - 1) + '… ';
1395 ret = move_num + '. ';
1402 * @param {string} move
1403 * @param {Number} halfmove_num
1405 var format_halfmove_with_number = function(move, halfmove_num) {
1406 return format_move_with_number(
1408 Math.floor(halfmove_num / 2) + 1,
1409 halfmove_num % 2 == 0);
1413 * @param {Object} data
1414 * @param {Number} halfmove_num
1416 var format_tooltip = function(data, halfmove_num) {
1417 if (data['score_history'][halfmove_num] ||
1418 halfmove_num === data['position']['pretty_history'].length) {
1421 if (halfmove_num === data['position']['pretty_history'].length) {
1422 move = data['position']['last_move'];
1423 short_score = format_short_score(data['score']);
1425 move = data['position']['pretty_history'][halfmove_num];
1426 short_score = format_short_score(data['score_history'][halfmove_num]);
1428 var move_with_number = format_halfmove_with_number(move, halfmove_num);
1430 return "After " + move_with_number + ": " + short_score;
1432 for (var i = halfmove_num; i --> 0; ) {
1433 if (data['score_history'][i]) {
1434 var move = data['position']['pretty_history'][i];
1435 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1442 * @param {boolean} sort_by_score
1444 var resort_refutation_lines = function(sort_by_score) {
1445 sort_refutation_lines_by_score = sort_by_score;
1446 if (supports_html5_storage()) {
1447 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1449 update_refutation_lines();
1451 window['resort_refutation_lines'] = resort_refutation_lines;
1454 * @param {boolean} truncate_history
1456 var set_truncate_history = function(truncate_history) {
1457 truncate_display_history = truncate_history;
1458 update_refutation_lines();
1460 window['set_truncate_history'] = set_truncate_history;
1463 * @param {number} line_num
1464 * @param {number} move_num
1466 var show_line = function(line_num, move_num) {
1467 if (line_num == -1) {
1468 current_display_line = null;
1469 current_display_move = null;
1470 hash_refutation_lines = null;
1471 if (displayed_analysis_data) {
1472 // TODO: Support exiting to history position if we are in an
1473 // analysis line of a history position.
1474 displayed_analysis_data = null;
1479 current_display_line = jQuery.extend({}, display_lines[line_num]); // Shallow clone.
1480 current_display_move = move_num + current_display_line.start_display_move_num;
1482 current_display_line_is_history = (line_num == 0);
1484 update_historic_analysis();
1485 update_displayed_line();
1486 update_board_highlight();
1487 update_move_highlight();
1490 window['show_line'] = show_line;
1492 var prev_move = function() {
1493 if (current_display_line &&
1494 current_display_move >= current_display_line.start_display_move_num) {
1495 --current_display_move;
1497 update_historic_analysis();
1498 update_displayed_line();
1499 update_move_highlight();
1501 window['prev_move'] = prev_move;
1503 var next_move = function() {
1504 if (current_display_line &&
1505 current_display_move < current_display_line.pretty_pv.length - 1) {
1506 ++current_display_move;
1508 update_historic_analysis();
1509 update_displayed_line();
1510 update_move_highlight();
1512 window['next_move'] = next_move;
1514 var update_historic_analysis = function() {
1515 if (!current_display_line_is_history) {
1518 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1519 displayed_analysis_data = null;
1523 // Fetch old analysis for this line if it exists.
1524 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1525 var filename = "/history/move" + (current_display_move + 1) + "-" +
1526 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1528 current_historic_xhr = $.ajax({
1530 }).done(function(data, textstatus, xhr) {
1531 displayed_analysis_data = data;
1533 }).fail(function(jqXHR, textStatus, errorThrown) {
1534 if (textStatus === "abort") {
1535 // Aborted because we are switching backends. Don't do anything;
1536 // we will already have been cleared.
1538 displayed_analysis_data = {'failed': true};
1545 * @param {string} fen
1547 var update_imbalance = function(fen) {
1548 var hiddenboard = new Chess(fen);
1549 var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1550 for (var row = 0; row < 8; ++row) {
1551 for (var col = 0; col < 8; ++col) {
1552 var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1553 var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1554 var square = col_text + row_text;
1555 var contents = hiddenboard.get(square);
1556 if (contents !== null) {
1557 if (contents.color === 'w') {
1558 ++imbalance[contents.type];
1560 --imbalance[contents.type];
1565 var white_imbalance = '';
1566 var black_imbalance = '';
1567 for (var piece in imbalance) {
1568 for (var i = 0; i < imbalance[piece]; ++i) {
1569 white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1571 for (var i = 0; i < -imbalance[piece]; ++i) {
1572 black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1575 $('#whiteimbalance').html(white_imbalance);
1576 $('#blackimbalance').html(black_imbalance);
1579 /** Mark the currently selected move in red.
1580 * Also replaces the PV with the current displayed line if it's not shown
1581 * anywhere else on the screen.
1583 var update_move_highlight = function() {
1584 if (highlighted_move !== null) {
1585 highlighted_move.removeClass('highlight');
1587 if (current_display_line) {
1588 var display_line_num = find_display_line_matching_num();
1589 if (display_line_num === null) {
1590 // Replace the PV with the (complete) line.
1591 $("#pvtitle").text("Exploring:");
1592 current_display_line.start_display_move_num = 0;
1593 display_lines.push(current_display_line);
1594 $("#pv").html(print_pv(display_lines.length - 1));
1595 display_line_num = display_lines.length - 1;
1598 highlighted_move = $("#automove" + display_line_num + "-" + (current_display_move - current_display_line.start_display_move_num));
1599 highlighted_move.addClass('highlight');
1604 * See if the current displayed line is identical to any of the ones
1605 * we have on screen. (It might not be if e.g. the analysis reloaded
1606 * since we started looking.)
1610 var find_display_line_matching_num = function() {
1611 for (var i = 0; i < display_lines.length; ++i) {
1612 var line = display_lines[i];
1613 if (line.start_display_move_num > 0) continue;
1614 if (current_display_line.start_fen !== line.start_fen) continue;
1615 if (current_display_line.pretty_pv.length !== line.pretty_pv.length) continue;
1617 for (var j = 0; j < line.pretty_pv.length; ++j) {
1618 if (current_display_line.pretty_pv[j] !== line.pretty_pv[j]) {
1630 var update_displayed_line = function() {
1631 if (current_display_line === null) {
1632 $("#linenav").hide();
1633 $("#linemsg").show();
1634 display_fen = base_fen;
1635 board.position(base_fen);
1636 update_imbalance(base_fen);
1640 $("#linenav").show();
1641 $("#linemsg").hide();
1643 if (current_display_move <= 0) {
1644 $("#prevmove").html("Previous");
1646 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1648 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1649 $("#nextmove").html("Next");
1651 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1654 var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pretty_pv, current_display_move);
1655 display_fen = hiddenboard.fen();
1656 board_is_animating = true;
1657 var old_fen = board.fen();
1658 board.position(hiddenboard.fen());
1659 if (board.fen() === old_fen) {
1660 board_is_animating = false;
1661 } else if (!current_display_line_is_history) {
1662 // Fire off a hash request, since we're now off the main position
1663 // and it just changed.
1664 explore_hash(display_fen);
1666 update_imbalance(hiddenboard.fen());
1670 * @param {boolean} param_enable_sound
1672 var set_sound = function(param_enable_sound) {
1673 enable_sound = param_enable_sound;
1675 $("#soundon").html("<strong>On</strong>");
1676 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1678 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1679 // and also preload the file since the user has selected audio.
1680 var ding = document.getElementById('ding');
1681 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1682 ding.src = 'ding.opus';
1686 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1687 $("#soundoff").html("<strong>Off</strong>");
1689 if (supports_html5_storage()) {
1690 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1693 window['set_sound'] = set_sound;
1695 /** Send off a hash probe request to the backend.
1696 * @param {string} fen
1698 var explore_hash = function(fen) {
1699 // If we already have a backend response going, abort it.
1700 if (current_hash_xhr) {
1701 current_hash_xhr.abort();
1703 if (current_hash_display_timer) {
1704 clearTimeout(current_hash_display_timer);
1705 current_hash_display_timer = null;
1707 $("#refutationlines").empty();
1708 current_hash_xhr = $.ajax({
1709 url: backend_hash_url + "?fen=" + fen
1710 }).done(function(data, textstatus, xhr) {
1711 show_explore_hash_results(data, fen);
1715 /** Process the JSON response from a hash probe request.
1716 * @param {!Object} data
1717 * @param {string} fen
1719 var show_explore_hash_results = function(data, fen) {
1720 if (board_is_animating) {
1721 // Updating while the animation is still going causes
1722 // the animation to jerk. This is pretty crude, but it will do.
1723 current_hash_display_timer = setTimeout(function() { show_explore_hash_results(data, fen); }, 100);
1726 current_hash_display_timer = null;
1727 hash_refutation_lines = data['lines'];
1731 // almost all of this stuff comes from the chessboard.js example page
1732 var onDragStart = function(source, piece, position, orientation) {
1733 var pseudogame = new Chess(display_fen);
1734 if (pseudogame.game_over() === true ||
1735 (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
1736 (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
1740 recommended_move = get_best_move(pseudogame, source, null, pseudogame.turn() === 'b');
1741 if (recommended_move) {
1742 var squareEl = $('#board .square-' + recommended_move.to);
1743 squareEl.addClass('highlight1-32417');
1748 var mousedownSquare = function(e) {
1749 reverse_dragging_from = null;
1750 var square = $(this).attr('data-square');
1752 var pseudogame = new Chess(display_fen);
1753 if (pseudogame.game_over() === true) {
1757 // If the square is empty, or has a piece of the side not to move,
1758 // we handle it. If not, normal piece dragging will take it.
1759 var position = board.position();
1760 if (!position.hasOwnProperty(square) ||
1761 (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
1762 (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
1763 reverse_dragging_from = square;
1764 recommended_move = get_best_move(pseudogame, null, square, pseudogame.turn() === 'b');
1765 if (recommended_move) {
1766 var squareEl = $('#board .square-' + recommended_move.from);
1767 squareEl.addClass('highlight1-32417');
1768 squareEl = $('#board .square-' + recommended_move.to);
1769 squareEl.addClass('highlight1-32417');
1774 var mouseupSquare = function(e) {
1775 if (reverse_dragging_from === null) {
1778 var source = $(this).attr('data-square');
1779 var target = reverse_dragging_from;
1780 reverse_dragging_from = null;
1781 if (onDrop(source, target) !== 'snapback') {
1782 onSnapEnd(source, target);
1784 $("#board").find('.square-55d63').removeClass('highlight1-32417');
1787 var get_best_move = function(game, source, target, invert) {
1788 var moves = game.moves({ verbose: true });
1789 if (source !== null) {
1790 moves = moves.filter(function(move) { return move.from == source; });
1792 if (target !== null) {
1793 moves = moves.filter(function(move) { return move.to == target; });
1795 if (moves.length == 0) {
1798 if (moves.length == 1) {
1802 // More than one move. Use the display lines (if we have them)
1803 // to disambiguate; otherwise, we have no information.
1805 for (var i = 0; i < moves.length; ++i) {
1806 move_hash[moves[i].san] = moves[i];
1809 // See if we're already exploring some line.
1810 if (current_display_line &&
1811 current_display_move < current_display_line.pretty_pv.length - 1) {
1812 var first_move = current_display_line.pretty_pv[current_display_move + 1];
1813 if (move_hash[first_move]) {
1814 return move_hash[first_move];
1818 // History and PV take priority over the display lines.
1819 for (var i = 0; i < 2; ++i) {
1820 var line = display_lines[i];
1821 var first_move = line.pretty_pv[line.start_display_move_num];
1822 if (move_hash[first_move]) {
1823 return move_hash[first_move];
1827 var best_move = null;
1828 var best_move_score = null;
1830 for (var move in refutation_lines) {
1831 var line = refutation_lines[move];
1832 if (!line['score']) {
1835 var first_move = line['pv_pretty'][0];
1836 if (move_hash[first_move]) {
1837 var score = compute_score_sort_key(line['score'], invert);
1838 if (best_move_score === null || score > best_move_score) {
1839 best_move = move_hash[first_move];
1840 best_move_score = score;
1847 var onDrop = function(source, target) {
1848 if (source === target) {
1849 if (recommended_move === null) {
1852 // Accept the move. It will be changed in onSnapEnd.
1856 // Suggestion not asked for.
1857 recommended_move = null;
1860 // see if the move is legal
1861 var pseudogame = new Chess(display_fen);
1862 var move = pseudogame.move({
1865 promotion: 'q' // NOTE: always promote to a queen for example simplicity
1869 if (move === null) return 'snapback';
1872 var onSnapEnd = function(source, target) {
1873 if (source === target && recommended_move !== null) {
1874 source = recommended_move.from;
1875 target = recommended_move.to;
1877 recommended_move = null;
1878 var pseudogame = new Chess(display_fen);
1879 var move = pseudogame.move({
1882 promotion: 'q' // NOTE: always promote to a queen for example simplicity
1885 if (current_display_line &&
1886 current_display_move < current_display_line.pretty_pv.length - 1 &&
1887 current_display_line.pretty_pv[current_display_move + 1] === move.san) {
1892 // Walk down the displayed lines until we find one that starts with
1893 // this move, then select that. Note that this gives us a good priority
1894 // order (history first, then PV, then multi-PV lines).
1895 for (var i = 0; i < display_lines.length; ++i) {
1896 var line = display_lines[i];
1897 if (line.pretty_pv[line.start_display_move_num] === move.san) {
1903 // Shouldn't really be here if we have hash probes, but there's really
1904 // nothing we can do.
1906 // End of dragging-related code.
1908 var pad = function(val, num_digits) {
1909 var s = val.toString();
1910 while (s.length < num_digits) {
1916 var fmt_cp = function(v) {
1920 return "+" + (v / 100).toFixed(2);
1923 return "-" + (v / 100).toFixed(2);
1927 var format_short_score = function(score) {
1931 if (score[0] === 'm') {
1932 if (score[2]) { // Is a bound.
1933 return score[2] + "\u00a0M" + pad(score[1], 3);
1935 return "M" + pad(score[1], 3);
1937 } else if (score[0] === 'd') {
1939 } else if (score[0] === 'cp') {
1940 if (score[2]) { // Is a bound.
1941 return score[2] + "\u00a0" + fmt_cp(score[1]);
1943 return pad(fmt_cp(score[1]), 5);
1949 var format_long_score = function(score) {
1950 if (score[0] === 'm') {
1952 return "White mates in " + score[1];
1954 return "Black mates in " + (-score[1]);
1956 } else if (score[0] === 'd') {
1957 return "Theoretical draw";
1958 } else if (score[0] === 'cp') {
1959 return "Score: " + format_short_score(score);
1964 var compute_plot_score = function(score) {
1965 if (score[0] === 'm') {
1971 } else if (score[0] === 'd') {
1973 } else if (score[0] === 'cp') {
1974 if (score[1] > 500) {
1976 } else if (score[1] < -500) {
1986 * @param score The score digest tuple.
1987 * @param {boolean} invert Whether black is to play.
1990 var compute_score_sort_key = function(score, invert) {
1995 if (score[0] === 'm') {
1998 s = 99999 - score[1];
2000 // Black mates (note the double negative for score[1]).
2001 s = -99999 - score[1];
2005 } else if (score[0] === 'd') {
2007 } else if (score[0] === 'cp') {
2008 return invert ? -score[1] : score[1];
2014 * @param {string} new_backend_url
2016 var switch_backend = function(new_backend_url, new_backend_hash_url) {
2017 // Stop looking at historic data.
2018 current_display_line = null;
2019 current_display_move = null;
2020 displayed_analysis_data = null;
2021 if (current_historic_xhr) {
2022 current_historic_xhr.abort();
2025 // If we already have a backend response going, abort it.
2026 if (current_analysis_xhr) {
2027 current_analysis_xhr.abort();
2029 if (current_hash_xhr) {
2030 current_hash_xhr.abort();
2033 // Otherwise, we should have a timer going to start a new one.
2035 if (current_analysis_request_timer) {
2036 clearTimeout(current_analysis_request_timer);
2037 current_analysis_request_timer = null;
2039 if (current_hash_display_timer) {
2040 clearTimeout(current_hash_display_timer);
2041 current_hash_display_timer = null;
2044 // Request an immediate fetch with the new backend.
2045 backend_url = new_backend_url;
2046 backend_hash_url = new_backend_hash_url;
2047 current_analysis_data = null;
2051 window['switch_backend'] = switch_backend;
2053 var init = function() {
2054 unique = get_unique();
2056 // Load settings from HTML5 local storage if available.
2057 if (supports_html5_storage() && localStorage['enable_sound']) {
2058 set_sound(parseInt(localStorage['enable_sound']));
2062 if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
2063 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
2065 sort_refutation_lines_by_score = true;
2069 board = new window.ChessBoard('board', {
2070 onMoveEnd: function() { board_is_animating = false; },
2073 onDragStart: onDragStart,
2075 onSnapEnd: onSnapEnd
2077 $("#board").on('mousedown', '.square-55d63', mousedownSquare);
2078 $("#board").on('mouseup', '.square-55d63', mouseupSquare);
2081 $(window).resize(function() {
2083 update_sparkline(displayed_analysis_data || current_analysis_data);
2084 update_board_highlight();
2087 $(window).keyup(function(event) {
2088 if (event.which == 39) {
2090 } else if (event.which == 37) {
2094 window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
2096 $(document).ready(init);