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 = 2016032201;
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.
56 var current_games = null;
71 /** @type {Array.<Array.<boolean>>} */
72 var occupied_by_arrows = [];
74 /** Currently displayed refutation lines (on-screen).
75 * Can either come from the current_analysis_data, displayed_analysis_data,
76 * or hash_refutation_lines.
78 var refutation_lines = [];
80 /** Refutation lines from current hash probe.
82 * If non-null, will override refutation lines from the base position.
83 * Note that these are relative to display_fen, not base_fen.
85 var hash_refutation_lines = null;
87 /** @type {!number} @private */
90 /** @type {!string} @private */
93 /** @type {number} @private */
96 /** @type {boolean} @private */
97 var sort_refutation_lines_by_score = true;
99 /** @type {boolean} @private */
100 var truncate_display_history = true;
102 /** @type {!string|undefined} @private */
103 var highlight_from = undefined;
105 /** @type {!string|undefined} @private */
106 var highlight_to = undefined;
108 /** The HTML object of the move currently being highlighted (in red).
111 var highlighted_move = null;
113 /** Currently suggested/recommended move when dragging.
114 * @type {?{from: !string, to: !string}}
117 var recommended_move = null;
119 /** If reverse-dragging (dragging from the destination square to the
120 * source square), the destination square.
124 var reverse_dragging_from = null;
126 /** @type {?number} @private */
129 /** @type {boolean} @private */
130 var enable_sound = false;
133 * Our best estimate of how many milliseconds we need to add to
134 * new Date() to get the true UTC time. Calibrated against the
140 var client_clock_offset_ms = null;
142 var clock_timer = null;
144 /** The current position being analyzed, represented as a FEN string.
145 * Note that this is not necessarily the same as display_fen.
151 /** The current position on the board, represented as a FEN string.
152 * Note that board.fen() does not contain e.g. who is to play.
156 var display_fen = null;
160 * pretty_pv: Array.<string>,
163 * scores: Array<{first_move: number, score: Object}>,
164 * start_display_move_num: number
167 * "start_display_move_num" is the (half-)move number to start displaying the PV at.
168 * "score" is also evaluated at this point.
171 /** All PVs that we currently know of.
173 * Element 0 is history (or null if no history).
174 * Element 1 is current main PV, or explored line if nowhere else on the screen.
175 * All remaining elements are refutation lines (multi-PV).
177 * @type {Array.<DisplayLine>}
180 var display_lines = [];
182 /** @type {?DisplayLine} @private */
183 var current_display_line = null;
185 /** @type {boolean} @private */
186 var current_display_line_is_history = false;
188 /** @type {?number} @private */
189 var current_display_move = null;
192 * The current backend request to get main analysis (not history), if any,
193 * so that we can abort it.
198 var current_analysis_xhr = null;
201 * The current timer to fire off a request to get main analysis (not history),
202 * if any, so that we can abort it.
207 var current_analysis_request_timer = null;
210 * The current backend request to get historic data, if any.
215 var current_historic_xhr = null;
218 * The current backend request to get hash probes, if any, so that we can abort it.
223 var current_hash_xhr = null;
226 * The current timer to display hash probe information (it could be waiting on the
227 * board to stop animating), if any, so that we can abort it.
232 var current_hash_display_timer = null;
234 var supports_html5_storage = function() {
236 return 'localStorage' in window && window['localStorage'] !== null;
242 // Make the unique token persistent so people refreshing the page won't count twice.
243 // Of course, you can never fully protect against people deliberately wanting to spam.
244 var get_unique = function() {
245 var use_local_storage = supports_html5_storage();
246 if (use_local_storage && localStorage['unique']) {
247 return localStorage['unique'];
249 var unique = Math.random();
250 if (use_local_storage) {
251 localStorage['unique'] = unique;
256 var request_update = function() {
257 current_analysis_request_timer = null;
259 current_analysis_xhr = $.ajax({
260 url: backend_url + "?ims=" + ims + "&unique=" + unique
261 }).done(function(data, textstatus, xhr) {
262 sync_server_clock(xhr.getResponseHeader('Date'));
263 ims = xhr.getResponseHeader('X-RGLM');
264 var num_viewers = xhr.getResponseHeader('X-RGNV');
266 if (Array.isArray(data)) {
267 new_data = JSON.parse(JSON.stringify(current_analysis_data));
268 JSON_delta.patch(new_data, data);
273 var minimum_version = xhr.getResponseHeader('X-RGMV');
274 if (minimum_version && minimum_version > SCRIPT_VERSION) {
275 // Upgrade to latest version with a force-reload.
276 location.reload(true);
279 possibly_play_sound(current_analysis_data, new_data);
280 current_analysis_data = new_data;
282 update_num_viewers(num_viewers);
285 current_analysis_request_timer = setTimeout(function() { request_update(); }, 100);
286 }).fail(function(jqXHR, textStatus, errorThrown) {
287 if (textStatus === "abort") {
288 // Aborted because we are switching backends. Abandon and don't retry,
289 // because another one is already started for us.
291 // Backend error or similar. Wait ten seconds, then try again.
292 current_analysis_request_timer = setTimeout(function() { request_update(); }, 10000);
297 var possibly_play_sound = function(old_data, new_data) {
301 if (old_data === null) {
304 var ding = document.getElementById('ding');
305 if (ding && ding.play) {
306 if (old_data['position'] && old_data['position']['fen'] &&
307 new_data['position'] && new_data['position']['fen'] &&
308 (old_data['position']['fen'] !== new_data['position']['fen'] ||
309 old_data['position']['move_num'] !== new_data['position']['move_num'])) {
316 * @type {!string} server_date_string
318 var sync_server_clock = function(server_date_string) {
319 var server_time_ms = new Date(server_date_string).getTime();
320 var client_time_ms = new Date().getTime();
321 var estimated_offset_ms = server_time_ms - client_time_ms;
323 // In order not to let the noise move us too much back and forth
324 // (the server only has one-second resolution anyway), we only
325 // change an existing skew if we are at least five seconds off.
326 if (client_clock_offset_ms === null ||
327 Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
328 client_clock_offset_ms = estimated_offset_ms;
332 var clear_arrows = function() {
333 for (var i = 0; i < arrows.length; ++i) {
335 if (arrows[i].svg.parentElement) {
336 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
338 delete arrows[i].svg;
343 occupied_by_arrows = [];
344 for (var y = 0; y < 8; ++y) {
345 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
349 var redraw_arrows = function() {
350 for (var i = 0; i < arrows.length; ++i) {
351 position_arrow(arrows[i]);
355 /** @param {!number} x
358 var sign = function(x) {
368 /** See if drawing this arrow on the board would cause unduly amount of confusion.
369 * @param {!string} from The square the arrow is from (e.g. e4).
370 * @param {!string} to The square the arrow is to (e.g. e4).
373 var interfering_arrow = function(from, to) {
374 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
375 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
376 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
377 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
379 occupied_by_arrows[from_row][from_col] = true;
381 // Knight move: Just check that we haven't been at the destination before.
382 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
383 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
384 return occupied_by_arrows[to_row][to_col];
387 // Sliding piece: Check if anything except the from-square is seen before.
388 var dx = sign(to_col - from_col);
389 var dy = sign(to_row - from_row);
395 if (occupied_by_arrows[y][x]) {
398 occupied_by_arrows[y][x] = true;
399 } while (x != to_col || y != to_row);
404 /** Find a point along the coordinate system given by the given line,
405 * <t> units forward from the start of the line, <u> units to the right of it.
406 * @param {!number} x1
407 * @param {!number} x2
408 * @param {!number} y1
409 * @param {!number} y2
412 * @return {!string} The point in "x y" form, suitable for SVG paths.
414 var point_from_start = function(x1, y1, x2, y2, t, u) {
418 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
422 var x = x1 + dx * t + dy * u;
423 var y = y1 + dy * t - dx * u;
427 /** Find a point along the coordinate system given by the given line,
428 * <t> units forward from the end of the line, <u> units to the right of it.
429 * @param {!number} x1
430 * @param {!number} x2
431 * @param {!number} y1
432 * @param {!number} y2
435 * @return {!string} The point in "x y" form, suitable for SVG paths.
437 var point_from_end = function(x1, y1, x2, y2, t, u) {
441 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
445 var x = x2 + dx * t + dy * u;
446 var y = y2 + dy * t - dx * u;
450 var position_arrow = function(arrow) {
452 if (arrow.svg.parentElement) {
453 arrow.svg.parentElement.removeChild(arrow.svg);
457 if (current_display_line !== null && !current_display_line_is_history) {
461 var pos = $(".square-a8").position();
463 var zoom_factor = $("#board").width() / 400.0;
464 var line_width = arrow.line_width * zoom_factor;
465 var arrow_size = arrow.arrow_size * zoom_factor;
467 var square_width = $(".square-a8").width();
468 var from_y = (7 - arrow.from_row + 0.5)*square_width;
469 var to_y = (7 - arrow.to_row + 0.5)*square_width;
470 var from_x = (arrow.from_col + 0.5)*square_width;
471 var to_x = (arrow.to_col + 0.5)*square_width;
473 var SVG_NS = "http://www.w3.org/2000/svg";
474 var XHTML_NS = "http://www.w3.org/1999/xhtml";
475 var svg = document.createElementNS(SVG_NS, "svg");
476 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
477 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
478 svg.setAttribute("style", "position: absolute");
479 svg.setAttribute("position", "absolute");
480 svg.setAttribute("version", "1.1");
481 svg.setAttribute("class", "c1");
482 svg.setAttribute("xmlns", XHTML_NS);
490 var outline = document.createElementNS(SVG_NS, "path");
491 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));
492 outline.setAttribute("xmlns", XHTML_NS);
493 outline.setAttribute("stroke", "#666");
494 outline.setAttribute("stroke-width", line_width + 2);
495 outline.setAttribute("fill", "none");
496 svg.appendChild(outline);
498 var path = document.createElementNS(SVG_NS, "path");
499 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));
500 path.setAttribute("xmlns", XHTML_NS);
501 path.setAttribute("stroke", arrow.fg_color);
502 path.setAttribute("stroke-width", line_width);
503 path.setAttribute("fill", "none");
504 svg.appendChild(path);
506 // Then the arrow head.
507 var head = document.createElementNS(SVG_NS, "path");
508 head.setAttribute("d",
509 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
510 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
511 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
512 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
513 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
514 head.setAttribute("xmlns", XHTML_NS);
515 head.setAttribute("stroke", "#000");
516 head.setAttribute("stroke-width", "1");
517 head.setAttribute("fill", arrow.fg_color);
518 svg.appendChild(head);
520 $(svg).css({ top: pos.top, left: pos.left, 'pointer-events': 'none' });
521 document.body.appendChild(svg);
526 * @param {!string} from_square
527 * @param {!string} to_square
528 * @param {!string} fg_color
529 * @param {number} line_width
530 * @param {number} arrow_size
532 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
533 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
534 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
535 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
536 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
544 line_width: line_width,
545 arrow_size: arrow_size,
549 position_arrow(arrow);
553 // Note: invert is ignored.
554 var compare_by_sort_key = function(refutation_lines, invert, a, b) {
555 var ska = refutation_lines[a]['sort_key'];
556 var skb = refutation_lines[b]['sort_key'];
557 if (ska < skb) return -1;
558 if (ska > skb) return 1;
562 var compare_by_score = function(refutation_lines, invert, a, b) {
563 var sa = compute_score_sort_key(refutation_lines[b]['score'], refutation_lines[b]['depth'], invert);
564 var sb = compute_score_sort_key(refutation_lines[a]['score'], refutation_lines[a]['depth'], invert);
569 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
570 * sorted by quality, descending.
572 * @param {!Object} data
573 * @param {number} margin The maximum number of centipawns worse than the
574 * best move can be and still be included.
575 * @param {boolean} margin Whether black is to play.
576 * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
577 * moves, in score order.
579 var find_nonstupid_moves = function(data, margin, invert) {
580 // First of all, if there are any moves that are more than 0.5 ahead of
581 // the primary move, the refutation lines are probably bunk, so just
583 var best_score = undefined;
584 var pv_score = undefined;
585 for (var move in data['refutation_lines']) {
586 var line = data['refutation_lines'][move];
587 var score = compute_score_sort_key(line['score'], line['depth'], invert);
588 if (move == data['pv_uci'][0]) {
591 if (best_score === undefined || score > best_score) {
594 if (line['depth'] < 8) {
599 if (best_score - pv_score > 50) {
603 // Now find all moves that are within “margin” of the best score.
604 // The PV move will always be first.
606 for (var move in data['refutation_lines']) {
607 var line = data['refutation_lines'][move];
608 var score = compute_score_sort_key(line['score'], line['depth'], invert);
609 if (move != data['pv_uci'][0] && best_score - score <= margin) {
613 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], data['position']['toplay'] === 'B', a, b) });
614 moves.unshift(data['pv_uci'][0]);
623 var thousands = function(x) {
624 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
628 * @param {!string} start_fen
629 * @param {Array.<string>} pretty_pv
630 * @param {number} move_num
631 * @param {!string} toplay
632 * @param {Array<{ first_move: integer, score: Object }>} scores
633 * @param {number} start_display_move_num
634 * @param {number=} opt_limit
635 * @param {boolean=} opt_showlast
637 var add_pv = function(start_fen, pretty_pv, move_num, toplay, scores, start_display_move_num, opt_limit, opt_showlast) {
639 start_fen: start_fen,
640 pretty_pv: pretty_pv,
641 move_num: parseInt(move_num),
644 start_display_move_num: start_display_move_num
646 return print_pv(display_lines.length - 1, opt_limit, opt_showlast);
650 * @param {number} line_num
651 * @param {number=} opt_limit If set, show at most this number of moves.
652 * @param {boolean=} opt_showlast If limit is set, show the last moves instead of the first ones.
654 var print_pv = function(line_num, opt_limit, opt_showlast) {
655 var display_line = display_lines[line_num];
656 var pretty_pv = display_line.pretty_pv;
657 var move_num = display_line.move_num;
658 var toplay = display_line.toplay;
660 // Truncate PV at the start if needed.
661 var start_display_move_num = display_line.start_display_move_num;
662 if (start_display_move_num > 0) {
663 pretty_pv = pretty_pv.slice(start_display_move_num);
664 var to_add = start_display_move_num;
665 if (toplay === 'B') {
670 if (to_add % 2 == 1) {
674 move_num += to_add / 2;
679 if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
680 // Truncate the PV at the beginning (instead of at the end).
681 // We assume here that toplay is 'W'. We also assume that if
682 // opt_showlast is set, then it is the history, and thus,
683 // the UI should be to expand the history.
684 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
685 i = pretty_pv.length - opt_limit;
690 } else if (toplay == 'B' && pretty_pv.length > 0) {
691 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
692 pv = move_num + '. … ' + move;
697 for ( ; i < pretty_pv.length; ++i) {
698 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
701 if (i > opt_limit && !opt_showlast) {
707 pv += move_num + '. ' + move;
718 /** Update the highlighted to/from squares on the board.
719 * Based on the global "highlight_from" and "highlight_to" variables.
721 var update_board_highlight = function() {
722 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
723 if ((current_display_line === null || current_display_line_is_history) &&
724 highlight_from !== undefined && highlight_to !== undefined) {
725 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
726 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
730 var update_history = function() {
731 if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
732 $("#history").html("No history");
733 } else if (truncate_display_history) {
734 $("#history").html(print_pv(0, 8, true));
737 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
743 * @param {!boolean} truncate_history
745 var collapse_history = function(truncate_history) {
746 truncate_display_history = truncate_history;
749 window['collapse_history'] = collapse_history;
751 /** Update the HTML display of multi-PV from the global "refutation_lines".
753 * Also recreates the global "display_lines".
755 var update_refutation_lines = function() {
756 if (base_fen === null) {
759 if (display_lines.length > 2) {
760 // Truncate so that only the history and PV is left.
761 display_lines = [ display_lines[0], display_lines[1] ];
763 var tbl = $("#refutationlines");
766 // Find out where the lines start from.
768 var base_scores = [];
769 var start_display_move_num = 0;
770 if (hash_refutation_lines) {
771 base_line = current_display_line.pretty_pv.slice(0, current_display_move + 1);
772 base_scores = current_display_line.scores;
773 start_display_move_num = base_line.length;
777 for (var move in refutation_lines) {
781 var invert = (toplay === 'B');
782 if (current_display_line && current_display_move % 2 == 0) {
785 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
786 moves = moves.sort(function(a, b) { return compare(refutation_lines, invert, a, b) });
787 for (var i = 0; i < moves.length; ++i) {
788 var line = refutation_lines[moves[i]];
790 var tr = document.createElement("tr");
792 var move_td = document.createElement("td");
793 tr.appendChild(move_td);
794 $(move_td).addClass("move");
796 var scores = base_scores.concat([{ first_move: start_display_move_num, score: line['score'] }]);
798 if (line['pv_pretty'].length == 0) {
799 // Not found, so just make a one-move PV.
800 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
801 $(move_td).html(move);
802 var score_td = document.createElement("td");
804 $(score_td).addClass("score");
805 $(score_td).text("—");
806 tr.appendChild(score_td);
808 var depth_td = document.createElement("td");
809 tr.appendChild(depth_td);
810 $(depth_td).addClass("depth");
811 $(depth_td).text("—");
813 var pv_td = document.createElement("td");
814 tr.appendChild(pv_td);
815 $(pv_td).addClass("pv");
816 $(pv_td).html(add_pv(base_fen, base_line.concat([ line['pretty_move'] ]), move_num, toplay, scores, start_display_move_num));
822 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
823 $(move_td).html(move);
825 var score_td = document.createElement("td");
826 tr.appendChild(score_td);
827 $(score_td).addClass("score");
828 $(score_td).text(format_short_score(line['score']));
830 var depth_td = document.createElement("td");
831 tr.appendChild(depth_td);
832 $(depth_td).addClass("depth");
833 if (line['depth'] && line['depth'] >= 0) {
834 $(depth_td).text("d" + line['depth']);
836 $(depth_td).text("—");
839 var pv_td = document.createElement("td");
840 tr.appendChild(pv_td);
841 $(pv_td).addClass("pv");
842 $(pv_td).html(add_pv(base_fen, base_line.concat(line['pv_pretty']), move_num, toplay, scores, start_display_move_num, 10));
847 // Make one of the links clickable and the other nonclickable.
848 if (sort_refutation_lines_by_score) {
849 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
850 $("#sortbyscore1").html("<strong>Score</strong>");
852 $("#sortbyscore0").html("<strong>Move</strong>");
853 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
856 // Update the move highlight, as we've rewritten all the HTML.
857 update_move_highlight();
861 * Create a Chess.js board object, containing the given position plus the given moves,
862 * up to the given limit.
864 * @param {?string} fen
865 * @param {Array.<string>} moves
866 * @param {number} last_move
868 var chess_from = function(fen, moves, last_move) {
869 var hiddenboard = new Chess();
871 hiddenboard.load(fen);
873 for (var i = 0; i <= last_move; ++i) {
874 if (moves[i] === '0-0') {
875 hiddenboard.move('O-O');
876 } else if (moves[i] === '0-0-0') {
877 hiddenboard.move('O-O-O');
879 hiddenboard.move(moves[i]);
885 var update_game_list = function(games) {
886 $("#games").text("");
887 if (games === null) {
891 var games_div = document.getElementById('games');
892 for (var game_num = 0; game_num < games.length; ++game_num) {
893 var game = games[game_num];
894 var game_span = document.createElement("span");
895 game_span.setAttribute("class", "game");
897 var game_name = document.createTextNode(game['name']);
898 if (game['url'] === backend_url) {
900 game_span.appendChild(game_name);
903 if (current_analysis_data['position']['result']) {
904 score = " (" + current_analysis_data['position']['result'] + ")";
906 score = " (" + format_short_score(current_analysis_data['score']) + ")";
908 game_span.appendChild(document.createTextNode(score));
911 var game_a = document.createElement("a");
912 game_a.setAttribute("href", "#" + game['id']);
913 game_a.appendChild(game_name);
914 game_span.appendChild(game_a);
917 if (game['result']) {
918 score = " (" + game['result'] + ")";
920 score = " (" + format_short_score(game['score']) + ")";
922 game_span.appendChild(document.createTextNode(score));
925 games_div.appendChild(game_span);
930 * Try to find a running game that matches with the current hash,
931 * and switch to it if we're not already displaying it.
933 var possibly_switch_game_from_hash = function() {
934 if (current_games === null) {
938 var hash = window.location.hash.replace(/^#/,'');
939 for (var i = 0; i < current_games.length; ++i) {
940 if (current_games[i]['id'] === hash) {
941 if (backend_url !== current_games[i]['url']) {
942 switch_backend(current_games[i]['url'], current_games[i]['hashurl']);
949 /** Update all the HTML on the page, based on current global state.
951 var update_board = function() {
952 var data = displayed_analysis_data || current_analysis_data;
953 var current_data = current_analysis_data; // Convenience alias.
957 // Print the history. This is pretty much the only thing that's
958 // unconditionally taken from current_data (we're not interested in
959 // historic history).
960 if (current_data['position']['pretty_history']) {
961 add_pv('start', current_data['position']['pretty_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 last_move = format_halfmove_with_number(
1036 current_display_line.pretty_pv[current_display_move],
1037 current_display_move + 1);
1038 headline += ' after ' + last_move;
1039 } else if (data['position']['last_move'] !== 'none') {
1040 last_move = format_move_with_number(
1041 data['position']['last_move'],
1042 data['position']['move_num'],
1043 data['position']['toplay'] == 'W');
1044 headline += ' after ' + last_move;
1048 $("#headline").text(headline);
1050 // The <title> contains a very brief headline.
1051 var title_elems = [];
1052 if (data['position'] && data['position']['result']) {
1053 title_elems.push(data['position']['result']);
1054 } else if (data['score']) {
1055 title_elems.push(format_short_score(data['score']));
1057 if (last_move !== null) {
1058 title_elems.push(last_move);
1061 if (title_elems.length != 0) {
1062 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
1064 document.title = 'analysis.sesse.net';
1067 // The last move (shown by highlighting the from and to squares).
1068 if (data['position'] && data['position']['last_move_uci']) {
1069 highlight_from = data['position']['last_move_uci'].substr(0, 2);
1070 highlight_to = data['position']['last_move_uci'].substr(2, 2);
1071 } else if (current_display_line_is_history && current_display_move >= 0) {
1072 // We don't have historic analysis for this position, but we
1073 // can reconstruct what the last move was by just replaying
1075 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1076 var moves = hiddenboard.history({ verbose: true });
1077 var last_move = moves.pop();
1078 highlight_from = last_move.from;
1079 highlight_to = last_move.to;
1081 highlight_from = highlight_to = undefined;
1083 update_board_highlight();
1085 if (data['failed']) {
1086 $("#score").text("No analysis for this move");
1087 $("#pvtitle").text("PV:");
1089 $("#searchstats").html(" ");
1090 $("#refutationlines").empty();
1091 $("#whiteclock").empty();
1092 $("#blackclock").empty();
1093 refutation_lines = [];
1094 update_refutation_lines();
1096 update_displayed_line();
1097 update_move_highlight();
1104 if (current_display_line && !current_display_line_is_history) {
1105 if (current_display_line.scores && current_display_line.scores.length > 0) {
1107 for (var i = 0; i < current_display_line.scores.length; ++i) {
1108 if (current_display_move < current_display_line.scores[i].first_move) {
1111 score = current_display_line.scores[i].score;
1113 $("#score").text(format_long_score(score));
1115 $("#score").text("No score for this move");
1117 } else if (data['score']) {
1118 $("#score").text(format_long_score(data['score']));
1121 // The search stats.
1122 if (data['searchstats']) {
1123 $("#searchstats").html(data['searchstats']);
1124 } else if (data['tablebase'] == 1) {
1125 $("#searchstats").text("Tablebase result");
1126 } else if (data['nodes'] && data['nps'] && data['depth']) {
1127 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
1128 if (data['seldepth']) {
1129 stats += ' (' + data['seldepth'] + ' selective)';
1131 if (data['tbhits'] && data['tbhits'] > 0) {
1132 if (data['tbhits'] == 1) {
1133 stats += ', one Syzygy hit';
1135 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
1139 $("#searchstats").text(stats);
1141 $("#searchstats").text("");
1144 // Update the board itself.
1145 base_fen = data['position']['fen'];
1146 update_displayed_line();
1149 $("#pvtitle").text("PV:");
1151 var scores = [{ first_move: 0, score: data['score'] }];
1152 $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay'], scores, 0));
1154 // Update the PV arrow.
1156 if (data['pv_uci'].length >= 1) {
1157 // draw a continuation arrow as long as it's the same piece
1158 for (var i = 0; i < data['pv_uci'].length; i += 2) {
1159 var from = data['pv_uci'][i].substr(0, 2);
1160 var to = data['pv_uci'][i].substr(2,4);
1161 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
1162 interfering_arrow(from, to)) {
1165 create_arrow(from, to, '#f66', 6, 20);
1168 var alt_moves = find_nonstupid_moves(data, 30, data['position']['toplay'] === 'B');
1169 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
1170 create_arrow(alt_moves[i].substr(0, 2),
1171 alt_moves[i].substr(2, 2), '#f66', 1, 10);
1175 // See if all semi-reasonable moves have only one possible response.
1176 if (data['pv_uci'].length >= 2) {
1177 var nonstupid_moves = find_nonstupid_moves(data, 300, data['position']['toplay'] === 'B');
1178 var response = data['pv_uci'][1];
1179 for (var i = 0; i < nonstupid_moves.length; ++i) {
1180 if (nonstupid_moves[i] == data['pv_uci'][0]) {
1181 // ignore the PV move for refutation lines.
1184 if (!data['refutation_lines'] ||
1185 !data['refutation_lines'][nonstupid_moves[i]] ||
1186 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
1187 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
1188 // Incomplete PV, abort.
1189 response = undefined;
1192 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
1193 if (response !== this_response) {
1194 // Different response depending on lines, abort.
1195 response = undefined;
1200 if (nonstupid_moves.length > 0 && response !== undefined) {
1201 create_arrow(response.substr(0, 2),
1202 response.substr(2, 2), '#66f', 6, 20);
1206 // Update the refutation lines.
1207 base_fen = data['position']['fen'];
1208 move_num = parseInt(data['position']['move_num']);
1209 toplay = data['position']['toplay'];
1210 refutation_lines = hash_refutation_lines || data['refutation_lines'];
1211 update_refutation_lines();
1213 // Update the sparkline last, since its size depends on how everything else reflowed.
1214 update_sparkline(data);
1217 var update_sparkline = function(data) {
1218 if (data && data['score_history']) {
1219 var first_move_num = undefined;
1220 for (var halfmove_num in data['score_history']) {
1221 halfmove_num = parseInt(halfmove_num);
1222 if (first_move_num === undefined || halfmove_num < first_move_num) {
1223 first_move_num = halfmove_num;
1226 if (first_move_num !== undefined) {
1227 var last_move_num = data['position']['move_num'] * 2 - 3;
1228 if (data['position']['toplay'] === 'B') {
1232 // Possibly truncate some moves if we don't have enough width.
1233 // FIXME: Sometimes width() for #scorecontainer (and by extent,
1234 // #scoresparkcontainer) on Chrome for mobile seems to start off
1235 // at something very small, and then suddenly snap back into place.
1237 var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
1238 if (last_move_num - first_move_num > max_moves) {
1239 first_move_num = last_move_num - max_moves;
1242 var min_score = -100;
1243 var max_score = 100;
1244 var last_score = null;
1246 for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1247 if (data['score_history'][halfmove_num]) {
1248 var score = compute_plot_score(data['score_history'][halfmove_num]);
1250 if (score < min_score) min_score = score;
1251 if (score > max_score) max_score = score;
1253 scores.push(last_score);
1255 if (data['score']) {
1256 scores.push(compute_plot_score(data['score']));
1258 // FIXME: at some widths, calling sparkline() seems to push
1259 // #scorecontainer under the board.
1260 $("#scorespark").sparkline(scores, {
1263 chartRangeMin: min_score,
1264 chartRangeMax: max_score,
1265 tooltipFormatter: function(sparkline, options, fields) {
1266 return format_tooltip(data, fields[0].offset + first_move_num);
1270 $("#scorespark").text("");
1273 $("#scorespark").text("");
1278 * @param {number} num_viewers
1280 var update_num_viewers = function(num_viewers) {
1281 if (num_viewers === null) {
1282 $("#numviewers").text("");
1283 } else if (num_viewers == 1) {
1284 $("#numviewers").text("You are the only current viewer");
1286 $("#numviewers").text(num_viewers + " current viewers");
1290 var update_clock = function() {
1291 clearTimeout(clock_timer);
1293 var data = displayed_analysis_data || current_analysis_data;
1294 if (data['position']) {
1295 var result = data['position']['result'];
1296 if (result === '1-0') {
1297 $("#whiteclock").text("1");
1298 $("#blackclock").text("0");
1299 $("#whiteclock").removeClass("running-clock");
1300 $("#blackclock").removeClass("running-clock");
1303 if (result === '1/2-1/2') {
1304 $("#whiteclock").text("1/2");
1305 $("#blackclock").text("1/2");
1306 $("#whiteclock").removeClass("running-clock");
1307 $("#blackclock").removeClass("running-clock");
1310 if (result === '0-1') {
1311 $("#whiteclock").text("0");
1312 $("#blackclock").text("1");
1313 $("#whiteclock").removeClass("running-clock");
1314 $("#blackclock").removeClass("running-clock");
1319 var white_clock_ms = null;
1320 var black_clock_ms = null;
1321 var show_seconds = false;
1324 if (data['position'] &&
1325 data['position']['white_clock'] &&
1326 data['position']['black_clock']) {
1327 white_clock_ms = data['position']['white_clock'] * 1000;
1328 black_clock_ms = data['position']['black_clock'] * 1000;
1331 // Dynamic clock (only one, obviously).
1333 if (data['position']['white_clock_target']) {
1335 $("#whiteclock").addClass("running-clock");
1336 $("#blackclock").removeClass("running-clock");
1337 } else if (data['position']['black_clock_target']) {
1339 $("#whiteclock").removeClass("running-clock");
1340 $("#blackclock").addClass("running-clock");
1342 $("#whiteclock").removeClass("running-clock");
1343 $("#blackclock").removeClass("running-clock");
1347 var now = new Date().getTime() + client_clock_offset_ms;
1348 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1349 if (color === "white") {
1350 white_clock_ms = remaining_ms;
1352 black_clock_ms = remaining_ms;
1356 if (white_clock_ms === null || black_clock_ms === null) {
1357 $("#whiteclock").empty();
1358 $("#blackclock").empty();
1362 // If either player has ten minutes or less left, add the second counters.
1363 var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
1366 // See when the clock will change next, and update right after that.
1369 next_update_ms = remaining_ms % 1000 + 100;
1371 next_update_ms = remaining_ms % 60000 + 100;
1373 clock_timer = setTimeout(update_clock, next_update_ms);
1376 $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1377 $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1381 * @param {Number} remaining_ms
1382 * @param {boolean} show_seconds
1384 var format_clock = function(remaining_ms, show_seconds) {
1385 if (remaining_ms <= 0) {
1393 var remaining = Math.floor(remaining_ms / 1000);
1394 var seconds = remaining % 60;
1395 remaining = (remaining - seconds) / 60;
1396 var minutes = remaining % 60;
1397 remaining = (remaining - minutes) / 60;
1398 var hours = remaining;
1400 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1402 return format_2d(hours) + ":" + format_2d(minutes);
1409 var format_2d = function(x) {
1418 * @param {string} move
1419 * @param {Number} move_num
1420 * @param {boolean} white_to_play
1422 var format_move_with_number = function(move, move_num, white_to_play) {
1424 if (white_to_play) {
1425 ret = (move_num - 1) + '… ';
1427 ret = move_num + '. ';
1434 * @param {string} move
1435 * @param {Number} halfmove_num
1437 var format_halfmove_with_number = function(move, halfmove_num) {
1438 return format_move_with_number(
1440 Math.floor(halfmove_num / 2) + 1,
1441 halfmove_num % 2 == 0);
1445 * @param {Object} data
1446 * @param {Number} halfmove_num
1448 var format_tooltip = function(data, halfmove_num) {
1449 if (data['score_history'][halfmove_num] ||
1450 halfmove_num === data['position']['pretty_history'].length) {
1453 if (halfmove_num === data['position']['pretty_history'].length) {
1454 move = data['position']['last_move'];
1455 short_score = format_short_score(data['score']);
1457 move = data['position']['pretty_history'][halfmove_num];
1458 short_score = format_short_score(data['score_history'][halfmove_num]);
1460 var move_with_number = format_halfmove_with_number(move, halfmove_num);
1462 return "After " + move_with_number + ": " + short_score;
1464 for (var i = halfmove_num; i --> 0; ) {
1465 if (data['score_history'][i]) {
1466 var move = data['position']['pretty_history'][i];
1467 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1474 * @param {boolean} sort_by_score
1476 var resort_refutation_lines = function(sort_by_score) {
1477 sort_refutation_lines_by_score = sort_by_score;
1478 if (supports_html5_storage()) {
1479 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1481 update_refutation_lines();
1483 window['resort_refutation_lines'] = resort_refutation_lines;
1486 * @param {boolean} truncate_history
1488 var set_truncate_history = function(truncate_history) {
1489 truncate_display_history = truncate_history;
1490 update_refutation_lines();
1492 window['set_truncate_history'] = set_truncate_history;
1495 * @param {number} line_num
1496 * @param {number} move_num
1498 var show_line = function(line_num, move_num) {
1499 if (line_num == -1) {
1500 current_display_line = null;
1501 current_display_move = null;
1502 hash_refutation_lines = null;
1503 if (displayed_analysis_data) {
1504 // TODO: Support exiting to history position if we are in an
1505 // analysis line of a history position.
1506 displayed_analysis_data = null;
1511 current_display_line = jQuery.extend({}, display_lines[line_num]); // Shallow clone.
1512 current_display_move = move_num + current_display_line.start_display_move_num;
1514 current_display_line_is_history = (line_num == 0);
1516 update_historic_analysis();
1517 update_displayed_line();
1518 update_board_highlight();
1519 update_move_highlight();
1522 window['show_line'] = show_line;
1524 var prev_move = function() {
1525 if (current_display_line &&
1526 current_display_move >= current_display_line.start_display_move_num) {
1527 --current_display_move;
1529 update_historic_analysis();
1530 update_displayed_line();
1531 update_move_highlight();
1533 window['prev_move'] = prev_move;
1535 var next_move = function() {
1536 if (current_display_line &&
1537 current_display_move < current_display_line.pretty_pv.length - 1) {
1538 ++current_display_move;
1540 update_historic_analysis();
1541 update_displayed_line();
1542 update_move_highlight();
1544 window['next_move'] = next_move;
1546 var next_game = function() {
1547 if (current_games === null) {
1551 // Try to find the game we are currently looking at.
1552 for (var game_num = 0; game_num < current_games.length; ++game_num) {
1553 var game = current_games[game_num];
1554 if (game['url'] === backend_url) {
1555 var next_game_num = (game_num + 1) % current_games.length;
1556 switch_backend(current_games[next_game_num]['url'], current_games[next_game_num]['hashurl']);
1561 // Couldn't find it; give up.
1564 var update_historic_analysis = function() {
1565 if (!current_display_line_is_history) {
1568 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1569 displayed_analysis_data = null;
1573 // Fetch old analysis for this line if it exists.
1574 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1575 var filename = "/history/move" + (current_display_move + 1) + "-" +
1576 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1578 current_historic_xhr = $.ajax({
1580 }).done(function(data, textstatus, xhr) {
1581 displayed_analysis_data = data;
1583 }).fail(function(jqXHR, textStatus, errorThrown) {
1584 if (textStatus === "abort") {
1585 // Aborted because we are switching backends. Don't do anything;
1586 // we will already have been cleared.
1588 displayed_analysis_data = {'failed': true};
1595 * @param {string} fen
1597 var update_imbalance = function(fen) {
1598 var hiddenboard = new Chess(fen);
1599 var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1600 for (var row = 0; row < 8; ++row) {
1601 for (var col = 0; col < 8; ++col) {
1602 var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1603 var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1604 var square = col_text + row_text;
1605 var contents = hiddenboard.get(square);
1606 if (contents !== null) {
1607 if (contents.color === 'w') {
1608 ++imbalance[contents.type];
1610 --imbalance[contents.type];
1615 var white_imbalance = '';
1616 var black_imbalance = '';
1617 for (var piece in imbalance) {
1618 for (var i = 0; i < imbalance[piece]; ++i) {
1619 white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1621 for (var i = 0; i < -imbalance[piece]; ++i) {
1622 black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1625 $('#whiteimbalance').html(white_imbalance);
1626 $('#blackimbalance').html(black_imbalance);
1629 /** Mark the currently selected move in red.
1630 * Also replaces the PV with the current displayed line if it's not shown
1631 * anywhere else on the screen.
1633 var update_move_highlight = function() {
1634 if (highlighted_move !== null) {
1635 highlighted_move.removeClass('highlight');
1637 if (current_display_line) {
1638 var display_line_num = find_display_line_matching_num();
1639 if (display_line_num === null) {
1640 // Replace the PV with the (complete) line.
1641 $("#pvtitle").text("Exploring:");
1642 current_display_line.start_display_move_num = 0;
1643 display_lines.push(current_display_line);
1644 $("#pv").html(print_pv(display_lines.length - 1));
1645 display_line_num = display_lines.length - 1;
1648 highlighted_move = $("#automove" + display_line_num + "-" + (current_display_move - current_display_line.start_display_move_num));
1649 highlighted_move.addClass('highlight');
1654 * See if the current displayed line is identical to any of the ones
1655 * we have on screen. (It might not be if e.g. the analysis reloaded
1656 * since we started looking.)
1660 var find_display_line_matching_num = function() {
1661 for (var i = 0; i < display_lines.length; ++i) {
1662 var line = display_lines[i];
1663 if (line.start_display_move_num > 0) continue;
1664 if (current_display_line.start_fen !== line.start_fen) continue;
1665 if (current_display_line.pretty_pv.length !== line.pretty_pv.length) continue;
1667 for (var j = 0; j < line.pretty_pv.length; ++j) {
1668 if (current_display_line.pretty_pv[j] !== line.pretty_pv[j]) {
1680 var update_displayed_line = function() {
1681 if (current_display_line === null) {
1682 $("#linenav").hide();
1683 $("#linemsg").show();
1684 display_fen = base_fen;
1685 board.position(base_fen);
1686 update_imbalance(base_fen);
1690 $("#linenav").show();
1691 $("#linemsg").hide();
1693 if (current_display_move <= 0) {
1694 $("#prevmove").html("Previous");
1696 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1698 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1699 $("#nextmove").html("Next");
1701 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1704 var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pretty_pv, current_display_move);
1705 display_fen = hiddenboard.fen();
1706 board_is_animating = true;
1707 var old_fen = board.fen();
1708 board.position(hiddenboard.fen());
1709 if (board.fen() === old_fen) {
1710 board_is_animating = false;
1711 } else if (!current_display_line_is_history) {
1712 // Fire off a hash request, since we're now off the main position
1713 // and it just changed.
1714 explore_hash(display_fen);
1716 update_imbalance(hiddenboard.fen());
1720 * @param {boolean} param_enable_sound
1722 var set_sound = function(param_enable_sound) {
1723 enable_sound = param_enable_sound;
1725 $("#soundon").html("<strong>On</strong>");
1726 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1728 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1729 // and also preload the file since the user has selected audio.
1730 var ding = document.getElementById('ding');
1731 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1732 ding.src = 'ding.opus';
1736 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1737 $("#soundoff").html("<strong>Off</strong>");
1739 if (supports_html5_storage()) {
1740 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1743 window['set_sound'] = set_sound;
1745 /** Send off a hash probe request to the backend.
1746 * @param {string} fen
1748 var explore_hash = function(fen) {
1749 // If we already have a backend response going, abort it.
1750 if (current_hash_xhr) {
1751 current_hash_xhr.abort();
1753 if (current_hash_display_timer) {
1754 clearTimeout(current_hash_display_timer);
1755 current_hash_display_timer = null;
1757 $("#refutationlines").empty();
1758 current_hash_xhr = $.ajax({
1759 url: backend_hash_url + "?fen=" + fen
1760 }).done(function(data, textstatus, xhr) {
1761 show_explore_hash_results(data, fen);
1765 /** Process the JSON response from a hash probe request.
1766 * @param {!Object} data
1767 * @param {string} fen
1769 var show_explore_hash_results = function(data, fen) {
1770 if (board_is_animating) {
1771 // Updating while the animation is still going causes
1772 // the animation to jerk. This is pretty crude, but it will do.
1773 current_hash_display_timer = setTimeout(function() { show_explore_hash_results(data, fen); }, 100);
1776 current_hash_display_timer = null;
1777 hash_refutation_lines = data['lines'];
1781 // almost all of this stuff comes from the chessboard.js example page
1782 var onDragStart = function(source, piece, position, orientation) {
1783 var pseudogame = new Chess(display_fen);
1784 if (pseudogame.game_over() === true ||
1785 (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
1786 (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
1790 recommended_move = get_best_move(pseudogame, source, null, pseudogame.turn() === 'b');
1791 if (recommended_move) {
1792 var squareEl = $('#board .square-' + recommended_move.to);
1793 squareEl.addClass('highlight1-32417');
1798 var mousedownSquare = function(e) {
1799 reverse_dragging_from = null;
1800 var square = $(this).attr('data-square');
1802 var pseudogame = new Chess(display_fen);
1803 if (pseudogame.game_over() === true) {
1807 // If the square is empty, or has a piece of the side not to move,
1808 // we handle it. If not, normal piece dragging will take it.
1809 var position = board.position();
1810 if (!position.hasOwnProperty(square) ||
1811 (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
1812 (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
1813 reverse_dragging_from = square;
1814 recommended_move = get_best_move(pseudogame, null, square, pseudogame.turn() === 'b');
1815 if (recommended_move) {
1816 var squareEl = $('#board .square-' + recommended_move.from);
1817 squareEl.addClass('highlight1-32417');
1818 squareEl = $('#board .square-' + recommended_move.to);
1819 squareEl.addClass('highlight1-32417');
1824 var mouseupSquare = function(e) {
1825 if (reverse_dragging_from === null) {
1828 var source = $(this).attr('data-square');
1829 var target = reverse_dragging_from;
1830 reverse_dragging_from = null;
1831 if (onDrop(source, target) !== 'snapback') {
1832 onSnapEnd(source, target);
1834 $("#board").find('.square-55d63').removeClass('highlight1-32417');
1837 var get_best_move = function(game, source, target, invert) {
1838 var moves = game.moves({ verbose: true });
1839 if (source !== null) {
1840 moves = moves.filter(function(move) { return move.from == source; });
1842 if (target !== null) {
1843 moves = moves.filter(function(move) { return move.to == target; });
1845 if (moves.length == 0) {
1848 if (moves.length == 1) {
1852 // More than one move. Use the display lines (if we have them)
1853 // to disambiguate; otherwise, we have no information.
1855 for (var i = 0; i < moves.length; ++i) {
1856 move_hash[moves[i].san] = moves[i];
1859 // See if we're already exploring some line.
1860 if (current_display_line &&
1861 current_display_move < current_display_line.pretty_pv.length - 1) {
1862 var first_move = current_display_line.pretty_pv[current_display_move + 1];
1863 if (move_hash[first_move]) {
1864 return move_hash[first_move];
1868 // History and PV take priority over the display lines.
1869 for (var i = 0; i < 2; ++i) {
1870 var line = display_lines[i];
1871 var first_move = line.pretty_pv[line.start_display_move_num];
1872 if (move_hash[first_move]) {
1873 return move_hash[first_move];
1877 var best_move = null;
1878 var best_move_score = null;
1880 for (var move in refutation_lines) {
1881 var line = refutation_lines[move];
1882 if (!line['score']) {
1885 var first_move = line['pv_pretty'][0];
1886 if (move_hash[first_move]) {
1887 var score = compute_score_sort_key(line['score'], line['depth'], invert);
1888 if (best_move_score === null || score > best_move_score) {
1889 best_move = move_hash[first_move];
1890 best_move_score = score;
1897 var onDrop = function(source, target) {
1898 if (source === target) {
1899 if (recommended_move === null) {
1902 // Accept the move. It will be changed in onSnapEnd.
1906 // Suggestion not asked for.
1907 recommended_move = null;
1910 // see if the move is legal
1911 var pseudogame = new Chess(display_fen);
1912 var move = pseudogame.move({
1915 promotion: 'q' // NOTE: always promote to a queen for example simplicity
1919 if (move === null) return 'snapback';
1922 var onSnapEnd = function(source, target) {
1923 if (source === target && recommended_move !== null) {
1924 source = recommended_move.from;
1925 target = recommended_move.to;
1927 recommended_move = null;
1928 var pseudogame = new Chess(display_fen);
1929 var move = pseudogame.move({
1932 promotion: 'q' // NOTE: always promote to a queen for example simplicity
1935 if (current_display_line &&
1936 current_display_move < current_display_line.pretty_pv.length - 1 &&
1937 current_display_line.pretty_pv[current_display_move + 1] === move.san) {
1942 // Walk down the displayed lines until we find one that starts with
1943 // this move, then select that. Note that this gives us a good priority
1944 // order (history first, then PV, then multi-PV lines).
1945 for (var i = 0; i < display_lines.length; ++i) {
1946 var line = display_lines[i];
1947 if (line.pretty_pv[line.start_display_move_num] === move.san) {
1953 // Shouldn't really be here if we have hash probes, but there's really
1954 // nothing we can do.
1956 // End of dragging-related code.
1958 var fmt_cp = function(v) {
1962 return "+" + (v / 100).toFixed(2);
1965 return "-" + (v / 100).toFixed(2);
1969 var format_short_score = function(score) {
1973 if (score[0] === 'm') {
1974 if (score[2]) { // Is a bound.
1975 return score[2] + "\u00a0M " + score[1];
1977 return "M " + score[1];
1979 } else if (score[0] === 'd') {
1981 } else if (score[0] === 'cp') {
1982 if (score[2]) { // Is a bound.
1983 return score[2] + "\u00a0" + fmt_cp(score[1]);
1985 return fmt_cp(score[1]);
1991 var format_long_score = function(score) {
1992 if (score[0] === 'm') {
1994 return "White mates in " + score[1];
1996 return "Black mates in " + (-score[1]);
1998 } else if (score[0] === 'd') {
1999 return "Theoretical draw";
2000 } else if (score[0] === 'cp') {
2001 return "Score: " + format_short_score(score);
2006 var compute_plot_score = function(score) {
2007 if (score[0] === 'm') {
2013 } else if (score[0] === 'd') {
2015 } else if (score[0] === 'cp') {
2016 if (score[1] > 500) {
2018 } else if (score[1] < -500) {
2028 * @param score The score digest tuple.
2029 * @param {?number} depth Depth the move has been computed to, or null.
2030 * @param {boolean} invert Whether black is to play.
2033 var compute_score_sort_key = function(score, depth, invert) {
2038 if (score[0] === 'm') {
2041 s = 99999 - score[1];
2043 // Black mates (note the double negative for score[1]).
2044 s = -99999 - score[1];
2046 } else if (score[0] === 'd') {
2048 } else if (score[0] === 'cp') {
2053 return s * 200 + (depth || 0);
2060 * @param {string} new_backend_url
2062 var switch_backend = function(new_backend_url, new_backend_hash_url) {
2063 // Stop looking at historic data.
2064 current_display_line = null;
2065 current_display_move = null;
2066 displayed_analysis_data = null;
2067 if (current_historic_xhr) {
2068 current_historic_xhr.abort();
2071 // If we already have a backend response going, abort it.
2072 if (current_analysis_xhr) {
2073 current_analysis_xhr.abort();
2075 if (current_hash_xhr) {
2076 current_hash_xhr.abort();
2079 // Otherwise, we should have a timer going to start a new one.
2081 if (current_analysis_request_timer) {
2082 clearTimeout(current_analysis_request_timer);
2083 current_analysis_request_timer = null;
2085 if (current_hash_display_timer) {
2086 clearTimeout(current_hash_display_timer);
2087 current_hash_display_timer = null;
2090 // Request an immediate fetch with the new backend.
2091 backend_url = new_backend_url;
2092 backend_hash_url = new_backend_hash_url;
2093 current_analysis_data = null;
2097 window['switch_backend'] = switch_backend;
2099 var init = function() {
2100 unique = get_unique();
2102 // Load settings from HTML5 local storage if available.
2103 if (supports_html5_storage() && localStorage['enable_sound']) {
2104 set_sound(parseInt(localStorage['enable_sound']));
2108 if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
2109 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
2111 sort_refutation_lines_by_score = true;
2115 board = new window.ChessBoard('board', {
2116 onMoveEnd: function() { board_is_animating = false; },
2119 onDragStart: onDragStart,
2121 onSnapEnd: onSnapEnd
2123 $("#board").on('mousedown', '.square-55d63', mousedownSquare);
2124 $("#board").on('mouseup', '.square-55d63', mouseupSquare);
2127 $(window).resize(function() {
2129 update_sparkline(displayed_analysis_data || current_analysis_data);
2130 update_board_highlight();
2133 $(window).keyup(function(event) {
2134 if (event.which == 39) { // Left arrow.
2136 } else if (event.which == 37) { // Right arrow.
2138 } else if (event.which >= 49 && event.which <= 57) { // 1-9.
2139 var num = event.which - 49;
2140 if (current_games && current_games.length >= num) {
2141 switch_backend(current_games[num]['url'], current_games[num]['hashurl']);
2143 } else if (event.which == 78) { // N.
2147 window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
2149 $(document).ready(init);