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 = 2016113007;
13 * The current backend URL.
18 var backend_url = "/analysis.pl";
19 var backend_hash_url = "/hash";
21 /** @type {window.ChessBoard} @private */
24 /** @type {boolean} @private */
25 var board_is_animating = false;
28 * The most recent analysis data we have from the server
29 * (about the most recent position).
33 var current_analysis_data = null;
36 * If we are displaying previous analysis or from hash, this is non-null,
37 * and will override most of current_analysis_data.
42 var displayed_analysis_data = null;
45 * Games currently in progress, if any.
57 var current_games = null;
72 /** @type {Array.<Array.<boolean>>} */
73 var occupied_by_arrows = [];
75 /** Currently displayed refutation lines (on-screen).
76 * Can either come from the current_analysis_data, displayed_analysis_data,
77 * or hash_refutation_lines.
79 var refutation_lines = [];
81 /** Refutation lines from current hash probe.
83 * If non-null, will override refutation lines from the base position.
84 * Note that these are relative to display_fen, not base_fen.
86 var hash_refutation_lines = null;
88 /** @type {!number} @private */
91 /** @type {!string} @private */
94 /** @type {number} @private */
97 /** @type {boolean} @private */
98 var truncate_display_history = true;
100 /** @type {!string|undefined} @private */
101 var highlight_from = undefined;
103 /** @type {!string|undefined} @private */
104 var highlight_to = undefined;
106 /** The HTML object of the move currently being highlighted (in red).
109 var highlighted_move = null;
111 /** Currently suggested/recommended move when dragging.
112 * @type {?{from: !string, to: !string}}
115 var recommended_move = null;
117 /** If reverse-dragging (dragging from the destination square to the
118 * source square), the destination square.
122 var reverse_dragging_from = null;
124 /** @type {?number} @private */
127 /** @type {boolean} @private */
128 var enable_sound = false;
131 * Our best estimate of how many milliseconds we need to add to
132 * new Date() to get the true UTC time. Calibrated against the
138 var client_clock_offset_ms = null;
140 var clock_timer = null;
142 /** The current position being analyzed, represented as a FEN string.
143 * Note that this is not necessarily the same as display_fen.
149 /** The current position on the board, represented as a FEN string.
150 * Note that board.fen() does not contain e.g. who is to play.
154 var display_fen = null;
158 * pv: Array.<string>,
161 * scores: Array<{first_move: number, score: Object}>,
162 * start_display_move_num: number
165 * "start_display_move_num" is the (half-)move number to start displaying the PV at.
166 * "score" is also evaluated at this point.
169 /** All PVs that we currently know of.
171 * Element 0 is history (or null if no history).
172 * Element 1 is current main PV, or explored line if nowhere else on the screen.
173 * All remaining elements are refutation lines (multi-PV).
175 * @type {Array.<DisplayLine>}
178 var display_lines = [];
180 /** @type {?DisplayLine} @private */
181 var current_display_line = null;
183 /** @type {boolean} @private */
184 var current_display_line_is_history = false;
186 /** @type {?number} @private */
187 var current_display_move = null;
190 * The current backend request to get main analysis (not history), if any,
191 * so that we can abort it.
196 var current_analysis_xhr = null;
199 * The current timer to fire off a request to get main analysis (not history),
200 * if any, so that we can abort it.
205 var current_analysis_request_timer = null;
208 * The current backend request to get historic data, if any.
213 var current_historic_xhr = null;
216 * The current backend request to get hash probes, if any, so that we can abort it.
221 var current_hash_xhr = null;
224 * The current timer to display hash probe information (it could be waiting on the
225 * board to stop animating), if any, so that we can abort it.
230 var current_hash_display_timer = null;
232 var supports_html5_storage = function() {
234 return 'localStorage' in window && window['localStorage'] !== null;
240 // Make the unique token persistent so people refreshing the page won't count twice.
241 // Of course, you can never fully protect against people deliberately wanting to spam.
242 var get_unique = function() {
243 var use_local_storage = supports_html5_storage();
244 if (use_local_storage && localStorage['unique']) {
245 return localStorage['unique'];
247 var unique = Math.random();
248 if (use_local_storage) {
249 localStorage['unique'] = unique;
254 var request_update = function() {
255 current_analysis_request_timer = null;
257 current_analysis_xhr = $.ajax({
258 url: backend_url + "?ims=" + ims + "&unique=" + unique
259 }).done(function(data, textstatus, xhr) {
260 sync_server_clock(xhr.getResponseHeader('Date'));
261 ims = xhr.getResponseHeader('X-RGLM');
262 var num_viewers = xhr.getResponseHeader('X-RGNV');
264 if (Array.isArray(data)) {
265 new_data = JSON.parse(JSON.stringify(current_analysis_data));
266 JSON_delta.patch(new_data, data);
271 var minimum_version = xhr.getResponseHeader('X-RGMV');
272 if (minimum_version && minimum_version > SCRIPT_VERSION) {
273 // Upgrade to latest version with a force-reload.
274 location.reload(true);
277 // Verify that the PV makes sense.
279 if (new_data['pv']) {
280 var hiddenboard = new Chess(new_data['position']['fen']);
281 for (var i = 0; i < new_data['pv'].length; ++i) {
282 if (hiddenboard.move(new_data['pv'][i]) === null) {
291 possibly_play_sound(current_analysis_data, new_data);
292 current_analysis_data = new_data;
294 update_num_viewers(num_viewers);
296 console.log("Received invalid update, waiting five seconds and trying again.");
297 location.reload(true);
301 if (!backend_url.match(/history/)) {
302 current_analysis_request_timer = setTimeout(function() { request_update(); }, timeout);
304 }).fail(function(jqXHR, textStatus, errorThrown) {
305 if (textStatus === "abort") {
306 // Aborted because we are switching backends. Abandon and don't retry,
307 // because another one is already started for us.
309 // Backend error or similar. Wait ten seconds, then try again.
310 current_analysis_request_timer = setTimeout(function() { request_update(); }, 10000);
315 var possibly_play_sound = function(old_data, new_data) {
319 if (old_data === null) {
322 var ding = document.getElementById('ding');
323 if (ding && ding.play) {
324 if (old_data['position'] && old_data['position']['fen'] &&
325 new_data['position'] && new_data['position']['fen'] &&
326 (old_data['position']['fen'] !== new_data['position']['fen'] ||
327 old_data['position']['move_num'] !== new_data['position']['move_num'])) {
334 * @type {!string} server_date_string
336 var sync_server_clock = function(server_date_string) {
337 var server_time_ms = new Date(server_date_string).getTime();
338 var client_time_ms = new Date().getTime();
339 var estimated_offset_ms = server_time_ms - client_time_ms;
341 // In order not to let the noise move us too much back and forth
342 // (the server only has one-second resolution anyway), we only
343 // change an existing skew if we are at least five seconds off.
344 if (client_clock_offset_ms === null ||
345 Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
346 client_clock_offset_ms = estimated_offset_ms;
350 var clear_arrows = function() {
351 for (var i = 0; i < arrows.length; ++i) {
353 if (arrows[i].svg.parentElement) {
354 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
356 delete arrows[i].svg;
361 occupied_by_arrows = [];
362 for (var y = 0; y < 8; ++y) {
363 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
367 var redraw_arrows = function() {
368 for (var i = 0; i < arrows.length; ++i) {
369 position_arrow(arrows[i]);
373 /** @param {!number} x
376 var sign = function(x) {
386 /** See if drawing this arrow on the board would cause unduly amount of confusion.
387 * @param {!string} from The square the arrow is from (e.g. e4).
388 * @param {!string} to The square the arrow is to (e.g. e4).
391 var interfering_arrow = function(from, to) {
392 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
393 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
394 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
395 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
397 occupied_by_arrows[from_row][from_col] = true;
399 // Knight move: Just check that we haven't been at the destination before.
400 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
401 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
402 return occupied_by_arrows[to_row][to_col];
405 // Sliding piece: Check if anything except the from-square is seen before.
406 var dx = sign(to_col - from_col);
407 var dy = sign(to_row - from_row);
413 if (occupied_by_arrows[y][x]) {
416 occupied_by_arrows[y][x] = true;
417 } while (x != to_col || y != to_row);
422 /** Find a point along the coordinate system given by the given line,
423 * <t> units forward from the start of the line, <u> units to the right of it.
424 * @param {!number} x1
425 * @param {!number} x2
426 * @param {!number} y1
427 * @param {!number} y2
430 * @return {!string} The point in "x y" form, suitable for SVG paths.
432 var point_from_start = function(x1, y1, x2, y2, t, u) {
436 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
440 var x = x1 + dx * t + dy * u;
441 var y = y1 + dy * t - dx * u;
445 /** Find a point along the coordinate system given by the given line,
446 * <t> units forward from the end of the line, <u> units to the right of it.
447 * @param {!number} x1
448 * @param {!number} x2
449 * @param {!number} y1
450 * @param {!number} y2
453 * @return {!string} The point in "x y" form, suitable for SVG paths.
455 var point_from_end = function(x1, y1, x2, y2, t, u) {
459 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
463 var x = x2 + dx * t + dy * u;
464 var y = y2 + dy * t - dx * u;
468 var position_arrow = function(arrow) {
470 if (arrow.svg.parentElement) {
471 arrow.svg.parentElement.removeChild(arrow.svg);
475 if (current_display_line !== null && !current_display_line_is_history) {
479 var zoom_factor = $("#board").width() / 400.0;
480 var line_width = arrow.line_width * zoom_factor;
481 var arrow_size = arrow.arrow_size * zoom_factor;
483 var square_width = $(".square-a8").width();
484 var pos, from_y, to_y, from_x, to_x;
485 if (board.orientation() === 'black') {
486 pos = $(".square-h1").position();
487 from_y = (arrow.from_row + 0.5)*square_width;
488 to_y = (arrow.to_row + 0.5)*square_width;
489 from_x = (7 - arrow.from_col + 0.5)*square_width;
490 to_x = (7 - arrow.to_col + 0.5)*square_width;
492 pos = $(".square-a8").position();
493 from_y = (7 - arrow.from_row + 0.5)*square_width;
494 to_y = (7 - arrow.to_row + 0.5)*square_width;
495 from_x = (arrow.from_col + 0.5)*square_width;
496 to_x = (arrow.to_col + 0.5)*square_width;
499 var SVG_NS = "http://www.w3.org/2000/svg";
500 var XHTML_NS = "http://www.w3.org/1999/xhtml";
501 var svg = document.createElementNS(SVG_NS, "svg");
502 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
503 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
504 svg.setAttribute("style", "position: absolute");
505 svg.setAttribute("position", "absolute");
506 svg.setAttribute("version", "1.1");
507 svg.setAttribute("class", "c1");
508 svg.setAttribute("xmlns", XHTML_NS);
516 var outline = document.createElementNS(SVG_NS, "path");
517 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));
518 outline.setAttribute("xmlns", XHTML_NS);
519 outline.setAttribute("stroke", "#666");
520 outline.setAttribute("stroke-width", line_width + 2);
521 outline.setAttribute("fill", "none");
522 svg.appendChild(outline);
524 var path = document.createElementNS(SVG_NS, "path");
525 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));
526 path.setAttribute("xmlns", XHTML_NS);
527 path.setAttribute("stroke", arrow.fg_color);
528 path.setAttribute("stroke-width", line_width);
529 path.setAttribute("fill", "none");
530 svg.appendChild(path);
532 // Then the arrow head.
533 var head = document.createElementNS(SVG_NS, "path");
534 head.setAttribute("d",
535 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
536 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
537 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
538 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
539 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
540 head.setAttribute("xmlns", XHTML_NS);
541 head.setAttribute("stroke", "#000");
542 head.setAttribute("stroke-width", "1");
543 head.setAttribute("fill", arrow.fg_color);
544 svg.appendChild(head);
546 $(svg).css({ top: pos.top, left: pos.left, 'pointer-events': 'none' });
547 document.body.appendChild(svg);
552 * @param {!string} from_square
553 * @param {!string} to_square
554 * @param {!string} fg_color
555 * @param {number} line_width
556 * @param {number} arrow_size
558 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
559 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
560 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
561 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
562 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
570 line_width: line_width,
571 arrow_size: arrow_size,
575 position_arrow(arrow);
579 var compare_by_score = function(refutation_lines, invert, a, b) {
580 var sa = compute_score_sort_key(refutation_lines[b]['score'], refutation_lines[b]['depth'], invert);
581 var sb = compute_score_sort_key(refutation_lines[a]['score'], refutation_lines[a]['depth'], invert);
586 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
587 * sorted by quality, descending.
589 * @param {!Object} data
590 * @param {number} margin The maximum number of centipawns worse than the
591 * best move can be and still be included.
592 * @param {boolean} invert Whether black is to play.
593 * @return {Array.<string>} The FEN representation (e.g. Ne4) of all
594 * moves, in score order.
596 var find_nonstupid_moves = function(data, margin, invert) {
597 // First of all, if there are any moves that are more than 0.5 ahead of
598 // the primary move, the refutation lines are probably bunk, so just
600 var best_score = undefined;
601 var pv_score = undefined;
602 for (var move in data['refutation_lines']) {
603 var line = data['refutation_lines'][move];
604 var score = compute_score_sort_key(line['score'], line['depth'], invert, false);
605 if (move == data['pv'][0]) {
608 if (best_score === undefined || score > best_score) {
611 if (line['depth'] < 8) {
616 if (best_score - pv_score > 50) {
620 // Now find all moves that are within “margin” of the best score.
621 // The PV move will always be first.
623 for (var move in data['refutation_lines']) {
624 var line = data['refutation_lines'][move];
625 var score = compute_score_sort_key(line['score'], line['depth'], invert);
626 if (move != data['pv'][0] && best_score - score <= margin) {
630 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], data['position']['toplay'] === 'B', a, b) });
631 moves.unshift(data['pv'][0]);
640 var thousands = function(x) {
641 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
645 * @param {!string} start_fen
646 * @param {Array.<string>} pv
647 * @param {number} move_num
648 * @param {!string} toplay
649 * @param {Array<{ first_move: integer, score: Object }>} scores
650 * @param {number} start_display_move_num
651 * @param {number=} opt_limit
652 * @param {boolean=} opt_showlast
654 var add_pv = function(start_fen, pv, move_num, toplay, scores, start_display_move_num, opt_limit, opt_showlast) {
656 start_fen: start_fen,
658 move_num: parseInt(move_num),
661 start_display_move_num: start_display_move_num
663 return print_pv(display_lines.length - 1, opt_limit, opt_showlast);
667 * @param {number} line_num
668 * @param {number=} opt_limit If set, show at most this number of moves.
669 * @param {boolean=} opt_showlast If limit is set, show the last moves instead of the first ones.
671 var print_pv = function(line_num, opt_limit, opt_showlast) {
672 var display_line = display_lines[line_num];
673 var pv = display_line.pv;
674 var move_num = display_line.move_num;
675 var toplay = display_line.toplay;
677 // Truncate PV at the start if needed.
678 var start_display_move_num = display_line.start_display_move_num;
679 if (start_display_move_num > 0) {
680 pv = pv.slice(start_display_move_num);
681 var to_add = start_display_move_num;
682 if (toplay === 'B') {
687 if (to_add % 2 == 1) {
691 move_num += to_add / 2;
696 if (opt_limit && opt_showlast && pv.length > opt_limit) {
697 // Truncate the PV at the beginning (instead of at the end).
698 // We assume here that toplay is 'W'. We also assume that if
699 // opt_showlast is set, then it is the history, and thus,
700 // the UI should be to expand the history.
701 ret = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
702 i = pv.length - opt_limit;
707 } else if (toplay == 'B' && pv.length > 0) {
708 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pv[0] + "</a>";
709 ret = move_num + '. … ' + move;
714 for ( ; i < pv.length; ++i) {
715 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pv[i] + "</a>";
718 if (i > opt_limit && !opt_showlast) {
724 ret += move_num + '. ' + move;
735 /** Update the highlighted to/from squares on the board.
736 * Based on the global "highlight_from" and "highlight_to" variables.
738 var update_board_highlight = function() {
739 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
740 if ((current_display_line === null || current_display_line_is_history) &&
741 highlight_from !== undefined && highlight_to !== undefined) {
742 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
743 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
747 var update_history = function() {
748 if (display_lines[0] === null || display_lines[0].pv.length == 0) {
749 $("#history").html("No history");
750 } else if (truncate_display_history) {
751 $("#history").html(print_pv(0, 8, true));
754 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
760 * @param {!boolean} truncate_history
762 var collapse_history = function(truncate_history) {
763 truncate_display_history = truncate_history;
766 window['collapse_history'] = collapse_history;
768 /** Update the HTML display of multi-PV from the global "refutation_lines".
770 * Also recreates the global "display_lines".
772 var update_refutation_lines = function() {
773 if (base_fen === null) {
776 if (display_lines.length > 2) {
777 // Truncate so that only the history and PV is left.
778 display_lines = [ display_lines[0], display_lines[1] ];
780 var tbl = $("#refutationlines");
783 // Find out where the lines start from.
785 var base_scores = display_lines[1].scores;
786 var start_display_move_num = 0;
787 if (hash_refutation_lines) {
788 base_line = current_display_line.pv.slice(0, current_display_move + 1);
789 base_scores = current_display_line.scores;
790 start_display_move_num = base_line.length;
794 for (var move in refutation_lines) {
798 var invert = (toplay === 'B');
799 if (current_display_line && current_display_move % 2 == 0 && !current_display_line_is_history) {
802 moves = moves.sort(function(a, b) { return compare_by_score(refutation_lines, invert, a, b) });
803 for (var i = 0; i < moves.length; ++i) {
804 var line = refutation_lines[moves[i]];
806 var tr = document.createElement("tr");
808 var move_td = document.createElement("td");
809 tr.appendChild(move_td);
810 $(move_td).addClass("move");
812 var scores = base_scores.concat([{ first_move: start_display_move_num, score: line['score'] }]);
814 if (line['pv'].length == 0) {
815 // Not found, so just make a one-move PV.
816 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['move'] + "</a>";
817 $(move_td).html(move);
818 var score_td = document.createElement("td");
820 $(score_td).addClass("score");
821 $(score_td).text("—");
822 tr.appendChild(score_td);
824 var depth_td = document.createElement("td");
825 tr.appendChild(depth_td);
826 $(depth_td).addClass("depth");
827 $(depth_td).text("—");
829 var pv_td = document.createElement("td");
830 tr.appendChild(pv_td);
831 $(pv_td).addClass("pv");
832 $(pv_td).html(add_pv(base_fen, base_line.concat([ line['move'] ]), move_num, toplay, scores, start_display_move_num));
838 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['move'] + "</a>";
839 $(move_td).html(move);
841 var score_td = document.createElement("td");
842 tr.appendChild(score_td);
843 $(score_td).addClass("score");
844 $(score_td).text(format_short_score(line['score']));
846 var depth_td = document.createElement("td");
847 tr.appendChild(depth_td);
848 $(depth_td).addClass("depth");
849 if (line['depth'] && line['depth'] >= 0) {
850 $(depth_td).text("d" + line['depth']);
852 $(depth_td).text("—");
855 var pv_td = document.createElement("td");
856 tr.appendChild(pv_td);
857 $(pv_td).addClass("pv");
858 $(pv_td).html(add_pv(base_fen, base_line.concat(line['pv']), move_num, toplay, scores, start_display_move_num, 10));
863 // Update the move highlight, as we've rewritten all the HTML.
864 update_move_highlight();
868 * Create a Chess.js board object, containing the given position plus the given moves,
869 * up to the given limit.
871 * @param {?string} fen
872 * @param {Array.<string>} moves
873 * @param {number} last_move
875 var chess_from = function(fen, moves, last_move) {
876 var hiddenboard = new Chess();
877 if (fen !== null && fen !== undefined) {
878 hiddenboard.load(fen);
880 for (var i = 0; i <= last_move; ++i) {
881 if (moves[i] === '0-0') {
882 hiddenboard.move('O-O');
883 } else if (moves[i] === '0-0-0') {
884 hiddenboard.move('O-O-O');
886 hiddenboard.move(moves[i]);
892 var update_game_list = function(games) {
893 $("#games").text("");
894 if (games === null) {
898 var games_div = document.getElementById('games');
899 for (var game_num = 0; game_num < games.length; ++game_num) {
900 var game = games[game_num];
901 var game_span = document.createElement("span");
902 game_span.setAttribute("class", "game");
904 var game_name = document.createTextNode(game['name']);
905 if (game['url'] === backend_url) {
907 game_span.appendChild(game_name);
909 if (current_analysis_data && current_analysis_data['position']) {
911 if (current_analysis_data['position']['result']) {
912 score = " (" + current_analysis_data['position']['result'] + ")";
914 score = " (" + format_short_score(current_analysis_data['score']) + ")";
916 game_span.appendChild(document.createTextNode(score));
920 var game_a = document.createElement("a");
921 game_a.setAttribute("href", "#" + game['id']);
922 game_a.appendChild(game_name);
923 game_span.appendChild(game_a);
926 if (game['result']) {
927 score = " (" + game['result'] + ")";
929 score = " (" + format_short_score(game['score']) + ")";
931 game_span.appendChild(document.createTextNode(score));
934 games_div.appendChild(game_span);
939 * Try to find a running game that matches with the current hash,
940 * and switch to it if we're not already displaying it.
942 var possibly_switch_game_from_hash = function() {
943 var history_match = window.location.hash.match(/^#history=([a-zA-Z0-9_-]+)/);
944 if (history_match !== null) {
945 var game_id = history_match[1];
947 url: '/history/' + game_id + '.json',
949 id: 'history=' + game_id
951 switch_backend(fake_game);
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]);
971 * If this is a Chess960 castling which doesn't move the king,
972 * move the rook instead.
974 var patch_move = function(move) {
975 if (move === null) return null;
976 if (move.from !== move.to) return move;
978 var f = move.rook_sq & 15;
979 var r = move.rook_sq >> 4;
980 var from = ('abcdefgh'.substring(f,f+1) + '87654321'.substring(r,r+1));
983 if (move.to === 'g1') {
985 } else if (move.to === 'g8') {
987 } else if (move.to === 'b1') {
989 } else if (move.to === 'b8') {
993 return { from: from, to: to };
996 /** Update all the HTML on the page, based on current global state.
998 var update_board = function() {
999 var data = displayed_analysis_data || current_analysis_data;
1000 var current_data = current_analysis_data; // Convenience alias.
1004 // Print the history. This is pretty much the only thing that's
1005 // unconditionally taken from current_data (we're not interested in
1006 // historic history).
1007 if (current_data['position']['history']) {
1008 var start = (current_data['position'] && current_data['position']['start_fen']) ? current_data['position']['start_fen'] : 'start';
1009 add_pv(start, current_data['position']['history'], 1, 'W', null, 0, 8, true);
1011 display_lines.push(null);
1015 // Games currently in progress, if any.
1016 if (current_data['games']) {
1017 current_games = current_data['games'];
1018 possibly_switch_game_from_hash();
1020 current_games = null;
1022 update_game_list(current_games);
1024 // The headline. Names are always fetched from current_data;
1025 // the rest can depend a bit.
1028 current_data['position']['player_w'] && current_data['position']['player_b']) {
1029 headline = current_data['position']['player_w'] + '–' +
1030 current_data['position']['player_b'] + ', analysis';
1032 headline = 'Analysis';
1035 // Credits, where applicable. Note that we don't want the footer to change a lot
1036 // when e.g. viewing history, so if any of these changed during the game,
1037 // use the current one still.
1038 if (current_data['using_lomonosov']) {
1039 $("#lomonosov").show();
1041 $("#lomonosov").hide();
1044 // Credits: The engine name/version.
1045 if (current_data['engine'] && current_data['engine']['name'] !== null) {
1046 $("#engineid").text(current_data['engine']['name']);
1049 // Credits: The engine URL.
1050 if (current_data['engine'] && current_data['engine']['url']) {
1051 $("#engineid").attr("href", current_data['engine']['url']);
1053 $("#engineid").removeAttr("href");
1056 // Credits: Engine details.
1057 if (current_data['engine'] && current_data['engine']['details']) {
1058 $("#enginedetails").text(" (" + current_data['engine']['details'] + ")");
1060 $("#enginedetails").text("");
1063 // Credits: Move source, possibly with URL.
1064 if (current_data['move_source'] && current_data['move_source_url']) {
1065 $("#movesource").text("Moves provided by ");
1066 var movesource_a = document.createElement("a");
1067 movesource_a.setAttribute("href", current_data['move_source_url']);
1068 var movesource_text = document.createTextNode(current_data['move_source']);
1069 movesource_a.appendChild(movesource_text);
1070 var movesource_period = document.createTextNode(".");
1071 document.getElementById("movesource").appendChild(movesource_a);
1072 document.getElementById("movesource").appendChild(movesource_period);
1073 } else if (current_data['move_source']) {
1074 $("#movesource").text("Moves provided by " + current_data['move_source'] + ".");
1076 $("#movesource").text("");
1080 if (displayed_analysis_data) {
1081 // Displaying some non-current position, pick out the last move
1082 // from the history. This will work even if the fetch failed.
1083 if (current_display_move !== -1) {
1084 last_move = format_halfmove_with_number(
1085 current_display_line.pv[current_display_move],
1086 current_display_move);
1087 headline += ' after ' + last_move;
1089 } else if (data['position']['last_move'] !== 'none') {
1090 // Find the previous move.
1091 var previous_move_num, previous_toplay;
1092 if (data['position']['toplay'] == 'B') {
1093 previous_move_num = data['position']['move_num'];
1094 previous_toplay = 'W';
1096 previous_move_num = data['position']['move_num'] - 1;
1097 previous_toplay = 'B';
1100 last_move = format_move_with_number(
1101 data['position']['last_move'],
1103 previous_toplay == 'W');
1104 headline += ' after ' + last_move;
1108 $("#headline").text(headline);
1110 // The <title> contains a very brief headline.
1111 var title_elems = [];
1112 if (data['position'] && data['position']['result']) {
1113 title_elems.push(data['position']['result']);
1114 } else if (data['score']) {
1115 title_elems.push(format_short_score(data['score']));
1117 if (last_move !== null) {
1118 title_elems.push(last_move);
1121 if (title_elems.length != 0) {
1122 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
1124 document.title = 'analysis.sesse.net';
1127 // The last move (shown by highlighting the from and to squares).
1128 if (data['position'] && data['position']['last_move_uci']) {
1129 highlight_from = data['position']['last_move_uci'].substr(0, 2);
1130 highlight_to = data['position']['last_move_uci'].substr(2, 2);
1131 } else if (current_display_line_is_history && current_display_line && current_display_move >= 0) {
1132 // We don't have historic analysis for this position, but we
1133 // can reconstruct what the last move was by just replaying
1135 var position = (data['position'] && data['position']['start_fen']) ? data['position']['start_fen'] : null;
1136 var hiddenboard = chess_from(position, current_display_line.pv, current_display_move);
1137 var moves = hiddenboard.history({ verbose: true });
1138 last_move = moves.pop();
1139 highlight_from = last_move.from;
1140 highlight_to = last_move.to;
1142 highlight_from = highlight_to = undefined;
1144 update_board_highlight();
1146 if (data['failed']) {
1147 $("#score").text("No analysis for this move");
1148 $("#pvtitle").text("PV:");
1150 $("#searchstats").html(" ");
1151 $("#refutationlines").empty();
1152 $("#whiteclock").empty();
1153 $("#blackclock").empty();
1154 refutation_lines = [];
1155 update_refutation_lines();
1157 update_displayed_line();
1158 update_move_highlight();
1165 if (current_display_line && !current_display_line_is_history) {
1167 if (current_display_line.scores && current_display_line.scores.length > 0) {
1168 for (var i = 0; i < current_display_line.scores.length; ++i) {
1169 if (current_display_move < current_display_line.scores[i].first_move) {
1172 score = current_display_line.scores[i].score;
1176 $("#score").text(format_long_score(score));
1178 $("#score").text("No score for this line");
1180 } else if (data['score']) {
1181 $("#score").text(format_long_score(data['score']));
1184 // The search stats.
1185 if (data['searchstats']) {
1186 $("#searchstats").html(data['searchstats']);
1187 } else if (data['tablebase'] == 1) {
1188 $("#searchstats").text("Tablebase result");
1189 } else if (data['nodes'] && data['nps'] && data['depth']) {
1190 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
1191 if (data['seldepth']) {
1192 stats += ' (' + data['seldepth'] + ' selective)';
1194 if (data['tbhits'] && data['tbhits'] > 0) {
1195 if (data['tbhits'] == 1) {
1196 stats += ', one Syzygy hit';
1198 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
1202 $("#searchstats").text(stats);
1204 $("#searchstats").text("");
1207 // Update the board itself.
1208 base_fen = data['position']['fen'];
1209 update_displayed_line();
1212 $("#pvtitle").text("PV:");
1214 var scores = [{ first_move: -1, score: data['score'] }];
1215 $("#pv").html(add_pv(data['position']['fen'], data['pv'], data['position']['move_num'], data['position']['toplay'], scores, 0));
1217 // Update the PV arrow.
1219 if (data['pv'].length >= 1) {
1220 var hiddenboard = new Chess(base_fen);
1222 // draw a continuation arrow as long as it's the same piece
1224 for (var i = 0; i < data['pv'].length; i += 2) {
1225 var move = patch_move(hiddenboard.move(data['pv'][i]));
1227 if ((i >= 2 && move.from != last_to) ||
1228 interfering_arrow(move.from, move.to)) {
1231 create_arrow(move.from, move.to, '#f66', 6, 20);
1233 hiddenboard.move(data['pv'][i + 1]); // To keep continuity.
1236 var alt_moves = find_nonstupid_moves(data, 30, data['position']['toplay'] === 'B');
1237 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
1238 hiddenboard = new Chess(base_fen);
1239 var move = patch_move(hiddenboard.move(alt_moves[i]));
1240 if (move !== null) {
1241 create_arrow(move.from, move.to, '#f66', 1, 10);
1246 // See if all semi-reasonable moves have only one possible response.
1247 if (data['pv'].length >= 2) {
1248 var nonstupid_moves = find_nonstupid_moves(data, 300, data['position']['toplay'] === 'B');
1251 var hiddenboard = new Chess(base_fen);
1252 hiddenboard.move(data['pv'][0]);
1253 response = hiddenboard.move(data['pv'][1]);
1255 for (var i = 0; i < nonstupid_moves.length; ++i) {
1256 if (nonstupid_moves[i] == data['pv'][0]) {
1257 // ignore the PV move for refutation lines.
1260 if (!data['refutation_lines'] ||
1261 !data['refutation_lines'][nonstupid_moves[i]] ||
1262 !data['refutation_lines'][nonstupid_moves[i]]['pv'] ||
1263 data['refutation_lines'][nonstupid_moves[i]]['pv'].length < 1) {
1264 // Incomplete PV, abort.
1265 response = undefined;
1268 var line = data['refutation_lines'][nonstupid_moves[i]];
1269 hiddenboard = new Chess(base_fen);
1270 hiddenboard.move(line['pv'][0]);
1271 var this_response = hiddenboard.move(line['pv'][1]);
1272 if (response.from !== this_response.from || response.to !== this_response.to) {
1273 // Different response depending on lines, abort.
1274 response = undefined;
1279 if (nonstupid_moves.length > 0 && response !== undefined) {
1280 create_arrow(response.from, response.to, '#66f', 6, 20);
1284 // Update the refutation lines.
1285 base_fen = data['position']['fen'];
1286 move_num = parseInt(data['position']['move_num']);
1287 toplay = data['position']['toplay'];
1288 refutation_lines = hash_refutation_lines || data['refutation_lines'];
1289 update_refutation_lines();
1291 // Update the sparkline last, since its size depends on how everything else reflowed.
1292 update_sparkline(data);
1295 var update_sparkline = function(data) {
1296 if (data && data['score_history']) {
1297 var first_move_num = undefined;
1298 for (var halfmove_num in data['score_history']) {
1299 halfmove_num = parseInt(halfmove_num);
1300 if (first_move_num === undefined || halfmove_num < first_move_num) {
1301 first_move_num = halfmove_num;
1304 if (first_move_num !== undefined) {
1305 var last_move_num = data['position']['move_num'] * 2 - 3;
1306 if (data['position']['toplay'] === 'B') {
1310 // Possibly truncate some moves if we don't have enough width.
1311 // FIXME: Sometimes width() for #scorecontainer (and by extent,
1312 // #scoresparkcontainer) on Chrome for mobile seems to start off
1313 // at something very small, and then suddenly snap back into place.
1315 var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
1316 if (last_move_num - first_move_num > max_moves) {
1317 first_move_num = last_move_num - max_moves;
1320 var min_score = -100;
1321 var max_score = 100;
1322 var last_score = null;
1324 for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1325 if (data['score_history'][halfmove_num]) {
1326 var score = compute_plot_score(data['score_history'][halfmove_num]);
1328 if (score < min_score) min_score = score;
1329 if (score > max_score) max_score = score;
1331 scores.push(last_score);
1333 if (data['score']) {
1334 scores.push(compute_plot_score(data['score']));
1336 // FIXME: at some widths, calling sparkline() seems to push
1337 // #scorecontainer under the board.
1338 $("#scorespark").sparkline(scores, {
1341 chartRangeMin: min_score,
1342 chartRangeMax: max_score,
1343 tooltipFormatter: function(sparkline, options, fields) {
1344 // score_history contains the Nth _position_, but format_tooltip
1345 // wants to format the Nth _move_; thus the -1.
1346 return format_tooltip(data, fields[0].offset + first_move_num - 1);
1349 $('#scorespark').bind('sparklineClick', function(event) {
1350 var sparkline = event.sparklines[0];
1351 var region = sparkline.getCurrentRegionFields();
1352 if (region[0].offset !== undefined) {
1353 show_line(0, first_move_num + region[0].offset - 1);
1357 $("#scorespark").text("");
1360 $("#scorespark").text("");
1365 * @param {number} num_viewers
1367 var update_num_viewers = function(num_viewers) {
1368 if (num_viewers === null) {
1369 $("#numviewers").text("");
1370 } else if (num_viewers == 1) {
1371 $("#numviewers").text("You are the only current viewer");
1373 $("#numviewers").text(num_viewers + " current viewers");
1377 var update_clock = function() {
1378 clearTimeout(clock_timer);
1380 var data = displayed_analysis_data || current_analysis_data;
1383 if (data['position']) {
1384 var result = data['position']['result'];
1385 if (result === '1-0') {
1386 $("#whiteclock").text("1");
1387 $("#blackclock").text("0");
1388 $("#whiteclock").removeClass("running-clock");
1389 $("#blackclock").removeClass("running-clock");
1392 if (result === '1/2-1/2') {
1393 $("#whiteclock").text("1/2");
1394 $("#blackclock").text("1/2");
1395 $("#whiteclock").removeClass("running-clock");
1396 $("#blackclock").removeClass("running-clock");
1399 if (result === '0-1') {
1400 $("#whiteclock").text("0");
1401 $("#blackclock").text("1");
1402 $("#whiteclock").removeClass("running-clock");
1403 $("#blackclock").removeClass("running-clock");
1408 var white_clock_ms = null;
1409 var black_clock_ms = null;
1412 if (data['position'] &&
1413 data['position']['white_clock'] &&
1414 data['position']['black_clock']) {
1415 white_clock_ms = data['position']['white_clock'] * 1000;
1416 black_clock_ms = data['position']['black_clock'] * 1000;
1419 // Dynamic clock (only one, obviously).
1421 if (data['position']['white_clock_target']) {
1423 $("#whiteclock").addClass("running-clock");
1424 $("#blackclock").removeClass("running-clock");
1425 } else if (data['position']['black_clock_target']) {
1427 $("#whiteclock").removeClass("running-clock");
1428 $("#blackclock").addClass("running-clock");
1430 $("#whiteclock").removeClass("running-clock");
1431 $("#blackclock").removeClass("running-clock");
1435 var now = new Date().getTime() + client_clock_offset_ms;
1436 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1437 if (color === "white") {
1438 white_clock_ms = remaining_ms;
1440 black_clock_ms = remaining_ms;
1444 if (white_clock_ms === null || black_clock_ms === null) {
1445 $("#whiteclock").empty();
1446 $("#blackclock").empty();
1450 // If either player has twenty minutes or less left, add the second counters.
1451 // This matches what DGT clocks do.
1452 var show_seconds = (white_clock_ms < 60 * 20 * 1000 || black_clock_ms < 60 * 20 * 1000);
1455 // See when the clock will change next, and update right after that.
1458 next_update_ms = remaining_ms % 1000 + 100;
1460 next_update_ms = remaining_ms % 60000 + 100;
1462 clock_timer = setTimeout(update_clock, next_update_ms);
1465 $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1466 $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1470 * @param {Number} remaining_ms
1471 * @param {boolean} show_seconds
1473 var format_clock = function(remaining_ms, show_seconds) {
1474 if (remaining_ms <= 0) {
1482 var remaining = Math.floor(remaining_ms / 1000);
1483 var seconds = remaining % 60;
1484 remaining = (remaining - seconds) / 60;
1485 var minutes = remaining % 60;
1486 remaining = (remaining - minutes) / 60;
1487 var hours = remaining;
1489 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1491 return format_2d(hours) + ":" + format_2d(minutes);
1498 var format_2d = function(x) {
1507 * @param {string} move
1508 * @param {Number} move_num Move number of this move.
1509 * @param {boolean} white_to_play Whether white is to play this move.
1511 var format_move_with_number = function(move, move_num, white_to_play) {
1513 if (white_to_play) {
1514 ret = move_num + '. ';
1516 ret = move_num + '… ';
1523 * @param {string} move
1524 * @param {Number} halfmove_num Half-move number that is to be played,
1527 var format_halfmove_with_number = function(move, halfmove_num) {
1528 return format_move_with_number(
1530 Math.floor(halfmove_num / 2) + 1,
1531 halfmove_num % 2 == 0);
1535 * @param {Object} data
1536 * @param {Number} halfmove_num
1538 var format_tooltip = function(data, halfmove_num) {
1539 if (data['score_history'][halfmove_num + 1] ||
1540 (halfmove_num + 1) === data['position']['history'].length) {
1541 // Position is in the history, or it is the current position
1542 // (which is implicitly tacked onto the history).
1545 if ((halfmove_num + 1) === data['position']['history'].length) {
1546 move = data['position']['last_move'];
1547 short_score = format_short_score(data['score']);
1549 move = data['position']['history'][halfmove_num];
1550 short_score = format_short_score(data['score_history'][halfmove_num + 1]);
1552 if (halfmove_num === -1) {
1553 return "Start position: " + short_score;
1555 var move_with_number = format_halfmove_with_number(move, halfmove_num);
1556 return "After " + move_with_number + ": " + short_score;
1559 for (var i = halfmove_num; i --> -1; ) {
1560 if (data['score_history'][i]) {
1561 var move = data['position']['history'][i];
1563 return "[Analysis kept from start position]";
1565 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1573 * @param {boolean} truncate_history
1575 var set_truncate_history = function(truncate_history) {
1576 truncate_display_history = truncate_history;
1577 update_refutation_lines();
1579 window['set_truncate_history'] = set_truncate_history;
1582 * @param {number} line_num
1583 * @param {number} move_num
1585 var show_line = function(line_num, move_num) {
1586 if (line_num == -1) {
1587 current_display_line = null;
1588 current_display_move = null;
1589 hash_refutation_lines = null;
1590 if (displayed_analysis_data) {
1591 // TODO: Support exiting to history position if we are in an
1592 // analysis line of a history position.
1593 displayed_analysis_data = null;
1598 current_display_line = jQuery.extend({}, display_lines[line_num]); // Shallow clone.
1599 current_display_move = move_num + current_display_line.start_display_move_num;
1601 current_display_line_is_history = (line_num == 0);
1603 update_historic_analysis();
1604 update_displayed_line();
1605 update_board_highlight();
1606 update_move_highlight();
1609 window['show_line'] = show_line;
1611 var prev_move = function() {
1612 if (current_display_line &&
1613 current_display_move >= current_display_line.start_display_move_num) {
1614 --current_display_move;
1616 update_historic_analysis();
1617 update_displayed_line();
1618 update_move_highlight();
1620 window['prev_move'] = prev_move;
1622 var next_move = function() {
1623 if (current_display_line &&
1624 current_display_move < current_display_line.pv.length - 1) {
1625 ++current_display_move;
1627 update_historic_analysis();
1628 update_displayed_line();
1629 update_move_highlight();
1631 window['next_move'] = next_move;
1633 var next_game = function() {
1634 if (current_games === null) {
1638 // Try to find the game we are currently looking at.
1639 for (var game_num = 0; game_num < current_games.length; ++game_num) {
1640 var game = current_games[game_num];
1641 if (game['url'] === backend_url) {
1642 var next_game_num = (game_num + 1) % current_games.length;
1643 switch_backend(current_games[next_game_num]);
1648 // Couldn't find it; give up.
1651 var update_historic_analysis = function() {
1652 if (!current_display_line_is_history) {
1655 if (current_display_move == current_display_line.pv.length - 1) {
1656 displayed_analysis_data = null;
1660 // Fetch old analysis for this line if it exists.
1661 var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pv, current_display_move);
1662 var filename = "/history/move" + (current_display_move + 1) + "-" +
1663 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1665 current_historic_xhr = $.ajax({
1667 }).done(function(data, textstatus, xhr) {
1668 displayed_analysis_data = data;
1670 }).fail(function(jqXHR, textStatus, errorThrown) {
1671 if (textStatus === "abort") {
1672 // Aborted because we are switching backends. Don't do anything;
1673 // we will already have been cleared.
1675 displayed_analysis_data = {'failed': true};
1682 * @param {string} fen
1684 var update_imbalance = function(fen) {
1685 var hiddenboard = new Chess(fen);
1686 var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1687 for (var row = 0; row < 8; ++row) {
1688 for (var col = 0; col < 8; ++col) {
1689 var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1690 var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1691 var square = col_text + row_text;
1692 var contents = hiddenboard.get(square);
1693 if (contents !== null) {
1694 if (contents.color === 'w') {
1695 ++imbalance[contents.type];
1697 --imbalance[contents.type];
1702 var white_imbalance = '';
1703 var black_imbalance = '';
1704 for (var piece in imbalance) {
1705 for (var i = 0; i < imbalance[piece]; ++i) {
1706 white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1708 for (var i = 0; i < -imbalance[piece]; ++i) {
1709 black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1712 $('#whiteimbalance').html(white_imbalance);
1713 $('#blackimbalance').html(black_imbalance);
1716 /** Mark the currently selected move in red.
1717 * Also replaces the PV with the current displayed line if it's not shown
1718 * anywhere else on the screen.
1720 var update_move_highlight = function() {
1721 if (highlighted_move !== null) {
1722 highlighted_move.removeClass('highlight');
1724 if (current_display_line) {
1725 var display_line_num = find_display_line_matching_num();
1726 if (display_line_num === null) {
1727 // Replace the PV with the (complete) line.
1728 $("#pvtitle").text("Exploring:");
1729 current_display_line.start_display_move_num = 0;
1730 display_lines.push(current_display_line);
1731 $("#pv").html(print_pv(display_lines.length - 1));
1732 display_line_num = display_lines.length - 1;
1734 // Clear out the PV, so it's not selected by anything later.
1735 display_lines[1].pv = [];
1738 highlighted_move = $("#automove" + display_line_num + "-" + (current_display_move - current_display_line.start_display_move_num));
1739 highlighted_move.addClass('highlight');
1744 * See if the current displayed line is identical to any of the ones
1745 * we have on screen. (It might not be if e.g. the analysis reloaded
1746 * since we started looking.)
1750 var find_display_line_matching_num = function() {
1751 for (var i = 0; i < display_lines.length; ++i) {
1752 var line = display_lines[i];
1753 if (line.start_display_move_num > 0) continue;
1754 if (current_display_line.start_fen !== line.start_fen) continue;
1755 if (current_display_line.pv.length !== line.pv.length) continue;
1757 for (var j = 0; j < line.pv.length; ++j) {
1758 if (current_display_line.pv[j] !== line.pv[j]) {
1770 /** Update the board based on the currently displayed line.
1772 * TODO: This should really be called only whenever something changes,
1773 * instead of all the time.
1775 var update_displayed_line = function() {
1776 if (current_display_line === null) {
1777 $("#linenav").hide();
1778 $("#linemsg").show();
1779 display_fen = base_fen;
1780 set_board_position(base_fen);
1781 update_imbalance(base_fen);
1785 $("#linenav").show();
1786 $("#linemsg").hide();
1788 if (current_display_move <= 0) {
1789 $("#prevmove").html("Previous");
1791 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1793 if (current_display_move == current_display_line.pv.length - 1) {
1794 $("#nextmove").html("Next");
1796 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1799 var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pv, current_display_move);
1800 set_board_position(hiddenboard.fen());
1801 if (display_fen !== hiddenboard.fen() && !current_display_line_is_history) {
1802 // Fire off a hash request, since we're now off the main position
1803 // and it just changed.
1804 explore_hash(hiddenboard.fen());
1806 display_fen = hiddenboard.fen();
1807 update_imbalance(hiddenboard.fen());
1810 var set_board_position = function(new_fen) {
1811 board_is_animating = true;
1812 var old_fen = board.fen();
1813 board.position(new_fen);
1814 if (board.fen() === old_fen) {
1815 board_is_animating = false;
1820 * @param {boolean} param_enable_sound
1822 var set_sound = function(param_enable_sound) {
1823 enable_sound = param_enable_sound;
1825 $("#soundon").html("<strong>On</strong>");
1826 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1828 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1829 // and also preload the file since the user has selected audio.
1830 var ding = document.getElementById('ding');
1831 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1832 ding.src = 'ding.opus';
1836 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1837 $("#soundoff").html("<strong>Off</strong>");
1839 if (supports_html5_storage()) {
1840 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1843 window['set_sound'] = set_sound;
1845 /** Send off a hash probe request to the backend.
1846 * @param {string} fen
1848 var explore_hash = function(fen) {
1849 // If we already have a backend response going, abort it.
1850 if (current_hash_xhr) {
1851 current_hash_xhr.abort();
1853 if (current_hash_display_timer) {
1854 clearTimeout(current_hash_display_timer);
1855 current_hash_display_timer = null;
1857 $("#refutationlines").empty();
1858 current_hash_xhr = $.ajax({
1859 url: backend_hash_url + "?fen=" + fen
1860 }).done(function(data, textstatus, xhr) {
1861 show_explore_hash_results(data, fen);
1865 /** Process the JSON response from a hash probe request.
1866 * @param {!Object} data
1867 * @param {string} fen
1869 var show_explore_hash_results = function(data, fen) {
1870 if (board_is_animating) {
1871 // Updating while the animation is still going causes
1872 // the animation to jerk. This is pretty crude, but it will do.
1873 current_hash_display_timer = setTimeout(function() { show_explore_hash_results(data, fen); }, 100);
1876 current_hash_display_timer = null;
1877 hash_refutation_lines = data['lines'];
1881 // almost all of this stuff comes from the chessboard.js example page
1882 var onDragStart = function(source, piece, position, orientation) {
1883 var pseudogame = new Chess(display_fen);
1884 if (pseudogame.game_over() === true ||
1885 (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
1886 (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
1890 recommended_move = get_best_move(pseudogame, source, null, pseudogame.turn() === 'b');
1891 if (recommended_move) {
1892 var squareEl = $('#board .square-' + recommended_move.to);
1893 squareEl.addClass('highlight1-32417');
1898 var mousedownSquare = function(e) {
1899 reverse_dragging_from = null;
1900 var square = $(this).attr('data-square');
1902 var pseudogame = new Chess(display_fen);
1903 if (pseudogame.game_over() === true) {
1907 // If the square is empty, or has a piece of the side not to move,
1908 // we handle it. If not, normal piece dragging will take it.
1909 var position = board.position();
1910 if (!position.hasOwnProperty(square) ||
1911 (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
1912 (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
1913 reverse_dragging_from = square;
1914 recommended_move = get_best_move(pseudogame, null, square, pseudogame.turn() === 'b');
1915 if (recommended_move) {
1916 var squareEl = $('#board .square-' + recommended_move.from);
1917 squareEl.addClass('highlight1-32417');
1918 squareEl = $('#board .square-' + recommended_move.to);
1919 squareEl.addClass('highlight1-32417');
1924 var mouseupSquare = function(e) {
1925 if (reverse_dragging_from === null) {
1928 var source = $(this).attr('data-square');
1929 var target = reverse_dragging_from;
1930 reverse_dragging_from = null;
1931 if (onDrop(source, target) !== 'snapback') {
1932 onSnapEnd(source, target);
1934 $("#board").find('.square-55d63').removeClass('highlight1-32417');
1937 var get_best_move = function(game, source, target, invert) {
1938 var moves = game.moves({ verbose: true });
1939 if (source !== null) {
1940 moves = moves.filter(function(move) { return move.from == source; });
1942 if (target !== null) {
1943 moves = moves.filter(function(move) { return move.to == target; });
1945 if (moves.length == 0) {
1948 if (moves.length == 1) {
1952 // More than one move. Use the display lines (if we have them)
1953 // to disambiguate; otherwise, we have no information.
1955 for (var i = 0; i < moves.length; ++i) {
1956 move_hash[moves[i].san] = moves[i];
1959 // See if we're already exploring some line.
1960 if (current_display_line &&
1961 current_display_move < current_display_line.pv.length - 1) {
1962 var first_move = current_display_line.pv[current_display_move + 1];
1963 if (move_hash[first_move]) {
1964 return move_hash[first_move];
1968 // History and PV take priority over the display lines.
1969 for (var i = 0; i < 2; ++i) {
1970 var line = display_lines[i];
1971 var first_move = line.pv[line.start_display_move_num];
1972 if (move_hash[first_move]) {
1973 return move_hash[first_move];
1977 var best_move = null;
1978 var best_move_score = null;
1980 for (var move in refutation_lines) {
1981 var line = refutation_lines[move];
1982 if (!line['score']) {
1985 var first_move = line['pv'][0];
1986 if (move_hash[first_move]) {
1987 var score = compute_score_sort_key(line['score'], line['depth'], invert);
1988 if (best_move_score === null || score > best_move_score) {
1989 best_move = move_hash[first_move];
1990 best_move_score = score;
1997 var onDrop = function(source, target) {
1998 if (source === target) {
1999 if (recommended_move === null) {
2002 // Accept the move. It will be changed in onSnapEnd.
2006 // Suggestion not asked for.
2007 recommended_move = null;
2010 // see if the move is legal
2011 var pseudogame = new Chess(display_fen);
2012 var move = pseudogame.move({
2015 promotion: 'q' // NOTE: always promote to a queen for example simplicity
2019 if (move === null) return 'snapback';
2022 var onSnapEnd = function(source, target) {
2023 if (source === target && recommended_move !== null) {
2024 source = recommended_move.from;
2025 target = recommended_move.to;
2027 recommended_move = null;
2028 var pseudogame = new Chess(display_fen);
2029 var move = pseudogame.move({
2032 promotion: 'q' // NOTE: always promote to a queen for example simplicity
2035 if (current_display_line &&
2036 current_display_move < current_display_line.pv.length - 1 &&
2037 current_display_line.pv[current_display_move + 1] === move.san) {
2042 // Walk down the displayed lines until we find one that starts with
2043 // this move, then select that. Note that this gives us a good priority
2044 // order (history first, then PV, then multi-PV lines).
2045 for (var i = 0; i < display_lines.length; ++i) {
2046 if (i == 1 && current_display_line) {
2047 // Do not choose PV if not on it.
2050 var line = display_lines[i];
2051 if (line.pv[line.start_display_move_num] === move.san) {
2057 // Shouldn't really be here if we have hash probes, but there's really
2058 // nothing we can do.
2060 // End of dragging-related code.
2062 var fmt_cp = function(v) {
2066 return "+" + (v / 100).toFixed(2);
2069 return "-" + (v / 100).toFixed(2);
2073 var format_short_score = function(score) {
2077 if (score[0] === 'm') {
2078 if (score[2]) { // Is a bound.
2079 return score[2] + "\u00a0M " + score[1];
2081 return "M " + score[1];
2083 } else if (score[0] === 'd') {
2085 } else if (score[0] === 'cp') {
2086 if (score[2]) { // Is a bound.
2087 return score[2] + "\u00a0" + fmt_cp(score[1]);
2089 return fmt_cp(score[1]);
2095 var format_long_score = function(score) {
2099 if (score[0] === 'm') {
2101 return "White mates in " + score[1];
2103 return "Black mates in " + (-score[1]);
2105 } else if (score[0] === 'd') {
2106 return "Theoretical draw";
2107 } else if (score[0] === 'cp') {
2108 return "Score: " + format_short_score(score);
2113 var compute_plot_score = function(score) {
2114 if (score[0] === 'm') {
2120 } else if (score[0] === 'd') {
2122 } else if (score[0] === 'cp') {
2123 if (score[1] > 500) {
2125 } else if (score[1] < -500) {
2135 * @param score The score digest tuple.
2136 * @param {?number} depth Depth the move has been computed to, or null.
2137 * @param {boolean} invert Whether black is to play.
2138 * @param {boolean=} depth_secondary_key
2141 var compute_score_sort_key = function(score, depth, invert, depth_secondary_key) {
2146 if (score[0] === 'm') {
2149 s = 99999 - score[1];
2151 // Black mates (note the double negative for score[1]).
2152 s = -99999 - score[1];
2154 } else if (score[0] === 'd') {
2156 } else if (score[0] === 'cp') {
2161 if (depth_secondary_key) {
2162 return s * 200 + (depth || 0);
2172 * @param {Object} game
2174 var switch_backend = function(game) {
2175 // Stop looking at historic data.
2176 current_display_line = null;
2177 current_display_move = null;
2178 displayed_analysis_data = null;
2179 if (current_historic_xhr) {
2180 current_historic_xhr.abort();
2183 // If we already have a backend response going, abort it.
2184 if (current_analysis_xhr) {
2185 current_analysis_xhr.abort();
2187 if (current_hash_xhr) {
2188 current_hash_xhr.abort();
2191 // Otherwise, we should have a timer going to start a new one.
2193 if (current_analysis_request_timer) {
2194 clearTimeout(current_analysis_request_timer);
2195 current_analysis_request_timer = null;
2197 if (current_hash_display_timer) {
2198 clearTimeout(current_hash_display_timer);
2199 current_hash_display_timer = null;
2202 // Request an immediate fetch with the new backend.
2203 backend_url = game['url'];
2204 backend_hash_url = game['hashurl'];
2205 window.location.hash = '#' + game['id'];
2206 current_analysis_data = null;
2210 window['switch_backend'] = switch_backend;
2212 window['flip'] = function() { board.flip(); redraw_arrows(); };
2214 var init = function() {
2215 unique = get_unique();
2217 // Load settings from HTML5 local storage if available.
2218 if (supports_html5_storage() && localStorage['enable_sound']) {
2219 set_sound(parseInt(localStorage['enable_sound']));
2225 board = new window.ChessBoard('board', {
2226 onMoveEnd: function() { board_is_animating = false; },
2229 onDragStart: onDragStart,
2231 onSnapEnd: onSnapEnd
2233 $("#board").on('mousedown', '.square-55d63', mousedownSquare);
2234 $("#board").on('mouseup', '.square-55d63', mouseupSquare);
2237 $(window).resize(function() {
2239 update_sparkline(displayed_analysis_data || current_analysis_data);
2240 update_board_highlight();
2243 $(window).keyup(function(event) {
2244 if (event.which == 39) { // Left arrow.
2246 } else if (event.which == 37) { // Right arrow.
2248 } else if (event.which >= 49 && event.which <= 57) { // 1-9.
2249 var num = event.which - 49;
2250 if (current_games && current_games.length >= num) {
2251 switch_backend(current_games[num]);
2253 } else if (event.which == 78) { // N.
2257 window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
2258 possibly_switch_game_from_hash();
2260 $(document).ready(init);