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 = 2015062104;
13 * The current backend URL.
18 var backend_url = "/analysis.pl";
20 /** @type {window.ChessBoard} @private */
24 * The most recent analysis data we have from the server
25 * (about the most recent position).
29 var current_analysis_data = null;
32 * If we are displaying previous analysis, this is non-null,
33 * and will override most of current_analysis_data.
38 var displayed_analysis_data = null;
41 * Games currently in progress, if any.
50 var current_games = null;
65 /** @type {Array.<Array.<boolean>>} */
66 var occupied_by_arrows = [];
68 var refutation_lines = [];
70 /** @type {!number} @private */
73 /** @type {!string} @private */
76 /** @type {number} @private */
79 /** @type {boolean} @private */
80 var sort_refutation_lines_by_score = true;
82 /** @type {boolean} @private */
83 var truncate_display_history = true;
85 /** @type {!string|undefined} @private */
86 var highlight_from = undefined;
88 /** @type {!string|undefined} @private */
89 var highlight_to = undefined;
91 /** The HTML object of the move currently being highlighted (in red).
94 var highlighted_move = null;
96 /** @type {?number} @private */
99 /** @type {boolean} @private */
100 var enable_sound = false;
103 * Our best estimate of how many milliseconds we need to add to
104 * new Date() to get the true UTC time. Calibrated against the
110 var client_clock_offset_ms = null;
112 var clock_timer = null;
114 /** The current position on the board, represented as a FEN string.
122 * uci_pv: Array.<string>,
123 * pretty_pv: Array.<string>,
128 /** All PVs that we currently know of.
130 * Element 0 is history (or null if no history).
131 * Element 1 is current main PV.
132 * All remaining elements are refutation lines (multi-PV).
134 * @type {Array.<DisplayLine>}
137 var display_lines = [];
139 /** @type {?DisplayLine} @private */
140 var current_display_line = null;
142 /** @type {boolean} @private */
143 var current_display_line_is_history = false;
145 /** @type {?number} @private */
146 var current_display_move = null;
149 * The current backend request to get main analysis (not history), if any,
150 * so that we can abort it.
155 var current_analysis_xhr = null;
158 * The current timer to fire off a request to get main analysis (not history),
159 * if any, so that we can abort it.
164 var current_analysis_request_timer = null;
167 * The current backend request to get historic data, if any.
172 var current_historic_xhr = null;
174 var supports_html5_storage = function() {
176 return 'localStorage' in window && window['localStorage'] !== null;
182 // Make the unique token persistent so people refreshing the page won't count twice.
183 // Of course, you can never fully protect against people deliberately wanting to spam.
184 var get_unique = function() {
185 var use_local_storage = supports_html5_storage();
186 if (use_local_storage && localStorage['unique']) {
187 return localStorage['unique'];
189 var unique = Math.random();
190 if (use_local_storage) {
191 localStorage['unique'] = unique;
196 var request_update = function() {
197 current_analysis_request_timer = null;
199 current_analysis_xhr = $.ajax({
200 url: backend_url + "?ims=" + ims + "&unique=" + unique
201 }).done(function(data, textstatus, xhr) {
202 sync_server_clock(xhr.getResponseHeader('Date'));
203 ims = xhr.getResponseHeader('X-RGLM');
204 var num_viewers = xhr.getResponseHeader('X-RGNV');
206 if (Array.isArray(data)) {
207 new_data = JSON.parse(JSON.stringify(current_analysis_data));
208 JSON_delta.patch(new_data, data);
213 var minimum_version = xhr.getResponseHeader('X-RGMV');
214 if (minimum_version && minimum_version > SCRIPT_VERSION) {
215 // Upgrade to latest version with a force-reload.
216 location.reload(true);
219 possibly_play_sound(current_analysis_data, new_data);
220 current_analysis_data = new_data;
221 update_board(current_analysis_data, displayed_analysis_data);
222 update_num_viewers(num_viewers);
225 current_analysis_request_timer = setTimeout(function() { request_update(); }, 100);
226 }).fail(function(jqXHR, textStatus, errorThrown) {
227 if (textStatus === "abort") {
228 // Aborted because we are switching backends. Abandon and don't retry,
229 // because another one is already started for us.
231 // Backend error or similar. Wait ten seconds, then try again.
232 current_analysis_request_timer = setTimeout(function() { request_update(); }, 10000);
237 var possibly_play_sound = function(old_data, new_data) {
241 if (old_data === null) {
244 var ding = document.getElementById('ding');
245 if (ding && ding.play) {
246 if (old_data['position'] && old_data['position']['fen'] &&
247 new_data['position'] && new_data['position']['fen'] &&
248 (old_data['position']['fen'] !== new_data['position']['fen'] ||
249 old_data['position']['move_num'] !== new_data['position']['move_num'])) {
256 * @type {!string} server_date_string
258 var sync_server_clock = function(server_date_string) {
259 var server_time_ms = new Date(server_date_string).getTime();
260 var client_time_ms = new Date().getTime();
261 var estimated_offset_ms = server_time_ms - client_time_ms;
263 // In order not to let the noise move us too much back and forth
264 // (the server only has one-second resolution anyway), we only
265 // change an existing skew if we are at least five seconds off.
266 if (client_clock_offset_ms === null ||
267 Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
268 client_clock_offset_ms = estimated_offset_ms;
272 var clear_arrows = function() {
273 for (var i = 0; i < arrows.length; ++i) {
275 if (arrows[i].svg.parentElement) {
276 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
278 delete arrows[i].svg;
283 occupied_by_arrows = [];
284 for (var y = 0; y < 8; ++y) {
285 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
289 var redraw_arrows = function() {
290 for (var i = 0; i < arrows.length; ++i) {
291 position_arrow(arrows[i]);
295 /** @param {!number} x
298 var sign = function(x) {
308 /** See if drawing this arrow on the board would cause unduly amount of confusion.
309 * @param {!string} from The square the arrow is from (e.g. e4).
310 * @param {!string} to The square the arrow is to (e.g. e4).
313 var interfering_arrow = function(from, to) {
314 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
315 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
316 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
317 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
319 occupied_by_arrows[from_row][from_col] = true;
321 // Knight move: Just check that we haven't been at the destination before.
322 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
323 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
324 return occupied_by_arrows[to_row][to_col];
327 // Sliding piece: Check if anything except the from-square is seen before.
328 var dx = sign(to_col - from_col);
329 var dy = sign(to_row - from_row);
335 if (occupied_by_arrows[y][x]) {
338 occupied_by_arrows[y][x] = true;
339 } while (x != to_col || y != to_row);
344 /** Find a point along the coordinate system given by the given line,
345 * <t> units forward from the start of the line, <u> units to the right of it.
346 * @param {!number} x1
347 * @param {!number} x2
348 * @param {!number} y1
349 * @param {!number} y2
352 * @return {!string} The point in "x y" form, suitable for SVG paths.
354 var point_from_start = function(x1, y1, x2, y2, t, u) {
358 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
362 var x = x1 + dx * t + dy * u;
363 var y = y1 + dy * t - dx * u;
367 /** Find a point along the coordinate system given by the given line,
368 * <t> units forward from the end of the line, <u> units to the right of it.
369 * @param {!number} x1
370 * @param {!number} x2
371 * @param {!number} y1
372 * @param {!number} y2
375 * @return {!string} The point in "x y" form, suitable for SVG paths.
377 var point_from_end = function(x1, y1, x2, y2, t, u) {
381 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
385 var x = x2 + dx * t + dy * u;
386 var y = y2 + dy * t - dx * u;
390 var position_arrow = function(arrow) {
392 if (arrow.svg.parentElement) {
393 arrow.svg.parentElement.removeChild(arrow.svg);
397 if (current_display_line !== null && !current_display_line_is_history) {
401 var pos = $(".square-a8").position();
403 var zoom_factor = $("#board").width() / 400.0;
404 var line_width = arrow.line_width * zoom_factor;
405 var arrow_size = arrow.arrow_size * zoom_factor;
407 var square_width = $(".square-a8").width();
408 var from_y = (7 - arrow.from_row + 0.5)*square_width;
409 var to_y = (7 - arrow.to_row + 0.5)*square_width;
410 var from_x = (arrow.from_col + 0.5)*square_width;
411 var to_x = (arrow.to_col + 0.5)*square_width;
413 var SVG_NS = "http://www.w3.org/2000/svg";
414 var XHTML_NS = "http://www.w3.org/1999/xhtml";
415 var svg = document.createElementNS(SVG_NS, "svg");
416 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
417 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
418 svg.setAttribute("style", "position: absolute");
419 svg.setAttribute("position", "absolute");
420 svg.setAttribute("version", "1.1");
421 svg.setAttribute("class", "c1");
422 svg.setAttribute("xmlns", XHTML_NS);
430 var outline = document.createElementNS(SVG_NS, "path");
431 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));
432 outline.setAttribute("xmlns", XHTML_NS);
433 outline.setAttribute("stroke", "#666");
434 outline.setAttribute("stroke-width", line_width + 2);
435 outline.setAttribute("fill", "none");
436 svg.appendChild(outline);
438 var path = document.createElementNS(SVG_NS, "path");
439 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));
440 path.setAttribute("xmlns", XHTML_NS);
441 path.setAttribute("stroke", arrow.fg_color);
442 path.setAttribute("stroke-width", line_width);
443 path.setAttribute("fill", "none");
444 svg.appendChild(path);
446 // Then the arrow head.
447 var head = document.createElementNS(SVG_NS, "path");
448 head.setAttribute("d",
449 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
450 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
451 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
452 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
453 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
454 head.setAttribute("xmlns", XHTML_NS);
455 head.setAttribute("stroke", "#000");
456 head.setAttribute("stroke-width", "1");
457 head.setAttribute("fill", arrow.fg_color);
458 svg.appendChild(head);
460 $(svg).css({ top: pos.top, left: pos.left });
461 document.body.appendChild(svg);
466 * @param {!string} from_square
467 * @param {!string} to_square
468 * @param {!string} fg_color
469 * @param {number} line_width
470 * @param {number} arrow_size
472 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
473 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
474 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
475 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
476 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
484 line_width: line_width,
485 arrow_size: arrow_size,
489 position_arrow(arrow);
493 var compare_by_sort_key = function(refutation_lines, a, b) {
494 var ska = refutation_lines[a]['sort_key'];
495 var skb = refutation_lines[b]['sort_key'];
496 if (ska < skb) return -1;
497 if (ska > skb) return 1;
501 var compare_by_score = function(refutation_lines, a, b) {
502 var sa = parseInt(refutation_lines[b]['score_sort_key'], 10);
503 var sb = parseInt(refutation_lines[a]['score_sort_key'], 10);
508 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
509 * sorted by quality, descending.
511 * @param {!Object} data
512 * @param {number} margin The maximum number of centipawns worse than the
513 * best move can be and still be included.
514 * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
515 * moves, in score order.
517 var find_nonstupid_moves = function(data, margin) {
518 // First of all, if there are any moves that are more than 0.5 ahead of
519 // the primary move, the refutation lines are probably bunk, so just
521 var best_score = undefined;
522 var pv_score = undefined;
523 for (var move in data['refutation_lines']) {
524 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
525 if (move == data['pv_uci'][0]) {
528 if (best_score === undefined || score > best_score) {
531 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
536 if (best_score - pv_score > 50) {
540 // Now find all moves that are within “margin” of the best score.
541 // The PV move will always be first.
543 for (var move in data['refutation_lines']) {
544 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
545 if (move != data['pv_uci'][0] && best_score - score <= margin) {
549 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], a, b) });
550 moves.unshift(data['pv_uci'][0]);
559 var thousands = function(x) {
560 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
564 * @param {!string} fen
565 * @param {Array.<string>} pretty_pv
566 * @param {number} move_num
567 * @param {!string} toplay
568 * @param {number=} opt_limit
569 * @param {boolean=} opt_showlast
571 var add_pv = function(fen, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
574 pretty_pv: pretty_pv,
575 line_number: display_lines.length
577 return print_pv(display_lines.length - 1, pretty_pv, move_num, toplay, opt_limit, opt_showlast);
581 * @param {number} line_num
582 * @param {Array.<string>} pretty_pv
583 * @param {number} move_num
584 * @param {!string} toplay
585 * @param {number=} opt_limit
586 * @param {boolean=} opt_showlast
588 var print_pv = function(line_num, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
591 if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
592 // Truncate the PV at the beginning (instead of at the end).
593 // We assume here that toplay is 'W'. We also assume that if
594 // opt_showlast is set, then it is the history, and thus,
595 // the UI should be to expand the history.
596 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
597 i = pretty_pv.length - opt_limit;
602 } else if (toplay == 'B' && pretty_pv.length > 0) {
603 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
604 pv = move_num + '. … ' + move;
609 for ( ; i < pretty_pv.length; ++i) {
610 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
613 if (i > opt_limit && !opt_showlast) {
619 pv += move_num + '. ' + move;
630 /** Update the highlighted to/from squares on the board.
631 * Based on the global "highlight_from" and "highlight_to" variables.
633 var update_board_highlight = function() {
634 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
635 if ((current_display_line === null || current_display_line_is_history) &&
636 highlight_from !== undefined && highlight_to !== undefined) {
637 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
638 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
642 var update_history = function() {
643 if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
644 $("#history").html("No history");
645 } else if (truncate_display_history) {
646 $("#history").html(print_pv(0, display_lines[0].pretty_pv, 1, 'W', 8, true));
649 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
650 print_pv(0, display_lines[0].pretty_pv, 1, 'W'));
655 * @param {!boolean} truncate_history
657 var collapse_history = function(truncate_history) {
658 truncate_display_history = truncate_history;
661 window['collapse_history'] = collapse_history;
663 /** Update the HTML display of multi-PV from the global "refutation_lines".
665 * Also recreates the global "display_lines".
667 var update_refutation_lines = function() {
671 if (display_lines.length > 2) {
672 // Truncate so that only the history and PV is left.
673 display_lines = [ display_lines[0], display_lines[1] ];
676 var tbl = $("#refutationlines");
680 for (var move in refutation_lines) {
683 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
684 moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
685 for (var i = 0; i < moves.length; ++i) {
686 var line = refutation_lines[moves[i]];
688 var tr = document.createElement("tr");
690 var move_td = document.createElement("td");
691 tr.appendChild(move_td);
692 $(move_td).addClass("move");
693 if (line['pv_pretty'].length == 0) {
694 $(move_td).text(line['pretty_move']);
696 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
697 $(move_td).html(move);
700 var score_td = document.createElement("td");
701 tr.appendChild(score_td);
702 $(score_td).addClass("score");
703 $(score_td).text(line['pretty_score']);
705 var depth_td = document.createElement("td");
706 tr.appendChild(depth_td);
707 $(depth_td).addClass("depth");
708 $(depth_td).text("d" + line['depth']);
710 var pv_td = document.createElement("td");
711 tr.appendChild(pv_td);
712 $(pv_td).addClass("pv");
713 $(pv_td).html(add_pv(fen, line['pv_pretty'], move_num, toplay, 10));
718 // Make one of the links clickable and the other nonclickable.
719 if (sort_refutation_lines_by_score) {
720 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
721 $("#sortbyscore1").html("<strong>Score</strong>");
723 $("#sortbyscore0").html("<strong>Move</strong>");
724 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
729 * Create a Chess.js board object, containing the given position plus the given moves,
730 * up to the given limit.
732 * @param {?string} fen
733 * @param {Array.<string>} moves
734 * @param {number} last_move
736 var chess_from = function(fen, moves, last_move) {
737 var hiddenboard = new Chess();
739 hiddenboard.load(fen);
741 for (var i = 0; i <= last_move; ++i) {
742 if (moves[i] === '0-0') {
743 hiddenboard.move('O-O');
744 } else if (moves[i] === '0-0-0') {
745 hiddenboard.move('O-O-O');
747 hiddenboard.move(moves[i]);
753 var update_game_list = function(games) {
754 $("#games").text("");
755 if (games === null) {
759 var games_div = document.getElementById('games');
760 for (var game_num = 0; game_num < games.length; ++game_num) {
761 var game = games[game_num];
762 var game_span = document.createElement("span");
763 game_span.setAttribute("class", "game");
765 var game_name = document.createTextNode(game['name']);
766 if (game['url'] === backend_url) {
767 game_span.appendChild(game_name);
769 var game_a = document.createElement("a");
770 game_a.setAttribute("href", "#" + game['id']);
771 game_a.appendChild(game_name);
772 game_span.appendChild(game_a);
774 games_div.appendChild(game_span);
779 * Try to find a running game that matches with the current hash,
780 * and switch to it if we're not already displaying it.
782 var possibly_switch_game_from_hash = function() {
783 if (current_games === null) {
787 var hash = window.location.hash.replace(/^#/,'');
788 for (var i = 0; i < current_games.length; ++i) {
789 if (current_games[i]['id'] === hash) {
790 if (backend_url !== current_games[i]['url']) {
791 switch_backend(current_games[i]['url']);
799 * @param {Object} data
800 * @param {?Object} display_data
802 var update_board = function(current_data, display_data) {
803 var data = display_data || current_data;
807 // Print the history. This is pretty much the only thing that's
808 // unconditionally taken from current_data (we're not interested in
809 // historic history).
810 if (current_data['position']['pretty_history']) {
811 add_pv('start', current_data['position']['pretty_history'], 1, 'W', 8, true);
813 display_lines.push(null);
817 // Games currently in progress, if any.
818 if (current_data['games']) {
819 current_games = current_data['games'];
820 possibly_switch_game_from_hash();
821 update_game_list(current_data['games']);
823 current_games = null;
824 update_game_list(null);
827 // The headline. Names are always fetched from current_data;
828 // the rest can depend a bit.
831 current_data['position']['player_w'] && current_data['position']['player_b']) {
832 headline = current_data['position']['player_w'] + '–' +
833 current_data['position']['player_b'] + ', analysis';
835 headline = 'Analysis';
838 // Credits, where applicable. Note that we don't want the footer to change a lot
839 // when e.g. viewing history, so if any of these changed during the game,
840 // use the current one still.
841 if (current_data['using_lomonosov']) {
842 $("#lomonosov").show();
844 $("#lomonosov").hide();
847 // Credits: The engine name/version.
848 if (current_data['engine'] && current_data['engine']['name'] !== null) {
849 $("#engineid").text(current_data['engine']['name']);
852 // Credits: The engine URL.
853 if (current_data['engine'] && current_data['engine']['url']) {
854 $("#engineid").attr("href", current_data['engine']['url']);
856 $("#engineid").removeAttr("href");
859 // Credits: Engine details.
860 if (current_data['engine'] && current_data['engine']['details']) {
861 $("#enginedetails").text(" (" + current_data['engine']['details'] + ")");
863 $("#enginedetails").text("");
866 // Credits: Move source, possibly with URL.
867 if (current_data['move_source'] && current_data['move_source_url']) {
868 $("#movesource").text("Moves provided by ");
869 var movesource_a = document.createElement("a");
870 movesource_a.setAttribute("href", current_data['move_source_url']);
871 var movesource_text = document.createTextNode(current_data['move_source']);
872 movesource_a.appendChild(movesource_text);
873 var movesource_period = document.createTextNode(".");
874 document.getElementById("movesource").appendChild(movesource_a);
875 document.getElementById("movesource").appendChild(movesource_period);
876 } else if (current_data['move_source']) {
877 $("#movesource").text("Moves provided by " + current_data['move_source'] + ".");
879 $("#movesource").text("");
884 // Displaying some non-current position, pick out the last move
885 // from the history. This will work even if the fetch failed.
886 last_move = format_halfmove_with_number(
887 current_display_line.pretty_pv[current_display_move],
888 current_display_move + 1);
889 headline += ' after ' + last_move;
890 } else if (data['position']['last_move'] !== 'none') {
891 last_move = format_move_with_number(
892 data['position']['last_move'],
893 data['position']['move_num'],
894 data['position']['toplay'] == 'W');
895 headline += ' after ' + last_move;
899 $("#headline").text(headline);
901 // The <title> contains a very brief headline.
902 var title_elems = [];
903 if (data['short_score'] !== undefined && data['short_score'] !== null) {
904 title_elems.push(data['short_score'].replace(/^ /, ""));
906 if (last_move !== null) {
907 title_elems.push(last_move);
910 if (title_elems.length != 0) {
911 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
913 document.title = 'analysis.sesse.net';
916 // The last move (shown by highlighting the from and to squares).
917 if (data['position'] && data['position']['last_move_uci']) {
918 highlight_from = data['position']['last_move_uci'].substr(0, 2);
919 highlight_to = data['position']['last_move_uci'].substr(2, 2);
920 } else if (current_display_line_is_history && current_display_move >= 0) {
921 // We don't have historic analysis for this position, but we
922 // can reconstruct what the last move was by just replaying
924 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
925 var moves = hiddenboard.history({ verbose: true });
926 var last_move = moves.pop();
927 highlight_from = last_move.from;
928 highlight_to = last_move.to;
930 highlight_from = highlight_to = undefined;
932 update_board_highlight();
934 if (data['failed']) {
935 $("#score").text("No analysis for this move");
937 $("#searchstats").html(" ");
938 $("#refutationlines").empty();
939 $("#whiteclock").empty();
940 $("#blackclock").empty();
941 refutation_lines = [];
942 update_refutation_lines();
944 update_displayed_line();
945 update_move_highlight();
952 if (data['score'] !== null) {
953 $("#score").text(data['score']);
957 if (data['tablebase'] == 1) {
958 $("#searchstats").text("Tablebase result");
959 } else if (data['nodes'] && data['nps'] && data['depth']) {
960 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
961 if (data['seldepth']) {
962 stats += ' (' + data['seldepth'] + ' selective)';
964 if (data['tbhits'] && data['tbhits'] > 0) {
965 if (data['tbhits'] == 1) {
966 stats += ', one Syzygy hit';
968 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
972 $("#searchstats").text(stats);
974 $("#searchstats").text("");
977 // Update the board itself.
978 fen = data['position']['fen'];
979 update_displayed_line();
980 update_move_highlight();
983 $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
985 // Update the PV arrow.
987 if (data['pv_uci'].length >= 1) {
988 // draw a continuation arrow as long as it's the same piece
989 for (var i = 0; i < data['pv_uci'].length; i += 2) {
990 var from = data['pv_uci'][i].substr(0, 2);
991 var to = data['pv_uci'][i].substr(2,4);
992 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
993 interfering_arrow(from, to)) {
996 create_arrow(from, to, '#f66', 6, 20);
999 var alt_moves = find_nonstupid_moves(data, 30);
1000 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
1001 create_arrow(alt_moves[i].substr(0, 2),
1002 alt_moves[i].substr(2, 2), '#f66', 1, 10);
1006 // See if all semi-reasonable moves have only one possible response.
1007 if (data['pv_uci'].length >= 2) {
1008 var nonstupid_moves = find_nonstupid_moves(data, 300);
1009 var response = data['pv_uci'][1];
1010 for (var i = 0; i < nonstupid_moves.length; ++i) {
1011 if (nonstupid_moves[i] == data['pv_uci'][0]) {
1012 // ignore the PV move for refutation lines.
1015 if (!data['refutation_lines'] ||
1016 !data['refutation_lines'][nonstupid_moves[i]] ||
1017 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
1018 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
1019 // Incomplete PV, abort.
1020 response = undefined;
1023 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
1024 if (response !== this_response) {
1025 // Different response depending on lines, abort.
1026 response = undefined;
1031 if (nonstupid_moves.length > 0 && response !== undefined) {
1032 create_arrow(response.substr(0, 2),
1033 response.substr(2, 2), '#66f', 6, 20);
1037 // Update the refutation lines.
1038 fen = data['position']['fen'];
1039 move_num = data['position']['move_num'];
1040 toplay = data['position']['toplay'];
1041 refutation_lines = data['refutation_lines'];
1042 update_refutation_lines();
1044 // Update the sparkline last, since its size depends on how everything else reflowed.
1045 update_sparkline(data);
1048 var update_sparkline = function(data) {
1049 if (data && data['score_history']) {
1050 var first_move_num = undefined;
1051 for (var halfmove_num in data['score_history']) {
1052 halfmove_num = parseInt(halfmove_num);
1053 if (first_move_num === undefined || halfmove_num < first_move_num) {
1054 first_move_num = halfmove_num;
1057 if (first_move_num !== undefined) {
1058 var last_move_num = data['position']['move_num'] * 2 - 3;
1059 if (data['position']['toplay'] === 'B') {
1063 // Possibly truncate some moves if we don't have enough width.
1064 // FIXME: Sometimes width() for #scorecontainer (and by extent,
1065 // #scoresparkcontainer) on Chrome for mobile seems to start off
1066 // at something very small, and then suddenly snap back into place.
1068 var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
1069 if (last_move_num - first_move_num > max_moves) {
1070 first_move_num = last_move_num - max_moves;
1073 var min_score = -100;
1074 var max_score = 100;
1075 var last_score = null;
1077 for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1078 if (data['score_history'][halfmove_num]) {
1079 var score = data['score_history'][halfmove_num][0];
1080 if (score < min_score) min_score = score;
1081 if (score > max_score) max_score = score;
1082 last_score = data['score_history'][halfmove_num][0];
1084 scores.push(last_score);
1086 if (data['plot_score']) {
1087 scores.push(data['plot_score']);
1089 // FIXME: at some widths, calling sparkline() seems to push
1090 // #scorecontainer under the board.
1091 $("#scorespark").sparkline(scores, {
1094 chartRangeMin: min_score,
1095 chartRangeMax: max_score,
1096 tooltipFormatter: function(sparkline, options, fields) {
1097 return format_tooltip(data, fields[0].offset + first_move_num);
1101 $("#scorespark").text("");
1104 $("#scorespark").text("");
1109 * @param {number} num_viewers
1111 var update_num_viewers = function(num_viewers) {
1112 if (num_viewers === null) {
1113 $("#numviewers").text("");
1114 } else if (num_viewers == 1) {
1115 $("#numviewers").text("You are the only current viewer");
1117 $("#numviewers").text(num_viewers + " current viewers");
1121 var update_clock = function() {
1122 clearTimeout(clock_timer);
1124 var data = displayed_analysis_data || current_analysis_data;
1125 if (data['position']) {
1126 var result = data['position']['result'];
1127 if (result === '1-0') {
1128 $("#whiteclock").text("1");
1129 $("#blackclock").text("0");
1130 $("#whiteclock").removeClass("running-clock");
1131 $("#blackclock").removeClass("running-clock");
1134 if (result === '1/2-1/2') {
1135 $("#whiteclock").text("1/2");
1136 $("#blackclock").text("1/2");
1137 $("#whiteclock").removeClass("running-clock");
1138 $("#blackclock").removeClass("running-clock");
1141 if (result === '0-1') {
1142 $("#whiteclock").text("0");
1143 $("#blackclock").text("1");
1144 $("#whiteclock").removeClass("running-clock");
1145 $("#blackclock").removeClass("running-clock");
1150 var white_clock_ms = null;
1151 var black_clock_ms = null;
1152 var show_seconds = false;
1155 if (data['position'] &&
1156 data['position']['white_clock'] &&
1157 data['position']['black_clock']) {
1158 white_clock_ms = data['position']['white_clock'] * 1000;
1159 black_clock_ms = data['position']['black_clock'] * 1000;
1162 // Dynamic clock (only one, obviously).
1164 if (data['position']['white_clock_target']) {
1166 $("#whiteclock").addClass("running-clock");
1167 $("#blackclock").removeClass("running-clock");
1168 } else if (data['position']['black_clock_target']) {
1170 $("#whiteclock").removeClass("running-clock");
1171 $("#blackclock").addClass("running-clock");
1173 $("#whiteclock").removeClass("running-clock");
1174 $("#blackclock").removeClass("running-clock");
1178 var now = new Date().getTime() + client_clock_offset_ms;
1179 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1180 if (color === "white") {
1181 white_clock_ms = remaining_ms;
1183 black_clock_ms = remaining_ms;
1187 if (white_clock_ms === null || black_clock_ms === null) {
1188 $("#whiteclock").empty();
1189 $("#blackclock").empty();
1193 // If either player has ten minutes or less left, add the second counters.
1194 var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
1197 // See when the clock will change next, and update right after that.
1200 next_update_ms = remaining_ms % 1000 + 100;
1202 next_update_ms = remaining_ms % 60000 + 100;
1204 clock_timer = setTimeout(update_clock, next_update_ms);
1207 $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1208 $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1212 * @param {Number} remaining_ms
1213 * @param {boolean} show_seconds
1215 var format_clock = function(remaining_ms, show_seconds) {
1216 if (remaining_ms <= 0) {
1224 var remaining = Math.floor(remaining_ms / 1000);
1225 var seconds = remaining % 60;
1226 remaining = (remaining - seconds) / 60;
1227 var minutes = remaining % 60;
1228 remaining = (remaining - minutes) / 60;
1229 var hours = remaining;
1231 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1233 return format_2d(hours) + ":" + format_2d(minutes);
1240 var format_2d = function(x) {
1249 * @param {string} move
1250 * @param {Number} move_num
1251 * @param {boolean} white_to_play
1253 var format_move_with_number = function(move, move_num, white_to_play) {
1255 if (white_to_play) {
1256 ret = (move_num - 1) + '… ';
1258 ret = move_num + '. ';
1265 * @param {string} move
1266 * @param {Number} halfmove_num
1268 var format_halfmove_with_number = function(move, halfmove_num) {
1269 return format_move_with_number(
1271 Math.floor(halfmove_num / 2) + 1,
1272 halfmove_num % 2 == 0);
1276 * @param {Object} data
1277 * @param {Number} halfmove_num
1279 var format_tooltip = function(data, halfmove_num) {
1280 if (data['score_history'][halfmove_num] ||
1281 halfmove_num === data['position']['pretty_history'].length) {
1284 if (halfmove_num === data['position']['pretty_history'].length) {
1285 move = data['position']['last_move'];
1286 short_score = data['short_score'];
1288 move = data['position']['pretty_history'][halfmove_num];
1289 short_score = data['score_history'][halfmove_num][1];
1291 var move_with_number = format_halfmove_with_number(move, halfmove_num);
1293 return "After " + move_with_number + ": " + short_score;
1295 for (var i = halfmove_num; i --> 0; ) {
1296 if (data['score_history'][i]) {
1297 var move = data['position']['pretty_history'][i];
1298 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1305 * @param {boolean} sort_by_score
1307 var resort_refutation_lines = function(sort_by_score) {
1308 sort_refutation_lines_by_score = sort_by_score;
1309 if (supports_html5_storage()) {
1310 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1312 update_refutation_lines();
1314 window['resort_refutation_lines'] = resort_refutation_lines;
1317 * @param {boolean} truncate_history
1319 var set_truncate_history = function(truncate_history) {
1320 truncate_display_history = truncate_history;
1321 update_refutation_lines();
1323 window['set_truncate_history'] = set_truncate_history;
1326 * @param {number} line_num
1327 * @param {number} move_num
1329 var show_line = function(line_num, move_num) {
1330 if (line_num == -1) {
1331 current_display_line = null;
1332 current_display_move = null;
1333 if (displayed_analysis_data) {
1334 // TODO: Support exiting to history position if we are in an
1335 // analysis line of a history position.
1336 displayed_analysis_data = null;
1337 update_board(current_analysis_data, displayed_analysis_data);
1340 current_display_line = display_lines[line_num];
1341 current_display_move = move_num;
1343 current_display_line_is_history = (line_num == 0);
1345 update_historic_analysis();
1346 update_displayed_line();
1347 update_board_highlight();
1350 window['show_line'] = show_line;
1352 var prev_move = function() {
1353 if (current_display_move > -1) {
1354 --current_display_move;
1356 update_historic_analysis();
1357 update_displayed_line();
1358 update_move_highlight();
1360 window['prev_move'] = prev_move;
1362 var next_move = function() {
1363 if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
1364 ++current_display_move;
1366 update_historic_analysis();
1367 update_displayed_line();
1368 update_move_highlight();
1370 window['next_move'] = next_move;
1372 var update_historic_analysis = function() {
1373 if (!current_display_line_is_history) {
1376 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1377 displayed_analysis_data = null;
1378 update_board(current_analysis_data, displayed_analysis_data);
1381 // Fetch old analysis for this line if it exists.
1382 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1383 var filename = "/history/move" + (current_display_move + 1) + "-" +
1384 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1386 current_historic_xhr = $.ajax({
1388 }).done(function(data, textstatus, xhr) {
1389 displayed_analysis_data = data;
1390 update_board(current_analysis_data, displayed_analysis_data);
1391 }).fail(function(jqXHR, textStatus, errorThrown) {
1392 if (textStatus === "abort") {
1393 // Aborted because we are switching backends. Don't do anything;
1394 // we will already have been cleared.
1396 displayed_analysis_data = {'failed': true};
1397 update_board(current_analysis_data, displayed_analysis_data);
1403 * @param {string} fen
1405 var update_imbalance = function(fen) {
1406 var hiddenboard = new Chess(fen);
1407 var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1408 for (var row = 0; row < 8; ++row) {
1409 for (var col = 0; col < 8; ++col) {
1410 var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1411 var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1412 var square = col_text + row_text;
1413 var contents = hiddenboard.get(square);
1414 if (contents !== null) {
1415 if (contents.color === 'w') {
1416 ++imbalance[contents.type];
1418 --imbalance[contents.type];
1423 var white_imbalance = '';
1424 var black_imbalance = '';
1425 for (var piece in imbalance) {
1426 for (var i = 0; i < imbalance[piece]; ++i) {
1427 white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1429 for (var i = 0; i < -imbalance[piece]; ++i) {
1430 black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1433 $('#whiteimbalance').html(white_imbalance);
1434 $('#blackimbalance').html(black_imbalance);
1437 /** Mark the currently selected move in red.
1439 var update_move_highlight = function() {
1440 if (highlighted_move !== null) {
1441 highlighted_move.removeClass('highlight');
1443 if (current_display_line !== null) {
1444 highlighted_move = $("#automove" + current_display_line.line_number + "-" + current_display_move);
1445 highlighted_move.addClass('highlight');
1449 var update_displayed_line = function() {
1450 if (current_display_line === null) {
1451 $("#linenav").hide();
1452 $("#linemsg").show();
1453 board.position(fen);
1454 update_imbalance(fen);
1458 $("#linenav").show();
1459 $("#linemsg").hide();
1461 if (current_display_move <= 0) {
1462 $("#prevmove").html("Previous");
1464 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1466 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1467 $("#nextmove").html("Next");
1469 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1472 var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pretty_pv, current_display_move);
1473 board.position(hiddenboard.fen());
1474 update_imbalance(hiddenboard.fen());
1478 * @param {boolean} param_enable_sound
1480 var set_sound = function(param_enable_sound) {
1481 enable_sound = param_enable_sound;
1483 $("#soundon").html("<strong>On</strong>");
1484 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1486 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1487 // and also preload the file since the user has selected audio.
1488 var ding = document.getElementById('ding');
1489 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1490 ding.src = 'ding.opus';
1494 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1495 $("#soundoff").html("<strong>Off</strong>");
1497 if (supports_html5_storage()) {
1498 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1501 window['set_sound'] = set_sound;
1504 * @param {string} new_backend_url
1506 var switch_backend = function(new_backend_url) {
1507 // Stop looking at historic data.
1508 current_display_line = null;
1509 current_display_move = null;
1510 displayed_analysis_data = null;
1511 if (current_historic_xhr) {
1512 current_historic_xhr.abort();
1515 // If we already have a backend response going, abort it.
1516 if (current_analysis_xhr) {
1517 current_analysis_xhr.abort();
1520 // Otherwise, we should have a timer going to start a new one.
1522 if (current_analysis_request_timer) {
1523 clearTimeout(current_analysis_request_timer);
1524 current_analysis_request_timer = null;
1527 // Request an immediate fetch with the new backend.
1528 backend_url = new_backend_url;
1529 current_analysis_data = null;
1533 window['switch_backend'] = switch_backend;
1535 var init = function() {
1536 unique = get_unique();
1538 // Load settings from HTML5 local storage if available.
1539 if (supports_html5_storage() && localStorage['enable_sound']) {
1540 set_sound(parseInt(localStorage['enable_sound']));
1544 if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
1545 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
1547 sort_refutation_lines_by_score = true;
1551 board = new window.ChessBoard('board', 'start');
1554 $(window).resize(function() {
1556 update_sparkline(displayed_analysis_data || current_analysis_data);
1557 update_board_highlight();
1560 $(window).keyup(function(event) {
1561 if (event.which == 39) {
1563 } else if (event.which == 37) {
1567 window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
1569 $(document).ready(init);