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>,
161 * start_display_move_num: number
164 * "start_display_move_num" is the (half-)move number to start displaying the PV at.
167 /** All PVs that we currently know of.
169 * Element 0 is history (or null if no history).
170 * Element 1 is current main PV, or explored line if nowhere else on the screen.
171 * All remaining elements are refutation lines (multi-PV).
173 * @type {Array.<DisplayLine>}
176 var display_lines = [];
178 /** @type {?DisplayLine} @private */
179 var current_display_line = null;
181 /** @type {boolean} @private */
182 var current_display_line_is_history = false;
184 /** @type {?number} @private */
185 var current_display_move = null;
188 * The current backend request to get main analysis (not history), if any,
189 * so that we can abort it.
194 var current_analysis_xhr = null;
197 * The current timer to fire off a request to get main analysis (not history),
198 * if any, so that we can abort it.
203 var current_analysis_request_timer = null;
206 * The current backend request to get historic data, if any.
211 var current_historic_xhr = null;
214 * The current backend request to get hash probes, if any, so that we can abort it.
219 var current_hash_xhr = null;
222 * The current timer to display hash probe information (it could be waiting on the
223 * board to stop animating), if any, so that we can abort it.
228 var current_hash_display_timer = null;
230 var supports_html5_storage = function() {
232 return 'localStorage' in window && window['localStorage'] !== null;
238 // Make the unique token persistent so people refreshing the page won't count twice.
239 // Of course, you can never fully protect against people deliberately wanting to spam.
240 var get_unique = function() {
241 var use_local_storage = supports_html5_storage();
242 if (use_local_storage && localStorage['unique']) {
243 return localStorage['unique'];
245 var unique = Math.random();
246 if (use_local_storage) {
247 localStorage['unique'] = unique;
252 var request_update = function() {
253 current_analysis_request_timer = null;
255 current_analysis_xhr = $.ajax({
256 url: backend_url + "?ims=" + ims + "&unique=" + unique
257 }).done(function(data, textstatus, xhr) {
258 sync_server_clock(xhr.getResponseHeader('Date'));
259 ims = xhr.getResponseHeader('X-RGLM');
260 var num_viewers = xhr.getResponseHeader('X-RGNV');
262 if (Array.isArray(data)) {
263 new_data = JSON.parse(JSON.stringify(current_analysis_data));
264 JSON_delta.patch(new_data, data);
269 var minimum_version = xhr.getResponseHeader('X-RGMV');
270 if (minimum_version && minimum_version > SCRIPT_VERSION) {
271 // Upgrade to latest version with a force-reload.
272 location.reload(true);
275 possibly_play_sound(current_analysis_data, new_data);
276 current_analysis_data = new_data;
278 update_num_viewers(num_viewers);
281 current_analysis_request_timer = setTimeout(function() { request_update(); }, 100);
282 }).fail(function(jqXHR, textStatus, errorThrown) {
283 if (textStatus === "abort") {
284 // Aborted because we are switching backends. Abandon and don't retry,
285 // because another one is already started for us.
287 // Backend error or similar. Wait ten seconds, then try again.
288 current_analysis_request_timer = setTimeout(function() { request_update(); }, 10000);
293 var possibly_play_sound = function(old_data, new_data) {
297 if (old_data === null) {
300 var ding = document.getElementById('ding');
301 if (ding && ding.play) {
302 if (old_data['position'] && old_data['position']['fen'] &&
303 new_data['position'] && new_data['position']['fen'] &&
304 (old_data['position']['fen'] !== new_data['position']['fen'] ||
305 old_data['position']['move_num'] !== new_data['position']['move_num'])) {
312 * @type {!string} server_date_string
314 var sync_server_clock = function(server_date_string) {
315 var server_time_ms = new Date(server_date_string).getTime();
316 var client_time_ms = new Date().getTime();
317 var estimated_offset_ms = server_time_ms - client_time_ms;
319 // In order not to let the noise move us too much back and forth
320 // (the server only has one-second resolution anyway), we only
321 // change an existing skew if we are at least five seconds off.
322 if (client_clock_offset_ms === null ||
323 Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
324 client_clock_offset_ms = estimated_offset_ms;
328 var clear_arrows = function() {
329 for (var i = 0; i < arrows.length; ++i) {
331 if (arrows[i].svg.parentElement) {
332 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
334 delete arrows[i].svg;
339 occupied_by_arrows = [];
340 for (var y = 0; y < 8; ++y) {
341 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
345 var redraw_arrows = function() {
346 for (var i = 0; i < arrows.length; ++i) {
347 position_arrow(arrows[i]);
351 /** @param {!number} x
354 var sign = function(x) {
364 /** See if drawing this arrow on the board would cause unduly amount of confusion.
365 * @param {!string} from The square the arrow is from (e.g. e4).
366 * @param {!string} to The square the arrow is to (e.g. e4).
369 var interfering_arrow = function(from, to) {
370 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
371 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
372 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
373 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
375 occupied_by_arrows[from_row][from_col] = true;
377 // Knight move: Just check that we haven't been at the destination before.
378 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
379 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
380 return occupied_by_arrows[to_row][to_col];
383 // Sliding piece: Check if anything except the from-square is seen before.
384 var dx = sign(to_col - from_col);
385 var dy = sign(to_row - from_row);
391 if (occupied_by_arrows[y][x]) {
394 occupied_by_arrows[y][x] = true;
395 } while (x != to_col || y != to_row);
400 /** Find a point along the coordinate system given by the given line,
401 * <t> units forward from the start of the line, <u> units to the right of it.
402 * @param {!number} x1
403 * @param {!number} x2
404 * @param {!number} y1
405 * @param {!number} y2
408 * @return {!string} The point in "x y" form, suitable for SVG paths.
410 var point_from_start = function(x1, y1, x2, y2, t, u) {
414 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
418 var x = x1 + dx * t + dy * u;
419 var y = y1 + dy * t - dx * u;
423 /** Find a point along the coordinate system given by the given line,
424 * <t> units forward from the end of the line, <u> units to the right of it.
425 * @param {!number} x1
426 * @param {!number} x2
427 * @param {!number} y1
428 * @param {!number} y2
431 * @return {!string} The point in "x y" form, suitable for SVG paths.
433 var point_from_end = function(x1, y1, x2, y2, t, u) {
437 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
441 var x = x2 + dx * t + dy * u;
442 var y = y2 + dy * t - dx * u;
446 var position_arrow = function(arrow) {
448 if (arrow.svg.parentElement) {
449 arrow.svg.parentElement.removeChild(arrow.svg);
453 if (current_display_line !== null && !current_display_line_is_history) {
457 var pos = $(".square-a8").position();
459 var zoom_factor = $("#board").width() / 400.0;
460 var line_width = arrow.line_width * zoom_factor;
461 var arrow_size = arrow.arrow_size * zoom_factor;
463 var square_width = $(".square-a8").width();
464 var from_y = (7 - arrow.from_row + 0.5)*square_width;
465 var to_y = (7 - arrow.to_row + 0.5)*square_width;
466 var from_x = (arrow.from_col + 0.5)*square_width;
467 var to_x = (arrow.to_col + 0.5)*square_width;
469 var SVG_NS = "http://www.w3.org/2000/svg";
470 var XHTML_NS = "http://www.w3.org/1999/xhtml";
471 var svg = document.createElementNS(SVG_NS, "svg");
472 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
473 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
474 svg.setAttribute("style", "position: absolute");
475 svg.setAttribute("position", "absolute");
476 svg.setAttribute("version", "1.1");
477 svg.setAttribute("class", "c1");
478 svg.setAttribute("xmlns", XHTML_NS);
486 var outline = document.createElementNS(SVG_NS, "path");
487 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));
488 outline.setAttribute("xmlns", XHTML_NS);
489 outline.setAttribute("stroke", "#666");
490 outline.setAttribute("stroke-width", line_width + 2);
491 outline.setAttribute("fill", "none");
492 svg.appendChild(outline);
494 var path = document.createElementNS(SVG_NS, "path");
495 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));
496 path.setAttribute("xmlns", XHTML_NS);
497 path.setAttribute("stroke", arrow.fg_color);
498 path.setAttribute("stroke-width", line_width);
499 path.setAttribute("fill", "none");
500 svg.appendChild(path);
502 // Then the arrow head.
503 var head = document.createElementNS(SVG_NS, "path");
504 head.setAttribute("d",
505 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
506 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
507 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 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, 0, 0));
510 head.setAttribute("xmlns", XHTML_NS);
511 head.setAttribute("stroke", "#000");
512 head.setAttribute("stroke-width", "1");
513 head.setAttribute("fill", arrow.fg_color);
514 svg.appendChild(head);
516 $(svg).css({ top: pos.top, left: pos.left, 'pointer-events': 'none' });
517 document.body.appendChild(svg);
522 * @param {!string} from_square
523 * @param {!string} to_square
524 * @param {!string} fg_color
525 * @param {number} line_width
526 * @param {number} arrow_size
528 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
529 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
530 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
531 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
532 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
540 line_width: line_width,
541 arrow_size: arrow_size,
545 position_arrow(arrow);
549 // Note: invert is ignored.
550 var compare_by_sort_key = function(refutation_lines, invert, a, b) {
551 var ska = refutation_lines[a]['sort_key'];
552 var skb = refutation_lines[b]['sort_key'];
553 if (ska < skb) return -1;
554 if (ska > skb) return 1;
558 var compare_by_score = function(refutation_lines, invert, a, b) {
559 var sa = compute_score_sort_key(refutation_lines[b]['score'], invert);
560 var sb = compute_score_sort_key(refutation_lines[a]['score'], invert);
565 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
566 * sorted by quality, descending.
568 * @param {!Object} data
569 * @param {number} margin The maximum number of centipawns worse than the
570 * best move can be and still be included.
571 * @param {boolean} margin Whether black is to play.
572 * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
573 * moves, in score order.
575 var find_nonstupid_moves = function(data, margin, invert) {
576 // First of all, if there are any moves that are more than 0.5 ahead of
577 // the primary move, the refutation lines are probably bunk, so just
579 var best_score = undefined;
580 var pv_score = undefined;
581 for (var move in data['refutation_lines']) {
582 var score = compute_score_sort_key(data['refutation_lines'][move]['score'], invert);
583 if (move == data['pv_uci'][0]) {
586 if (best_score === undefined || score > best_score) {
589 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
594 if (best_score - pv_score > 50) {
598 // Now find all moves that are within “margin” of the best score.
599 // The PV move will always be first.
601 for (var move in data['refutation_lines']) {
602 var score = compute_score_sort_key(data['refutation_lines'][move]['score'], invert);
603 if (move != data['pv_uci'][0] && best_score - score <= margin) {
607 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], data['position']['toplay'] === 'B', a, b) });
608 moves.unshift(data['pv_uci'][0]);
617 var thousands = function(x) {
618 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
622 * @param {!string} start_fen
623 * @param {Array.<string>} pretty_pv
624 * @param {number} move_num
625 * @param {!string} toplay
626 * @param {number} start_display_move_num
627 * @param {number=} opt_limit
628 * @param {boolean=} opt_showlast
630 var add_pv = function(start_fen, pretty_pv, move_num, toplay, start_display_move_num, opt_limit, opt_showlast) {
632 start_fen: start_fen,
633 pretty_pv: pretty_pv,
634 move_num: parseInt(move_num),
636 start_display_move_num: start_display_move_num,
638 return print_pv(display_lines.length - 1, opt_limit, opt_showlast);
642 * @param {number} line_num
643 * @param {number=} opt_limit
644 * @param {boolean=} opt_showlast
646 var print_pv = function(line_num, opt_limit, opt_showlast) {
647 var display_line = display_lines[line_num];
648 var pretty_pv = display_line.pretty_pv;
649 var move_num = display_line.move_num;
650 var toplay = display_line.toplay;
652 // Truncate PV at the start if needed.
653 var start_display_move_num = display_line.start_display_move_num;
654 if (start_display_move_num > 0) {
655 pretty_pv = pretty_pv.slice(start_display_move_num);
656 var to_add = start_display_move_num;
657 if (toplay === 'B') {
662 if (to_add % 2 == 1) {
666 move_num += to_add / 2;
671 if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
672 // Truncate the PV at the beginning (instead of at the end).
673 // We assume here that toplay is 'W'. We also assume that if
674 // opt_showlast is set, then it is the history, and thus,
675 // the UI should be to expand the history.
676 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
677 i = pretty_pv.length - opt_limit;
682 } else if (toplay == 'B' && pretty_pv.length > 0) {
683 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
684 pv = move_num + '. … ' + move;
689 for ( ; i < pretty_pv.length; ++i) {
690 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
693 if (i > opt_limit && !opt_showlast) {
699 pv += move_num + '. ' + move;
710 /** Update the highlighted to/from squares on the board.
711 * Based on the global "highlight_from" and "highlight_to" variables.
713 var update_board_highlight = function() {
714 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
715 if ((current_display_line === null || current_display_line_is_history) &&
716 highlight_from !== undefined && highlight_to !== undefined) {
717 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
718 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
722 var update_history = function() {
723 if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
724 $("#history").html("No history");
725 } else if (truncate_display_history) {
726 $("#history").html(print_pv(0, 8, true));
729 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
730 print_pv(0, 1, 'W'));
735 * @param {!boolean} truncate_history
737 var collapse_history = function(truncate_history) {
738 truncate_display_history = truncate_history;
741 window['collapse_history'] = collapse_history;
743 /** Update the HTML display of multi-PV from the global "refutation_lines".
745 * Also recreates the global "display_lines".
747 var update_refutation_lines = function() {
748 if (base_fen === null) {
751 if (display_lines.length > 2) {
752 // Truncate so that only the history and PV is left.
753 display_lines = [ display_lines[0], display_lines[1] ];
755 var tbl = $("#refutationlines");
758 // Find out where the lines start from.
760 var start_display_move_num = 0;
761 if (hash_refutation_lines) {
762 base_line = current_display_line.pretty_pv.slice(0, current_display_move + 1);
763 start_display_move_num = base_line.length;
767 for (var move in refutation_lines) {
771 var invert = (toplay === 'B');
772 if (current_display_line && current_display_move % 2 == 0) {
775 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
776 moves = moves.sort(function(a, b) { return compare(refutation_lines, invert, a, b) });
777 for (var i = 0; i < moves.length; ++i) {
778 var line = refutation_lines[moves[i]];
780 var tr = document.createElement("tr");
782 var move_td = document.createElement("td");
783 tr.appendChild(move_td);
784 $(move_td).addClass("move");
786 if (line['pv_pretty'].length == 0) {
787 // Not found, so just make a one-move PV.
788 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
789 $(move_td).html(move);
790 var score_td = document.createElement("td");
792 $(score_td).addClass("score");
793 $(score_td).text("—");
794 tr.appendChild(score_td);
796 var depth_td = document.createElement("td");
797 tr.appendChild(depth_td);
798 $(depth_td).addClass("depth");
799 $(depth_td).text("—");
801 var pv_td = document.createElement("td");
802 tr.appendChild(pv_td);
803 $(pv_td).addClass("pv");
804 $(pv_td).html(add_pv(base_fen, base_line.concat([ line['pretty_move'] ]), move_num, toplay, start_display_move_num));
810 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
811 $(move_td).html(move);
813 var score_td = document.createElement("td");
814 tr.appendChild(score_td);
815 $(score_td).addClass("score");
816 $(score_td).text(format_short_score(line['score']));
818 var depth_td = document.createElement("td");
819 tr.appendChild(depth_td);
820 $(depth_td).addClass("depth");
821 $(depth_td).text("d" + line['depth']);
823 var pv_td = document.createElement("td");
824 tr.appendChild(pv_td);
825 $(pv_td).addClass("pv");
826 $(pv_td).html(add_pv(base_fen, base_line.concat(line['pv_pretty']), move_num, toplay, start_display_move_num, 10));
831 // Make one of the links clickable and the other nonclickable.
832 if (sort_refutation_lines_by_score) {
833 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
834 $("#sortbyscore1").html("<strong>Score</strong>");
836 $("#sortbyscore0").html("<strong>Move</strong>");
837 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
840 // Update the move highlight, as we've rewritten all the HTML.
841 update_move_highlight();
845 * Create a Chess.js board object, containing the given position plus the given moves,
846 * up to the given limit.
848 * @param {?string} fen
849 * @param {Array.<string>} moves
850 * @param {number} last_move
852 var chess_from = function(fen, moves, last_move) {
853 var hiddenboard = new Chess();
855 hiddenboard.load(fen);
857 for (var i = 0; i <= last_move; ++i) {
858 if (moves[i] === '0-0') {
859 hiddenboard.move('O-O');
860 } else if (moves[i] === '0-0-0') {
861 hiddenboard.move('O-O-O');
863 hiddenboard.move(moves[i]);
869 var update_game_list = function(games) {
870 $("#games").text("");
871 if (games === null) {
875 var games_div = document.getElementById('games');
876 for (var game_num = 0; game_num < games.length; ++game_num) {
877 var game = games[game_num];
878 var game_span = document.createElement("span");
879 game_span.setAttribute("class", "game");
881 var game_name = document.createTextNode(game['name']);
882 if (game['url'] === backend_url) {
883 game_span.appendChild(game_name);
885 var game_a = document.createElement("a");
886 game_a.setAttribute("href", "#" + game['id']);
887 game_a.appendChild(game_name);
888 game_span.appendChild(game_a);
890 games_div.appendChild(game_span);
895 * Try to find a running game that matches with the current hash,
896 * and switch to it if we're not already displaying it.
898 var possibly_switch_game_from_hash = function() {
899 if (current_games === null) {
903 var hash = window.location.hash.replace(/^#/,'');
904 for (var i = 0; i < current_games.length; ++i) {
905 if (current_games[i]['id'] === hash) {
906 if (backend_url !== current_games[i]['url']) {
907 switch_backend(current_games[i]['url']);
914 /** Update all the HTML on the page, based on current global state.
916 var update_board = function() {
917 var data = displayed_analysis_data || current_analysis_data;
918 var current_data = current_analysis_data; // Convenience alias.
922 // Print the history. This is pretty much the only thing that's
923 // unconditionally taken from current_data (we're not interested in
924 // historic history).
925 if (current_data['position']['pretty_history']) {
926 add_pv('start', current_data['position']['pretty_history'], 1, 'W', 0, 8, true);
928 display_lines.push(null);
932 // Games currently in progress, if any.
933 if (current_data['games']) {
934 current_games = current_data['games'];
935 possibly_switch_game_from_hash();
936 update_game_list(current_data['games']);
938 current_games = null;
939 update_game_list(null);
942 // The headline. Names are always fetched from current_data;
943 // the rest can depend a bit.
946 current_data['position']['player_w'] && current_data['position']['player_b']) {
947 headline = current_data['position']['player_w'] + '–' +
948 current_data['position']['player_b'] + ', analysis';
950 headline = 'Analysis';
953 // Credits, where applicable. Note that we don't want the footer to change a lot
954 // when e.g. viewing history, so if any of these changed during the game,
955 // use the current one still.
956 if (current_data['using_lomonosov']) {
957 $("#lomonosov").show();
959 $("#lomonosov").hide();
962 // Credits: The engine name/version.
963 if (current_data['engine'] && current_data['engine']['name'] !== null) {
964 $("#engineid").text(current_data['engine']['name']);
967 // Credits: The engine URL.
968 if (current_data['engine'] && current_data['engine']['url']) {
969 $("#engineid").attr("href", current_data['engine']['url']);
971 $("#engineid").removeAttr("href");
974 // Credits: Engine details.
975 if (current_data['engine'] && current_data['engine']['details']) {
976 $("#enginedetails").text(" (" + current_data['engine']['details'] + ")");
978 $("#enginedetails").text("");
981 // Credits: Move source, possibly with URL.
982 if (current_data['move_source'] && current_data['move_source_url']) {
983 $("#movesource").text("Moves provided by ");
984 var movesource_a = document.createElement("a");
985 movesource_a.setAttribute("href", current_data['move_source_url']);
986 var movesource_text = document.createTextNode(current_data['move_source']);
987 movesource_a.appendChild(movesource_text);
988 var movesource_period = document.createTextNode(".");
989 document.getElementById("movesource").appendChild(movesource_a);
990 document.getElementById("movesource").appendChild(movesource_period);
991 } else if (current_data['move_source']) {
992 $("#movesource").text("Moves provided by " + current_data['move_source'] + ".");
994 $("#movesource").text("");
998 if (displayed_analysis_data) {
999 // Displaying some non-current position, pick out the last move
1000 // from the history. This will work even if the fetch failed.
1001 last_move = format_halfmove_with_number(
1002 current_display_line.pretty_pv[current_display_move],
1003 current_display_move + 1);
1004 headline += ' after ' + last_move;
1005 } else if (data['position']['last_move'] !== 'none') {
1006 last_move = format_move_with_number(
1007 data['position']['last_move'],
1008 data['position']['move_num'],
1009 data['position']['toplay'] == 'W');
1010 headline += ' after ' + last_move;
1014 $("#headline").text(headline);
1016 // The <title> contains a very brief headline.
1017 var title_elems = [];
1018 if (data['score']) {
1019 title_elems.push(format_short_score(data['score']).replace(/^ /, ""));
1021 if (last_move !== null) {
1022 title_elems.push(last_move);
1025 if (title_elems.length != 0) {
1026 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
1028 document.title = 'analysis.sesse.net';
1031 // The last move (shown by highlighting the from and to squares).
1032 if (data['position'] && data['position']['last_move_uci']) {
1033 highlight_from = data['position']['last_move_uci'].substr(0, 2);
1034 highlight_to = data['position']['last_move_uci'].substr(2, 2);
1035 } else if (current_display_line_is_history && current_display_move >= 0) {
1036 // We don't have historic analysis for this position, but we
1037 // can reconstruct what the last move was by just replaying
1039 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1040 var moves = hiddenboard.history({ verbose: true });
1041 var last_move = moves.pop();
1042 highlight_from = last_move.from;
1043 highlight_to = last_move.to;
1045 highlight_from = highlight_to = undefined;
1047 update_board_highlight();
1049 if (data['failed']) {
1050 $("#score").text("No analysis for this move");
1051 $("#pvtitle").text("PV:");
1053 $("#searchstats").html(" ");
1054 $("#refutationlines").empty();
1055 $("#whiteclock").empty();
1056 $("#blackclock").empty();
1057 refutation_lines = [];
1058 update_refutation_lines();
1060 update_displayed_line();
1061 update_move_highlight();
1068 if (data['score']) {
1069 $("#score").text(format_long_score(data['score']));
1072 // The search stats.
1073 if (data['searchstats']) {
1074 $("#searchstats").html(data['searchstats']);
1075 } else if (data['tablebase'] == 1) {
1076 $("#searchstats").text("Tablebase result");
1077 } else if (data['nodes'] && data['nps'] && data['depth']) {
1078 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
1079 if (data['seldepth']) {
1080 stats += ' (' + data['seldepth'] + ' selective)';
1082 if (data['tbhits'] && data['tbhits'] > 0) {
1083 if (data['tbhits'] == 1) {
1084 stats += ', one Syzygy hit';
1086 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
1090 $("#searchstats").text(stats);
1092 $("#searchstats").text("");
1095 // Update the board itself.
1096 base_fen = data['position']['fen'];
1097 update_displayed_line();
1100 $("#pvtitle").text("PV:");
1101 $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay'], 0));
1103 // Update the PV arrow.
1105 if (data['pv_uci'].length >= 1) {
1106 // draw a continuation arrow as long as it's the same piece
1107 for (var i = 0; i < data['pv_uci'].length; i += 2) {
1108 var from = data['pv_uci'][i].substr(0, 2);
1109 var to = data['pv_uci'][i].substr(2,4);
1110 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
1111 interfering_arrow(from, to)) {
1114 create_arrow(from, to, '#f66', 6, 20);
1117 var alt_moves = find_nonstupid_moves(data, 30, data['position']['toplay'] === 'B');
1118 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
1119 create_arrow(alt_moves[i].substr(0, 2),
1120 alt_moves[i].substr(2, 2), '#f66', 1, 10);
1124 // See if all semi-reasonable moves have only one possible response.
1125 if (data['pv_uci'].length >= 2) {
1126 var nonstupid_moves = find_nonstupid_moves(data, 300, data['position']['toplay'] === 'B');
1127 var response = data['pv_uci'][1];
1128 for (var i = 0; i < nonstupid_moves.length; ++i) {
1129 if (nonstupid_moves[i] == data['pv_uci'][0]) {
1130 // ignore the PV move for refutation lines.
1133 if (!data['refutation_lines'] ||
1134 !data['refutation_lines'][nonstupid_moves[i]] ||
1135 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
1136 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
1137 // Incomplete PV, abort.
1138 response = undefined;
1141 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
1142 if (response !== this_response) {
1143 // Different response depending on lines, abort.
1144 response = undefined;
1149 if (nonstupid_moves.length > 0 && response !== undefined) {
1150 create_arrow(response.substr(0, 2),
1151 response.substr(2, 2), '#66f', 6, 20);
1155 // Update the refutation lines.
1156 base_fen = data['position']['fen'];
1157 move_num = parseInt(data['position']['move_num']);
1158 toplay = data['position']['toplay'];
1159 refutation_lines = hash_refutation_lines || data['refutation_lines'];
1160 update_refutation_lines();
1162 // Update the sparkline last, since its size depends on how everything else reflowed.
1163 update_sparkline(data);
1166 var update_sparkline = function(data) {
1167 if (data && data['score_history']) {
1168 var first_move_num = undefined;
1169 for (var halfmove_num in data['score_history']) {
1170 halfmove_num = parseInt(halfmove_num);
1171 if (first_move_num === undefined || halfmove_num < first_move_num) {
1172 first_move_num = halfmove_num;
1175 if (first_move_num !== undefined) {
1176 var last_move_num = data['position']['move_num'] * 2 - 3;
1177 if (data['position']['toplay'] === 'B') {
1181 // Possibly truncate some moves if we don't have enough width.
1182 // FIXME: Sometimes width() for #scorecontainer (and by extent,
1183 // #scoresparkcontainer) on Chrome for mobile seems to start off
1184 // at something very small, and then suddenly snap back into place.
1186 var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
1187 if (last_move_num - first_move_num > max_moves) {
1188 first_move_num = last_move_num - max_moves;
1191 var min_score = -100;
1192 var max_score = 100;
1193 var last_score = null;
1195 for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1196 if (data['score_history'][halfmove_num]) {
1197 var score = compute_plot_score(data['score_history'][halfmove_num]);
1199 if (score < min_score) min_score = score;
1200 if (score > max_score) max_score = score;
1202 scores.push(last_score);
1204 if (data['score']) {
1205 scores.push(compute_plot_score(data['score']));
1207 // FIXME: at some widths, calling sparkline() seems to push
1208 // #scorecontainer under the board.
1209 $("#scorespark").sparkline(scores, {
1212 chartRangeMin: min_score,
1213 chartRangeMax: max_score,
1214 tooltipFormatter: function(sparkline, options, fields) {
1215 return format_tooltip(data, fields[0].offset + first_move_num);
1219 $("#scorespark").text("");
1222 $("#scorespark").text("");
1227 * @param {number} num_viewers
1229 var update_num_viewers = function(num_viewers) {
1230 if (num_viewers === null) {
1231 $("#numviewers").text("");
1232 } else if (num_viewers == 1) {
1233 $("#numviewers").text("You are the only current viewer");
1235 $("#numviewers").text(num_viewers + " current viewers");
1239 var update_clock = function() {
1240 clearTimeout(clock_timer);
1242 var data = displayed_analysis_data || current_analysis_data;
1243 if (data['position']) {
1244 var result = data['position']['result'];
1245 if (result === '1-0') {
1246 $("#whiteclock").text("1");
1247 $("#blackclock").text("0");
1248 $("#whiteclock").removeClass("running-clock");
1249 $("#blackclock").removeClass("running-clock");
1252 if (result === '1/2-1/2') {
1253 $("#whiteclock").text("1/2");
1254 $("#blackclock").text("1/2");
1255 $("#whiteclock").removeClass("running-clock");
1256 $("#blackclock").removeClass("running-clock");
1259 if (result === '0-1') {
1260 $("#whiteclock").text("0");
1261 $("#blackclock").text("1");
1262 $("#whiteclock").removeClass("running-clock");
1263 $("#blackclock").removeClass("running-clock");
1268 var white_clock_ms = null;
1269 var black_clock_ms = null;
1270 var show_seconds = false;
1273 if (data['position'] &&
1274 data['position']['white_clock'] &&
1275 data['position']['black_clock']) {
1276 white_clock_ms = data['position']['white_clock'] * 1000;
1277 black_clock_ms = data['position']['black_clock'] * 1000;
1280 // Dynamic clock (only one, obviously).
1282 if (data['position']['white_clock_target']) {
1284 $("#whiteclock").addClass("running-clock");
1285 $("#blackclock").removeClass("running-clock");
1286 } else if (data['position']['black_clock_target']) {
1288 $("#whiteclock").removeClass("running-clock");
1289 $("#blackclock").addClass("running-clock");
1291 $("#whiteclock").removeClass("running-clock");
1292 $("#blackclock").removeClass("running-clock");
1296 var now = new Date().getTime() + client_clock_offset_ms;
1297 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1298 if (color === "white") {
1299 white_clock_ms = remaining_ms;
1301 black_clock_ms = remaining_ms;
1305 if (white_clock_ms === null || black_clock_ms === null) {
1306 $("#whiteclock").empty();
1307 $("#blackclock").empty();
1311 // If either player has ten minutes or less left, add the second counters.
1312 var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
1315 // See when the clock will change next, and update right after that.
1318 next_update_ms = remaining_ms % 1000 + 100;
1320 next_update_ms = remaining_ms % 60000 + 100;
1322 clock_timer = setTimeout(update_clock, next_update_ms);
1325 $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1326 $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1330 * @param {Number} remaining_ms
1331 * @param {boolean} show_seconds
1333 var format_clock = function(remaining_ms, show_seconds) {
1334 if (remaining_ms <= 0) {
1342 var remaining = Math.floor(remaining_ms / 1000);
1343 var seconds = remaining % 60;
1344 remaining = (remaining - seconds) / 60;
1345 var minutes = remaining % 60;
1346 remaining = (remaining - minutes) / 60;
1347 var hours = remaining;
1349 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1351 return format_2d(hours) + ":" + format_2d(minutes);
1358 var format_2d = function(x) {
1367 * @param {string} move
1368 * @param {Number} move_num
1369 * @param {boolean} white_to_play
1371 var format_move_with_number = function(move, move_num, white_to_play) {
1373 if (white_to_play) {
1374 ret = (move_num - 1) + '… ';
1376 ret = move_num + '. ';
1383 * @param {string} move
1384 * @param {Number} halfmove_num
1386 var format_halfmove_with_number = function(move, halfmove_num) {
1387 return format_move_with_number(
1389 Math.floor(halfmove_num / 2) + 1,
1390 halfmove_num % 2 == 0);
1394 * @param {Object} data
1395 * @param {Number} halfmove_num
1397 var format_tooltip = function(data, halfmove_num) {
1398 if (data['score_history'][halfmove_num] ||
1399 halfmove_num === data['position']['pretty_history'].length) {
1402 if (halfmove_num === data['position']['pretty_history'].length) {
1403 move = data['position']['last_move'];
1404 short_score = format_short_score(data['score']);
1406 move = data['position']['pretty_history'][halfmove_num];
1407 short_score = format_short_score(data['score_history'][halfmove_num]);
1409 var move_with_number = format_halfmove_with_number(move, halfmove_num);
1411 return "After " + move_with_number + ": " + short_score;
1413 for (var i = halfmove_num; i --> 0; ) {
1414 if (data['score_history'][i]) {
1415 var move = data['position']['pretty_history'][i];
1416 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1423 * @param {boolean} sort_by_score
1425 var resort_refutation_lines = function(sort_by_score) {
1426 sort_refutation_lines_by_score = sort_by_score;
1427 if (supports_html5_storage()) {
1428 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1430 update_refutation_lines();
1432 window['resort_refutation_lines'] = resort_refutation_lines;
1435 * @param {boolean} truncate_history
1437 var set_truncate_history = function(truncate_history) {
1438 truncate_display_history = truncate_history;
1439 update_refutation_lines();
1441 window['set_truncate_history'] = set_truncate_history;
1444 * @param {number} line_num
1445 * @param {number} move_num
1447 var show_line = function(line_num, move_num) {
1448 if (line_num == -1) {
1449 current_display_line = null;
1450 current_display_move = null;
1451 hash_refutation_lines = null;
1452 if (displayed_analysis_data) {
1453 // TODO: Support exiting to history position if we are in an
1454 // analysis line of a history position.
1455 displayed_analysis_data = null;
1460 current_display_line = jQuery.extend({}, display_lines[line_num]); // Shallow clone.
1461 current_display_move = move_num + current_display_line.start_display_move_num;
1463 current_display_line_is_history = (line_num == 0);
1465 update_historic_analysis();
1466 update_displayed_line();
1467 update_board_highlight();
1468 update_move_highlight();
1471 window['show_line'] = show_line;
1473 var prev_move = function() {
1474 if (current_display_line &&
1475 current_display_move >= current_display_line.start_display_move_num) {
1476 --current_display_move;
1478 update_historic_analysis();
1479 update_displayed_line();
1480 update_move_highlight();
1482 window['prev_move'] = prev_move;
1484 var next_move = function() {
1485 if (current_display_line &&
1486 current_display_move < current_display_line.pretty_pv.length - 1) {
1487 ++current_display_move;
1489 update_historic_analysis();
1490 update_displayed_line();
1491 update_move_highlight();
1493 window['next_move'] = next_move;
1495 var update_historic_analysis = function() {
1496 if (!current_display_line_is_history) {
1499 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1500 displayed_analysis_data = null;
1504 // Fetch old analysis for this line if it exists.
1505 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1506 var filename = "/history/move" + (current_display_move + 1) + "-" +
1507 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1509 current_historic_xhr = $.ajax({
1511 }).done(function(data, textstatus, xhr) {
1512 displayed_analysis_data = data;
1514 }).fail(function(jqXHR, textStatus, errorThrown) {
1515 if (textStatus === "abort") {
1516 // Aborted because we are switching backends. Don't do anything;
1517 // we will already have been cleared.
1519 displayed_analysis_data = {'failed': true};
1526 * @param {string} fen
1528 var update_imbalance = function(fen) {
1529 var hiddenboard = new Chess(fen);
1530 var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1531 for (var row = 0; row < 8; ++row) {
1532 for (var col = 0; col < 8; ++col) {
1533 var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1534 var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1535 var square = col_text + row_text;
1536 var contents = hiddenboard.get(square);
1537 if (contents !== null) {
1538 if (contents.color === 'w') {
1539 ++imbalance[contents.type];
1541 --imbalance[contents.type];
1546 var white_imbalance = '';
1547 var black_imbalance = '';
1548 for (var piece in imbalance) {
1549 for (var i = 0; i < imbalance[piece]; ++i) {
1550 white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1552 for (var i = 0; i < -imbalance[piece]; ++i) {
1553 black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1556 $('#whiteimbalance').html(white_imbalance);
1557 $('#blackimbalance').html(black_imbalance);
1560 /** Mark the currently selected move in red.
1561 * Also replaces the PV with the current displayed line if it's not shown
1562 * anywhere else on the screen.
1564 var update_move_highlight = function() {
1565 if (highlighted_move !== null) {
1566 highlighted_move.removeClass('highlight');
1568 if (current_display_line) {
1569 var display_line_num = find_display_line_matching_num();
1570 if (display_line_num === null) {
1571 // Replace the PV with the (complete) line.
1572 $("#pvtitle").text("Exploring:");
1573 current_display_line.start_display_move_num = 0;
1574 display_lines.push(current_display_line);
1575 $("#pv").html(print_pv(display_lines.length - 1));
1576 display_line_num = display_lines.length - 1;
1579 highlighted_move = $("#automove" + display_line_num + "-" + (current_display_move - current_display_line.start_display_move_num));
1580 highlighted_move.addClass('highlight');
1585 * See if the current displayed line is identical to any of the ones
1586 * we have on screen. (It might not be if e.g. the analysis reloaded
1587 * since we started looking.)
1591 var find_display_line_matching_num = function() {
1592 for (var i = 0; i < display_lines.length; ++i) {
1593 var line = display_lines[i];
1594 if (line.start_display_move_num > 0) continue;
1595 if (current_display_line.start_fen !== line.start_fen) continue;
1596 if (current_display_line.pretty_pv.length !== line.pretty_pv.length) continue;
1598 for (var j = 0; j < line.pretty_pv.length; ++j) {
1599 if (current_display_line.pretty_pv[j] !== line.pretty_pv[j]) {
1611 var update_displayed_line = function() {
1612 if (current_display_line === null) {
1613 $("#linenav").hide();
1614 $("#linemsg").show();
1615 display_fen = base_fen;
1616 board.position(base_fen);
1617 update_imbalance(base_fen);
1621 $("#linenav").show();
1622 $("#linemsg").hide();
1624 if (current_display_move <= 0) {
1625 $("#prevmove").html("Previous");
1627 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1629 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1630 $("#nextmove").html("Next");
1632 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1635 var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pretty_pv, current_display_move);
1636 display_fen = hiddenboard.fen();
1637 board_is_animating = true;
1638 var old_fen = board.fen();
1639 board.position(hiddenboard.fen());
1640 if (board.fen() === old_fen) {
1641 board_is_animating = false;
1642 } else if (!current_display_line_is_history) {
1643 // Fire off a hash request, since we're now off the main position
1644 // and it just changed.
1645 explore_hash(display_fen);
1647 update_imbalance(hiddenboard.fen());
1651 * @param {boolean} param_enable_sound
1653 var set_sound = function(param_enable_sound) {
1654 enable_sound = param_enable_sound;
1656 $("#soundon").html("<strong>On</strong>");
1657 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1659 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1660 // and also preload the file since the user has selected audio.
1661 var ding = document.getElementById('ding');
1662 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1663 ding.src = 'ding.opus';
1667 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1668 $("#soundoff").html("<strong>Off</strong>");
1670 if (supports_html5_storage()) {
1671 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1674 window['set_sound'] = set_sound;
1676 /** Send off a hash probe request to the backend.
1677 * @param {string} fen
1679 var explore_hash = function(fen) {
1680 // If we already have a backend response going, abort it.
1681 if (current_hash_xhr) {
1682 current_hash_xhr.abort();
1684 if (current_hash_display_timer) {
1685 clearTimeout(current_hash_display_timer);
1686 current_hash_display_timer = null;
1688 $("#refutationlines").empty();
1689 current_hash_xhr = $.ajax({
1690 url: backend_hash_url + "?fen=" + fen
1691 }).done(function(data, textstatus, xhr) {
1692 show_explore_hash_results(data, fen);
1696 /** Process the JSON response from a hash probe request.
1697 * @param {!Object} data
1698 * @param {string} fen
1700 var show_explore_hash_results = function(data, fen) {
1701 if (board_is_animating) {
1702 // Updating while the animation is still going causes
1703 // the animation to jerk. This is pretty crude, but it will do.
1704 current_hash_display_timer = setTimeout(function() { show_explore_hash_results(data, fen); }, 100);
1707 current_hash_display_timer = null;
1708 hash_refutation_lines = data['lines'];
1712 // almost all of this stuff comes from the chessboard.js example page
1713 var onDragStart = function(source, piece, position, orientation) {
1714 var pseudogame = new Chess(display_fen);
1715 if (pseudogame.game_over() === true ||
1716 (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
1717 (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
1721 recommended_move = get_best_move(pseudogame, source, null, pseudogame.turn() === 'b');
1722 if (recommended_move) {
1723 var squareEl = $('#board .square-' + recommended_move.to);
1724 squareEl.addClass('highlight1-32417');
1729 var mousedownSquare = function(e) {
1730 reverse_dragging_from = null;
1731 var square = $(this).attr('data-square');
1733 var pseudogame = new Chess(display_fen);
1734 if (pseudogame.game_over() === true) {
1738 // If the square is empty, or has a piece of the side not to move,
1739 // we handle it. If not, normal piece dragging will take it.
1740 var position = board.position();
1741 if (!position.hasOwnProperty(square) ||
1742 (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
1743 (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
1744 reverse_dragging_from = square;
1745 recommended_move = get_best_move(pseudogame, null, square, pseudogame.turn() === 'b');
1746 if (recommended_move) {
1747 var squareEl = $('#board .square-' + recommended_move.from);
1748 squareEl.addClass('highlight1-32417');
1749 squareEl = $('#board .square-' + recommended_move.to);
1750 squareEl.addClass('highlight1-32417');
1755 var mouseupSquare = function(e) {
1756 if (reverse_dragging_from === null) {
1759 var source = $(this).attr('data-square');
1760 var target = reverse_dragging_from;
1761 reverse_dragging_from = null;
1762 if (onDrop(source, target) !== 'snapback') {
1763 onSnapEnd(source, target);
1765 $("#board").find('.square-55d63').removeClass('highlight1-32417');
1768 var get_best_move = function(game, source, target, invert) {
1769 var moves = game.moves({ verbose: true });
1770 if (source !== null) {
1771 moves = moves.filter(function(move) { return move.from == source; });
1773 if (target !== null) {
1774 moves = moves.filter(function(move) { return move.to == target; });
1776 if (moves.length == 0) {
1779 if (moves.length == 1) {
1783 // More than one move. Use the display lines (if we have them)
1784 // to disambiguate; otherwise, we have no information.
1786 for (var i = 0; i < moves.length; ++i) {
1787 move_hash[moves[i].san] = moves[i];
1790 // History and PV take priority over the display lines.
1791 for (var i = 0; i < 2; ++i) {
1792 var line = display_lines[i];
1793 var first_move = line.pretty_pv[line.start_display_move_num];
1794 if (move_hash[first_move]) {
1795 return move_hash[first_move];
1799 var best_move = null;
1800 var best_move_score = null;
1802 for (var move in refutation_lines) {
1803 var line = refutation_lines[move];
1804 if (!line['score']) {
1807 var first_move = line['pv_pretty'][0];
1808 if (move_hash[first_move]) {
1809 var score = compute_score_sort_key(line['score'], invert);
1810 if (best_move_score === null || score > best_move_score) {
1811 best_move = move_hash[first_move];
1812 best_move_score = score;
1819 var onDrop = function(source, target) {
1820 if (source === target) {
1821 if (recommended_move === null) {
1824 // Accept the move. It will be changed in onSnapEnd.
1828 // Suggestion not asked for.
1829 recommended_move = null;
1832 // see if the move is legal
1833 var pseudogame = new Chess(display_fen);
1834 var move = pseudogame.move({
1837 promotion: 'q' // NOTE: always promote to a queen for example simplicity
1841 if (move === null) return 'snapback';
1844 var onSnapEnd = function(source, target) {
1845 if (source === target && recommended_move !== null) {
1846 source = recommended_move.from;
1847 target = recommended_move.to;
1849 recommended_move = null;
1850 var pseudogame = new Chess(display_fen);
1851 var move = pseudogame.move({
1854 promotion: 'q' // NOTE: always promote to a queen for example simplicity
1857 if (current_display_line &&
1858 current_display_move < current_display_line.pretty_pv.length - 1 &&
1859 current_display_line.pretty_pv[current_display_move] === move.san) {
1864 // Walk down the displayed lines until we find one that starts with
1865 // this move, then select that. Note that this gives us a good priority
1866 // order (history first, then PV, then multi-PV lines).
1867 for (var i = 0; i < display_lines.length; ++i) {
1868 var line = display_lines[i];
1869 if (line.pretty_pv[line.start_display_move_num] === move.san) {
1875 // Shouldn't really be here if we have hash probes, but there's really
1876 // nothing we can do.
1878 // End of dragging-related code.
1880 var pad = function(val, num_digits) {
1881 var s = val.toString();
1882 while (s.length < num_digits) {
1888 var fmt_cp = function(v) {
1892 return "+" + (v / 100).toFixed(2);
1895 return "-" + (v / 100).toFixed(2);
1899 var format_short_score = function(score) {
1900 if (score[0] === 'm') {
1901 if (score[2]) { // Is a bound.
1902 return score[2] + "\u00a0M" + pad(score[1], 3);
1904 return "M" + pad(score[1], 3);
1906 } else if (score[0] === 'd') {
1908 } else if (score[0] === 'cp') {
1909 if (score[2]) { // Is a bound.
1910 return score[2] + "\u00a0" + fmt_cp(score[1]);
1912 return pad(fmt_cp(score[1]), 5);
1918 var format_long_score = function(score) {
1919 if (score[0] === 'm') {
1921 return "White mates in " + score[1];
1923 return "Black mates in " + (-score[1]);
1925 } else if (score[0] === 'd') {
1926 return "Theoretical draw";
1927 } else if (score[0] === 'cp') {
1928 return "Score: " + format_short_score(score);
1933 var compute_plot_score = function(score) {
1934 if (score[0] === 'm') {
1940 } else if (score[0] === 'd') {
1942 } else if (score[0] === 'cp') {
1943 if (score[1] > 500) {
1945 } else if (score[1] < -500) {
1955 * @param score The score digest tuple.
1956 * @param {boolean} invert Whether black is to play.
1959 var compute_score_sort_key = function(score, invert) {
1964 if (score[0] === 'm') {
1967 s = 99999 - score[1];
1969 // Black mates (note the double negative for score[1]).
1970 s = -99999 - score[1];
1974 } else if (score[0] === 'd') {
1976 } else if (score[0] === 'cp') {
1977 return invert ? -score[1] : score[1];
1983 * @param {string} new_backend_url
1985 var switch_backend = function(new_backend_url) {
1986 // Stop looking at historic data.
1987 current_display_line = null;
1988 current_display_move = null;
1989 displayed_analysis_data = null;
1990 if (current_historic_xhr) {
1991 current_historic_xhr.abort();
1994 // If we already have a backend response going, abort it.
1995 if (current_analysis_xhr) {
1996 current_analysis_xhr.abort();
1998 if (current_hash_xhr) {
1999 current_hash_xhr.abort();
2002 // Otherwise, we should have a timer going to start a new one.
2004 if (current_analysis_request_timer) {
2005 clearTimeout(current_analysis_request_timer);
2006 current_analysis_request_timer = null;
2008 if (current_hash_display_timer) {
2009 clearTimeout(current_hash_display_timer);
2010 current_hash_display_timer = null;
2013 // Request an immediate fetch with the new backend.
2014 backend_url = new_backend_url;
2015 current_analysis_data = null;
2019 window['switch_backend'] = switch_backend;
2021 var init = function() {
2022 unique = get_unique();
2024 // Load settings from HTML5 local storage if available.
2025 if (supports_html5_storage() && localStorage['enable_sound']) {
2026 set_sound(parseInt(localStorage['enable_sound']));
2030 if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
2031 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
2033 sort_refutation_lines_by_score = true;
2037 board = new window.ChessBoard('board', {
2038 onMoveEnd: function() { board_is_animating = false; },
2041 onDragStart: onDragStart,
2043 onSnapEnd: onSnapEnd
2045 $("#board").on('mousedown', '.square-55d63', mousedownSquare);
2046 $("#board").on('mouseup', '.square-55d63', mouseupSquare);
2049 $(window).resize(function() {
2051 update_sparkline(displayed_analysis_data || current_analysis_data);
2052 update_board_highlight();
2055 $(window).keyup(function(event) {
2056 if (event.which == 39) {
2058 } else if (event.which == 37) {
2062 window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
2064 $(document).ready(init);