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 = 2016113002;
13 * The current backend URL.
18 var backend_url = "/analysis.pl";
19 var backend_hash_url = "/hash";
21 /** @type {window.ChessBoard} @private */
24 /** @type {boolean} @private */
25 var board_is_animating = false;
28 * The most recent analysis data we have from the server
29 * (about the most recent position).
33 var current_analysis_data = null;
36 * If we are displaying previous analysis or from hash, this is non-null,
37 * and will override most of current_analysis_data.
42 var displayed_analysis_data = null;
45 * Games currently in progress, if any.
57 var current_games = null;
72 /** @type {Array.<Array.<boolean>>} */
73 var occupied_by_arrows = [];
75 /** Currently displayed refutation lines (on-screen).
76 * Can either come from the current_analysis_data, displayed_analysis_data,
77 * or hash_refutation_lines.
79 var refutation_lines = [];
81 /** Refutation lines from current hash probe.
83 * If non-null, will override refutation lines from the base position.
84 * Note that these are relative to display_fen, not base_fen.
86 var hash_refutation_lines = null;
88 /** @type {!number} @private */
91 /** @type {!string} @private */
94 /** @type {number} @private */
97 /** @type {boolean} @private */
98 var 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 * pv: Array.<string>,
161 * scores: Array<{first_move: number, score: Object}>,
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 // Verify that the PV makes sense.
279 if (new_data['pv']) {
280 var hiddenboard = new Chess(new_data['position']['fen']);
281 for (var i = 0; i < new_data['pv'].length; ++i) {
282 if (hiddenboard.move(new_data['pv'][i]) === null) {
291 possibly_play_sound(current_analysis_data, new_data);
292 current_analysis_data = new_data;
294 update_num_viewers(num_viewers);
296 console.log("Received invalid update, waiting five seconds and trying again.");
297 location.reload(true);
301 current_analysis_request_timer = setTimeout(function() { request_update(); }, timeout);
302 }).fail(function(jqXHR, textStatus, errorThrown) {
303 if (textStatus === "abort") {
304 // Aborted because we are switching backends. Abandon and don't retry,
305 // because another one is already started for us.
307 // Backend error or similar. Wait ten seconds, then try again.
308 current_analysis_request_timer = setTimeout(function() { request_update(); }, 10000);
313 var possibly_play_sound = function(old_data, new_data) {
317 if (old_data === null) {
320 var ding = document.getElementById('ding');
321 if (ding && ding.play) {
322 if (old_data['position'] && old_data['position']['fen'] &&
323 new_data['position'] && new_data['position']['fen'] &&
324 (old_data['position']['fen'] !== new_data['position']['fen'] ||
325 old_data['position']['move_num'] !== new_data['position']['move_num'])) {
332 * @type {!string} server_date_string
334 var sync_server_clock = function(server_date_string) {
335 var server_time_ms = new Date(server_date_string).getTime();
336 var client_time_ms = new Date().getTime();
337 var estimated_offset_ms = server_time_ms - client_time_ms;
339 // In order not to let the noise move us too much back and forth
340 // (the server only has one-second resolution anyway), we only
341 // change an existing skew if we are at least five seconds off.
342 if (client_clock_offset_ms === null ||
343 Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
344 client_clock_offset_ms = estimated_offset_ms;
348 var clear_arrows = function() {
349 for (var i = 0; i < arrows.length; ++i) {
351 if (arrows[i].svg.parentElement) {
352 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
354 delete arrows[i].svg;
359 occupied_by_arrows = [];
360 for (var y = 0; y < 8; ++y) {
361 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
365 var redraw_arrows = function() {
366 for (var i = 0; i < arrows.length; ++i) {
367 position_arrow(arrows[i]);
371 /** @param {!number} x
374 var sign = function(x) {
384 /** See if drawing this arrow on the board would cause unduly amount of confusion.
385 * @param {!string} from The square the arrow is from (e.g. e4).
386 * @param {!string} to The square the arrow is to (e.g. e4).
389 var interfering_arrow = function(from, to) {
390 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
391 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
392 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
393 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
395 occupied_by_arrows[from_row][from_col] = true;
397 // Knight move: Just check that we haven't been at the destination before.
398 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
399 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
400 return occupied_by_arrows[to_row][to_col];
403 // Sliding piece: Check if anything except the from-square is seen before.
404 var dx = sign(to_col - from_col);
405 var dy = sign(to_row - from_row);
411 if (occupied_by_arrows[y][x]) {
414 occupied_by_arrows[y][x] = true;
415 } while (x != to_col || y != to_row);
420 /** Find a point along the coordinate system given by the given line,
421 * <t> units forward from the start of the line, <u> units to the right of it.
422 * @param {!number} x1
423 * @param {!number} x2
424 * @param {!number} y1
425 * @param {!number} y2
428 * @return {!string} The point in "x y" form, suitable for SVG paths.
430 var point_from_start = function(x1, y1, x2, y2, t, u) {
434 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
438 var x = x1 + dx * t + dy * u;
439 var y = y1 + dy * t - dx * u;
443 /** Find a point along the coordinate system given by the given line,
444 * <t> units forward from the end of the line, <u> units to the right of it.
445 * @param {!number} x1
446 * @param {!number} x2
447 * @param {!number} y1
448 * @param {!number} y2
451 * @return {!string} The point in "x y" form, suitable for SVG paths.
453 var point_from_end = function(x1, y1, x2, y2, t, u) {
457 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
461 var x = x2 + dx * t + dy * u;
462 var y = y2 + dy * t - dx * u;
466 var position_arrow = function(arrow) {
468 if (arrow.svg.parentElement) {
469 arrow.svg.parentElement.removeChild(arrow.svg);
473 if (current_display_line !== null && !current_display_line_is_history) {
477 var pos = $(".square-a8").position();
479 var zoom_factor = $("#board").width() / 400.0;
480 var line_width = arrow.line_width * zoom_factor;
481 var arrow_size = arrow.arrow_size * zoom_factor;
483 var square_width = $(".square-a8").width();
484 var from_y = (7 - arrow.from_row + 0.5)*square_width;
485 var to_y = (7 - arrow.to_row + 0.5)*square_width;
486 var from_x = (arrow.from_col + 0.5)*square_width;
487 var to_x = (arrow.to_col + 0.5)*square_width;
489 var SVG_NS = "http://www.w3.org/2000/svg";
490 var XHTML_NS = "http://www.w3.org/1999/xhtml";
491 var svg = document.createElementNS(SVG_NS, "svg");
492 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
493 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
494 svg.setAttribute("style", "position: absolute");
495 svg.setAttribute("position", "absolute");
496 svg.setAttribute("version", "1.1");
497 svg.setAttribute("class", "c1");
498 svg.setAttribute("xmlns", XHTML_NS);
506 var outline = document.createElementNS(SVG_NS, "path");
507 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));
508 outline.setAttribute("xmlns", XHTML_NS);
509 outline.setAttribute("stroke", "#666");
510 outline.setAttribute("stroke-width", line_width + 2);
511 outline.setAttribute("fill", "none");
512 svg.appendChild(outline);
514 var path = document.createElementNS(SVG_NS, "path");
515 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));
516 path.setAttribute("xmlns", XHTML_NS);
517 path.setAttribute("stroke", arrow.fg_color);
518 path.setAttribute("stroke-width", line_width);
519 path.setAttribute("fill", "none");
520 svg.appendChild(path);
522 // Then the arrow head.
523 var head = document.createElementNS(SVG_NS, "path");
524 head.setAttribute("d",
525 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
526 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
527 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
528 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
529 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
530 head.setAttribute("xmlns", XHTML_NS);
531 head.setAttribute("stroke", "#000");
532 head.setAttribute("stroke-width", "1");
533 head.setAttribute("fill", arrow.fg_color);
534 svg.appendChild(head);
536 $(svg).css({ top: pos.top, left: pos.left, 'pointer-events': 'none' });
537 document.body.appendChild(svg);
542 * @param {!string} from_square
543 * @param {!string} to_square
544 * @param {!string} fg_color
545 * @param {number} line_width
546 * @param {number} arrow_size
548 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
549 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
550 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
551 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
552 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
560 line_width: line_width,
561 arrow_size: arrow_size,
565 position_arrow(arrow);
569 var compare_by_score = function(refutation_lines, invert, a, b) {
570 var sa = compute_score_sort_key(refutation_lines[b]['score'], refutation_lines[b]['depth'], invert);
571 var sb = compute_score_sort_key(refutation_lines[a]['score'], refutation_lines[a]['depth'], invert);
576 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
577 * sorted by quality, descending.
579 * @param {!Object} data
580 * @param {number} margin The maximum number of centipawns worse than the
581 * best move can be and still be included.
582 * @param {boolean} invert Whether black is to play.
583 * @return {Array.<string>} The FEN representation (e.g. Ne4) of all
584 * moves, in score order.
586 var find_nonstupid_moves = function(data, margin, invert) {
587 // First of all, if there are any moves that are more than 0.5 ahead of
588 // the primary move, the refutation lines are probably bunk, so just
590 var best_score = undefined;
591 var pv_score = undefined;
592 for (var move in data['refutation_lines']) {
593 var line = data['refutation_lines'][move];
594 var score = compute_score_sort_key(line['score'], line['depth'], invert, false);
595 if (move == data['pv'][0]) {
598 if (best_score === undefined || score > best_score) {
601 if (line['depth'] < 8) {
606 if (best_score - pv_score > 50) {
610 // Now find all moves that are within “margin” of the best score.
611 // The PV move will always be first.
613 for (var move in data['refutation_lines']) {
614 var line = data['refutation_lines'][move];
615 var score = compute_score_sort_key(line['score'], line['depth'], invert);
616 if (move != data['pv'][0] && best_score - score <= margin) {
620 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], data['position']['toplay'] === 'B', a, b) });
621 moves.unshift(data['pv'][0]);
630 var thousands = function(x) {
631 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
635 * @param {!string} start_fen
636 * @param {Array.<string>} pv
637 * @param {number} move_num
638 * @param {!string} toplay
639 * @param {Array<{ first_move: integer, score: Object }>} scores
640 * @param {number} start_display_move_num
641 * @param {number=} opt_limit
642 * @param {boolean=} opt_showlast
644 var add_pv = function(start_fen, pv, move_num, toplay, scores, start_display_move_num, opt_limit, opt_showlast) {
646 start_fen: start_fen,
648 move_num: parseInt(move_num),
651 start_display_move_num: start_display_move_num
653 return print_pv(display_lines.length - 1, opt_limit, opt_showlast);
657 * @param {number} line_num
658 * @param {number=} opt_limit If set, show at most this number of moves.
659 * @param {boolean=} opt_showlast If limit is set, show the last moves instead of the first ones.
661 var print_pv = function(line_num, opt_limit, opt_showlast) {
662 var display_line = display_lines[line_num];
663 var pv = display_line.pv;
664 var move_num = display_line.move_num;
665 var toplay = display_line.toplay;
667 // Truncate PV at the start if needed.
668 var start_display_move_num = display_line.start_display_move_num;
669 if (start_display_move_num > 0) {
670 pv = pv.slice(start_display_move_num);
671 var to_add = start_display_move_num;
672 if (toplay === 'B') {
677 if (to_add % 2 == 1) {
681 move_num += to_add / 2;
686 if (opt_limit && opt_showlast && pv.length > opt_limit) {
687 // Truncate the PV at the beginning (instead of at the end).
688 // We assume here that toplay is 'W'. We also assume that if
689 // opt_showlast is set, then it is the history, and thus,
690 // the UI should be to expand the history.
691 ret = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
692 i = pv.length - opt_limit;
697 } else if (toplay == 'B' && pv.length > 0) {
698 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pv[0] + "</a>";
699 ret = move_num + '. … ' + move;
704 for ( ; i < pv.length; ++i) {
705 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pv[i] + "</a>";
708 if (i > opt_limit && !opt_showlast) {
714 ret += move_num + '. ' + move;
725 /** Update the highlighted to/from squares on the board.
726 * Based on the global "highlight_from" and "highlight_to" variables.
728 var update_board_highlight = function() {
729 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
730 if ((current_display_line === null || current_display_line_is_history) &&
731 highlight_from !== undefined && highlight_to !== undefined) {
732 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
733 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
737 var update_history = function() {
738 if (display_lines[0] === null || display_lines[0].pv.length == 0) {
739 $("#history").html("No history");
740 } else if (truncate_display_history) {
741 $("#history").html(print_pv(0, 8, true));
744 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
750 * @param {!boolean} truncate_history
752 var collapse_history = function(truncate_history) {
753 truncate_display_history = truncate_history;
756 window['collapse_history'] = collapse_history;
758 /** Update the HTML display of multi-PV from the global "refutation_lines".
760 * Also recreates the global "display_lines".
762 var update_refutation_lines = function() {
763 if (base_fen === null) {
766 if (display_lines.length > 2) {
767 // Truncate so that only the history and PV is left.
768 display_lines = [ display_lines[0], display_lines[1] ];
770 var tbl = $("#refutationlines");
773 // Find out where the lines start from.
775 var base_scores = display_lines[1].scores;
776 var start_display_move_num = 0;
777 if (hash_refutation_lines) {
778 base_line = current_display_line.pv.slice(0, current_display_move + 1);
779 base_scores = current_display_line.scores;
780 start_display_move_num = base_line.length;
784 for (var move in refutation_lines) {
788 var invert = (toplay === 'B');
789 if (current_display_line && current_display_move % 2 == 0) {
792 moves = moves.sort(function(a, b) { return compare_by_score(refutation_lines, invert, a, b) });
793 for (var i = 0; i < moves.length; ++i) {
794 var line = refutation_lines[moves[i]];
796 var tr = document.createElement("tr");
798 var move_td = document.createElement("td");
799 tr.appendChild(move_td);
800 $(move_td).addClass("move");
802 var scores = base_scores.concat([{ first_move: start_display_move_num, score: line['score'] }]);
804 if (line['pv'].length == 0) {
805 // Not found, so just make a one-move PV.
806 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['move'] + "</a>";
807 $(move_td).html(move);
808 var score_td = document.createElement("td");
810 $(score_td).addClass("score");
811 $(score_td).text("—");
812 tr.appendChild(score_td);
814 var depth_td = document.createElement("td");
815 tr.appendChild(depth_td);
816 $(depth_td).addClass("depth");
817 $(depth_td).text("—");
819 var pv_td = document.createElement("td");
820 tr.appendChild(pv_td);
821 $(pv_td).addClass("pv");
822 $(pv_td).html(add_pv(base_fen, base_line.concat([ line['move'] ]), move_num, toplay, scores, start_display_move_num));
828 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['move'] + "</a>";
829 $(move_td).html(move);
831 var score_td = document.createElement("td");
832 tr.appendChild(score_td);
833 $(score_td).addClass("score");
834 $(score_td).text(format_short_score(line['score']));
836 var depth_td = document.createElement("td");
837 tr.appendChild(depth_td);
838 $(depth_td).addClass("depth");
839 if (line['depth'] && line['depth'] >= 0) {
840 $(depth_td).text("d" + line['depth']);
842 $(depth_td).text("—");
845 var pv_td = document.createElement("td");
846 tr.appendChild(pv_td);
847 $(pv_td).addClass("pv");
848 $(pv_td).html(add_pv(base_fen, base_line.concat(line['pv']), move_num, toplay, scores, start_display_move_num, 10));
853 // Update the move highlight, as we've rewritten all the HTML.
854 update_move_highlight();
858 * Create a Chess.js board object, containing the given position plus the given moves,
859 * up to the given limit.
861 * @param {?string} fen
862 * @param {Array.<string>} moves
863 * @param {number} last_move
865 var chess_from = function(fen, moves, last_move) {
866 var hiddenboard = new Chess();
867 if (fen !== null && fen !== undefined) {
868 hiddenboard.load(fen);
870 for (var i = 0; i <= last_move; ++i) {
871 if (moves[i] === '0-0') {
872 hiddenboard.move('O-O');
873 } else if (moves[i] === '0-0-0') {
874 hiddenboard.move('O-O-O');
876 hiddenboard.move(moves[i]);
882 var update_game_list = function(games) {
883 $("#games").text("");
884 if (games === null) {
888 var games_div = document.getElementById('games');
889 for (var game_num = 0; game_num < games.length; ++game_num) {
890 var game = games[game_num];
891 var game_span = document.createElement("span");
892 game_span.setAttribute("class", "game");
894 var game_name = document.createTextNode(game['name']);
895 if (game['url'] === backend_url) {
897 game_span.appendChild(game_name);
899 if (current_analysis_data && current_analysis_data['position']) {
901 if (current_analysis_data['position']['result']) {
902 score = " (" + current_analysis_data['position']['result'] + ")";
904 score = " (" + format_short_score(current_analysis_data['score']) + ")";
906 game_span.appendChild(document.createTextNode(score));
910 var game_a = document.createElement("a");
911 game_a.setAttribute("href", "#" + game['id']);
912 game_a.appendChild(game_name);
913 game_span.appendChild(game_a);
916 if (game['result']) {
917 score = " (" + game['result'] + ")";
919 score = " (" + format_short_score(game['score']) + ")";
921 game_span.appendChild(document.createTextNode(score));
924 games_div.appendChild(game_span);
929 * Try to find a running game that matches with the current hash,
930 * and switch to it if we're not already displaying it.
932 var possibly_switch_game_from_hash = function() {
933 if (current_games === null) {
937 var hash = window.location.hash.replace(/^#/,'');
938 for (var i = 0; i < current_games.length; ++i) {
939 if (current_games[i]['id'] === hash) {
940 if (backend_url !== current_games[i]['url']) {
941 switch_backend(current_games[i]);
948 /** Update all the HTML on the page, based on current global state.
950 var update_board = function() {
951 var data = displayed_analysis_data || current_analysis_data;
952 var current_data = current_analysis_data; // Convenience alias.
956 // Print the history. This is pretty much the only thing that's
957 // unconditionally taken from current_data (we're not interested in
958 // historic history).
959 if (current_data['position']['history']) {
960 var start = (current_data['position'] && current_data['position']['start_fen']) ? current_data['position']['start_fen'] : 'start';
961 add_pv(start, current_data['position']['history'], 1, 'W', null, 0, 8, true);
963 display_lines.push(null);
967 // Games currently in progress, if any.
968 if (current_data['games']) {
969 current_games = current_data['games'];
970 possibly_switch_game_from_hash();
972 current_games = null;
974 update_game_list(current_games);
976 // The headline. Names are always fetched from current_data;
977 // the rest can depend a bit.
980 current_data['position']['player_w'] && current_data['position']['player_b']) {
981 headline = current_data['position']['player_w'] + '–' +
982 current_data['position']['player_b'] + ', analysis';
984 headline = 'Analysis';
987 // Credits, where applicable. Note that we don't want the footer to change a lot
988 // when e.g. viewing history, so if any of these changed during the game,
989 // use the current one still.
990 if (current_data['using_lomonosov']) {
991 $("#lomonosov").show();
993 $("#lomonosov").hide();
996 // Credits: The engine name/version.
997 if (current_data['engine'] && current_data['engine']['name'] !== null) {
998 $("#engineid").text(current_data['engine']['name']);
1001 // Credits: The engine URL.
1002 if (current_data['engine'] && current_data['engine']['url']) {
1003 $("#engineid").attr("href", current_data['engine']['url']);
1005 $("#engineid").removeAttr("href");
1008 // Credits: Engine details.
1009 if (current_data['engine'] && current_data['engine']['details']) {
1010 $("#enginedetails").text(" (" + current_data['engine']['details'] + ")");
1012 $("#enginedetails").text("");
1015 // Credits: Move source, possibly with URL.
1016 if (current_data['move_source'] && current_data['move_source_url']) {
1017 $("#movesource").text("Moves provided by ");
1018 var movesource_a = document.createElement("a");
1019 movesource_a.setAttribute("href", current_data['move_source_url']);
1020 var movesource_text = document.createTextNode(current_data['move_source']);
1021 movesource_a.appendChild(movesource_text);
1022 var movesource_period = document.createTextNode(".");
1023 document.getElementById("movesource").appendChild(movesource_a);
1024 document.getElementById("movesource").appendChild(movesource_period);
1025 } else if (current_data['move_source']) {
1026 $("#movesource").text("Moves provided by " + current_data['move_source'] + ".");
1028 $("#movesource").text("");
1032 if (displayed_analysis_data) {
1033 // Displaying some non-current position, pick out the last move
1034 // from the history. This will work even if the fetch failed.
1035 if (current_display_move !== -1) {
1036 last_move = format_halfmove_with_number(
1037 current_display_line.pv[current_display_move],
1038 current_display_move);
1039 headline += ' after ' + last_move;
1041 } else if (data['position']['last_move'] !== 'none') {
1042 // Find the previous move.
1043 var previous_move_num, previous_toplay;
1044 if (data['position']['toplay'] == 'B') {
1045 previous_move_num = data['position']['move_num'];
1046 previous_toplay = 'W';
1048 previous_move_num = data['position']['move_num'] - 1;
1049 previous_toplay = 'B';
1052 last_move = format_move_with_number(
1053 data['position']['last_move'],
1055 previous_toplay == 'W');
1056 headline += ' after ' + last_move;
1060 $("#headline").text(headline);
1062 // The <title> contains a very brief headline.
1063 var title_elems = [];
1064 if (data['position'] && data['position']['result']) {
1065 title_elems.push(data['position']['result']);
1066 } else if (data['score']) {
1067 title_elems.push(format_short_score(data['score']));
1069 if (last_move !== null) {
1070 title_elems.push(last_move);
1073 if (title_elems.length != 0) {
1074 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
1076 document.title = 'analysis.sesse.net';
1079 // The last move (shown by highlighting the from and to squares).
1080 if (data['position'] && data['position']['last_move_uci']) {
1081 highlight_from = data['position']['last_move_uci'].substr(0, 2);
1082 highlight_to = data['position']['last_move_uci'].substr(2, 2);
1083 } else if (current_display_line_is_history && current_display_line && current_display_move >= 0) {
1084 // We don't have historic analysis for this position, but we
1085 // can reconstruct what the last move was by just replaying
1087 var position = (data['position'] && data['position']['start_fen']) ? data['position']['start_fen'] : null;
1088 var hiddenboard = chess_from(position, current_display_line.pv, current_display_move);
1089 var moves = hiddenboard.history({ verbose: true });
1090 last_move = moves.pop();
1091 highlight_from = last_move.from;
1092 highlight_to = last_move.to;
1094 highlight_from = highlight_to = undefined;
1096 update_board_highlight();
1098 if (data['failed']) {
1099 $("#score").text("No analysis for this move");
1100 $("#pvtitle").text("PV:");
1102 $("#searchstats").html(" ");
1103 $("#refutationlines").empty();
1104 $("#whiteclock").empty();
1105 $("#blackclock").empty();
1106 refutation_lines = [];
1107 update_refutation_lines();
1109 update_displayed_line();
1110 update_move_highlight();
1117 if (current_display_line && !current_display_line_is_history) {
1119 if (current_display_line.scores && current_display_line.scores.length > 0) {
1120 for (var i = 0; i < current_display_line.scores.length; ++i) {
1121 if (current_display_move < current_display_line.scores[i].first_move) {
1124 score = current_display_line.scores[i].score;
1128 $("#score").text(format_long_score(score));
1130 $("#score").text("No score for this line");
1132 } else if (data['score']) {
1133 $("#score").text(format_long_score(data['score']));
1136 // The search stats.
1137 if (data['searchstats']) {
1138 $("#searchstats").html(data['searchstats']);
1139 } else if (data['tablebase'] == 1) {
1140 $("#searchstats").text("Tablebase result");
1141 } else if (data['nodes'] && data['nps'] && data['depth']) {
1142 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
1143 if (data['seldepth']) {
1144 stats += ' (' + data['seldepth'] + ' selective)';
1146 if (data['tbhits'] && data['tbhits'] > 0) {
1147 if (data['tbhits'] == 1) {
1148 stats += ', one Syzygy hit';
1150 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
1154 $("#searchstats").text(stats);
1156 $("#searchstats").text("");
1159 // Update the board itself.
1160 base_fen = data['position']['fen'];
1161 update_displayed_line();
1164 $("#pvtitle").text("PV:");
1166 var scores = [{ first_move: -1, score: data['score'] }];
1167 $("#pv").html(add_pv(data['position']['fen'], data['pv'], data['position']['move_num'], data['position']['toplay'], scores, 0));
1169 // Update the PV arrow.
1171 if (data['pv'].length >= 1) {
1172 var hiddenboard = new Chess(base_fen);
1174 // draw a continuation arrow as long as it's the same piece
1176 for (var i = 0; i < data['pv'].length; i += 2) {
1177 var move = hiddenboard.move(data['pv'][i]);
1178 if ((i >= 2 && move.from != last_to) ||
1179 interfering_arrow(move.from, move.to)) {
1182 create_arrow(move.from, move.to, '#f66', 6, 20);
1183 last_to = move.from;
1184 hiddenboard.move(data['pv'][i + 1]); // To keep continuity.
1187 var alt_moves = find_nonstupid_moves(data, 30, data['position']['toplay'] === 'B');
1188 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
1189 hiddenboard = new Chess(base_fen);
1190 var move = hiddenboard.move(alt_moves[i]);
1191 if (move !== null) {
1192 create_arrow(move.from, move.to, '#f66', 1, 10);
1197 // See if all semi-reasonable moves have only one possible response.
1198 if (data['pv'].length >= 2) {
1199 var nonstupid_moves = find_nonstupid_moves(data, 300, data['position']['toplay'] === 'B');
1202 var hiddenboard = new Chess(base_fen);
1203 hiddenboard.move(data['pv'][0]);
1204 response = hiddenboard.move(data['pv'][1]);
1206 for (var i = 0; i < nonstupid_moves.length; ++i) {
1207 if (nonstupid_moves[i] == data['pv'][0]) {
1208 // ignore the PV move for refutation lines.
1211 if (!data['refutation_lines'] ||
1212 !data['refutation_lines'][nonstupid_moves[i]] ||
1213 !data['refutation_lines'][nonstupid_moves[i]]['pv'] ||
1214 data['refutation_lines'][nonstupid_moves[i]]['pv'].length < 1) {
1215 // Incomplete PV, abort.
1216 response = undefined;
1219 var line = data['refutation_lines'][nonstupid_moves[i]];
1220 hiddenboard = new Chess(base_fen);
1221 hiddenboard.move(line['pv'][0]);
1222 var this_response = hiddenboard.move(line['pv'][1]);
1223 if (response.from !== this_response.from || response.to !== this_response.to) {
1224 // Different response depending on lines, abort.
1225 response = undefined;
1230 if (nonstupid_moves.length > 0 && response !== undefined) {
1231 create_arrow(response.from, response.to, '#66f', 6, 20);
1235 // Update the refutation lines.
1236 base_fen = data['position']['fen'];
1237 move_num = parseInt(data['position']['move_num']);
1238 toplay = data['position']['toplay'];
1239 refutation_lines = hash_refutation_lines || data['refutation_lines'];
1240 update_refutation_lines();
1242 // Update the sparkline last, since its size depends on how everything else reflowed.
1243 update_sparkline(data);
1246 var update_sparkline = function(data) {
1247 if (data && data['score_history']) {
1248 var first_move_num = undefined;
1249 for (var halfmove_num in data['score_history']) {
1250 halfmove_num = parseInt(halfmove_num);
1251 if (first_move_num === undefined || halfmove_num < first_move_num) {
1252 first_move_num = halfmove_num;
1255 if (first_move_num !== undefined) {
1256 var last_move_num = data['position']['move_num'] * 2 - 3;
1257 if (data['position']['toplay'] === 'B') {
1261 // Possibly truncate some moves if we don't have enough width.
1262 // FIXME: Sometimes width() for #scorecontainer (and by extent,
1263 // #scoresparkcontainer) on Chrome for mobile seems to start off
1264 // at something very small, and then suddenly snap back into place.
1266 var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
1267 if (last_move_num - first_move_num > max_moves) {
1268 first_move_num = last_move_num - max_moves;
1271 var min_score = -100;
1272 var max_score = 100;
1273 var last_score = null;
1275 for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1276 if (data['score_history'][halfmove_num]) {
1277 var score = compute_plot_score(data['score_history'][halfmove_num]);
1279 if (score < min_score) min_score = score;
1280 if (score > max_score) max_score = score;
1282 scores.push(last_score);
1284 if (data['score']) {
1285 scores.push(compute_plot_score(data['score']));
1287 // FIXME: at some widths, calling sparkline() seems to push
1288 // #scorecontainer under the board.
1289 $("#scorespark").sparkline(scores, {
1292 chartRangeMin: min_score,
1293 chartRangeMax: max_score,
1294 tooltipFormatter: function(sparkline, options, fields) {
1295 // score_history contains the Nth _position_, but format_tooltip
1296 // wants to format the Nth _move_; thus the -1.
1297 return format_tooltip(data, fields[0].offset + first_move_num - 1);
1300 $('#scorespark').bind('sparklineClick', function(event) {
1301 var sparkline = event.sparklines[0];
1302 var region = sparkline.getCurrentRegionFields();
1303 if (region[0].offset !== undefined) {
1304 show_line(0, first_move_num + region[0].offset - 1);
1308 $("#scorespark").text("");
1311 $("#scorespark").text("");
1316 * @param {number} num_viewers
1318 var update_num_viewers = function(num_viewers) {
1319 if (num_viewers === null) {
1320 $("#numviewers").text("");
1321 } else if (num_viewers == 1) {
1322 $("#numviewers").text("You are the only current viewer");
1324 $("#numviewers").text(num_viewers + " current viewers");
1328 var update_clock = function() {
1329 clearTimeout(clock_timer);
1331 var data = displayed_analysis_data || current_analysis_data;
1334 if (data['position']) {
1335 var result = data['position']['result'];
1336 if (result === '1-0') {
1337 $("#whiteclock").text("1");
1338 $("#blackclock").text("0");
1339 $("#whiteclock").removeClass("running-clock");
1340 $("#blackclock").removeClass("running-clock");
1343 if (result === '1/2-1/2') {
1344 $("#whiteclock").text("1/2");
1345 $("#blackclock").text("1/2");
1346 $("#whiteclock").removeClass("running-clock");
1347 $("#blackclock").removeClass("running-clock");
1350 if (result === '0-1') {
1351 $("#whiteclock").text("0");
1352 $("#blackclock").text("1");
1353 $("#whiteclock").removeClass("running-clock");
1354 $("#blackclock").removeClass("running-clock");
1359 var white_clock_ms = null;
1360 var black_clock_ms = null;
1363 if (data['position'] &&
1364 data['position']['white_clock'] &&
1365 data['position']['black_clock']) {
1366 white_clock_ms = data['position']['white_clock'] * 1000;
1367 black_clock_ms = data['position']['black_clock'] * 1000;
1370 // Dynamic clock (only one, obviously).
1372 if (data['position']['white_clock_target']) {
1374 $("#whiteclock").addClass("running-clock");
1375 $("#blackclock").removeClass("running-clock");
1376 } else if (data['position']['black_clock_target']) {
1378 $("#whiteclock").removeClass("running-clock");
1379 $("#blackclock").addClass("running-clock");
1381 $("#whiteclock").removeClass("running-clock");
1382 $("#blackclock").removeClass("running-clock");
1386 var now = new Date().getTime() + client_clock_offset_ms;
1387 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1388 if (color === "white") {
1389 white_clock_ms = remaining_ms;
1391 black_clock_ms = remaining_ms;
1395 if (white_clock_ms === null || black_clock_ms === null) {
1396 $("#whiteclock").empty();
1397 $("#blackclock").empty();
1401 // If either player has twenty minutes or less left, add the second counters.
1402 // This matches what DGT clocks do.
1403 var show_seconds = (white_clock_ms < 60 * 20 * 1000 || black_clock_ms < 60 * 20 * 1000);
1406 // See when the clock will change next, and update right after that.
1409 next_update_ms = remaining_ms % 1000 + 100;
1411 next_update_ms = remaining_ms % 60000 + 100;
1413 clock_timer = setTimeout(update_clock, next_update_ms);
1416 $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1417 $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1421 * @param {Number} remaining_ms
1422 * @param {boolean} show_seconds
1424 var format_clock = function(remaining_ms, show_seconds) {
1425 if (remaining_ms <= 0) {
1433 var remaining = Math.floor(remaining_ms / 1000);
1434 var seconds = remaining % 60;
1435 remaining = (remaining - seconds) / 60;
1436 var minutes = remaining % 60;
1437 remaining = (remaining - minutes) / 60;
1438 var hours = remaining;
1440 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1442 return format_2d(hours) + ":" + format_2d(minutes);
1449 var format_2d = function(x) {
1458 * @param {string} move
1459 * @param {Number} move_num Move number of this move.
1460 * @param {boolean} white_to_play Whether white is to play this move.
1462 var format_move_with_number = function(move, move_num, white_to_play) {
1464 if (white_to_play) {
1465 ret = move_num + '. ';
1467 ret = move_num + '… ';
1474 * @param {string} move
1475 * @param {Number} halfmove_num Half-move number that is to be played,
1478 var format_halfmove_with_number = function(move, halfmove_num) {
1479 return format_move_with_number(
1481 Math.floor(halfmove_num / 2) + 1,
1482 halfmove_num % 2 == 0);
1486 * @param {Object} data
1487 * @param {Number} halfmove_num
1489 var format_tooltip = function(data, halfmove_num) {
1490 if (data['score_history'][halfmove_num + 1] ||
1491 (halfmove_num + 1) === data['position']['history'].length) {
1492 // Position is in the history, or it is the current position
1493 // (which is implicitly tacked onto the history).
1496 if ((halfmove_num + 1) === data['position']['history'].length) {
1497 move = data['position']['last_move'];
1498 short_score = format_short_score(data['score']);
1500 move = data['position']['history'][halfmove_num];
1501 short_score = format_short_score(data['score_history'][halfmove_num + 1]);
1503 if (halfmove_num === -1) {
1504 return "Start position: " + short_score;
1506 var move_with_number = format_halfmove_with_number(move, halfmove_num);
1507 return "After " + move_with_number + ": " + short_score;
1510 for (var i = halfmove_num; i --> -1; ) {
1511 if (data['score_history'][i]) {
1512 var move = data['position']['history'][i];
1514 return "[Analysis kept from start position]";
1516 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1524 * @param {boolean} truncate_history
1526 var set_truncate_history = function(truncate_history) {
1527 truncate_display_history = truncate_history;
1528 update_refutation_lines();
1530 window['set_truncate_history'] = set_truncate_history;
1533 * @param {number} line_num
1534 * @param {number} move_num
1536 var show_line = function(line_num, move_num) {
1537 if (line_num == -1) {
1538 current_display_line = null;
1539 current_display_move = null;
1540 hash_refutation_lines = null;
1541 if (displayed_analysis_data) {
1542 // TODO: Support exiting to history position if we are in an
1543 // analysis line of a history position.
1544 displayed_analysis_data = null;
1549 current_display_line = jQuery.extend({}, display_lines[line_num]); // Shallow clone.
1550 current_display_move = move_num + current_display_line.start_display_move_num;
1552 current_display_line_is_history = (line_num == 0);
1554 update_historic_analysis();
1555 update_displayed_line();
1556 update_board_highlight();
1557 update_move_highlight();
1560 window['show_line'] = show_line;
1562 var prev_move = function() {
1563 if (current_display_line &&
1564 current_display_move >= current_display_line.start_display_move_num) {
1565 --current_display_move;
1567 update_historic_analysis();
1568 update_displayed_line();
1569 update_move_highlight();
1571 window['prev_move'] = prev_move;
1573 var next_move = function() {
1574 if (current_display_line &&
1575 current_display_move < current_display_line.pv.length - 1) {
1576 ++current_display_move;
1578 update_historic_analysis();
1579 update_displayed_line();
1580 update_move_highlight();
1582 window['next_move'] = next_move;
1584 var next_game = function() {
1585 if (current_games === null) {
1589 // Try to find the game we are currently looking at.
1590 for (var game_num = 0; game_num < current_games.length; ++game_num) {
1591 var game = current_games[game_num];
1592 if (game['url'] === backend_url) {
1593 var next_game_num = (game_num + 1) % current_games.length;
1594 switch_backend(current_games[next_game_num]);
1599 // Couldn't find it; give up.
1602 var update_historic_analysis = function() {
1603 if (!current_display_line_is_history) {
1606 if (current_display_move == current_display_line.pv.length - 1) {
1607 displayed_analysis_data = null;
1611 // Fetch old analysis for this line if it exists.
1612 var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pv, current_display_move);
1613 var filename = "/history/move" + (current_display_move + 1) + "-" +
1614 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1616 current_historic_xhr = $.ajax({
1618 }).done(function(data, textstatus, xhr) {
1619 displayed_analysis_data = data;
1621 }).fail(function(jqXHR, textStatus, errorThrown) {
1622 if (textStatus === "abort") {
1623 // Aborted because we are switching backends. Don't do anything;
1624 // we will already have been cleared.
1626 displayed_analysis_data = {'failed': true};
1633 * @param {string} fen
1635 var update_imbalance = function(fen) {
1636 var hiddenboard = new Chess(fen);
1637 var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1638 for (var row = 0; row < 8; ++row) {
1639 for (var col = 0; col < 8; ++col) {
1640 var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1641 var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1642 var square = col_text + row_text;
1643 var contents = hiddenboard.get(square);
1644 if (contents !== null) {
1645 if (contents.color === 'w') {
1646 ++imbalance[contents.type];
1648 --imbalance[contents.type];
1653 var white_imbalance = '';
1654 var black_imbalance = '';
1655 for (var piece in imbalance) {
1656 for (var i = 0; i < imbalance[piece]; ++i) {
1657 white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1659 for (var i = 0; i < -imbalance[piece]; ++i) {
1660 black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1663 $('#whiteimbalance').html(white_imbalance);
1664 $('#blackimbalance').html(black_imbalance);
1667 /** Mark the currently selected move in red.
1668 * Also replaces the PV with the current displayed line if it's not shown
1669 * anywhere else on the screen.
1671 var update_move_highlight = function() {
1672 if (highlighted_move !== null) {
1673 highlighted_move.removeClass('highlight');
1675 if (current_display_line) {
1676 var display_line_num = find_display_line_matching_num();
1677 if (display_line_num === null) {
1678 // Replace the PV with the (complete) line.
1679 $("#pvtitle").text("Exploring:");
1680 current_display_line.start_display_move_num = 0;
1681 display_lines.push(current_display_line);
1682 $("#pv").html(print_pv(display_lines.length - 1));
1683 display_line_num = display_lines.length - 1;
1685 // Clear out the PV, so it's not selected by anything later.
1686 display_lines[1].pv = [];
1689 highlighted_move = $("#automove" + display_line_num + "-" + (current_display_move - current_display_line.start_display_move_num));
1690 highlighted_move.addClass('highlight');
1695 * See if the current displayed line is identical to any of the ones
1696 * we have on screen. (It might not be if e.g. the analysis reloaded
1697 * since we started looking.)
1701 var find_display_line_matching_num = function() {
1702 for (var i = 0; i < display_lines.length; ++i) {
1703 var line = display_lines[i];
1704 if (line.start_display_move_num > 0) continue;
1705 if (current_display_line.start_fen !== line.start_fen) continue;
1706 if (current_display_line.pv.length !== line.pv.length) continue;
1708 for (var j = 0; j < line.pv.length; ++j) {
1709 if (current_display_line.pv[j] !== line.pv[j]) {
1721 /** Update the board based on the currently displayed line.
1723 * TODO: This should really be called only whenever something changes,
1724 * instead of all the time.
1726 var update_displayed_line = function() {
1727 if (current_display_line === null) {
1728 $("#linenav").hide();
1729 $("#linemsg").show();
1730 display_fen = base_fen;
1731 set_board_position(base_fen);
1732 update_imbalance(base_fen);
1736 $("#linenav").show();
1737 $("#linemsg").hide();
1739 if (current_display_move <= 0) {
1740 $("#prevmove").html("Previous");
1742 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1744 if (current_display_move == current_display_line.pv.length - 1) {
1745 $("#nextmove").html("Next");
1747 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1750 var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pv, current_display_move);
1751 set_board_position(hiddenboard.fen());
1752 if (display_fen !== hiddenboard.fen() && !current_display_line_is_history) {
1753 // Fire off a hash request, since we're now off the main position
1754 // and it just changed.
1755 explore_hash(hiddenboard.fen());
1757 display_fen = hiddenboard.fen();
1758 update_imbalance(hiddenboard.fen());
1761 var set_board_position = function(new_fen) {
1762 board_is_animating = true;
1763 var old_fen = board.fen();
1764 board.position(new_fen);
1765 if (board.fen() === old_fen) {
1766 board_is_animating = false;
1771 * @param {boolean} param_enable_sound
1773 var set_sound = function(param_enable_sound) {
1774 enable_sound = param_enable_sound;
1776 $("#soundon").html("<strong>On</strong>");
1777 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1779 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1780 // and also preload the file since the user has selected audio.
1781 var ding = document.getElementById('ding');
1782 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1783 ding.src = 'ding.opus';
1787 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1788 $("#soundoff").html("<strong>Off</strong>");
1790 if (supports_html5_storage()) {
1791 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1794 window['set_sound'] = set_sound;
1796 /** Send off a hash probe request to the backend.
1797 * @param {string} fen
1799 var explore_hash = function(fen) {
1800 // If we already have a backend response going, abort it.
1801 if (current_hash_xhr) {
1802 current_hash_xhr.abort();
1804 if (current_hash_display_timer) {
1805 clearTimeout(current_hash_display_timer);
1806 current_hash_display_timer = null;
1808 $("#refutationlines").empty();
1809 current_hash_xhr = $.ajax({
1810 url: backend_hash_url + "?fen=" + fen
1811 }).done(function(data, textstatus, xhr) {
1812 show_explore_hash_results(data, fen);
1816 /** Process the JSON response from a hash probe request.
1817 * @param {!Object} data
1818 * @param {string} fen
1820 var show_explore_hash_results = function(data, fen) {
1821 if (board_is_animating) {
1822 // Updating while the animation is still going causes
1823 // the animation to jerk. This is pretty crude, but it will do.
1824 current_hash_display_timer = setTimeout(function() { show_explore_hash_results(data, fen); }, 100);
1827 current_hash_display_timer = null;
1828 hash_refutation_lines = data['lines'];
1832 // almost all of this stuff comes from the chessboard.js example page
1833 var onDragStart = function(source, piece, position, orientation) {
1834 var pseudogame = new Chess(display_fen);
1835 if (pseudogame.game_over() === true ||
1836 (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
1837 (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
1841 recommended_move = get_best_move(pseudogame, source, null, pseudogame.turn() === 'b');
1842 if (recommended_move) {
1843 var squareEl = $('#board .square-' + recommended_move.to);
1844 squareEl.addClass('highlight1-32417');
1849 var mousedownSquare = function(e) {
1850 reverse_dragging_from = null;
1851 var square = $(this).attr('data-square');
1853 var pseudogame = new Chess(display_fen);
1854 if (pseudogame.game_over() === true) {
1858 // If the square is empty, or has a piece of the side not to move,
1859 // we handle it. If not, normal piece dragging will take it.
1860 var position = board.position();
1861 if (!position.hasOwnProperty(square) ||
1862 (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
1863 (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
1864 reverse_dragging_from = square;
1865 recommended_move = get_best_move(pseudogame, null, square, pseudogame.turn() === 'b');
1866 if (recommended_move) {
1867 var squareEl = $('#board .square-' + recommended_move.from);
1868 squareEl.addClass('highlight1-32417');
1869 squareEl = $('#board .square-' + recommended_move.to);
1870 squareEl.addClass('highlight1-32417');
1875 var mouseupSquare = function(e) {
1876 if (reverse_dragging_from === null) {
1879 var source = $(this).attr('data-square');
1880 var target = reverse_dragging_from;
1881 reverse_dragging_from = null;
1882 if (onDrop(source, target) !== 'snapback') {
1883 onSnapEnd(source, target);
1885 $("#board").find('.square-55d63').removeClass('highlight1-32417');
1888 var get_best_move = function(game, source, target, invert) {
1889 var moves = game.moves({ verbose: true });
1890 if (source !== null) {
1891 moves = moves.filter(function(move) { return move.from == source; });
1893 if (target !== null) {
1894 moves = moves.filter(function(move) { return move.to == target; });
1896 if (moves.length == 0) {
1899 if (moves.length == 1) {
1903 // More than one move. Use the display lines (if we have them)
1904 // to disambiguate; otherwise, we have no information.
1906 for (var i = 0; i < moves.length; ++i) {
1907 move_hash[moves[i].san] = moves[i];
1910 // See if we're already exploring some line.
1911 if (current_display_line &&
1912 current_display_move < current_display_line.pv.length - 1) {
1913 var first_move = current_display_line.pv[current_display_move + 1];
1914 if (move_hash[first_move]) {
1915 return move_hash[first_move];
1919 // History and PV take priority over the display lines.
1920 for (var i = 0; i < 2; ++i) {
1921 var line = display_lines[i];
1922 var first_move = line.pv[line.start_display_move_num];
1923 if (move_hash[first_move]) {
1924 return move_hash[first_move];
1928 var best_move = null;
1929 var best_move_score = null;
1931 for (var move in refutation_lines) {
1932 var line = refutation_lines[move];
1933 if (!line['score']) {
1936 var first_move = line['pv'][0];
1937 if (move_hash[first_move]) {
1938 var score = compute_score_sort_key(line['score'], line['depth'], invert);
1939 if (best_move_score === null || score > best_move_score) {
1940 best_move = move_hash[first_move];
1941 best_move_score = score;
1948 var onDrop = function(source, target) {
1949 if (source === target) {
1950 if (recommended_move === null) {
1953 // Accept the move. It will be changed in onSnapEnd.
1957 // Suggestion not asked for.
1958 recommended_move = null;
1961 // see if the move is legal
1962 var pseudogame = new Chess(display_fen);
1963 var move = pseudogame.move({
1966 promotion: 'q' // NOTE: always promote to a queen for example simplicity
1970 if (move === null) return 'snapback';
1973 var onSnapEnd = function(source, target) {
1974 if (source === target && recommended_move !== null) {
1975 source = recommended_move.from;
1976 target = recommended_move.to;
1978 recommended_move = null;
1979 var pseudogame = new Chess(display_fen);
1980 var move = pseudogame.move({
1983 promotion: 'q' // NOTE: always promote to a queen for example simplicity
1986 if (current_display_line &&
1987 current_display_move < current_display_line.pv.length - 1 &&
1988 current_display_line.pv[current_display_move + 1] === move.san) {
1993 // Walk down the displayed lines until we find one that starts with
1994 // this move, then select that. Note that this gives us a good priority
1995 // order (history first, then PV, then multi-PV lines).
1996 for (var i = 0; i < display_lines.length; ++i) {
1997 if (i == 1 && current_display_line) {
1998 // Do not choose PV if not on it.
2001 var line = display_lines[i];
2002 if (line.pv[line.start_display_move_num] === move.san) {
2008 // Shouldn't really be here if we have hash probes, but there's really
2009 // nothing we can do.
2011 // End of dragging-related code.
2013 var fmt_cp = function(v) {
2017 return "+" + (v / 100).toFixed(2);
2020 return "-" + (v / 100).toFixed(2);
2024 var format_short_score = function(score) {
2028 if (score[0] === 'm') {
2029 if (score[2]) { // Is a bound.
2030 return score[2] + "\u00a0M " + score[1];
2032 return "M " + score[1];
2034 } else if (score[0] === 'd') {
2036 } else if (score[0] === 'cp') {
2037 if (score[2]) { // Is a bound.
2038 return score[2] + "\u00a0" + fmt_cp(score[1]);
2040 return fmt_cp(score[1]);
2046 var format_long_score = function(score) {
2050 if (score[0] === 'm') {
2052 return "White mates in " + score[1];
2054 return "Black mates in " + (-score[1]);
2056 } else if (score[0] === 'd') {
2057 return "Theoretical draw";
2058 } else if (score[0] === 'cp') {
2059 return "Score: " + format_short_score(score);
2064 var compute_plot_score = function(score) {
2065 if (score[0] === 'm') {
2071 } else if (score[0] === 'd') {
2073 } else if (score[0] === 'cp') {
2074 if (score[1] > 500) {
2076 } else if (score[1] < -500) {
2086 * @param score The score digest tuple.
2087 * @param {?number} depth Depth the move has been computed to, or null.
2088 * @param {boolean} invert Whether black is to play.
2089 * @param {boolean=} depth_secondary_key
2092 var compute_score_sort_key = function(score, depth, invert, depth_secondary_key) {
2097 if (score[0] === 'm') {
2100 s = 99999 - score[1];
2102 // Black mates (note the double negative for score[1]).
2103 s = -99999 - score[1];
2105 } else if (score[0] === 'd') {
2107 } else if (score[0] === 'cp') {
2112 if (depth_secondary_key) {
2113 return s * 200 + (depth || 0);
2123 * @param {Object} game
2125 var switch_backend = function(game) {
2126 // Stop looking at historic data.
2127 current_display_line = null;
2128 current_display_move = null;
2129 displayed_analysis_data = null;
2130 if (current_historic_xhr) {
2131 current_historic_xhr.abort();
2134 // If we already have a backend response going, abort it.
2135 if (current_analysis_xhr) {
2136 current_analysis_xhr.abort();
2138 if (current_hash_xhr) {
2139 current_hash_xhr.abort();
2142 // Otherwise, we should have a timer going to start a new one.
2144 if (current_analysis_request_timer) {
2145 clearTimeout(current_analysis_request_timer);
2146 current_analysis_request_timer = null;
2148 if (current_hash_display_timer) {
2149 clearTimeout(current_hash_display_timer);
2150 current_hash_display_timer = null;
2153 // Request an immediate fetch with the new backend.
2154 backend_url = game['url'];
2155 backend_hash_url = game['hashurl'];
2156 window.location.hash = '#' + game['id'];
2157 current_analysis_data = null;
2161 window['switch_backend'] = switch_backend;
2163 var init = function() {
2164 unique = get_unique();
2166 // Load settings from HTML5 local storage if available.
2167 if (supports_html5_storage() && localStorage['enable_sound']) {
2168 set_sound(parseInt(localStorage['enable_sound']));
2174 board = new window.ChessBoard('board', {
2175 onMoveEnd: function() { board_is_animating = false; },
2178 onDragStart: onDragStart,
2180 onSnapEnd: onSnapEnd
2182 $("#board").on('mousedown', '.square-55d63', mousedownSquare);
2183 $("#board").on('mouseup', '.square-55d63', mouseupSquare);
2186 $(window).resize(function() {
2188 update_sparkline(displayed_analysis_data || current_analysis_data);
2189 update_board_highlight();
2192 $(window).keyup(function(event) {
2193 if (event.which == 39) { // Left arrow.
2195 } else if (event.which == 37) { // Right arrow.
2197 } else if (event.which >= 49 && event.which <= 57) { // 1-9.
2198 var num = event.which - 49;
2199 if (current_games && current_games.length >= num) {
2200 switch_backend(current_games[num]);
2202 } else if (event.which == 78) { // N.
2206 window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
2208 $(document).ready(init);