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 = 2016091401;
13 * The current backend URL.
18 var backend_url = "/analysis.pl";
19 var backend_hash_url = "/hash";
21 /** @type {window.ChessBoard} @private */
24 /** @type {boolean} @private */
25 var board_is_animating = false;
28 * The most recent analysis data we have from the server
29 * (about the most recent position).
33 var current_analysis_data = null;
36 * If we are displaying previous analysis or from hash, this is non-null,
37 * and will override most of current_analysis_data.
42 var displayed_analysis_data = null;
45 * Games currently in progress, if any.
57 var current_games = null;
72 /** @type {Array.<Array.<boolean>>} */
73 var occupied_by_arrows = [];
75 /** Currently displayed refutation lines (on-screen).
76 * Can either come from the current_analysis_data, displayed_analysis_data,
77 * or hash_refutation_lines.
79 var refutation_lines = [];
81 /** Refutation lines from current hash probe.
83 * If non-null, will override refutation lines from the base position.
84 * Note that these are relative to display_fen, not base_fen.
86 var hash_refutation_lines = null;
88 /** @type {!number} @private */
91 /** @type {!string} @private */
94 /** @type {number} @private */
97 /** @type {boolean} @private */
98 var sort_refutation_lines_by_score = true;
100 /** @type {boolean} @private */
101 var truncate_display_history = true;
103 /** @type {!string|undefined} @private */
104 var highlight_from = undefined;
106 /** @type {!string|undefined} @private */
107 var highlight_to = undefined;
109 /** The HTML object of the move currently being highlighted (in red).
112 var highlighted_move = null;
114 /** Currently suggested/recommended move when dragging.
115 * @type {?{from: !string, to: !string}}
118 var recommended_move = null;
120 /** If reverse-dragging (dragging from the destination square to the
121 * source square), the destination square.
125 var reverse_dragging_from = null;
127 /** @type {?number} @private */
130 /** @type {boolean} @private */
131 var enable_sound = false;
134 * Our best estimate of how many milliseconds we need to add to
135 * new Date() to get the true UTC time. Calibrated against the
141 var client_clock_offset_ms = null;
143 var clock_timer = null;
145 /** The current position being analyzed, represented as a FEN string.
146 * Note that this is not necessarily the same as display_fen.
152 /** The current position on the board, represented as a FEN string.
153 * Note that board.fen() does not contain e.g. who is to play.
157 var display_fen = null;
161 * pv: Array.<string>,
164 * scores: Array<{first_move: number, score: Object}>,
165 * start_display_move_num: number
168 * "start_display_move_num" is the (half-)move number to start displaying the PV at.
169 * "score" is also evaluated at this point.
172 /** All PVs that we currently know of.
174 * Element 0 is history (or null if no history).
175 * Element 1 is current main PV, or explored line if nowhere else on the screen.
176 * All remaining elements are refutation lines (multi-PV).
178 * @type {Array.<DisplayLine>}
181 var display_lines = [];
183 /** @type {?DisplayLine} @private */
184 var current_display_line = null;
186 /** @type {boolean} @private */
187 var current_display_line_is_history = false;
189 /** @type {?number} @private */
190 var current_display_move = null;
193 * The current backend request to get main analysis (not history), if any,
194 * so that we can abort it.
199 var current_analysis_xhr = null;
202 * The current timer to fire off a request to get main analysis (not history),
203 * if any, so that we can abort it.
208 var current_analysis_request_timer = null;
211 * The current backend request to get historic data, if any.
216 var current_historic_xhr = null;
219 * The current backend request to get hash probes, if any, so that we can abort it.
224 var current_hash_xhr = null;
227 * The current timer to display hash probe information (it could be waiting on the
228 * board to stop animating), if any, so that we can abort it.
233 var current_hash_display_timer = null;
235 var supports_html5_storage = function() {
237 return 'localStorage' in window && window['localStorage'] !== null;
243 // Make the unique token persistent so people refreshing the page won't count twice.
244 // Of course, you can never fully protect against people deliberately wanting to spam.
245 var get_unique = function() {
246 var use_local_storage = supports_html5_storage();
247 if (use_local_storage && localStorage['unique']) {
248 return localStorage['unique'];
250 var unique = Math.random();
251 if (use_local_storage) {
252 localStorage['unique'] = unique;
257 var request_update = function() {
258 current_analysis_request_timer = null;
260 current_analysis_xhr = $.ajax({
261 url: backend_url + "?ims=" + ims + "&unique=" + unique
262 }).done(function(data, textstatus, xhr) {
263 sync_server_clock(xhr.getResponseHeader('Date'));
264 ims = xhr.getResponseHeader('X-RGLM');
265 var num_viewers = xhr.getResponseHeader('X-RGNV');
267 if (Array.isArray(data)) {
268 new_data = JSON.parse(JSON.stringify(current_analysis_data));
269 JSON_delta.patch(new_data, data);
274 var minimum_version = xhr.getResponseHeader('X-RGMV');
275 if (minimum_version && minimum_version > SCRIPT_VERSION) {
276 // Upgrade to latest version with a force-reload.
277 location.reload(true);
280 // Verify that the PV makes sense.
282 if (new_data['pv']) {
283 var hiddenboard = new Chess(new_data['position']['fen']);
284 for (var i = 0; i < new_data['pv'].length; ++i) {
285 if (hiddenboard.move(new_data['pv'][i]) === null) {
294 possibly_play_sound(current_analysis_data, new_data);
295 current_analysis_data = new_data;
297 update_num_viewers(num_viewers);
299 console.log("Received invalid update, waiting five seconds and trying again.");
300 location.reload(true);
304 current_analysis_request_timer = setTimeout(function() { request_update(); }, timeout);
305 }).fail(function(jqXHR, textStatus, errorThrown) {
306 if (textStatus === "abort") {
307 // Aborted because we are switching backends. Abandon and don't retry,
308 // because another one is already started for us.
310 // Backend error or similar. Wait ten seconds, then try again.
311 current_analysis_request_timer = setTimeout(function() { request_update(); }, 10000);
316 var possibly_play_sound = function(old_data, new_data) {
320 if (old_data === null) {
323 var ding = document.getElementById('ding');
324 if (ding && ding.play) {
325 if (old_data['position'] && old_data['position']['fen'] &&
326 new_data['position'] && new_data['position']['fen'] &&
327 (old_data['position']['fen'] !== new_data['position']['fen'] ||
328 old_data['position']['move_num'] !== new_data['position']['move_num'])) {
335 * @type {!string} server_date_string
337 var sync_server_clock = function(server_date_string) {
338 var server_time_ms = new Date(server_date_string).getTime();
339 var client_time_ms = new Date().getTime();
340 var estimated_offset_ms = server_time_ms - client_time_ms;
342 // In order not to let the noise move us too much back and forth
343 // (the server only has one-second resolution anyway), we only
344 // change an existing skew if we are at least five seconds off.
345 if (client_clock_offset_ms === null ||
346 Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
347 client_clock_offset_ms = estimated_offset_ms;
351 var clear_arrows = function() {
352 for (var i = 0; i < arrows.length; ++i) {
354 if (arrows[i].svg.parentElement) {
355 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
357 delete arrows[i].svg;
362 occupied_by_arrows = [];
363 for (var y = 0; y < 8; ++y) {
364 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
368 var redraw_arrows = function() {
369 for (var i = 0; i < arrows.length; ++i) {
370 position_arrow(arrows[i]);
374 /** @param {!number} x
377 var sign = function(x) {
387 /** See if drawing this arrow on the board would cause unduly amount of confusion.
388 * @param {!string} from The square the arrow is from (e.g. e4).
389 * @param {!string} to The square the arrow is to (e.g. e4).
392 var interfering_arrow = function(from, to) {
393 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
394 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
395 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
396 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
398 occupied_by_arrows[from_row][from_col] = true;
400 // Knight move: Just check that we haven't been at the destination before.
401 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
402 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
403 return occupied_by_arrows[to_row][to_col];
406 // Sliding piece: Check if anything except the from-square is seen before.
407 var dx = sign(to_col - from_col);
408 var dy = sign(to_row - from_row);
414 if (occupied_by_arrows[y][x]) {
417 occupied_by_arrows[y][x] = true;
418 } while (x != to_col || y != to_row);
423 /** Find a point along the coordinate system given by the given line,
424 * <t> units forward from the start 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_start = function(x1, y1, x2, y2, t, u) {
437 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
441 var x = x1 + dx * t + dy * u;
442 var y = y1 + dy * t - dx * u;
446 /** Find a point along the coordinate system given by the given line,
447 * <t> units forward from the end of the line, <u> units to the right of it.
448 * @param {!number} x1
449 * @param {!number} x2
450 * @param {!number} y1
451 * @param {!number} y2
454 * @return {!string} The point in "x y" form, suitable for SVG paths.
456 var point_from_end = function(x1, y1, x2, y2, t, u) {
460 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
464 var x = x2 + dx * t + dy * u;
465 var y = y2 + dy * t - dx * u;
469 var position_arrow = function(arrow) {
471 if (arrow.svg.parentElement) {
472 arrow.svg.parentElement.removeChild(arrow.svg);
476 if (current_display_line !== null && !current_display_line_is_history) {
480 var pos = $(".square-a8").position();
482 var zoom_factor = $("#board").width() / 400.0;
483 var line_width = arrow.line_width * zoom_factor;
484 var arrow_size = arrow.arrow_size * zoom_factor;
486 var square_width = $(".square-a8").width();
487 var from_y = (7 - arrow.from_row + 0.5)*square_width;
488 var to_y = (7 - arrow.to_row + 0.5)*square_width;
489 var from_x = (arrow.from_col + 0.5)*square_width;
490 var to_x = (arrow.to_col + 0.5)*square_width;
492 var SVG_NS = "http://www.w3.org/2000/svg";
493 var XHTML_NS = "http://www.w3.org/1999/xhtml";
494 var svg = document.createElementNS(SVG_NS, "svg");
495 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
496 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
497 svg.setAttribute("style", "position: absolute");
498 svg.setAttribute("position", "absolute");
499 svg.setAttribute("version", "1.1");
500 svg.setAttribute("class", "c1");
501 svg.setAttribute("xmlns", XHTML_NS);
509 var outline = document.createElementNS(SVG_NS, "path");
510 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));
511 outline.setAttribute("xmlns", XHTML_NS);
512 outline.setAttribute("stroke", "#666");
513 outline.setAttribute("stroke-width", line_width + 2);
514 outline.setAttribute("fill", "none");
515 svg.appendChild(outline);
517 var path = document.createElementNS(SVG_NS, "path");
518 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));
519 path.setAttribute("xmlns", XHTML_NS);
520 path.setAttribute("stroke", arrow.fg_color);
521 path.setAttribute("stroke-width", line_width);
522 path.setAttribute("fill", "none");
523 svg.appendChild(path);
525 // Then the arrow head.
526 var head = document.createElementNS(SVG_NS, "path");
527 head.setAttribute("d",
528 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
529 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
530 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
531 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
532 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
533 head.setAttribute("xmlns", XHTML_NS);
534 head.setAttribute("stroke", "#000");
535 head.setAttribute("stroke-width", "1");
536 head.setAttribute("fill", arrow.fg_color);
537 svg.appendChild(head);
539 $(svg).css({ top: pos.top, left: pos.left, 'pointer-events': 'none' });
540 document.body.appendChild(svg);
545 * @param {!string} from_square
546 * @param {!string} to_square
547 * @param {!string} fg_color
548 * @param {number} line_width
549 * @param {number} arrow_size
551 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
552 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
553 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
554 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
555 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
563 line_width: line_width,
564 arrow_size: arrow_size,
568 position_arrow(arrow);
572 // Note: invert is ignored.
573 var compare_by_name = function(refutation_lines, invert, a, b) {
574 var ska = refutation_lines[a]['move'];
575 var skb = refutation_lines[b]['move'];
576 if (ska < skb) return -1;
577 if (ska > skb) return 1;
581 var compare_by_score = function(refutation_lines, invert, a, b) {
582 var sa = compute_score_sort_key(refutation_lines[b]['score'], refutation_lines[b]['depth'], invert);
583 var sb = compute_score_sort_key(refutation_lines[a]['score'], refutation_lines[a]['depth'], invert);
588 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
589 * sorted by quality, descending.
591 * @param {!Object} data
592 * @param {number} margin The maximum number of centipawns worse than the
593 * best move can be and still be included.
594 * @param {boolean} invert Whether black is to play.
595 * @return {Array.<string>} The FEN representation (e.g. Ne4) of all
596 * moves, in score order.
598 var find_nonstupid_moves = function(data, margin, invert) {
599 // First of all, if there are any moves that are more than 0.5 ahead of
600 // the primary move, the refutation lines are probably bunk, so just
602 var best_score = undefined;
603 var pv_score = undefined;
604 for (var move in data['refutation_lines']) {
605 var line = data['refutation_lines'][move];
606 var score = compute_score_sort_key(line['score'], line['depth'], invert, false);
607 if (move == data['pv'][0]) {
610 if (best_score === undefined || score > best_score) {
613 if (line['depth'] < 8) {
618 if (best_score - pv_score > 50) {
622 // Now find all moves that are within “margin” of the best score.
623 // The PV move will always be first.
625 for (var move in data['refutation_lines']) {
626 var line = data['refutation_lines'][move];
627 var score = compute_score_sort_key(line['score'], line['depth'], invert);
628 if (move != data['pv'][0] && best_score - score <= margin) {
632 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], data['position']['toplay'] === 'B', a, b) });
633 moves.unshift(data['pv'][0]);
642 var thousands = function(x) {
643 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
647 * @param {!string} start_fen
648 * @param {Array.<string>} pv
649 * @param {number} move_num
650 * @param {!string} toplay
651 * @param {Array<{ first_move: integer, score: Object }>} scores
652 * @param {number} start_display_move_num
653 * @param {number=} opt_limit
654 * @param {boolean=} opt_showlast
656 var add_pv = function(start_fen, pv, move_num, toplay, scores, start_display_move_num, opt_limit, opt_showlast) {
658 start_fen: start_fen,
660 move_num: parseInt(move_num),
663 start_display_move_num: start_display_move_num
665 return print_pv(display_lines.length - 1, opt_limit, opt_showlast);
669 * @param {number} line_num
670 * @param {number=} opt_limit If set, show at most this number of moves.
671 * @param {boolean=} opt_showlast If limit is set, show the last moves instead of the first ones.
673 var print_pv = function(line_num, opt_limit, opt_showlast) {
674 var display_line = display_lines[line_num];
675 var pv = display_line.pv;
676 var move_num = display_line.move_num;
677 var toplay = display_line.toplay;
679 // Truncate PV at the start if needed.
680 var start_display_move_num = display_line.start_display_move_num;
681 if (start_display_move_num > 0) {
682 pv = pv.slice(start_display_move_num);
683 var to_add = start_display_move_num;
684 if (toplay === 'B') {
689 if (to_add % 2 == 1) {
693 move_num += to_add / 2;
698 if (opt_limit && opt_showlast && pv.length > opt_limit) {
699 // Truncate the PV at the beginning (instead of at the end).
700 // We assume here that toplay is 'W'. We also assume that if
701 // opt_showlast is set, then it is the history, and thus,
702 // the UI should be to expand the history.
703 ret = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
704 i = pv.length - opt_limit;
709 } else if (toplay == 'B' && pv.length > 0) {
710 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pv[0] + "</a>";
711 ret = move_num + '. … ' + move;
716 for ( ; i < pv.length; ++i) {
717 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pv[i] + "</a>";
720 if (i > opt_limit && !opt_showlast) {
726 ret += move_num + '. ' + move;
737 /** Update the highlighted to/from squares on the board.
738 * Based on the global "highlight_from" and "highlight_to" variables.
740 var update_board_highlight = function() {
741 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
742 if ((current_display_line === null || current_display_line_is_history) &&
743 highlight_from !== undefined && highlight_to !== undefined) {
744 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
745 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
749 var update_history = function() {
750 if (display_lines[0] === null || display_lines[0].pv.length == 0) {
751 $("#history").html("No history");
752 } else if (truncate_display_history) {
753 $("#history").html(print_pv(0, 8, true));
756 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
762 * @param {!boolean} truncate_history
764 var collapse_history = function(truncate_history) {
765 truncate_display_history = truncate_history;
768 window['collapse_history'] = collapse_history;
770 /** Update the HTML display of multi-PV from the global "refutation_lines".
772 * Also recreates the global "display_lines".
774 var update_refutation_lines = function() {
775 if (base_fen === null) {
778 if (display_lines.length > 2) {
779 // Truncate so that only the history and PV is left.
780 display_lines = [ display_lines[0], display_lines[1] ];
782 var tbl = $("#refutationlines");
785 // Find out where the lines start from.
787 var base_scores = display_lines[1].scores;
788 var start_display_move_num = 0;
789 if (hash_refutation_lines) {
790 base_line = current_display_line.pv.slice(0, current_display_move + 1);
791 base_scores = current_display_line.scores;
792 start_display_move_num = base_line.length;
796 for (var move in refutation_lines) {
800 var invert = (toplay === 'B');
801 if (current_display_line && current_display_move % 2 == 0) {
804 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_name;
805 moves = moves.sort(function(a, b) { return compare(refutation_lines, invert, a, b) });
806 for (var i = 0; i < moves.length; ++i) {
807 var line = refutation_lines[moves[i]];
809 var tr = document.createElement("tr");
811 var move_td = document.createElement("td");
812 tr.appendChild(move_td);
813 $(move_td).addClass("move");
815 var scores = base_scores.concat([{ first_move: start_display_move_num, score: line['score'] }]);
817 if (line['pv'].length == 0) {
818 // Not found, so just make a one-move PV.
819 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['move'] + "</a>";
820 $(move_td).html(move);
821 var score_td = document.createElement("td");
823 $(score_td).addClass("score");
824 $(score_td).text("—");
825 tr.appendChild(score_td);
827 var depth_td = document.createElement("td");
828 tr.appendChild(depth_td);
829 $(depth_td).addClass("depth");
830 $(depth_td).text("—");
832 var pv_td = document.createElement("td");
833 tr.appendChild(pv_td);
834 $(pv_td).addClass("pv");
835 $(pv_td).html(add_pv(base_fen, base_line.concat([ line['move'] ]), move_num, toplay, scores, start_display_move_num));
841 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['move'] + "</a>";
842 $(move_td).html(move);
844 var score_td = document.createElement("td");
845 tr.appendChild(score_td);
846 $(score_td).addClass("score");
847 $(score_td).text(format_short_score(line['score']));
849 var depth_td = document.createElement("td");
850 tr.appendChild(depth_td);
851 $(depth_td).addClass("depth");
852 if (line['depth'] && line['depth'] >= 0) {
853 $(depth_td).text("d" + line['depth']);
855 $(depth_td).text("—");
858 var pv_td = document.createElement("td");
859 tr.appendChild(pv_td);
860 $(pv_td).addClass("pv");
861 $(pv_td).html(add_pv(base_fen, base_line.concat(line['pv']), move_num, toplay, scores, start_display_move_num, 10));
866 // Make one of the links clickable and the other nonclickable.
867 if (sort_refutation_lines_by_score) {
868 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
869 $("#sortbyscore1").html("<strong>Score</strong>");
871 $("#sortbyscore0").html("<strong>Move</strong>");
872 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
875 // Update the move highlight, as we've rewritten all the HTML.
876 update_move_highlight();
880 * Create a Chess.js board object, containing the given position plus the given moves,
881 * up to the given limit.
883 * @param {?string} fen
884 * @param {Array.<string>} moves
885 * @param {number} last_move
887 var chess_from = function(fen, moves, last_move) {
888 var hiddenboard = new Chess();
890 hiddenboard.load(fen);
892 for (var i = 0; i <= last_move; ++i) {
893 if (moves[i] === '0-0') {
894 hiddenboard.move('O-O');
895 } else if (moves[i] === '0-0-0') {
896 hiddenboard.move('O-O-O');
898 hiddenboard.move(moves[i]);
904 var update_game_list = function(games) {
905 $("#games").text("");
906 if (games === null) {
910 var games_div = document.getElementById('games');
911 for (var game_num = 0; game_num < games.length; ++game_num) {
912 var game = games[game_num];
913 var game_span = document.createElement("span");
914 game_span.setAttribute("class", "game");
916 var game_name = document.createTextNode(game['name']);
917 if (game['url'] === backend_url) {
919 game_span.appendChild(game_name);
921 if (current_analysis_data && current_analysis_data['position']) {
923 if (current_analysis_data['position']['result']) {
924 score = " (" + current_analysis_data['position']['result'] + ")";
926 score = " (" + format_short_score(current_analysis_data['score']) + ")";
928 game_span.appendChild(document.createTextNode(score));
932 var game_a = document.createElement("a");
933 game_a.setAttribute("href", "#" + game['id']);
934 game_a.appendChild(game_name);
935 game_span.appendChild(game_a);
938 if (game['result']) {
939 score = " (" + game['result'] + ")";
941 score = " (" + format_short_score(game['score']) + ")";
943 game_span.appendChild(document.createTextNode(score));
946 games_div.appendChild(game_span);
951 * Try to find a running game that matches with the current hash,
952 * and switch to it if we're not already displaying it.
954 var possibly_switch_game_from_hash = function() {
955 if (current_games === null) {
959 var hash = window.location.hash.replace(/^#/,'');
960 for (var i = 0; i < current_games.length; ++i) {
961 if (current_games[i]['id'] === hash) {
962 if (backend_url !== current_games[i]['url']) {
963 switch_backend(current_games[i]);
970 /** Update all the HTML on the page, based on current global state.
972 var update_board = function() {
973 var data = displayed_analysis_data || current_analysis_data;
974 var current_data = current_analysis_data; // Convenience alias.
978 // Print the history. This is pretty much the only thing that's
979 // unconditionally taken from current_data (we're not interested in
980 // historic history).
981 if (current_data['position']['history']) {
982 add_pv('start', current_data['position']['history'], 1, 'W', null, 0, 8, true);
984 display_lines.push(null);
988 // Games currently in progress, if any.
989 if (current_data['games']) {
990 current_games = current_data['games'];
991 possibly_switch_game_from_hash();
993 current_games = null;
995 update_game_list(current_games);
997 // The headline. Names are always fetched from current_data;
998 // the rest can depend a bit.
1001 current_data['position']['player_w'] && current_data['position']['player_b']) {
1002 headline = current_data['position']['player_w'] + '–' +
1003 current_data['position']['player_b'] + ', analysis';
1005 headline = 'Analysis';
1008 // Credits, where applicable. Note that we don't want the footer to change a lot
1009 // when e.g. viewing history, so if any of these changed during the game,
1010 // use the current one still.
1011 if (current_data['using_lomonosov']) {
1012 $("#lomonosov").show();
1014 $("#lomonosov").hide();
1017 // Credits: The engine name/version.
1018 if (current_data['engine'] && current_data['engine']['name'] !== null) {
1019 $("#engineid").text(current_data['engine']['name']);
1022 // Credits: The engine URL.
1023 if (current_data['engine'] && current_data['engine']['url']) {
1024 $("#engineid").attr("href", current_data['engine']['url']);
1026 $("#engineid").removeAttr("href");
1029 // Credits: Engine details.
1030 if (current_data['engine'] && current_data['engine']['details']) {
1031 $("#enginedetails").text(" (" + current_data['engine']['details'] + ")");
1033 $("#enginedetails").text("");
1036 // Credits: Move source, possibly with URL.
1037 if (current_data['move_source'] && current_data['move_source_url']) {
1038 $("#movesource").text("Moves provided by ");
1039 var movesource_a = document.createElement("a");
1040 movesource_a.setAttribute("href", current_data['move_source_url']);
1041 var movesource_text = document.createTextNode(current_data['move_source']);
1042 movesource_a.appendChild(movesource_text);
1043 var movesource_period = document.createTextNode(".");
1044 document.getElementById("movesource").appendChild(movesource_a);
1045 document.getElementById("movesource").appendChild(movesource_period);
1046 } else if (current_data['move_source']) {
1047 $("#movesource").text("Moves provided by " + current_data['move_source'] + ".");
1049 $("#movesource").text("");
1053 if (displayed_analysis_data) {
1054 // Displaying some non-current position, pick out the last move
1055 // from the history. This will work even if the fetch failed.
1056 last_move = format_halfmove_with_number(
1057 current_display_line.pv[current_display_move],
1058 current_display_move + 1);
1059 headline += ' after ' + last_move;
1060 } else if (data['position']['last_move'] !== 'none') {
1061 last_move = format_move_with_number(
1062 data['position']['last_move'],
1063 data['position']['move_num'],
1064 data['position']['toplay'] == 'W');
1065 headline += ' after ' + last_move;
1069 $("#headline").text(headline);
1071 // The <title> contains a very brief headline.
1072 var title_elems = [];
1073 if (data['position'] && data['position']['result']) {
1074 title_elems.push(data['position']['result']);
1075 } else if (data['score']) {
1076 title_elems.push(format_short_score(data['score']));
1078 if (last_move !== null) {
1079 title_elems.push(last_move);
1082 if (title_elems.length != 0) {
1083 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
1085 document.title = 'analysis.sesse.net';
1088 // The last move (shown by highlighting the from and to squares).
1089 if (data['position'] && data['position']['last_move_uci']) {
1090 highlight_from = data['position']['last_move_uci'].substr(0, 2);
1091 highlight_to = data['position']['last_move_uci'].substr(2, 2);
1092 } else if (current_display_line_is_history && current_display_line && current_display_move >= 0) {
1093 // We don't have historic analysis for this position, but we
1094 // can reconstruct what the last move was by just replaying
1096 var hiddenboard = chess_from(null, current_display_line.pv, current_display_move);
1097 var moves = hiddenboard.history({ verbose: true });
1098 last_move = moves.pop();
1099 highlight_from = last_move.from;
1100 highlight_to = last_move.to;
1102 highlight_from = highlight_to = undefined;
1104 update_board_highlight();
1106 if (data['failed']) {
1107 $("#score").text("No analysis for this move");
1108 $("#pvtitle").text("PV:");
1110 $("#searchstats").html(" ");
1111 $("#refutationlines").empty();
1112 $("#whiteclock").empty();
1113 $("#blackclock").empty();
1114 refutation_lines = [];
1115 update_refutation_lines();
1117 update_displayed_line();
1118 update_move_highlight();
1125 if (current_display_line && !current_display_line_is_history) {
1127 if (current_display_line.scores && current_display_line.scores.length > 0) {
1128 for (var i = 0; i < current_display_line.scores.length; ++i) {
1129 if (current_display_move < current_display_line.scores[i].first_move) {
1132 score = current_display_line.scores[i].score;
1136 $("#score").text(format_long_score(score));
1138 $("#score").text("No score for this line");
1140 } else if (data['score']) {
1141 $("#score").text(format_long_score(data['score']));
1144 // The search stats.
1145 if (data['searchstats']) {
1146 $("#searchstats").html(data['searchstats']);
1147 } else if (data['tablebase'] == 1) {
1148 $("#searchstats").text("Tablebase result");
1149 } else if (data['nodes'] && data['nps'] && data['depth']) {
1150 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
1151 if (data['seldepth']) {
1152 stats += ' (' + data['seldepth'] + ' selective)';
1154 if (data['tbhits'] && data['tbhits'] > 0) {
1155 if (data['tbhits'] == 1) {
1156 stats += ', one Syzygy hit';
1158 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
1162 $("#searchstats").text(stats);
1164 $("#searchstats").text("");
1167 // Update the board itself.
1168 base_fen = data['position']['fen'];
1169 update_displayed_line();
1172 $("#pvtitle").text("PV:");
1174 var scores = [{ first_move: -1, score: data['score'] }];
1175 $("#pv").html(add_pv(data['position']['fen'], data['pv'], data['position']['move_num'], data['position']['toplay'], scores, 0));
1177 // Update the PV arrow.
1179 if (data['pv'].length >= 1) {
1180 var hiddenboard = new Chess(base_fen);
1182 // draw a continuation arrow as long as it's the same piece
1184 for (var i = 0; i < data['pv'].length; i += 2) {
1185 var move = hiddenboard.move(data['pv'][i]);
1186 if ((i >= 2 && move.from != last_to) ||
1187 interfering_arrow(move.from, move.to)) {
1190 create_arrow(move.from, move.to, '#f66', 6, 20);
1191 last_to = move.from;
1192 hiddenboard.move(data['pv'][i + 1]); // To keep continuity.
1195 var alt_moves = find_nonstupid_moves(data, 30, data['position']['toplay'] === 'B');
1196 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
1197 hiddenboard = new Chess(base_fen);
1198 var move = hiddenboard.move(alt_moves[i]);
1199 create_arrow(move.from, move.to, '#f66', 1, 10);
1203 // See if all semi-reasonable moves have only one possible response.
1204 if (data['pv'].length >= 2) {
1205 var nonstupid_moves = find_nonstupid_moves(data, 300, data['position']['toplay'] === 'B');
1208 var hiddenboard = new Chess(base_fen);
1209 hiddenboard.move(data['pv'][0]);
1210 response = hiddenboard.move(data['pv'][1]);
1212 for (var i = 0; i < nonstupid_moves.length; ++i) {
1213 if (nonstupid_moves[i] == data['pv'][0]) {
1214 // ignore the PV move for refutation lines.
1217 if (!data['refutation_lines'] ||
1218 !data['refutation_lines'][nonstupid_moves[i]] ||
1219 !data['refutation_lines'][nonstupid_moves[i]]['pv'] ||
1220 data['refutation_lines'][nonstupid_moves[i]]['pv'].length < 1) {
1221 // Incomplete PV, abort.
1222 response = undefined;
1225 var line = data['refutation_lines'][nonstupid_moves[i]];
1226 hiddenboard = new Chess(base_fen);
1227 hiddenboard.move(line['pv'][0]);
1228 var this_response = hiddenboard.move(line['pv'][1]);
1229 if (response.from !== this_response.from || response.to !== this_response.to) {
1230 // Different response depending on lines, abort.
1231 response = undefined;
1236 if (nonstupid_moves.length > 0 && response !== undefined) {
1237 create_arrow(response.from, response.to, '#66f', 6, 20);
1241 // Update the refutation lines.
1242 base_fen = data['position']['fen'];
1243 move_num = parseInt(data['position']['move_num']);
1244 toplay = data['position']['toplay'];
1245 refutation_lines = hash_refutation_lines || data['refutation_lines'];
1246 update_refutation_lines();
1248 // Update the sparkline last, since its size depends on how everything else reflowed.
1249 update_sparkline(data);
1252 var update_sparkline = function(data) {
1253 if (data && data['score_history']) {
1254 var first_move_num = undefined;
1255 for (var halfmove_num in data['score_history']) {
1256 halfmove_num = parseInt(halfmove_num);
1257 if (first_move_num === undefined || halfmove_num < first_move_num) {
1258 first_move_num = halfmove_num;
1261 if (first_move_num !== undefined) {
1262 var last_move_num = data['position']['move_num'] * 2 - 3;
1263 if (data['position']['toplay'] === 'B') {
1267 // Possibly truncate some moves if we don't have enough width.
1268 // FIXME: Sometimes width() for #scorecontainer (and by extent,
1269 // #scoresparkcontainer) on Chrome for mobile seems to start off
1270 // at something very small, and then suddenly snap back into place.
1272 var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
1273 if (last_move_num - first_move_num > max_moves) {
1274 first_move_num = last_move_num - max_moves;
1277 var min_score = -100;
1278 var max_score = 100;
1279 var last_score = null;
1281 for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1282 if (data['score_history'][halfmove_num]) {
1283 var score = compute_plot_score(data['score_history'][halfmove_num]);
1285 if (score < min_score) min_score = score;
1286 if (score > max_score) max_score = score;
1288 scores.push(last_score);
1290 if (data['score']) {
1291 scores.push(compute_plot_score(data['score']));
1293 // FIXME: at some widths, calling sparkline() seems to push
1294 // #scorecontainer under the board.
1295 $("#scorespark").sparkline(scores, {
1298 chartRangeMin: min_score,
1299 chartRangeMax: max_score,
1300 tooltipFormatter: function(sparkline, options, fields) {
1301 return format_tooltip(data, fields[0].offset + first_move_num);
1305 $("#scorespark").text("");
1308 $("#scorespark").text("");
1313 * @param {number} num_viewers
1315 var update_num_viewers = function(num_viewers) {
1316 if (num_viewers === null) {
1317 $("#numviewers").text("");
1318 } else if (num_viewers == 1) {
1319 $("#numviewers").text("You are the only current viewer");
1321 $("#numviewers").text(num_viewers + " current viewers");
1325 var update_clock = function() {
1326 clearTimeout(clock_timer);
1328 var data = displayed_analysis_data || current_analysis_data;
1331 if (data['position']) {
1332 var result = data['position']['result'];
1333 if (result === '1-0') {
1334 $("#whiteclock").text("1");
1335 $("#blackclock").text("0");
1336 $("#whiteclock").removeClass("running-clock");
1337 $("#blackclock").removeClass("running-clock");
1340 if (result === '1/2-1/2') {
1341 $("#whiteclock").text("1/2");
1342 $("#blackclock").text("1/2");
1343 $("#whiteclock").removeClass("running-clock");
1344 $("#blackclock").removeClass("running-clock");
1347 if (result === '0-1') {
1348 $("#whiteclock").text("0");
1349 $("#blackclock").text("1");
1350 $("#whiteclock").removeClass("running-clock");
1351 $("#blackclock").removeClass("running-clock");
1356 var white_clock_ms = null;
1357 var black_clock_ms = null;
1360 if (data['position'] &&
1361 data['position']['white_clock'] &&
1362 data['position']['black_clock']) {
1363 white_clock_ms = data['position']['white_clock'] * 1000;
1364 black_clock_ms = data['position']['black_clock'] * 1000;
1367 // Dynamic clock (only one, obviously).
1369 if (data['position']['white_clock_target']) {
1371 $("#whiteclock").addClass("running-clock");
1372 $("#blackclock").removeClass("running-clock");
1373 } else if (data['position']['black_clock_target']) {
1375 $("#whiteclock").removeClass("running-clock");
1376 $("#blackclock").addClass("running-clock");
1378 $("#whiteclock").removeClass("running-clock");
1379 $("#blackclock").removeClass("running-clock");
1383 var now = new Date().getTime() + client_clock_offset_ms;
1384 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1385 if (color === "white") {
1386 white_clock_ms = remaining_ms;
1388 black_clock_ms = remaining_ms;
1392 if (white_clock_ms === null || black_clock_ms === null) {
1393 $("#whiteclock").empty();
1394 $("#blackclock").empty();
1398 // If either player has ten minutes or less left, add the second counters.
1399 var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
1402 // See when the clock will change next, and update right after that.
1405 next_update_ms = remaining_ms % 1000 + 100;
1407 next_update_ms = remaining_ms % 60000 + 100;
1409 clock_timer = setTimeout(update_clock, next_update_ms);
1412 $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1413 $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1417 * @param {Number} remaining_ms
1418 * @param {boolean} show_seconds
1420 var format_clock = function(remaining_ms, show_seconds) {
1421 if (remaining_ms <= 0) {
1429 var remaining = Math.floor(remaining_ms / 1000);
1430 var seconds = remaining % 60;
1431 remaining = (remaining - seconds) / 60;
1432 var minutes = remaining % 60;
1433 remaining = (remaining - minutes) / 60;
1434 var hours = remaining;
1436 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1438 return format_2d(hours) + ":" + format_2d(minutes);
1445 var format_2d = function(x) {
1454 * @param {string} move
1455 * @param {Number} move_num
1456 * @param {boolean} white_to_play
1458 var format_move_with_number = function(move, move_num, white_to_play) {
1460 if (white_to_play) {
1461 ret = (move_num - 1) + '… ';
1463 ret = move_num + '. ';
1470 * @param {string} move
1471 * @param {Number} halfmove_num
1473 var format_halfmove_with_number = function(move, halfmove_num) {
1474 return format_move_with_number(
1476 Math.floor(halfmove_num / 2) + 1,
1477 halfmove_num % 2 == 0);
1481 * @param {Object} data
1482 * @param {Number} halfmove_num
1484 var format_tooltip = function(data, halfmove_num) {
1485 if (data['score_history'][halfmove_num] ||
1486 halfmove_num === data['position']['history'].length) {
1489 if (halfmove_num === data['position']['history'].length) {
1490 move = data['position']['last_move'];
1491 short_score = format_short_score(data['score']);
1493 move = data['position']['history'][halfmove_num];
1494 short_score = format_short_score(data['score_history'][halfmove_num]);
1496 var move_with_number = format_halfmove_with_number(move, halfmove_num);
1498 return "After " + move_with_number + ": " + short_score;
1500 for (var i = halfmove_num; i --> 0; ) {
1501 if (data['score_history'][i]) {
1502 var move = data['position']['history'][i];
1503 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1510 * @param {boolean} sort_by_score
1512 var resort_refutation_lines = function(sort_by_score) {
1513 sort_refutation_lines_by_score = sort_by_score;
1514 if (supports_html5_storage()) {
1515 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1517 update_refutation_lines();
1519 window['resort_refutation_lines'] = resort_refutation_lines;
1522 * @param {boolean} truncate_history
1524 var set_truncate_history = function(truncate_history) {
1525 truncate_display_history = truncate_history;
1526 update_refutation_lines();
1528 window['set_truncate_history'] = set_truncate_history;
1531 * @param {number} line_num
1532 * @param {number} move_num
1534 var show_line = function(line_num, move_num) {
1535 if (line_num == -1) {
1536 current_display_line = null;
1537 current_display_move = null;
1538 hash_refutation_lines = null;
1539 if (displayed_analysis_data) {
1540 // TODO: Support exiting to history position if we are in an
1541 // analysis line of a history position.
1542 displayed_analysis_data = null;
1547 current_display_line = jQuery.extend({}, display_lines[line_num]); // Shallow clone.
1548 current_display_move = move_num + current_display_line.start_display_move_num;
1550 current_display_line_is_history = (line_num == 0);
1552 update_historic_analysis();
1553 update_displayed_line();
1554 update_board_highlight();
1555 update_move_highlight();
1558 window['show_line'] = show_line;
1560 var prev_move = function() {
1561 if (current_display_line &&
1562 current_display_move >= current_display_line.start_display_move_num) {
1563 --current_display_move;
1565 update_historic_analysis();
1566 update_displayed_line();
1567 update_move_highlight();
1569 window['prev_move'] = prev_move;
1571 var next_move = function() {
1572 if (current_display_line &&
1573 current_display_move < current_display_line.pv.length - 1) {
1574 ++current_display_move;
1576 update_historic_analysis();
1577 update_displayed_line();
1578 update_move_highlight();
1580 window['next_move'] = next_move;
1582 var next_game = function() {
1583 if (current_games === null) {
1587 // Try to find the game we are currently looking at.
1588 for (var game_num = 0; game_num < current_games.length; ++game_num) {
1589 var game = current_games[game_num];
1590 if (game['url'] === backend_url) {
1591 var next_game_num = (game_num + 1) % current_games.length;
1592 switch_backend(current_games[next_game_num]);
1597 // Couldn't find it; give up.
1600 var update_historic_analysis = function() {
1601 if (!current_display_line_is_history) {
1604 if (current_display_move == current_display_line.pv.length - 1) {
1605 displayed_analysis_data = null;
1609 // Fetch old analysis for this line if it exists.
1610 var hiddenboard = chess_from(null, current_display_line.pv, current_display_move);
1611 var filename = "/history/move" + (current_display_move + 1) + "-" +
1612 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1614 current_historic_xhr = $.ajax({
1616 }).done(function(data, textstatus, xhr) {
1617 displayed_analysis_data = data;
1619 }).fail(function(jqXHR, textStatus, errorThrown) {
1620 if (textStatus === "abort") {
1621 // Aborted because we are switching backends. Don't do anything;
1622 // we will already have been cleared.
1624 displayed_analysis_data = {'failed': true};
1631 * @param {string} fen
1633 var update_imbalance = function(fen) {
1634 var hiddenboard = new Chess(fen);
1635 var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1636 for (var row = 0; row < 8; ++row) {
1637 for (var col = 0; col < 8; ++col) {
1638 var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1639 var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1640 var square = col_text + row_text;
1641 var contents = hiddenboard.get(square);
1642 if (contents !== null) {
1643 if (contents.color === 'w') {
1644 ++imbalance[contents.type];
1646 --imbalance[contents.type];
1651 var white_imbalance = '';
1652 var black_imbalance = '';
1653 for (var piece in imbalance) {
1654 for (var i = 0; i < imbalance[piece]; ++i) {
1655 white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1657 for (var i = 0; i < -imbalance[piece]; ++i) {
1658 black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1661 $('#whiteimbalance').html(white_imbalance);
1662 $('#blackimbalance').html(black_imbalance);
1665 /** Mark the currently selected move in red.
1666 * Also replaces the PV with the current displayed line if it's not shown
1667 * anywhere else on the screen.
1669 var update_move_highlight = function() {
1670 if (highlighted_move !== null) {
1671 highlighted_move.removeClass('highlight');
1673 if (current_display_line) {
1674 var display_line_num = find_display_line_matching_num();
1675 if (display_line_num === null) {
1676 // Replace the PV with the (complete) line.
1677 $("#pvtitle").text("Exploring:");
1678 current_display_line.start_display_move_num = 0;
1679 display_lines.push(current_display_line);
1680 $("#pv").html(print_pv(display_lines.length - 1));
1681 display_line_num = display_lines.length - 1;
1683 // Clear out the PV, so it's not selected by anything later.
1684 display_lines[1].pv = [];
1687 highlighted_move = $("#automove" + display_line_num + "-" + (current_display_move - current_display_line.start_display_move_num));
1688 highlighted_move.addClass('highlight');
1693 * See if the current displayed line is identical to any of the ones
1694 * we have on screen. (It might not be if e.g. the analysis reloaded
1695 * since we started looking.)
1699 var find_display_line_matching_num = function() {
1700 for (var i = 0; i < display_lines.length; ++i) {
1701 var line = display_lines[i];
1702 if (line.start_display_move_num > 0) continue;
1703 if (current_display_line.start_fen !== line.start_fen) continue;
1704 if (current_display_line.pv.length !== line.pv.length) continue;
1706 for (var j = 0; j < line.pv.length; ++j) {
1707 if (current_display_line.pv[j] !== line.pv[j]) {
1719 /** Update the board based on the currently displayed line.
1721 * TODO: This should really be called only whenever something changes,
1722 * instead of all the time.
1724 var update_displayed_line = function() {
1725 if (current_display_line === null) {
1726 $("#linenav").hide();
1727 $("#linemsg").show();
1728 display_fen = base_fen;
1729 set_board_position(base_fen);
1730 update_imbalance(base_fen);
1734 $("#linenav").show();
1735 $("#linemsg").hide();
1737 if (current_display_move <= 0) {
1738 $("#prevmove").html("Previous");
1740 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1742 if (current_display_move == current_display_line.pv.length - 1) {
1743 $("#nextmove").html("Next");
1745 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1748 var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pv, current_display_move);
1749 set_board_position(hiddenboard.fen());
1750 if (display_fen !== hiddenboard.fen() && !current_display_line_is_history) {
1751 // Fire off a hash request, since we're now off the main position
1752 // and it just changed.
1753 explore_hash(hiddenboard.fen());
1755 display_fen = hiddenboard.fen();
1756 update_imbalance(hiddenboard.fen());
1759 var set_board_position = function(new_fen) {
1760 board_is_animating = true;
1761 var old_fen = board.fen();
1762 board.position(new_fen);
1763 if (board.fen() === old_fen) {
1764 board_is_animating = false;
1769 * @param {boolean} param_enable_sound
1771 var set_sound = function(param_enable_sound) {
1772 enable_sound = param_enable_sound;
1774 $("#soundon").html("<strong>On</strong>");
1775 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1777 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1778 // and also preload the file since the user has selected audio.
1779 var ding = document.getElementById('ding');
1780 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1781 ding.src = 'ding.opus';
1785 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1786 $("#soundoff").html("<strong>Off</strong>");
1788 if (supports_html5_storage()) {
1789 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1792 window['set_sound'] = set_sound;
1794 /** Send off a hash probe request to the backend.
1795 * @param {string} fen
1797 var explore_hash = function(fen) {
1798 // If we already have a backend response going, abort it.
1799 if (current_hash_xhr) {
1800 current_hash_xhr.abort();
1802 if (current_hash_display_timer) {
1803 clearTimeout(current_hash_display_timer);
1804 current_hash_display_timer = null;
1806 $("#refutationlines").empty();
1807 current_hash_xhr = $.ajax({
1808 url: backend_hash_url + "?fen=" + fen
1809 }).done(function(data, textstatus, xhr) {
1810 show_explore_hash_results(data, fen);
1814 /** Process the JSON response from a hash probe request.
1815 * @param {!Object} data
1816 * @param {string} fen
1818 var show_explore_hash_results = function(data, fen) {
1819 if (board_is_animating) {
1820 // Updating while the animation is still going causes
1821 // the animation to jerk. This is pretty crude, but it will do.
1822 current_hash_display_timer = setTimeout(function() { show_explore_hash_results(data, fen); }, 100);
1825 current_hash_display_timer = null;
1826 hash_refutation_lines = data['lines'];
1830 // almost all of this stuff comes from the chessboard.js example page
1831 var onDragStart = function(source, piece, position, orientation) {
1832 var pseudogame = new Chess(display_fen);
1833 if (pseudogame.game_over() === true ||
1834 (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
1835 (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
1839 recommended_move = get_best_move(pseudogame, source, null, pseudogame.turn() === 'b');
1840 if (recommended_move) {
1841 var squareEl = $('#board .square-' + recommended_move.to);
1842 squareEl.addClass('highlight1-32417');
1847 var mousedownSquare = function(e) {
1848 reverse_dragging_from = null;
1849 var square = $(this).attr('data-square');
1851 var pseudogame = new Chess(display_fen);
1852 if (pseudogame.game_over() === true) {
1856 // If the square is empty, or has a piece of the side not to move,
1857 // we handle it. If not, normal piece dragging will take it.
1858 var position = board.position();
1859 if (!position.hasOwnProperty(square) ||
1860 (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
1861 (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
1862 reverse_dragging_from = square;
1863 recommended_move = get_best_move(pseudogame, null, square, pseudogame.turn() === 'b');
1864 if (recommended_move) {
1865 var squareEl = $('#board .square-' + recommended_move.from);
1866 squareEl.addClass('highlight1-32417');
1867 squareEl = $('#board .square-' + recommended_move.to);
1868 squareEl.addClass('highlight1-32417');
1873 var mouseupSquare = function(e) {
1874 if (reverse_dragging_from === null) {
1877 var source = $(this).attr('data-square');
1878 var target = reverse_dragging_from;
1879 reverse_dragging_from = null;
1880 if (onDrop(source, target) !== 'snapback') {
1881 onSnapEnd(source, target);
1883 $("#board").find('.square-55d63').removeClass('highlight1-32417');
1886 var get_best_move = function(game, source, target, invert) {
1887 var moves = game.moves({ verbose: true });
1888 if (source !== null) {
1889 moves = moves.filter(function(move) { return move.from == source; });
1891 if (target !== null) {
1892 moves = moves.filter(function(move) { return move.to == target; });
1894 if (moves.length == 0) {
1897 if (moves.length == 1) {
1901 // More than one move. Use the display lines (if we have them)
1902 // to disambiguate; otherwise, we have no information.
1904 for (var i = 0; i < moves.length; ++i) {
1905 move_hash[moves[i].san] = moves[i];
1908 // See if we're already exploring some line.
1909 if (current_display_line &&
1910 current_display_move < current_display_line.pv.length - 1) {
1911 var first_move = current_display_line.pv[current_display_move + 1];
1912 if (move_hash[first_move]) {
1913 return move_hash[first_move];
1917 // History and PV take priority over the display lines.
1918 for (var i = 0; i < 2; ++i) {
1919 var line = display_lines[i];
1920 var first_move = line.pv[line.start_display_move_num];
1921 if (move_hash[first_move]) {
1922 return move_hash[first_move];
1926 var best_move = null;
1927 var best_move_score = null;
1929 for (var move in refutation_lines) {
1930 var line = refutation_lines[move];
1931 if (!line['score']) {
1934 var first_move = line['pv'][0];
1935 if (move_hash[first_move]) {
1936 var score = compute_score_sort_key(line['score'], line['depth'], invert);
1937 if (best_move_score === null || score > best_move_score) {
1938 best_move = move_hash[first_move];
1939 best_move_score = score;
1946 var onDrop = function(source, target) {
1947 if (source === target) {
1948 if (recommended_move === null) {
1951 // Accept the move. It will be changed in onSnapEnd.
1955 // Suggestion not asked for.
1956 recommended_move = null;
1959 // see if the move is legal
1960 var pseudogame = new Chess(display_fen);
1961 var move = pseudogame.move({
1964 promotion: 'q' // NOTE: always promote to a queen for example simplicity
1968 if (move === null) return 'snapback';
1971 var onSnapEnd = function(source, target) {
1972 if (source === target && recommended_move !== null) {
1973 source = recommended_move.from;
1974 target = recommended_move.to;
1976 recommended_move = null;
1977 var pseudogame = new Chess(display_fen);
1978 var move = pseudogame.move({
1981 promotion: 'q' // NOTE: always promote to a queen for example simplicity
1984 if (current_display_line &&
1985 current_display_move < current_display_line.pv.length - 1 &&
1986 current_display_line.pv[current_display_move + 1] === move.san) {
1991 // Walk down the displayed lines until we find one that starts with
1992 // this move, then select that. Note that this gives us a good priority
1993 // order (history first, then PV, then multi-PV lines).
1994 for (var i = 0; i < display_lines.length; ++i) {
1995 if (i == 1 && current_display_line) {
1996 // Do not choose PV if not on it.
1999 var line = display_lines[i];
2000 if (line.pv[line.start_display_move_num] === move.san) {
2006 // Shouldn't really be here if we have hash probes, but there's really
2007 // nothing we can do.
2009 // End of dragging-related code.
2011 var fmt_cp = function(v) {
2015 return "+" + (v / 100).toFixed(2);
2018 return "-" + (v / 100).toFixed(2);
2022 var format_short_score = function(score) {
2026 if (score[0] === 'm') {
2027 if (score[2]) { // Is a bound.
2028 return score[2] + "\u00a0M " + score[1];
2030 return "M " + score[1];
2032 } else if (score[0] === 'd') {
2034 } else if (score[0] === 'cp') {
2035 if (score[2]) { // Is a bound.
2036 return score[2] + "\u00a0" + fmt_cp(score[1]);
2038 return fmt_cp(score[1]);
2044 var format_long_score = function(score) {
2048 if (score[0] === 'm') {
2050 return "White mates in " + score[1];
2052 return "Black mates in " + (-score[1]);
2054 } else if (score[0] === 'd') {
2055 return "Theoretical draw";
2056 } else if (score[0] === 'cp') {
2057 return "Score: " + format_short_score(score);
2062 var compute_plot_score = function(score) {
2063 if (score[0] === 'm') {
2069 } else if (score[0] === 'd') {
2071 } else if (score[0] === 'cp') {
2072 if (score[1] > 500) {
2074 } else if (score[1] < -500) {
2084 * @param score The score digest tuple.
2085 * @param {?number} depth Depth the move has been computed to, or null.
2086 * @param {boolean} invert Whether black is to play.
2087 * @param {boolean=} depth_secondary_key
2090 var compute_score_sort_key = function(score, depth, invert, depth_secondary_key) {
2095 if (score[0] === 'm') {
2098 s = 99999 - score[1];
2100 // Black mates (note the double negative for score[1]).
2101 s = -99999 - score[1];
2103 } else if (score[0] === 'd') {
2105 } else if (score[0] === 'cp') {
2110 if (depth_secondary_key) {
2111 return s * 200 + (depth || 0);
2121 * @param {Object} game
2123 var switch_backend = function(game) {
2124 // Stop looking at historic data.
2125 current_display_line = null;
2126 current_display_move = null;
2127 displayed_analysis_data = null;
2128 if (current_historic_xhr) {
2129 current_historic_xhr.abort();
2132 // If we already have a backend response going, abort it.
2133 if (current_analysis_xhr) {
2134 current_analysis_xhr.abort();
2136 if (current_hash_xhr) {
2137 current_hash_xhr.abort();
2140 // Otherwise, we should have a timer going to start a new one.
2142 if (current_analysis_request_timer) {
2143 clearTimeout(current_analysis_request_timer);
2144 current_analysis_request_timer = null;
2146 if (current_hash_display_timer) {
2147 clearTimeout(current_hash_display_timer);
2148 current_hash_display_timer = null;
2151 // Request an immediate fetch with the new backend.
2152 backend_url = game['url'];
2153 backend_hash_url = game['hashurl'];
2154 window.location.hash = '#' + game['id'];
2155 current_analysis_data = null;
2159 window['switch_backend'] = switch_backend;
2161 var init = function() {
2162 unique = get_unique();
2164 // Load settings from HTML5 local storage if available.
2165 if (supports_html5_storage() && localStorage['enable_sound']) {
2166 set_sound(parseInt(localStorage['enable_sound']));
2170 if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
2171 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
2173 sort_refutation_lines_by_score = true;
2177 board = new window.ChessBoard('board', {
2178 onMoveEnd: function() { board_is_animating = false; },
2181 onDragStart: onDragStart,
2183 onSnapEnd: onSnapEnd
2185 $("#board").on('mousedown', '.square-55d63', mousedownSquare);
2186 $("#board").on('mouseup', '.square-55d63', mouseupSquare);
2189 $(window).resize(function() {
2191 update_sparkline(displayed_analysis_data || current_analysis_data);
2192 update_board_highlight();
2195 $(window).keyup(function(event) {
2196 if (event.which == 39) { // Left arrow.
2198 } else if (event.which == 37) { // Right arrow.
2200 } else if (event.which >= 49 && event.which <= 57) { // 1-9.
2201 var num = event.which - 49;
2202 if (current_games && current_games.length >= num) {
2203 switch_backend(current_games[num]);
2205 } else if (event.which == 78) { // N.
2209 window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
2211 $(document).ready(init);