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 = 2016032000;
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.
54 var current_games = null;
69 /** @type {Array.<Array.<boolean>>} */
70 var occupied_by_arrows = [];
72 /** Currently displayed refutation lines (on-screen).
73 * Can either come from the current_analysis_data, displayed_analysis_data,
74 * or hash_refutation_lines.
76 var refutation_lines = [];
78 /** Refutation lines from current hash probe.
80 * If non-null, will override refutation lines from the base position.
81 * Note that these are relative to display_fen, not base_fen.
83 var hash_refutation_lines = null;
85 /** @type {!number} @private */
88 /** @type {!string} @private */
91 /** @type {number} @private */
94 /** @type {boolean} @private */
95 var sort_refutation_lines_by_score = true;
97 /** @type {boolean} @private */
98 var truncate_display_history = true;
100 /** @type {!string|undefined} @private */
101 var highlight_from = undefined;
103 /** @type {!string|undefined} @private */
104 var highlight_to = undefined;
106 /** The HTML object of the move currently being highlighted (in red).
109 var highlighted_move = null;
111 /** Currently suggested/recommended move when dragging.
112 * @type {?{from: !string, to: !string}}
115 var recommended_move = null;
117 /** If reverse-dragging (dragging from the destination square to the
118 * source square), the destination square.
122 var reverse_dragging_from = null;
124 /** @type {?number} @private */
127 /** @type {boolean} @private */
128 var enable_sound = false;
131 * Our best estimate of how many milliseconds we need to add to
132 * new Date() to get the true UTC time. Calibrated against the
138 var client_clock_offset_ms = null;
140 var clock_timer = null;
142 /** The current position being analyzed, represented as a FEN string.
143 * Note that this is not necessarily the same as display_fen.
149 /** The current position on the board, represented as a FEN string.
150 * Note that board.fen() does not contain e.g. who is to play.
154 var display_fen = null;
158 * pretty_pv: Array.<string>,
162 * start_display_move_num: number
165 * "start_display_move_num" is the (half-)move number to start displaying the PV at.
166 * "score" is also evaluated at this point.
169 /** All PVs that we currently know of.
171 * Element 0 is history (or null if no history).
172 * Element 1 is current main PV, or explored line if nowhere else on the screen.
173 * All remaining elements are refutation lines (multi-PV).
175 * @type {Array.<DisplayLine>}
178 var display_lines = [];
180 /** @type {?DisplayLine} @private */
181 var current_display_line = null;
183 /** @type {boolean} @private */
184 var current_display_line_is_history = false;
186 /** @type {?number} @private */
187 var current_display_move = null;
190 * The current backend request to get main analysis (not history), if any,
191 * so that we can abort it.
196 var current_analysis_xhr = null;
199 * The current timer to fire off a request to get main analysis (not history),
200 * if any, so that we can abort it.
205 var current_analysis_request_timer = null;
208 * The current backend request to get historic data, if any.
213 var current_historic_xhr = null;
216 * The current backend request to get hash probes, if any, so that we can abort it.
221 var current_hash_xhr = null;
224 * The current timer to display hash probe information (it could be waiting on the
225 * board to stop animating), if any, so that we can abort it.
230 var current_hash_display_timer = null;
232 var supports_html5_storage = function() {
234 return 'localStorage' in window && window['localStorage'] !== null;
240 // Make the unique token persistent so people refreshing the page won't count twice.
241 // Of course, you can never fully protect against people deliberately wanting to spam.
242 var get_unique = function() {
243 var use_local_storage = supports_html5_storage();
244 if (use_local_storage && localStorage['unique']) {
245 return localStorage['unique'];
247 var unique = Math.random();
248 if (use_local_storage) {
249 localStorage['unique'] = unique;
254 var request_update = function() {
255 current_analysis_request_timer = null;
257 current_analysis_xhr = $.ajax({
258 url: backend_url + "?ims=" + ims + "&unique=" + unique
259 }).done(function(data, textstatus, xhr) {
260 sync_server_clock(xhr.getResponseHeader('Date'));
261 ims = xhr.getResponseHeader('X-RGLM');
262 var num_viewers = xhr.getResponseHeader('X-RGNV');
264 if (Array.isArray(data)) {
265 new_data = JSON.parse(JSON.stringify(current_analysis_data));
266 JSON_delta.patch(new_data, data);
271 var minimum_version = xhr.getResponseHeader('X-RGMV');
272 if (minimum_version && minimum_version > SCRIPT_VERSION) {
273 // Upgrade to latest version with a force-reload.
274 location.reload(true);
277 possibly_play_sound(current_analysis_data, new_data);
278 current_analysis_data = new_data;
280 update_num_viewers(num_viewers);
283 current_analysis_request_timer = setTimeout(function() { request_update(); }, 100);
284 }).fail(function(jqXHR, textStatus, errorThrown) {
285 if (textStatus === "abort") {
286 // Aborted because we are switching backends. Abandon and don't retry,
287 // because another one is already started for us.
289 // Backend error or similar. Wait ten seconds, then try again.
290 current_analysis_request_timer = setTimeout(function() { request_update(); }, 10000);
295 var possibly_play_sound = function(old_data, new_data) {
299 if (old_data === null) {
302 var ding = document.getElementById('ding');
303 if (ding && ding.play) {
304 if (old_data['position'] && old_data['position']['fen'] &&
305 new_data['position'] && new_data['position']['fen'] &&
306 (old_data['position']['fen'] !== new_data['position']['fen'] ||
307 old_data['position']['move_num'] !== new_data['position']['move_num'])) {
314 * @type {!string} server_date_string
316 var sync_server_clock = function(server_date_string) {
317 var server_time_ms = new Date(server_date_string).getTime();
318 var client_time_ms = new Date().getTime();
319 var estimated_offset_ms = server_time_ms - client_time_ms;
321 // In order not to let the noise move us too much back and forth
322 // (the server only has one-second resolution anyway), we only
323 // change an existing skew if we are at least five seconds off.
324 if (client_clock_offset_ms === null ||
325 Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
326 client_clock_offset_ms = estimated_offset_ms;
330 var clear_arrows = function() {
331 for (var i = 0; i < arrows.length; ++i) {
333 if (arrows[i].svg.parentElement) {
334 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
336 delete arrows[i].svg;
341 occupied_by_arrows = [];
342 for (var y = 0; y < 8; ++y) {
343 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
347 var redraw_arrows = function() {
348 for (var i = 0; i < arrows.length; ++i) {
349 position_arrow(arrows[i]);
353 /** @param {!number} x
356 var sign = function(x) {
366 /** See if drawing this arrow on the board would cause unduly amount of confusion.
367 * @param {!string} from The square the arrow is from (e.g. e4).
368 * @param {!string} to The square the arrow is to (e.g. e4).
371 var interfering_arrow = function(from, to) {
372 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
373 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
374 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
375 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
377 occupied_by_arrows[from_row][from_col] = true;
379 // Knight move: Just check that we haven't been at the destination before.
380 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
381 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
382 return occupied_by_arrows[to_row][to_col];
385 // Sliding piece: Check if anything except the from-square is seen before.
386 var dx = sign(to_col - from_col);
387 var dy = sign(to_row - from_row);
393 if (occupied_by_arrows[y][x]) {
396 occupied_by_arrows[y][x] = true;
397 } while (x != to_col || y != to_row);
402 /** Find a point along the coordinate system given by the given line,
403 * <t> units forward from the start of the line, <u> units to the right of it.
404 * @param {!number} x1
405 * @param {!number} x2
406 * @param {!number} y1
407 * @param {!number} y2
410 * @return {!string} The point in "x y" form, suitable for SVG paths.
412 var point_from_start = function(x1, y1, x2, y2, t, u) {
416 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
420 var x = x1 + dx * t + dy * u;
421 var y = y1 + dy * t - dx * u;
425 /** Find a point along the coordinate system given by the given line,
426 * <t> units forward from the end of the line, <u> units to the right of it.
427 * @param {!number} x1
428 * @param {!number} x2
429 * @param {!number} y1
430 * @param {!number} y2
433 * @return {!string} The point in "x y" form, suitable for SVG paths.
435 var point_from_end = function(x1, y1, x2, y2, t, u) {
439 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
443 var x = x2 + dx * t + dy * u;
444 var y = y2 + dy * t - dx * u;
448 var position_arrow = function(arrow) {
450 if (arrow.svg.parentElement) {
451 arrow.svg.parentElement.removeChild(arrow.svg);
455 if (current_display_line !== null && !current_display_line_is_history) {
459 var pos = $(".square-a8").position();
461 var zoom_factor = $("#board").width() / 400.0;
462 var line_width = arrow.line_width * zoom_factor;
463 var arrow_size = arrow.arrow_size * zoom_factor;
465 var square_width = $(".square-a8").width();
466 var from_y = (7 - arrow.from_row + 0.5)*square_width;
467 var to_y = (7 - arrow.to_row + 0.5)*square_width;
468 var from_x = (arrow.from_col + 0.5)*square_width;
469 var to_x = (arrow.to_col + 0.5)*square_width;
471 var SVG_NS = "http://www.w3.org/2000/svg";
472 var XHTML_NS = "http://www.w3.org/1999/xhtml";
473 var svg = document.createElementNS(SVG_NS, "svg");
474 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
475 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
476 svg.setAttribute("style", "position: absolute");
477 svg.setAttribute("position", "absolute");
478 svg.setAttribute("version", "1.1");
479 svg.setAttribute("class", "c1");
480 svg.setAttribute("xmlns", XHTML_NS);
488 var outline = document.createElementNS(SVG_NS, "path");
489 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));
490 outline.setAttribute("xmlns", XHTML_NS);
491 outline.setAttribute("stroke", "#666");
492 outline.setAttribute("stroke-width", line_width + 2);
493 outline.setAttribute("fill", "none");
494 svg.appendChild(outline);
496 var path = document.createElementNS(SVG_NS, "path");
497 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));
498 path.setAttribute("xmlns", XHTML_NS);
499 path.setAttribute("stroke", arrow.fg_color);
500 path.setAttribute("stroke-width", line_width);
501 path.setAttribute("fill", "none");
502 svg.appendChild(path);
504 // Then the arrow head.
505 var head = document.createElementNS(SVG_NS, "path");
506 head.setAttribute("d",
507 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
508 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
509 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
510 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
511 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
512 head.setAttribute("xmlns", XHTML_NS);
513 head.setAttribute("stroke", "#000");
514 head.setAttribute("stroke-width", "1");
515 head.setAttribute("fill", arrow.fg_color);
516 svg.appendChild(head);
518 $(svg).css({ top: pos.top, left: pos.left, 'pointer-events': 'none' });
519 document.body.appendChild(svg);
524 * @param {!string} from_square
525 * @param {!string} to_square
526 * @param {!string} fg_color
527 * @param {number} line_width
528 * @param {number} arrow_size
530 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
531 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
532 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
533 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
534 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
542 line_width: line_width,
543 arrow_size: arrow_size,
547 position_arrow(arrow);
551 // Note: invert is ignored.
552 var compare_by_sort_key = function(refutation_lines, invert, a, b) {
553 var ska = refutation_lines[a]['sort_key'];
554 var skb = refutation_lines[b]['sort_key'];
555 if (ska < skb) return -1;
556 if (ska > skb) return 1;
560 var compare_by_score = function(refutation_lines, invert, a, b) {
561 var sa = compute_score_sort_key(refutation_lines[b]['score'], invert);
562 var sb = compute_score_sort_key(refutation_lines[a]['score'], invert);
567 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
568 * sorted by quality, descending.
570 * @param {!Object} data
571 * @param {number} margin The maximum number of centipawns worse than the
572 * best move can be and still be included.
573 * @param {boolean} margin Whether black is to play.
574 * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
575 * moves, in score order.
577 var find_nonstupid_moves = function(data, margin, invert) {
578 // First of all, if there are any moves that are more than 0.5 ahead of
579 // the primary move, the refutation lines are probably bunk, so just
581 var best_score = undefined;
582 var pv_score = undefined;
583 for (var move in data['refutation_lines']) {
584 var score = compute_score_sort_key(data['refutation_lines'][move]['score'], invert);
585 if (move == data['pv_uci'][0]) {
588 if (best_score === undefined || score > best_score) {
591 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
596 if (best_score - pv_score > 50) {
600 // Now find all moves that are within “margin” of the best score.
601 // The PV move will always be first.
603 for (var move in data['refutation_lines']) {
604 var score = compute_score_sort_key(data['refutation_lines'][move]['score'], invert);
605 if (move != data['pv_uci'][0] && best_score - score <= margin) {
609 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], data['position']['toplay'] === 'B', a, b) });
610 moves.unshift(data['pv_uci'][0]);
619 var thousands = function(x) {
620 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
624 * @param {!string} start_fen
625 * @param {Array.<string>} pretty_pv
626 * @param {number} move_num
627 * @param {!string} toplay
628 * @param {!string} score
629 * @param {number} start_display_move_num
630 * @param {number=} opt_limit
631 * @param {boolean=} opt_showlast
633 var add_pv = function(start_fen, pretty_pv, move_num, toplay, score, start_display_move_num, opt_limit, opt_showlast) {
635 start_fen: start_fen,
636 pretty_pv: pretty_pv,
637 move_num: parseInt(move_num),
640 start_display_move_num: start_display_move_num
642 return print_pv(display_lines.length - 1, opt_limit, opt_showlast);
646 * @param {number} line_num
647 * @param {number=} opt_limit
648 * @param {boolean=} opt_showlast
650 var print_pv = function(line_num, opt_limit, opt_showlast) {
651 var display_line = display_lines[line_num];
652 var pretty_pv = display_line.pretty_pv;
653 var move_num = display_line.move_num;
654 var toplay = display_line.toplay;
656 // Truncate PV at the start if needed.
657 var start_display_move_num = display_line.start_display_move_num;
658 if (start_display_move_num > 0) {
659 pretty_pv = pretty_pv.slice(start_display_move_num);
660 var to_add = start_display_move_num;
661 if (toplay === 'B') {
666 if (to_add % 2 == 1) {
670 move_num += to_add / 2;
675 if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
676 // Truncate the PV at the beginning (instead of at the end).
677 // We assume here that toplay is 'W'. We also assume that if
678 // opt_showlast is set, then it is the history, and thus,
679 // the UI should be to expand the history.
680 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
681 i = pretty_pv.length - opt_limit;
686 } else if (toplay == 'B' && pretty_pv.length > 0) {
687 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
688 pv = move_num + '. … ' + move;
693 for ( ; i < pretty_pv.length; ++i) {
694 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
697 if (i > opt_limit && !opt_showlast) {
703 pv += move_num + '. ' + move;
714 /** Update the highlighted to/from squares on the board.
715 * Based on the global "highlight_from" and "highlight_to" variables.
717 var update_board_highlight = function() {
718 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
719 if ((current_display_line === null || current_display_line_is_history) &&
720 highlight_from !== undefined && highlight_to !== undefined) {
721 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
722 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
726 var update_history = function() {
727 if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
728 $("#history").html("No history");
729 } else if (truncate_display_history) {
730 $("#history").html(print_pv(0, 8, true));
733 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
734 print_pv(0, 1, 'W'));
739 * @param {!boolean} truncate_history
741 var collapse_history = function(truncate_history) {
742 truncate_display_history = truncate_history;
745 window['collapse_history'] = collapse_history;
747 /** Update the HTML display of multi-PV from the global "refutation_lines".
749 * Also recreates the global "display_lines".
751 var update_refutation_lines = function() {
752 if (base_fen === null) {
755 if (display_lines.length > 2) {
756 // Truncate so that only the history and PV is left.
757 display_lines = [ display_lines[0], display_lines[1] ];
759 var tbl = $("#refutationlines");
762 // Find out where the lines start from.
764 var start_display_move_num = 0;
765 if (hash_refutation_lines) {
766 base_line = current_display_line.pretty_pv.slice(0, current_display_move + 1);
767 start_display_move_num = base_line.length;
771 for (var move in refutation_lines) {
775 var invert = (toplay === 'B');
776 if (current_display_line && current_display_move % 2 == 0) {
779 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
780 moves = moves.sort(function(a, b) { return compare(refutation_lines, invert, a, b) });
781 for (var i = 0; i < moves.length; ++i) {
782 var line = refutation_lines[moves[i]];
784 var tr = document.createElement("tr");
786 var move_td = document.createElement("td");
787 tr.appendChild(move_td);
788 $(move_td).addClass("move");
790 if (line['pv_pretty'].length == 0) {
791 // Not found, so just make a one-move PV.
792 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
793 $(move_td).html(move);
794 var score_td = document.createElement("td");
796 $(score_td).addClass("score");
797 $(score_td).text("—");
798 tr.appendChild(score_td);
800 var depth_td = document.createElement("td");
801 tr.appendChild(depth_td);
802 $(depth_td).addClass("depth");
803 $(depth_td).text("—");
805 var pv_td = document.createElement("td");
806 tr.appendChild(pv_td);
807 $(pv_td).addClass("pv");
808 $(pv_td).html(add_pv(base_fen, base_line.concat([ line['pretty_move'] ]), move_num, toplay, line['score'], start_display_move_num));
814 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
815 $(move_td).html(move);
817 var score_td = document.createElement("td");
818 tr.appendChild(score_td);
819 $(score_td).addClass("score");
820 $(score_td).text(format_short_score(line['score']));
822 var depth_td = document.createElement("td");
823 tr.appendChild(depth_td);
824 $(depth_td).addClass("depth");
825 $(depth_td).text("d" + line['depth']);
827 var pv_td = document.createElement("td");
828 tr.appendChild(pv_td);
829 $(pv_td).addClass("pv");
830 $(pv_td).html(add_pv(base_fen, base_line.concat(line['pv_pretty']), move_num, toplay, line['score'], start_display_move_num, 10));
835 // Make one of the links clickable and the other nonclickable.
836 if (sort_refutation_lines_by_score) {
837 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
838 $("#sortbyscore1").html("<strong>Score</strong>");
840 $("#sortbyscore0").html("<strong>Move</strong>");
841 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
844 // Update the move highlight, as we've rewritten all the HTML.
845 update_move_highlight();
849 * Create a Chess.js board object, containing the given position plus the given moves,
850 * up to the given limit.
852 * @param {?string} fen
853 * @param {Array.<string>} moves
854 * @param {number} last_move
856 var chess_from = function(fen, moves, last_move) {
857 var hiddenboard = new Chess();
859 hiddenboard.load(fen);
861 for (var i = 0; i <= last_move; ++i) {
862 if (moves[i] === '0-0') {
863 hiddenboard.move('O-O');
864 } else if (moves[i] === '0-0-0') {
865 hiddenboard.move('O-O-O');
867 hiddenboard.move(moves[i]);
873 var update_game_list = function(games) {
874 $("#games").text("");
875 if (games === null) {
879 var games_div = document.getElementById('games');
880 for (var game_num = 0; game_num < games.length; ++game_num) {
881 var game = games[game_num];
882 var game_span = document.createElement("span");
883 game_span.setAttribute("class", "game");
885 var game_name = document.createTextNode(game['name']);
886 if (game['url'] === backend_url) {
887 game_span.appendChild(game_name);
889 var game_a = document.createElement("a");
890 game_a.setAttribute("href", "#" + game['id']);
891 game_a.appendChild(game_name);
892 game_span.appendChild(game_a);
894 games_div.appendChild(game_span);
899 * Try to find a running game that matches with the current hash,
900 * and switch to it if we're not already displaying it.
902 var possibly_switch_game_from_hash = function() {
903 if (current_games === null) {
907 var hash = window.location.hash.replace(/^#/,'');
908 for (var i = 0; i < current_games.length; ++i) {
909 if (current_games[i]['id'] === hash) {
910 if (backend_url !== current_games[i]['url']) {
911 switch_backend(current_games[i]['url']);
918 /** Update all the HTML on the page, based on current global state.
920 var update_board = function() {
921 var data = displayed_analysis_data || current_analysis_data;
922 var current_data = current_analysis_data; // Convenience alias.
926 // Print the history. This is pretty much the only thing that's
927 // unconditionally taken from current_data (we're not interested in
928 // historic history).
929 if (current_data['position']['pretty_history']) {
930 add_pv('start', current_data['position']['pretty_history'], 1, 'W', null, 0, 8, true);
932 display_lines.push(null);
936 // Games currently in progress, if any.
937 if (current_data['games']) {
938 current_games = current_data['games'];
939 possibly_switch_game_from_hash();
940 update_game_list(current_data['games']);
942 current_games = null;
943 update_game_list(null);
946 // The headline. Names are always fetched from current_data;
947 // the rest can depend a bit.
950 current_data['position']['player_w'] && current_data['position']['player_b']) {
951 headline = current_data['position']['player_w'] + '–' +
952 current_data['position']['player_b'] + ', analysis';
954 headline = 'Analysis';
957 // Credits, where applicable. Note that we don't want the footer to change a lot
958 // when e.g. viewing history, so if any of these changed during the game,
959 // use the current one still.
960 if (current_data['using_lomonosov']) {
961 $("#lomonosov").show();
963 $("#lomonosov").hide();
966 // Credits: The engine name/version.
967 if (current_data['engine'] && current_data['engine']['name'] !== null) {
968 $("#engineid").text(current_data['engine']['name']);
971 // Credits: The engine URL.
972 if (current_data['engine'] && current_data['engine']['url']) {
973 $("#engineid").attr("href", current_data['engine']['url']);
975 $("#engineid").removeAttr("href");
978 // Credits: Engine details.
979 if (current_data['engine'] && current_data['engine']['details']) {
980 $("#enginedetails").text(" (" + current_data['engine']['details'] + ")");
982 $("#enginedetails").text("");
985 // Credits: Move source, possibly with URL.
986 if (current_data['move_source'] && current_data['move_source_url']) {
987 $("#movesource").text("Moves provided by ");
988 var movesource_a = document.createElement("a");
989 movesource_a.setAttribute("href", current_data['move_source_url']);
990 var movesource_text = document.createTextNode(current_data['move_source']);
991 movesource_a.appendChild(movesource_text);
992 var movesource_period = document.createTextNode(".");
993 document.getElementById("movesource").appendChild(movesource_a);
994 document.getElementById("movesource").appendChild(movesource_period);
995 } else if (current_data['move_source']) {
996 $("#movesource").text("Moves provided by " + current_data['move_source'] + ".");
998 $("#movesource").text("");
1002 if (displayed_analysis_data) {
1003 // Displaying some non-current position, pick out the last move
1004 // from the history. This will work even if the fetch failed.
1005 last_move = format_halfmove_with_number(
1006 current_display_line.pretty_pv[current_display_move],
1007 current_display_move + 1);
1008 headline += ' after ' + last_move;
1009 } else if (data['position']['last_move'] !== 'none') {
1010 last_move = format_move_with_number(
1011 data['position']['last_move'],
1012 data['position']['move_num'],
1013 data['position']['toplay'] == 'W');
1014 headline += ' after ' + last_move;
1018 $("#headline").text(headline);
1020 // The <title> contains a very brief headline.
1021 var title_elems = [];
1022 if (data['score']) {
1023 title_elems.push(format_short_score(data['score']).replace(/^ /, ""));
1025 if (last_move !== null) {
1026 title_elems.push(last_move);
1029 if (title_elems.length != 0) {
1030 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
1032 document.title = 'analysis.sesse.net';
1035 // The last move (shown by highlighting the from and to squares).
1036 if (data['position'] && data['position']['last_move_uci']) {
1037 highlight_from = data['position']['last_move_uci'].substr(0, 2);
1038 highlight_to = data['position']['last_move_uci'].substr(2, 2);
1039 } else if (current_display_line_is_history && current_display_move >= 0) {
1040 // We don't have historic analysis for this position, but we
1041 // can reconstruct what the last move was by just replaying
1043 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1044 var moves = hiddenboard.history({ verbose: true });
1045 var last_move = moves.pop();
1046 highlight_from = last_move.from;
1047 highlight_to = last_move.to;
1049 highlight_from = highlight_to = undefined;
1051 update_board_highlight();
1053 if (data['failed']) {
1054 $("#score").text("No analysis for this move");
1055 $("#pvtitle").text("PV:");
1057 $("#searchstats").html(" ");
1058 $("#refutationlines").empty();
1059 $("#whiteclock").empty();
1060 $("#blackclock").empty();
1061 refutation_lines = [];
1062 update_refutation_lines();
1064 update_displayed_line();
1065 update_move_highlight();
1072 if (current_display_line) {
1073 if (current_display_line.score) {
1074 $("#score").text(format_long_score(current_display_line.score));
1076 $("#score").text("No score for this move");
1078 } else if (data['score']) {
1079 $("#score").text(format_long_score(data['score']));
1082 // The search stats.
1083 if (data['searchstats']) {
1084 $("#searchstats").html(data['searchstats']);
1085 } else if (data['tablebase'] == 1) {
1086 $("#searchstats").text("Tablebase result");
1087 } else if (data['nodes'] && data['nps'] && data['depth']) {
1088 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
1089 if (data['seldepth']) {
1090 stats += ' (' + data['seldepth'] + ' selective)';
1092 if (data['tbhits'] && data['tbhits'] > 0) {
1093 if (data['tbhits'] == 1) {
1094 stats += ', one Syzygy hit';
1096 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
1100 $("#searchstats").text(stats);
1102 $("#searchstats").text("");
1105 // Update the board itself.
1106 base_fen = data['position']['fen'];
1107 update_displayed_line();
1110 $("#pvtitle").text("PV:");
1111 $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay'], data['score'], 0));
1113 // Update the PV arrow.
1115 if (data['pv_uci'].length >= 1) {
1116 // draw a continuation arrow as long as it's the same piece
1117 for (var i = 0; i < data['pv_uci'].length; i += 2) {
1118 var from = data['pv_uci'][i].substr(0, 2);
1119 var to = data['pv_uci'][i].substr(2,4);
1120 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
1121 interfering_arrow(from, to)) {
1124 create_arrow(from, to, '#f66', 6, 20);
1127 var alt_moves = find_nonstupid_moves(data, 30, data['position']['toplay'] === 'B');
1128 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
1129 create_arrow(alt_moves[i].substr(0, 2),
1130 alt_moves[i].substr(2, 2), '#f66', 1, 10);
1134 // See if all semi-reasonable moves have only one possible response.
1135 if (data['pv_uci'].length >= 2) {
1136 var nonstupid_moves = find_nonstupid_moves(data, 300, data['position']['toplay'] === 'B');
1137 var response = data['pv_uci'][1];
1138 for (var i = 0; i < nonstupid_moves.length; ++i) {
1139 if (nonstupid_moves[i] == data['pv_uci'][0]) {
1140 // ignore the PV move for refutation lines.
1143 if (!data['refutation_lines'] ||
1144 !data['refutation_lines'][nonstupid_moves[i]] ||
1145 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
1146 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
1147 // Incomplete PV, abort.
1148 response = undefined;
1151 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
1152 if (response !== this_response) {
1153 // Different response depending on lines, abort.
1154 response = undefined;
1159 if (nonstupid_moves.length > 0 && response !== undefined) {
1160 create_arrow(response.substr(0, 2),
1161 response.substr(2, 2), '#66f', 6, 20);
1165 // Update the refutation lines.
1166 base_fen = data['position']['fen'];
1167 move_num = parseInt(data['position']['move_num']);
1168 toplay = data['position']['toplay'];
1169 refutation_lines = hash_refutation_lines || data['refutation_lines'];
1170 update_refutation_lines();
1172 // Update the sparkline last, since its size depends on how everything else reflowed.
1173 update_sparkline(data);
1176 var update_sparkline = function(data) {
1177 if (data && data['score_history']) {
1178 var first_move_num = undefined;
1179 for (var halfmove_num in data['score_history']) {
1180 halfmove_num = parseInt(halfmove_num);
1181 if (first_move_num === undefined || halfmove_num < first_move_num) {
1182 first_move_num = halfmove_num;
1185 if (first_move_num !== undefined) {
1186 var last_move_num = data['position']['move_num'] * 2 - 3;
1187 if (data['position']['toplay'] === 'B') {
1191 // Possibly truncate some moves if we don't have enough width.
1192 // FIXME: Sometimes width() for #scorecontainer (and by extent,
1193 // #scoresparkcontainer) on Chrome for mobile seems to start off
1194 // at something very small, and then suddenly snap back into place.
1196 var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
1197 if (last_move_num - first_move_num > max_moves) {
1198 first_move_num = last_move_num - max_moves;
1201 var min_score = -100;
1202 var max_score = 100;
1203 var last_score = null;
1205 for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1206 if (data['score_history'][halfmove_num]) {
1207 var score = compute_plot_score(data['score_history'][halfmove_num]);
1209 if (score < min_score) min_score = score;
1210 if (score > max_score) max_score = score;
1212 scores.push(last_score);
1214 if (data['score']) {
1215 scores.push(compute_plot_score(data['score']));
1217 // FIXME: at some widths, calling sparkline() seems to push
1218 // #scorecontainer under the board.
1219 $("#scorespark").sparkline(scores, {
1222 chartRangeMin: min_score,
1223 chartRangeMax: max_score,
1224 tooltipFormatter: function(sparkline, options, fields) {
1225 return format_tooltip(data, fields[0].offset + first_move_num);
1229 $("#scorespark").text("");
1232 $("#scorespark").text("");
1237 * @param {number} num_viewers
1239 var update_num_viewers = function(num_viewers) {
1240 if (num_viewers === null) {
1241 $("#numviewers").text("");
1242 } else if (num_viewers == 1) {
1243 $("#numviewers").text("You are the only current viewer");
1245 $("#numviewers").text(num_viewers + " current viewers");
1249 var update_clock = function() {
1250 clearTimeout(clock_timer);
1252 var data = displayed_analysis_data || current_analysis_data;
1253 if (data['position']) {
1254 var result = data['position']['result'];
1255 if (result === '1-0') {
1256 $("#whiteclock").text("1");
1257 $("#blackclock").text("0");
1258 $("#whiteclock").removeClass("running-clock");
1259 $("#blackclock").removeClass("running-clock");
1262 if (result === '1/2-1/2') {
1263 $("#whiteclock").text("1/2");
1264 $("#blackclock").text("1/2");
1265 $("#whiteclock").removeClass("running-clock");
1266 $("#blackclock").removeClass("running-clock");
1269 if (result === '0-1') {
1270 $("#whiteclock").text("0");
1271 $("#blackclock").text("1");
1272 $("#whiteclock").removeClass("running-clock");
1273 $("#blackclock").removeClass("running-clock");
1278 var white_clock_ms = null;
1279 var black_clock_ms = null;
1280 var show_seconds = false;
1283 if (data['position'] &&
1284 data['position']['white_clock'] &&
1285 data['position']['black_clock']) {
1286 white_clock_ms = data['position']['white_clock'] * 1000;
1287 black_clock_ms = data['position']['black_clock'] * 1000;
1290 // Dynamic clock (only one, obviously).
1292 if (data['position']['white_clock_target']) {
1294 $("#whiteclock").addClass("running-clock");
1295 $("#blackclock").removeClass("running-clock");
1296 } else if (data['position']['black_clock_target']) {
1298 $("#whiteclock").removeClass("running-clock");
1299 $("#blackclock").addClass("running-clock");
1301 $("#whiteclock").removeClass("running-clock");
1302 $("#blackclock").removeClass("running-clock");
1306 var now = new Date().getTime() + client_clock_offset_ms;
1307 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1308 if (color === "white") {
1309 white_clock_ms = remaining_ms;
1311 black_clock_ms = remaining_ms;
1315 if (white_clock_ms === null || black_clock_ms === null) {
1316 $("#whiteclock").empty();
1317 $("#blackclock").empty();
1321 // If either player has ten minutes or less left, add the second counters.
1322 var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
1325 // See when the clock will change next, and update right after that.
1328 next_update_ms = remaining_ms % 1000 + 100;
1330 next_update_ms = remaining_ms % 60000 + 100;
1332 clock_timer = setTimeout(update_clock, next_update_ms);
1335 $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1336 $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1340 * @param {Number} remaining_ms
1341 * @param {boolean} show_seconds
1343 var format_clock = function(remaining_ms, show_seconds) {
1344 if (remaining_ms <= 0) {
1352 var remaining = Math.floor(remaining_ms / 1000);
1353 var seconds = remaining % 60;
1354 remaining = (remaining - seconds) / 60;
1355 var minutes = remaining % 60;
1356 remaining = (remaining - minutes) / 60;
1357 var hours = remaining;
1359 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1361 return format_2d(hours) + ":" + format_2d(minutes);
1368 var format_2d = function(x) {
1377 * @param {string} move
1378 * @param {Number} move_num
1379 * @param {boolean} white_to_play
1381 var format_move_with_number = function(move, move_num, white_to_play) {
1383 if (white_to_play) {
1384 ret = (move_num - 1) + '… ';
1386 ret = move_num + '. ';
1393 * @param {string} move
1394 * @param {Number} halfmove_num
1396 var format_halfmove_with_number = function(move, halfmove_num) {
1397 return format_move_with_number(
1399 Math.floor(halfmove_num / 2) + 1,
1400 halfmove_num % 2 == 0);
1404 * @param {Object} data
1405 * @param {Number} halfmove_num
1407 var format_tooltip = function(data, halfmove_num) {
1408 if (data['score_history'][halfmove_num] ||
1409 halfmove_num === data['position']['pretty_history'].length) {
1412 if (halfmove_num === data['position']['pretty_history'].length) {
1413 move = data['position']['last_move'];
1414 short_score = format_short_score(data['score']);
1416 move = data['position']['pretty_history'][halfmove_num];
1417 short_score = format_short_score(data['score_history'][halfmove_num]);
1419 var move_with_number = format_halfmove_with_number(move, halfmove_num);
1421 return "After " + move_with_number + ": " + short_score;
1423 for (var i = halfmove_num; i --> 0; ) {
1424 if (data['score_history'][i]) {
1425 var move = data['position']['pretty_history'][i];
1426 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1433 * @param {boolean} sort_by_score
1435 var resort_refutation_lines = function(sort_by_score) {
1436 sort_refutation_lines_by_score = sort_by_score;
1437 if (supports_html5_storage()) {
1438 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1440 update_refutation_lines();
1442 window['resort_refutation_lines'] = resort_refutation_lines;
1445 * @param {boolean} truncate_history
1447 var set_truncate_history = function(truncate_history) {
1448 truncate_display_history = truncate_history;
1449 update_refutation_lines();
1451 window['set_truncate_history'] = set_truncate_history;
1454 * @param {number} line_num
1455 * @param {number} move_num
1457 var show_line = function(line_num, move_num) {
1458 if (line_num == -1) {
1459 current_display_line = null;
1460 current_display_move = null;
1461 hash_refutation_lines = null;
1462 if (displayed_analysis_data) {
1463 // TODO: Support exiting to history position if we are in an
1464 // analysis line of a history position.
1465 displayed_analysis_data = null;
1470 current_display_line = jQuery.extend({}, display_lines[line_num]); // Shallow clone.
1471 current_display_move = move_num + current_display_line.start_display_move_num;
1473 current_display_line_is_history = (line_num == 0);
1475 update_historic_analysis();
1476 update_displayed_line();
1477 update_board_highlight();
1478 update_move_highlight();
1481 window['show_line'] = show_line;
1483 var prev_move = function() {
1484 if (current_display_line &&
1485 current_display_move >= current_display_line.start_display_move_num) {
1486 --current_display_move;
1488 update_historic_analysis();
1489 update_displayed_line();
1490 update_move_highlight();
1492 window['prev_move'] = prev_move;
1494 var next_move = function() {
1495 if (current_display_line &&
1496 current_display_move < current_display_line.pretty_pv.length - 1) {
1497 ++current_display_move;
1499 update_historic_analysis();
1500 update_displayed_line();
1501 update_move_highlight();
1503 window['next_move'] = next_move;
1505 var update_historic_analysis = function() {
1506 if (!current_display_line_is_history) {
1509 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1510 displayed_analysis_data = null;
1514 // Fetch old analysis for this line if it exists.
1515 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1516 var filename = "/history/move" + (current_display_move + 1) + "-" +
1517 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1519 current_historic_xhr = $.ajax({
1521 }).done(function(data, textstatus, xhr) {
1522 displayed_analysis_data = data;
1524 }).fail(function(jqXHR, textStatus, errorThrown) {
1525 if (textStatus === "abort") {
1526 // Aborted because we are switching backends. Don't do anything;
1527 // we will already have been cleared.
1529 displayed_analysis_data = {'failed': true};
1536 * @param {string} fen
1538 var update_imbalance = function(fen) {
1539 var hiddenboard = new Chess(fen);
1540 var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1541 for (var row = 0; row < 8; ++row) {
1542 for (var col = 0; col < 8; ++col) {
1543 var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1544 var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1545 var square = col_text + row_text;
1546 var contents = hiddenboard.get(square);
1547 if (contents !== null) {
1548 if (contents.color === 'w') {
1549 ++imbalance[contents.type];
1551 --imbalance[contents.type];
1556 var white_imbalance = '';
1557 var black_imbalance = '';
1558 for (var piece in imbalance) {
1559 for (var i = 0; i < imbalance[piece]; ++i) {
1560 white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1562 for (var i = 0; i < -imbalance[piece]; ++i) {
1563 black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1566 $('#whiteimbalance').html(white_imbalance);
1567 $('#blackimbalance').html(black_imbalance);
1570 /** Mark the currently selected move in red.
1571 * Also replaces the PV with the current displayed line if it's not shown
1572 * anywhere else on the screen.
1574 var update_move_highlight = function() {
1575 if (highlighted_move !== null) {
1576 highlighted_move.removeClass('highlight');
1578 if (current_display_line) {
1579 var display_line_num = find_display_line_matching_num();
1580 if (display_line_num === null) {
1581 // Replace the PV with the (complete) line.
1582 $("#pvtitle").text("Exploring:");
1583 current_display_line.start_display_move_num = 0;
1584 display_lines.push(current_display_line);
1585 $("#pv").html(print_pv(display_lines.length - 1));
1586 display_line_num = display_lines.length - 1;
1589 highlighted_move = $("#automove" + display_line_num + "-" + (current_display_move - current_display_line.start_display_move_num));
1590 highlighted_move.addClass('highlight');
1595 * See if the current displayed line is identical to any of the ones
1596 * we have on screen. (It might not be if e.g. the analysis reloaded
1597 * since we started looking.)
1601 var find_display_line_matching_num = function() {
1602 for (var i = 0; i < display_lines.length; ++i) {
1603 var line = display_lines[i];
1604 if (line.start_display_move_num > 0) continue;
1605 if (current_display_line.start_fen !== line.start_fen) continue;
1606 if (current_display_line.pretty_pv.length !== line.pretty_pv.length) continue;
1608 for (var j = 0; j < line.pretty_pv.length; ++j) {
1609 if (current_display_line.pretty_pv[j] !== line.pretty_pv[j]) {
1621 var update_displayed_line = function() {
1622 if (current_display_line === null) {
1623 $("#linenav").hide();
1624 $("#linemsg").show();
1625 display_fen = base_fen;
1626 board.position(base_fen);
1627 update_imbalance(base_fen);
1631 $("#linenav").show();
1632 $("#linemsg").hide();
1634 if (current_display_move <= 0) {
1635 $("#prevmove").html("Previous");
1637 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1639 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1640 $("#nextmove").html("Next");
1642 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1645 var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pretty_pv, current_display_move);
1646 display_fen = hiddenboard.fen();
1647 board_is_animating = true;
1648 var old_fen = board.fen();
1649 board.position(hiddenboard.fen());
1650 if (board.fen() === old_fen) {
1651 board_is_animating = false;
1652 } else if (!current_display_line_is_history) {
1653 // Fire off a hash request, since we're now off the main position
1654 // and it just changed.
1655 explore_hash(display_fen);
1657 update_imbalance(hiddenboard.fen());
1661 * @param {boolean} param_enable_sound
1663 var set_sound = function(param_enable_sound) {
1664 enable_sound = param_enable_sound;
1666 $("#soundon").html("<strong>On</strong>");
1667 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1669 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1670 // and also preload the file since the user has selected audio.
1671 var ding = document.getElementById('ding');
1672 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1673 ding.src = 'ding.opus';
1677 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1678 $("#soundoff").html("<strong>Off</strong>");
1680 if (supports_html5_storage()) {
1681 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1684 window['set_sound'] = set_sound;
1686 /** Send off a hash probe request to the backend.
1687 * @param {string} fen
1689 var explore_hash = function(fen) {
1690 // If we already have a backend response going, abort it.
1691 if (current_hash_xhr) {
1692 current_hash_xhr.abort();
1694 if (current_hash_display_timer) {
1695 clearTimeout(current_hash_display_timer);
1696 current_hash_display_timer = null;
1698 $("#refutationlines").empty();
1699 current_hash_xhr = $.ajax({
1700 url: backend_hash_url + "?fen=" + fen
1701 }).done(function(data, textstatus, xhr) {
1702 show_explore_hash_results(data, fen);
1706 /** Process the JSON response from a hash probe request.
1707 * @param {!Object} data
1708 * @param {string} fen
1710 var show_explore_hash_results = function(data, fen) {
1711 if (board_is_animating) {
1712 // Updating while the animation is still going causes
1713 // the animation to jerk. This is pretty crude, but it will do.
1714 current_hash_display_timer = setTimeout(function() { show_explore_hash_results(data, fen); }, 100);
1717 current_hash_display_timer = null;
1718 hash_refutation_lines = data['lines'];
1722 // almost all of this stuff comes from the chessboard.js example page
1723 var onDragStart = function(source, piece, position, orientation) {
1724 var pseudogame = new Chess(display_fen);
1725 if (pseudogame.game_over() === true ||
1726 (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
1727 (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
1731 recommended_move = get_best_move(pseudogame, source, null, pseudogame.turn() === 'b');
1732 if (recommended_move) {
1733 var squareEl = $('#board .square-' + recommended_move.to);
1734 squareEl.addClass('highlight1-32417');
1739 var mousedownSquare = function(e) {
1740 reverse_dragging_from = null;
1741 var square = $(this).attr('data-square');
1743 var pseudogame = new Chess(display_fen);
1744 if (pseudogame.game_over() === true) {
1748 // If the square is empty, or has a piece of the side not to move,
1749 // we handle it. If not, normal piece dragging will take it.
1750 var position = board.position();
1751 if (!position.hasOwnProperty(square) ||
1752 (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
1753 (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
1754 reverse_dragging_from = square;
1755 recommended_move = get_best_move(pseudogame, null, square, pseudogame.turn() === 'b');
1756 if (recommended_move) {
1757 var squareEl = $('#board .square-' + recommended_move.from);
1758 squareEl.addClass('highlight1-32417');
1759 squareEl = $('#board .square-' + recommended_move.to);
1760 squareEl.addClass('highlight1-32417');
1765 var mouseupSquare = function(e) {
1766 if (reverse_dragging_from === null) {
1769 var source = $(this).attr('data-square');
1770 var target = reverse_dragging_from;
1771 reverse_dragging_from = null;
1772 if (onDrop(source, target) !== 'snapback') {
1773 onSnapEnd(source, target);
1775 $("#board").find('.square-55d63').removeClass('highlight1-32417');
1778 var get_best_move = function(game, source, target, invert) {
1779 var moves = game.moves({ verbose: true });
1780 if (source !== null) {
1781 moves = moves.filter(function(move) { return move.from == source; });
1783 if (target !== null) {
1784 moves = moves.filter(function(move) { return move.to == target; });
1786 if (moves.length == 0) {
1789 if (moves.length == 1) {
1793 // More than one move. Use the display lines (if we have them)
1794 // to disambiguate; otherwise, we have no information.
1796 for (var i = 0; i < moves.length; ++i) {
1797 move_hash[moves[i].san] = moves[i];
1800 // History and PV take priority over the display lines.
1801 for (var i = 0; i < 2; ++i) {
1802 var line = display_lines[i];
1803 var first_move = line.pretty_pv[line.start_display_move_num];
1804 if (move_hash[first_move]) {
1805 return move_hash[first_move];
1809 var best_move = null;
1810 var best_move_score = null;
1812 for (var move in refutation_lines) {
1813 var line = refutation_lines[move];
1814 if (!line['score']) {
1817 var first_move = line['pv_pretty'][0];
1818 if (move_hash[first_move]) {
1819 var score = compute_score_sort_key(line['score'], invert);
1820 if (best_move_score === null || score > best_move_score) {
1821 best_move = move_hash[first_move];
1822 best_move_score = score;
1829 var onDrop = function(source, target) {
1830 if (source === target) {
1831 if (recommended_move === null) {
1834 // Accept the move. It will be changed in onSnapEnd.
1838 // Suggestion not asked for.
1839 recommended_move = null;
1842 // see if the move is legal
1843 var pseudogame = new Chess(display_fen);
1844 var move = pseudogame.move({
1847 promotion: 'q' // NOTE: always promote to a queen for example simplicity
1851 if (move === null) return 'snapback';
1854 var onSnapEnd = function(source, target) {
1855 if (source === target && recommended_move !== null) {
1856 source = recommended_move.from;
1857 target = recommended_move.to;
1859 recommended_move = null;
1860 var pseudogame = new Chess(display_fen);
1861 var move = pseudogame.move({
1864 promotion: 'q' // NOTE: always promote to a queen for example simplicity
1867 if (current_display_line &&
1868 current_display_move < current_display_line.pretty_pv.length - 1 &&
1869 current_display_line.pretty_pv[current_display_move] === move.san) {
1874 // Walk down the displayed lines until we find one that starts with
1875 // this move, then select that. Note that this gives us a good priority
1876 // order (history first, then PV, then multi-PV lines).
1877 for (var i = 0; i < display_lines.length; ++i) {
1878 var line = display_lines[i];
1879 if (line.pretty_pv[line.start_display_move_num] === move.san) {
1885 // Shouldn't really be here if we have hash probes, but there's really
1886 // nothing we can do.
1888 // End of dragging-related code.
1890 var pad = function(val, num_digits) {
1891 var s = val.toString();
1892 while (s.length < num_digits) {
1898 var fmt_cp = function(v) {
1902 return "+" + (v / 100).toFixed(2);
1905 return "-" + (v / 100).toFixed(2);
1909 var format_short_score = function(score) {
1910 if (score[0] === 'm') {
1911 if (score[2]) { // Is a bound.
1912 return score[2] + "\u00a0M" + pad(score[1], 3);
1914 return "M" + pad(score[1], 3);
1916 } else if (score[0] === 'd') {
1918 } else if (score[0] === 'cp') {
1919 if (score[2]) { // Is a bound.
1920 return score[2] + "\u00a0" + fmt_cp(score[1]);
1922 return pad(fmt_cp(score[1]), 5);
1928 var format_long_score = function(score) {
1929 if (score[0] === 'm') {
1931 return "White mates in " + score[1];
1933 return "Black mates in " + (-score[1]);
1935 } else if (score[0] === 'd') {
1936 return "Theoretical draw";
1937 } else if (score[0] === 'cp') {
1938 return "Score: " + format_short_score(score);
1943 var compute_plot_score = function(score) {
1944 if (score[0] === 'm') {
1950 } else if (score[0] === 'd') {
1952 } else if (score[0] === 'cp') {
1953 if (score[1] > 500) {
1955 } else if (score[1] < -500) {
1965 * @param score The score digest tuple.
1966 * @param {boolean} invert Whether black is to play.
1969 var compute_score_sort_key = function(score, invert) {
1974 if (score[0] === 'm') {
1977 s = 99999 - score[1];
1979 // Black mates (note the double negative for score[1]).
1980 s = -99999 - score[1];
1984 } else if (score[0] === 'd') {
1986 } else if (score[0] === 'cp') {
1987 return invert ? -score[1] : score[1];
1993 * @param {string} new_backend_url
1995 var switch_backend = function(new_backend_url) {
1996 // Stop looking at historic data.
1997 current_display_line = null;
1998 current_display_move = null;
1999 displayed_analysis_data = null;
2000 if (current_historic_xhr) {
2001 current_historic_xhr.abort();
2004 // If we already have a backend response going, abort it.
2005 if (current_analysis_xhr) {
2006 current_analysis_xhr.abort();
2008 if (current_hash_xhr) {
2009 current_hash_xhr.abort();
2012 // Otherwise, we should have a timer going to start a new one.
2014 if (current_analysis_request_timer) {
2015 clearTimeout(current_analysis_request_timer);
2016 current_analysis_request_timer = null;
2018 if (current_hash_display_timer) {
2019 clearTimeout(current_hash_display_timer);
2020 current_hash_display_timer = null;
2023 // Request an immediate fetch with the new backend.
2024 backend_url = new_backend_url;
2025 current_analysis_data = null;
2029 window['switch_backend'] = switch_backend;
2031 var init = function() {
2032 unique = get_unique();
2034 // Load settings from HTML5 local storage if available.
2035 if (supports_html5_storage() && localStorage['enable_sound']) {
2036 set_sound(parseInt(localStorage['enable_sound']));
2040 if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
2041 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
2043 sort_refutation_lines_by_score = true;
2047 board = new window.ChessBoard('board', {
2048 onMoveEnd: function() { board_is_animating = false; },
2051 onDragStart: onDragStart,
2053 onSnapEnd: onSnapEnd
2055 $("#board").on('mousedown', '.square-55d63', mousedownSquare);
2056 $("#board").on('mouseup', '.square-55d63', mouseupSquare);
2059 $(window).resize(function() {
2061 update_sparkline(displayed_analysis_data || current_analysis_data);
2062 update_board_highlight();
2065 $(window).keyup(function(event) {
2066 if (event.which == 39) {
2068 } else if (event.which == 37) {
2072 window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
2074 $(document).ready(init);