3 /** @type {window.ChessBoard} @private */
7 * The most recent analysis data we have from the server
8 * (about the most recent position).
12 var current_analysis_data = null;
15 * If we are displaying previous analysis, this is non-null,
16 * and will override most of current_analysis_data.
21 var displayed_analysis_data = null;
36 /** @type {Array.<Array.<boolean>>} */
37 var occupied_by_arrows = [];
39 var refutation_lines = [];
41 /** @type {!number} @private */
44 /** @type {!string} @private */
47 /** @type {number} @private */
50 /** @type {boolean} @private */
51 var sort_refutation_lines_by_score = true;
53 /** @type {boolean} @private */
54 var truncate_display_history = true;
56 /** @type {!string|undefined} @private */
57 var highlight_from = undefined;
59 /** @type {!string|undefined} @private */
60 var highlight_to = undefined;
62 /** @type {?jQuery} @private */
63 var highlighted_move = null;
65 /** @type {?number} @private */
68 /** @type {boolean} @private */
69 var enable_sound = false;
72 * Our best estimate of how many milliseconds we need to add to
73 * new Date() to get the true UTC time. Calibrated against the
79 var client_clock_offset_ms = null;
81 var clock_timer = null;
83 /** The current position on the board, represented as a FEN string.
91 * uci_pv: Array.<string>,
92 * pretty_pv: Array.<string>,
97 /** @type {Array.<DisplayLine>}
100 var display_lines = [];
102 /** @type {?DisplayLine} @private */
103 var current_display_line = null;
105 /** @type {boolean} @private */
106 var current_display_line_is_history = false;
108 /** @type {?number} @private */
109 var current_display_move = null;
111 var supports_html5_storage = function() {
113 return 'localStorage' in window && window['localStorage'] !== null;
119 // Make the unique token persistent so people refreshing the page won't count twice.
120 // Of course, you can never fully protect against people deliberately wanting to spam.
121 var get_unique = function() {
122 var use_local_storage = supports_html5_storage();
123 if (use_local_storage && localStorage['unique']) {
124 return localStorage['unique'];
126 var unique = Math.random();
127 if (use_local_storage) {
128 localStorage['unique'] = unique;
133 var request_update = function() {
135 url: "/analysis.pl?ims=" + ims + "&unique=" + unique
136 }).done(function(data, textstatus, xhr) {
137 sync_server_clock(xhr.getResponseHeader('Date'));
138 ims = xhr.getResponseHeader('X-RGLM');
139 var num_viewers = xhr.getResponseHeader('X-RGNV');
141 if (Array.isArray(data)) {
142 new_data = JSON.parse(JSON.stringify(current_analysis_data));
143 JSON_delta.patch(new_data, data);
147 possibly_play_sound(current_analysis_data, new_data);
148 current_analysis_data = new_data;
149 update_board(current_analysis_data, displayed_analysis_data);
150 update_num_viewers(num_viewers);
153 setTimeout(function() { request_update(); }, 100);
155 // Wait ten seconds, then try again.
156 setTimeout(function() { request_update(); }, 10000);
160 var possibly_play_sound = function(old_data, new_data) {
164 if (old_data === null) {
167 var ding = document.getElementById('ding');
168 if (ding && ding.play) {
169 if (old_data['position'] && old_data['position']['fen'] &&
170 new_data['position'] && new_data['position']['fen'] &&
171 (old_data['position']['fen'] !== new_data['position']['fen'] ||
172 old_data['position']['move_num'] !== new_data['position']['move_num'])) {
179 * @type {!string} server_date_string
181 var sync_server_clock = function(server_date_string) {
182 var server_time_ms = new Date(server_date_string).getTime();
183 var client_time_ms = new Date().getTime();
184 var estimated_offset_ms = server_time_ms - client_time_ms;
186 // In order not to let the noise move us too much back and forth
187 // (the server only has one-second resolution anyway), we only
188 // change an existing skew if we are at least five seconds off.
189 if (client_clock_offset_ms === null ||
190 Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
191 client_clock_offset_ms = estimated_offset_ms;
195 var clear_arrows = function() {
196 for (var i = 0; i < arrows.length; ++i) {
198 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
199 delete arrows[i].svg;
204 occupied_by_arrows = [];
205 for (var y = 0; y < 8; ++y) {
206 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
210 var redraw_arrows = function() {
211 for (var i = 0; i < arrows.length; ++i) {
212 position_arrow(arrows[i]);
216 /** @param {!number} x
219 var sign = function(x) {
229 /** See if drawing this arrow on the board would cause unduly amount of confusion.
230 * @param {!string} from The square the arrow is from (e.g. e4).
231 * @param {!string} to The square the arrow is to (e.g. e4).
234 var interfering_arrow = function(from, to) {
235 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
236 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
237 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
238 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
240 occupied_by_arrows[from_row][from_col] = true;
242 // Knight move: Just check that we haven't been at the destination before.
243 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
244 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
245 return occupied_by_arrows[to_row][to_col];
248 // Sliding piece: Check if anything except the from-square is seen before.
249 var dx = sign(to_col - from_col);
250 var dy = sign(to_row - from_row);
256 if (occupied_by_arrows[y][x]) {
259 occupied_by_arrows[y][x] = true;
260 } while (x != to_col || y != to_row);
265 /** Find a point along the coordinate system given by the given line,
266 * <t> units forward from the start of the line, <u> units to the right of it.
267 * @param {!number} x1
268 * @param {!number} x2
269 * @param {!number} y1
270 * @param {!number} y2
273 * @return {!string} The point in "x y" form, suitable for SVG paths.
275 var point_from_start = function(x1, y1, x2, y2, t, u) {
279 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
283 var x = x1 + dx * t + dy * u;
284 var y = y1 + dy * t - dx * u;
288 /** Find a point along the coordinate system given by the given line,
289 * <t> units forward from the end of the line, <u> units to the right of it.
290 * @param {!number} x1
291 * @param {!number} x2
292 * @param {!number} y1
293 * @param {!number} y2
296 * @return {!string} The point in "x y" form, suitable for SVG paths.
298 var point_from_end = function(x1, y1, x2, y2, t, u) {
302 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
306 var x = x2 + dx * t + dy * u;
307 var y = y2 + dy * t - dx * u;
311 var position_arrow = function(arrow) {
313 arrow.svg.parentElement.removeChild(arrow.svg);
316 if (current_display_line !== null && !current_display_line_is_history) {
320 var pos = $(".square-a8").position();
322 var zoom_factor = $("#board").width() / 400.0;
323 var line_width = arrow.line_width * zoom_factor;
324 var arrow_size = arrow.arrow_size * zoom_factor;
326 var square_width = $(".square-a8").width();
327 var from_y = (7 - arrow.from_row + 0.5)*square_width;
328 var to_y = (7 - arrow.to_row + 0.5)*square_width;
329 var from_x = (arrow.from_col + 0.5)*square_width;
330 var to_x = (arrow.to_col + 0.5)*square_width;
332 var SVG_NS = "http://www.w3.org/2000/svg";
333 var XHTML_NS = "http://www.w3.org/1999/xhtml";
334 var svg = document.createElementNS(SVG_NS, "svg");
335 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
336 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
337 svg.setAttribute("style", "position: absolute");
338 svg.setAttribute("position", "absolute");
339 svg.setAttribute("version", "1.1");
340 svg.setAttribute("class", "c1");
341 svg.setAttribute("xmlns", XHTML_NS);
349 var outline = document.createElementNS(SVG_NS, "path");
350 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));
351 outline.setAttribute("xmlns", XHTML_NS);
352 outline.setAttribute("stroke", "#666");
353 outline.setAttribute("stroke-width", line_width + 2);
354 outline.setAttribute("fill", "none");
355 svg.appendChild(outline);
357 var path = document.createElementNS(SVG_NS, "path");
358 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));
359 path.setAttribute("xmlns", XHTML_NS);
360 path.setAttribute("stroke", arrow.fg_color);
361 path.setAttribute("stroke-width", line_width);
362 path.setAttribute("fill", "none");
363 svg.appendChild(path);
365 // Then the arrow head.
366 var head = document.createElementNS(SVG_NS, "path");
367 head.setAttribute("d",
368 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
369 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
370 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
371 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
372 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
373 head.setAttribute("xmlns", XHTML_NS);
374 head.setAttribute("stroke", "#000");
375 head.setAttribute("stroke-width", "1");
376 head.setAttribute("fill", arrow.fg_color);
377 svg.appendChild(head);
379 $(svg).css({ top: pos.top, left: pos.left });
380 document.body.appendChild(svg);
385 * @param {!string} from_square
386 * @param {!string} to_square
387 * @param {!string} fg_color
388 * @param {number} line_width
389 * @param {number} arrow_size
391 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
392 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
393 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
394 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
395 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
403 line_width: line_width,
404 arrow_size: arrow_size,
408 position_arrow(arrow);
412 var compare_by_sort_key = function(refutation_lines, a, b) {
413 var ska = refutation_lines[a]['sort_key'];
414 var skb = refutation_lines[b]['sort_key'];
415 if (ska < skb) return -1;
416 if (ska > skb) return 1;
420 var compare_by_score = function(refutation_lines, a, b) {
421 var sa = parseInt(refutation_lines[b]['score_sort_key'], 10);
422 var sb = parseInt(refutation_lines[a]['score_sort_key'], 10);
427 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
428 * sorted by quality, descending.
430 * @param {!Object} data
431 * @param {number} margin The maximum number of centipawns worse than the
432 * best move can be and still be included.
433 * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
434 * moves, in score order.
436 var find_nonstupid_moves = function(data, margin) {
437 // First of all, if there are any moves that are more than 0.5 ahead of
438 // the primary move, the refutation lines are probably bunk, so just
440 var best_score = undefined;
441 var pv_score = undefined;
442 for (var move in data['refutation_lines']) {
443 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
444 if (move == data['pv_uci'][0]) {
447 if (best_score === undefined || score > best_score) {
450 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
455 if (best_score - pv_score > 50) {
459 // Now find all moves that are within “margin” of the best score.
460 // The PV move will always be first.
462 for (var move in data['refutation_lines']) {
463 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
464 if (move != data['pv_uci'][0] && best_score - score <= margin) {
468 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], a, b) });
469 moves.unshift(data['pv_uci'][0]);
478 var thousands = function(x) {
479 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
483 * @param {!string} fen
484 * @param {Array.<string>} pretty_pv
485 * @param {number} move_num
486 * @param {!string} toplay
487 * @param {number=} opt_limit
488 * @param {boolean=} opt_showlast
490 var add_pv = function(fen, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
493 pretty_pv: pretty_pv,
494 line_number: display_lines.length
496 return print_pv(display_lines.length - 1, pretty_pv, move_num, toplay, opt_limit, opt_showlast);
500 * @param {number} line_num
501 * @param {Array.<string>} pretty_pv
502 * @param {number} move_num
503 * @param {!string} toplay
504 * @param {number=} opt_limit
505 * @param {boolean=} opt_showlast
507 var print_pv = function(line_num, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
510 if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
511 // Truncate the PV at the beginning (instead of at the end).
512 // We assume here that toplay is 'W'. We also assume that if
513 // opt_showlast is set, then it is the history, and thus,
514 // the UI should be to expand the history.
515 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
516 i = pretty_pv.length - opt_limit;
521 } else if (toplay == 'B' && pretty_pv.length > 0) {
522 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
523 pv = move_num + '. … ' + move;
528 for ( ; i < pretty_pv.length; ++i) {
529 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
532 if (i > opt_limit && !opt_showlast) {
538 pv += move_num + '. ' + move;
549 var update_highlight = function() {
550 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
551 if ((current_display_line === null || current_display_line_is_history) &&
552 highlight_from !== undefined && highlight_to !== undefined) {
553 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
554 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
558 var update_history = function() {
559 if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
560 $("#history").html("No history");
561 } else if (truncate_display_history) {
562 $("#history").html(print_pv(0, display_lines[0].pretty_pv, 1, 'W', 8, true));
565 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
566 print_pv(0, display_lines[0].pretty_pv, 1, 'W'));
571 * @param {!boolean} truncate_history
573 var collapse_history = function(truncate_history) {
574 truncate_display_history = truncate_history;
577 window['collapse_history'] = collapse_history;
579 var update_refutation_lines = function() {
583 if (display_lines.length > 2) {
584 display_lines = [ display_lines[0], display_lines[1] ];
587 var tbl = $("#refutationlines");
591 for (var move in refutation_lines) {
594 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
595 moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
596 for (var i = 0; i < moves.length; ++i) {
597 var line = refutation_lines[moves[i]];
599 var tr = document.createElement("tr");
601 var move_td = document.createElement("td");
602 tr.appendChild(move_td);
603 $(move_td).addClass("move");
604 if (line['pv_pretty'].length == 0) {
605 $(move_td).text(line['pretty_move']);
607 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
608 $(move_td).html(move);
611 var score_td = document.createElement("td");
612 tr.appendChild(score_td);
613 $(score_td).addClass("score");
614 $(score_td).text(line['pretty_score']);
616 var depth_td = document.createElement("td");
617 tr.appendChild(depth_td);
618 $(depth_td).addClass("depth");
619 $(depth_td).text("d" + line['depth']);
621 var pv_td = document.createElement("td");
622 tr.appendChild(pv_td);
623 $(pv_td).addClass("pv");
624 $(pv_td).html(add_pv(fen, line['pv_pretty'], move_num, toplay, 10));
629 // Make one of the links clickable and the other nonclickable.
630 if (sort_refutation_lines_by_score) {
631 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
632 $("#sortbyscore1").html("<strong>Score</strong>");
634 $("#sortbyscore0").html("<strong>Move</strong>");
635 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
640 * @param {?string} fen
641 * @param {Array.<string>} moves
642 * @param {number} last_move
644 var chess_from = function(fen, moves, last_move) {
645 var hiddenboard = new Chess();
647 hiddenboard.load(fen);
649 for (var i = 0; i <= last_move; ++i) {
650 if (moves[i] === '0-0') {
651 hiddenboard.move('O-O');
652 } else if (moves[i] === '0-0-0') {
653 hiddenboard.move('O-O-O');
655 hiddenboard.move(moves[i]);
662 * @param {Object} data
663 * @param {?Object} display_data
665 var update_board = function(current_data, display_data) {
666 var data = display_data || current_data;
670 // Print the history. This is pretty much the only thing that's
671 // unconditionally taken from current_data (we're not interested in
672 // historic history).
673 if (current_data['position']['pretty_history']) {
674 add_pv('start', current_data['position']['pretty_history'], 1, 'W', 8, true);
676 display_lines.push(null);
680 // The headline. Names are always fetched from current_data;
681 // the rest can depend a bit.
684 current_data['position']['player_w'] && current_data['position']['player_b']) {
685 headline = current_data['position']['player_w'] + '–' +
686 current_data['position']['player_b'] + ', analysis';
688 headline = 'Analysis';
693 // Displaying some non-current position, pick out the last move
694 // from the history. This will work even if the fetch failed.
695 last_move = format_move_with_number(
696 current_display_line.pretty_pv[current_display_move],
697 Math.floor((current_display_move + 1) / 2) + 1,
698 (current_display_move % 2 == 1));
699 headline += ' after ' + last_move;
700 } else if (data['position']['last_move'] !== 'none') {
701 last_move = format_move_with_number(
702 data['position']['last_move'],
703 data['position']['move_num'],
704 data['position']['toplay'] == 'W');
705 headline += ' after ' + last_move;
709 $("#headline").text(headline);
711 // The <title> contains a very brief headline.
712 var title_elems = [];
713 if (data['short_score'] !== undefined && data['short_score'] !== null) {
714 title_elems.push(data['short_score'].replace(/^ /, ""));
716 if (last_move !== null) {
717 title_elems.push(last_move);
720 if (title_elems.length != 0) {
721 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
723 document.title = 'analysis.sesse.net';
726 // The last move (shown by highlighting the from and to squares).
727 if (data['position'] && data['position']['last_move_uci']) {
728 highlight_from = data['position']['last_move_uci'].substr(0, 2);
729 highlight_to = data['position']['last_move_uci'].substr(2, 2);
730 } else if (current_display_line_is_history && current_display_move >= 0) {
731 // We don't have historic analysis for this position, but we
732 // can reconstruct what the last move was by just replaying
734 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
735 var moves = hiddenboard.history({ verbose: true });
736 var last_move = moves.pop();
737 highlight_from = last_move.from;
738 highlight_to = last_move.to;
740 highlight_from = highlight_to = undefined;
744 if (data['failed']) {
745 $("#score").text("No analysis for this move");
747 $("#searchstats").html(" ");
748 $("#refutationlines").empty();
749 $("#whiteclock").empty();
750 $("#blackclock").empty();
751 refutation_lines = [];
752 update_refutation_lines();
754 update_displayed_line();
761 if (data['id'] && data['id']['name'] !== null) {
762 $("#engineid").text(data['id']['name']);
766 if (data['score'] !== null) {
767 $("#score").text(data['score']);
771 if (data['tablebase'] == 1) {
772 $("#searchstats").text("Tablebase result");
773 } else if (data['nodes'] && data['nps'] && data['depth']) {
774 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
775 if (data['seldepth']) {
776 stats += ' (' + data['seldepth'] + ' selective)';
778 if (data['tbhits'] && data['tbhits'] > 0) {
779 if (data['tbhits'] == 1) {
780 stats += ', one Syzygy hit';
782 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
786 $("#searchstats").text(stats);
788 $("#searchstats").text("");
791 // Update the board itself.
792 fen = data['position']['fen'];
793 update_displayed_line();
796 $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
798 // Update the PV arrow.
800 if (data['pv_uci'].length >= 1) {
801 // draw a continuation arrow as long as it's the same piece
802 for (var i = 0; i < data['pv_uci'].length; i += 2) {
803 var from = data['pv_uci'][i].substr(0, 2);
804 var to = data['pv_uci'][i].substr(2,4);
805 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
806 interfering_arrow(from, to)) {
809 create_arrow(from, to, '#f66', 6, 20);
812 var alt_moves = find_nonstupid_moves(data, 30);
813 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
814 create_arrow(alt_moves[i].substr(0, 2),
815 alt_moves[i].substr(2, 2), '#f66', 1, 10);
819 // See if all semi-reasonable moves have only one possible response.
820 if (data['pv_uci'].length >= 2) {
821 var nonstupid_moves = find_nonstupid_moves(data, 300);
822 var response = data['pv_uci'][1];
823 for (var i = 0; i < nonstupid_moves.length; ++i) {
824 if (nonstupid_moves[i] == data['pv_uci'][0]) {
825 // ignore the PV move for refutation lines.
828 if (!data['refutation_lines'] ||
829 !data['refutation_lines'][nonstupid_moves[i]] ||
830 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
831 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
832 // Incomplete PV, abort.
833 response = undefined;
836 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
837 if (response !== this_response) {
838 // Different response depending on lines, abort.
839 response = undefined;
844 if (nonstupid_moves.length > 0 && response !== undefined) {
845 create_arrow(response.substr(0, 2),
846 response.substr(2, 2), '#66f', 6, 20);
850 // Update the refutation lines.
851 fen = data['position']['fen'];
852 move_num = data['position']['move_num'];
853 toplay = data['position']['toplay'];
854 refutation_lines = data['refutation_lines'];
855 update_refutation_lines();
859 * @param {number} num_viewers
861 var update_num_viewers = function(num_viewers) {
862 if (num_viewers === null) {
863 $("#numviewers").text("");
864 } else if (num_viewers == 1) {
865 $("#numviewers").text("You are the only current viewer");
867 $("#numviewers").text(num_viewers + " current viewers");
871 var update_clock = function() {
872 clearTimeout(clock_timer);
874 var data = displayed_analysis_data || current_analysis_data;
875 if (data['position']) {
876 var result = data['position']['result'];
877 if (result === '1-0') {
878 $("#whiteclock").text("1");
879 $("#blackclock").text("0");
880 $("#whiteclock").removeClass("running-clock");
881 $("#blackclock").removeClass("running-clock");
884 if (result === '1/2-1/2') {
885 $("#whiteclock").text("1/2");
886 $("#blackclock").text("1/2");
887 $("#whiteclock").removeClass("running-clock");
888 $("#blackclock").removeClass("running-clock");
891 if (result === '0-1') {
892 $("#whiteclock").text("0");
893 $("#blackclock").text("1");
894 $("#whiteclock").removeClass("running-clock");
895 $("#blackclock").removeClass("running-clock");
900 var white_clock_ms = null;
901 var black_clock_ms = null;
902 var show_seconds = false;
905 if (data['position'] &&
906 data['position']['white_clock'] &&
907 data['position']['black_clock']) {
908 white_clock_ms = data['position']['white_clock'] * 1000;
909 black_clock_ms = data['position']['black_clock'] * 1000;
912 // Dynamic clock (only one, obviously).
914 if (data['position']['white_clock_target']) {
916 $("#whiteclock").addClass("running-clock");
917 $("#blackclock").removeClass("running-clock");
918 } else if (data['position']['black_clock_target']) {
920 $("#whiteclock").removeClass("running-clock");
921 $("#blackclock").addClass("running-clock");
923 $("#whiteclock").removeClass("running-clock");
924 $("#blackclock").removeClass("running-clock");
928 var now = new Date().getTime() + client_clock_offset_ms;
929 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
930 if (color === "white") {
931 white_clock_ms = remaining_ms;
933 black_clock_ms = remaining_ms;
937 if (white_clock_ms === null || black_clock_ms === null) {
938 $("#whiteclock").empty();
939 $("#blackclock").empty();
943 // If either player has ten minutes or less left, add the second counters.
944 var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
947 // See when the clock will change next, and update right after that.
950 next_update_ms = remaining_ms % 1000 + 100;
952 next_update_ms = remaining_ms % 60000 + 100;
954 clock_timer = setTimeout(update_clock, next_update_ms);
957 $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
958 $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
962 * @param {Number} remaining_ms
963 * @param {boolean} show_seconds
965 var format_clock = function(remaining_ms, show_seconds) {
966 if (remaining_ms <= 0) {
974 var remaining = Math.floor(remaining_ms / 1000);
975 var seconds = remaining % 60;
976 remaining = (remaining - seconds) / 60;
977 var minutes = remaining % 60;
978 remaining = (remaining - minutes) / 60;
979 var hours = remaining;
981 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
983 return format_2d(hours) + ":" + format_2d(minutes);
990 var format_2d = function(x) {
999 * @param {string} move
1000 * @param {Number} move_num
1001 * @param {boolean} white_to_play
1003 var format_move_with_number = function(move, move_num, white_to_play) {
1005 if (white_to_play) {
1006 ret = (move_num - 1) + '… ';
1008 ret = move_num + '. ';
1015 * @param {boolean} sort_by_score
1017 var resort_refutation_lines = function(sort_by_score) {
1018 sort_refutation_lines_by_score = sort_by_score;
1019 if (supports_html5_storage()) {
1020 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1022 update_refutation_lines();
1024 window['resort_refutation_lines'] = resort_refutation_lines;
1027 * @param {boolean} truncate_history
1029 var set_truncate_history = function(truncate_history) {
1030 truncate_display_history = truncate_history;
1031 update_refutation_lines();
1033 window['set_truncate_history'] = set_truncate_history;
1036 * @param {number} line_num
1037 * @param {number} move_num
1039 var show_line = function(line_num, move_num) {
1040 if (line_num == -1) {
1041 current_display_line = null;
1042 current_display_move = null;
1043 if (displayed_analysis_data) {
1044 // TODO: Support exiting to history position if we are in an
1045 // analysis line of a history position.
1046 displayed_analysis_data = null;
1047 update_board(current_analysis_data, displayed_analysis_data);
1050 current_display_line = display_lines[line_num];
1051 current_display_move = move_num;
1053 current_display_line_is_history = (line_num == 0);
1055 update_historic_analysis();
1056 update_displayed_line();
1060 window['show_line'] = show_line;
1062 var prev_move = function() {
1063 if (current_display_move > -1) {
1064 --current_display_move;
1066 update_historic_analysis();
1067 update_displayed_line();
1069 window['prev_move'] = prev_move;
1071 var next_move = function() {
1072 if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
1073 ++current_display_move;
1075 update_historic_analysis();
1076 update_displayed_line();
1078 window['next_move'] = next_move;
1080 var update_historic_analysis = function() {
1081 if (!current_display_line_is_history) {
1084 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1085 displayed_analysis_data = null;
1086 update_board(current_analysis_data, displayed_analysis_data);
1089 // Fetch old analysis for this line if it exists.
1090 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1091 var filename = "/history/move" + (current_display_move + 1) + "-" +
1092 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1096 }).done(function(data, textstatus, xhr) {
1097 displayed_analysis_data = data;
1098 update_board(current_analysis_data, displayed_analysis_data);
1099 }).fail(function() {
1100 displayed_analysis_data = {'failed': true};
1101 update_board(current_analysis_data, displayed_analysis_data);
1106 * @param {string} fen
1108 var update_imbalance = function(fen) {
1109 var hiddenboard = new Chess(fen);
1110 var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1111 for (var row = 0; row < 8; ++row) {
1112 for (var col = 0; col < 8; ++col) {
1113 var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1114 var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1115 var square = col_text + row_text;
1116 var contents = hiddenboard.get(square);
1117 if (contents !== null) {
1118 if (contents.color === 'w') {
1119 ++imbalance[contents.type];
1121 --imbalance[contents.type];
1126 var white_imbalance = '';
1127 var black_imbalance = '';
1128 for (var piece in imbalance) {
1129 for (var i = 0; i < imbalance[piece]; ++i) {
1130 white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1132 for (var i = 0; i < -imbalance[piece]; ++i) {
1133 black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1136 $('#whiteimbalance').html(white_imbalance);
1137 $('#blackimbalance').html(black_imbalance);
1140 var update_displayed_line = function() {
1141 if (highlighted_move !== null) {
1142 highlighted_move.removeClass('highlight');
1144 if (current_display_line === null) {
1145 $("#linenav").hide();
1146 $("#linemsg").show();
1147 board.position(fen);
1148 update_imbalance(fen);
1152 $("#linenav").show();
1153 $("#linemsg").hide();
1155 if (current_display_move <= 0) {
1156 $("#prevmove").html("Previous");
1158 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1160 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1161 $("#nextmove").html("Next");
1163 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1166 highlighted_move = $("#automove" + current_display_line.line_number + "-" + current_display_move);
1167 highlighted_move.addClass('highlight');
1169 var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pretty_pv, current_display_move);
1170 board.position(hiddenboard.fen());
1171 update_imbalance(hiddenboard.fen());
1175 * @param {boolean} param_enable_sound
1177 var set_sound = function(param_enable_sound) {
1178 enable_sound = param_enable_sound;
1180 $("#soundon").html("<strong>On</strong>");
1181 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1183 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1184 // and also preload the file since the user has selected audio.
1185 var ding = document.getElementById('ding');
1186 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1187 ding.src = 'ding.opus';
1191 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1192 $("#soundoff").html("<strong>Off</strong>");
1194 if (supports_html5_storage()) {
1195 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1198 window['set_sound'] = set_sound;
1200 var init = function() {
1201 unique = get_unique();
1203 // Load settings from HTML5 local storage if available.
1204 if (supports_html5_storage() && localStorage['enable_sound']) {
1205 set_sound(parseInt(localStorage['enable_sound']));
1209 if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
1210 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
1212 sort_refutation_lines_by_score = true;
1216 board = new window.ChessBoard('board', 'start');
1219 $(window).resize(function() {
1224 $(window).keyup(function(event) {
1225 if (event.which == 39) {
1227 } else if (event.which == 37) {
1232 $(document).ready(init);