3 /** @type {window.ChessBoard} @private */
6 /** @type {window.ChessBoard} @private */
7 var hiddenboard = null;
22 /** @type {Array.<Array.<boolean>>} */
23 var occupied_by_arrows = [];
25 var refutation_lines = [];
27 /** @type {!number} @private */
30 /** @type {!string} @private */
33 /** @type {number} @private */
36 /** @type {boolean} @private */
37 var sort_refutation_lines_by_score = true;
39 /** @type {boolean} @private */
40 var truncate_display_history = true;
42 /** @type {!string|undefined} @private */
43 var highlight_from = undefined;
45 /** @type {!string|undefined} @private */
46 var highlight_to = undefined;
48 /** @type {?jQuery} @private */
49 var highlighted_move = null;
51 /** @type {?number} @private */
54 /** The current position on the board, represented as a FEN string.
62 * uci_pv: Array.<string>,
63 * pretty_pv: Array.<string>,
68 /** @type {Array.<DisplayLine>}
71 var display_lines = [];
73 /** @type {?DisplayLine} @private */
74 var current_display_line = null;
76 /** @type {?number} @private */
77 var current_display_move = null;
79 var supports_html5_storage = function() {
81 return 'localStorage' in window && window['localStorage'] !== null;
87 // Make the unique token persistent so people refreshing the page won't count twice.
88 // Of course, you can never fully protect against people deliberately wanting to spam.
89 var get_unique = function() {
90 var use_local_storage = supports_html5_storage();
91 if (use_local_storage && localStorage['unique']) {
92 return localStorage['unique'];
94 var unique = Math.random();
95 if (use_local_storage) {
96 localStorage['unique'] = unique;
101 var request_update = function() {
103 url: "/analysis.pl?ims=" + ims + "&unique=" + unique
104 }).done(function(data, textstatus, xhr) {
105 ims = xhr.getResponseHeader('X-Remoteglot-Last-Modified');
106 var num_viewers = xhr.getResponseHeader('X-Remoteglot-Num-Viewers');
107 update_board(data, num_viewers);
109 // Wait ten seconds, then try again.
110 setTimeout(function() { request_update(); }, 10000);
114 var clear_arrows = function() {
115 for (var i = 0; i < arrows.length; ++i) {
117 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
118 delete arrows[i].svg;
123 occupied_by_arrows = [];
124 for (var y = 0; y < 8; ++y) {
125 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
129 var redraw_arrows = function() {
130 for (var i = 0; i < arrows.length; ++i) {
131 position_arrow(arrows[i]);
135 /** @param {!number} x
138 var sign = function(x) {
148 /** See if drawing this arrow on the board would cause unduly amount of confusion.
149 * @param {!string} from The square the arrow is from (e.g. e4).
150 * @param {!string} to The square the arrow is to (e.g. e4).
153 var interfering_arrow = function(from, to) {
154 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
155 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
156 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
157 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
159 occupied_by_arrows[from_row][from_col] = true;
161 // Knight move: Just check that we haven't been at the destination before.
162 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
163 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
164 return occupied_by_arrows[to_row][to_col];
167 // Sliding piece: Check if anything except the from-square is seen before.
168 var dx = sign(to_col - from_col);
169 var dy = sign(to_row - from_row);
175 if (occupied_by_arrows[y][x]) {
178 occupied_by_arrows[y][x] = true;
179 } while (x != to_col || y != to_row);
184 /** Find a point along the coordinate system given by the given line,
185 * <t> units forward from the start of the line, <u> units to the right of it.
186 * @param {!number} x1
187 * @param {!number} x2
188 * @param {!number} y1
189 * @param {!number} y2
192 * @return {!string} The point in "x y" form, suitable for SVG paths.
194 var point_from_start = function(x1, y1, x2, y2, t, u) {
198 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
202 var x = x1 + dx * t + dy * u;
203 var y = y1 + dy * t - dx * u;
207 /** Find a point along the coordinate system given by the given line,
208 * <t> units forward from the end of the line, <u> units to the right of it.
209 * @param {!number} x1
210 * @param {!number} x2
211 * @param {!number} y1
212 * @param {!number} y2
215 * @return {!string} The point in "x y" form, suitable for SVG paths.
217 var point_from_end = function(x1, y1, x2, y2, t, u) {
221 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
225 var x = x2 + dx * t + dy * u;
226 var y = y2 + dy * t - dx * u;
230 var position_arrow = function(arrow) {
232 arrow.svg.parentElement.removeChild(arrow.svg);
235 if (current_display_line !== null) {
239 var pos = $(".square-a8").position();
241 var zoom_factor = $("#board").width() / 400.0;
242 var line_width = arrow.line_width * zoom_factor;
243 var arrow_size = arrow.arrow_size * zoom_factor;
245 var square_width = $(".square-a8").width();
246 var from_y = (7 - arrow.from_row + 0.5)*square_width;
247 var to_y = (7 - arrow.to_row + 0.5)*square_width;
248 var from_x = (arrow.from_col + 0.5)*square_width;
249 var to_x = (arrow.to_col + 0.5)*square_width;
251 var SVG_NS = "http://www.w3.org/2000/svg";
252 var XHTML_NS = "http://www.w3.org/1999/xhtml";
253 var svg = document.createElementNS(SVG_NS, "svg");
254 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
255 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
256 svg.setAttribute("style", "position: absolute");
257 svg.setAttribute("position", "absolute");
258 svg.setAttribute("version", "1.1");
259 svg.setAttribute("class", "c1");
260 svg.setAttribute("xmlns", XHTML_NS);
268 var outline = document.createElementNS(SVG_NS, "path");
269 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));
270 outline.setAttribute("xmlns", XHTML_NS);
271 outline.setAttribute("stroke", "#666");
272 outline.setAttribute("stroke-width", line_width + 2);
273 outline.setAttribute("fill", "none");
274 svg.appendChild(outline);
276 var path = document.createElementNS(SVG_NS, "path");
277 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));
278 path.setAttribute("xmlns", XHTML_NS);
279 path.setAttribute("stroke", arrow.fg_color);
280 path.setAttribute("stroke-width", line_width);
281 path.setAttribute("fill", "none");
282 svg.appendChild(path);
284 // Then the arrow head.
285 var head = document.createElementNS(SVG_NS, "path");
286 head.setAttribute("d",
287 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
288 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
289 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
290 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
291 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
292 head.setAttribute("xmlns", XHTML_NS);
293 head.setAttribute("stroke", "#000");
294 head.setAttribute("stroke-width", "1");
295 head.setAttribute("fill", arrow.fg_color);
296 svg.appendChild(head);
298 $(svg).css({ top: pos.top, left: pos.left });
299 document.body.appendChild(svg);
304 * @param {!string} from_square
305 * @param {!string} to_square
306 * @param {!string} fg_color
307 * @param {number} line_width
308 * @param {number} arrow_size
310 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
311 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
312 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
313 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
314 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
322 line_width: line_width,
323 arrow_size: arrow_size,
327 position_arrow(arrow);
331 var compare_by_sort_key = function(refutation_lines, a, b) {
332 var ska = refutation_lines[a]['sort_key'];
333 var skb = refutation_lines[b]['sort_key'];
334 if (ska < skb) return -1;
335 if (ska > skb) return 1;
339 var compare_by_score = function(refutation_lines, a, b) {
340 var sa = parseInt(refutation_lines[b]['score_sort_key'], 10);
341 var sb = parseInt(refutation_lines[a]['score_sort_key'], 10);
346 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
347 * sorted by quality, descending.
349 * @param {!Object} data
350 * @param {number} margin The maximum number of centipawns worse than the
351 * best move can be and still be included.
352 * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
353 * moves, in score order.
355 var find_nonstupid_moves = function(data, margin) {
356 // First of all, if there are any moves that are more than 0.5 ahead of
357 // the primary move, the refutation lines are probably bunk, so just
359 var best_score = undefined;
360 var pv_score = undefined;
361 for (var move in data['refutation_lines']) {
362 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
363 if (move == data['pv_uci'][0]) {
366 if (best_score === undefined || score > best_score) {
369 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
374 if (best_score - pv_score > 50) {
378 // Now find all moves that are within “margin” of the best score.
379 // The PV move will always be first.
381 for (var move in data['refutation_lines']) {
382 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
383 if (move != data['pv_uci'][0] && best_score - score <= margin) {
387 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], a, b) });
388 moves.unshift(data['pv_uci'][0]);
397 var thousands = function(x) {
398 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
402 * @param {!string} fen
403 * @param {Array.<string>} uci_pv
404 * @param {Array.<string>} pretty_pv
405 * @param {number} move_num
406 * @param {!string} toplay
407 * @param {number=} opt_limit
408 * @param {boolean=} opt_showlast
410 var add_pv = function(fen, uci_pv, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
414 pretty_pv: pretty_pv,
415 line_number: display_lines.length
417 return print_pv(display_lines.length - 1, pretty_pv, move_num, toplay, opt_limit, opt_showlast);
421 * @param {number} line_num
422 * @param {Array.<string>} pretty_pv
423 * @param {number} move_num
424 * @param {!string} toplay
425 * @param {number=} opt_limit
426 * @param {boolean=} opt_showlast
428 var print_pv = function(line_num, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
431 if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
432 // Truncate the PV at the beginning (instead of at the end).
433 // We assume here that toplay is 'W'. We also assume that if
434 // opt_showlast is set, then it is the history, and thus,
435 // the UI should be to expand the history.
436 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
437 i = pretty_pv.length - opt_limit;
442 } else if (toplay == 'B' && pretty_pv.length > 0) {
443 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
444 pv = move_num + '. … ' + move;
449 for ( ; i < pretty_pv.length; ++i) {
450 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
453 if (i > opt_limit && !opt_showlast) {
459 pv += move_num + '. ' + move;
470 var update_highlight = function() {
471 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
472 if (current_display_line === null && highlight_from !== undefined && highlight_to !== undefined) {
473 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
474 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
478 var update_history = function() {
479 if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
480 $("#history").html("No history");
481 } else if (truncate_display_history) {
482 $("#history").html(print_pv(0, display_lines[0].pretty_pv, 1, 'W', 8, true));
485 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
486 print_pv(0, display_lines[0].pretty_pv, 1, 'W'));
491 * @param {!boolean} truncate_history
493 var collapse_history = function(truncate_history) {
494 truncate_display_history = truncate_history;
497 window['collapse_history'] = collapse_history;
499 var update_refutation_lines = function() {
503 if (display_lines.length > 2) {
504 display_lines = [ display_lines[0], display_lines[1] ];
507 var tbl = $("#refutationlines");
511 for (var move in refutation_lines) {
514 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
515 moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
516 for (var i = 0; i < moves.length; ++i) {
517 var line = refutation_lines[moves[i]];
519 var tr = document.createElement("tr");
521 var move_td = document.createElement("td");
522 tr.appendChild(move_td);
523 $(move_td).addClass("move");
524 if (line['pv_uci'].length == 0) {
525 $(move_td).text(line['pretty_move']);
527 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
528 $(move_td).html(move);
531 var score_td = document.createElement("td");
532 tr.appendChild(score_td);
533 $(score_td).addClass("score");
534 $(score_td).text(line['pretty_score']);
536 var depth_td = document.createElement("td");
537 tr.appendChild(depth_td);
538 $(depth_td).addClass("depth");
539 $(depth_td).text("d" + line['depth']);
541 var pv_td = document.createElement("td");
542 tr.appendChild(pv_td);
543 $(pv_td).addClass("pv");
544 $(pv_td).html(add_pv(fen, line['pv_uci'], line['pv_pretty'], move_num, toplay, 10));
549 // Make one of the links clickable and the other nonclickable.
550 if (sort_refutation_lines_by_score) {
551 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
552 $("#sortbyscore1").html("<strong>Score</strong>");
554 $("#sortbyscore0").html("<strong>Move</strong>");
555 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
560 * @param {Object} data
561 * @param {number} num_viewers
563 var update_board = function(data, num_viewers) {
568 if (data['position']['player_w'] && data['position']['player_b']) {
569 headline = data['position']['player_w'] + '–' +
570 data['position']['player_b'] + ', analysis';
572 headline = 'Analysis';
575 if (data['position']['last_move'] !== 'none') {
576 if (data['position']['toplay'] == 'W') {
577 last_move = (data['position']['move_num']-1) + '… ';
579 last_move = data['position']['move_num'] + '. ';
581 last_move += data['position']['last_move'];
583 headline += ' after ' + last_move;
588 $("#headline").text(headline);
590 if (num_viewers === null) {
591 $("#numviewers").text("");
592 } else if (num_viewers == 1) {
593 $("#numviewers").text("You are the only current viewer");
595 $("#numviewers").text(num_viewers + " current viewers");
599 if (data['id'] && data['id']['name'] !== null) {
600 $("#engineid").text(data['id']['name']);
604 if (data['score'] !== null) {
605 $("#score").text(data['score']);
608 var title_elems = [];
609 if (data['short_score'] !== undefined && data['short_score'] !== null) {
610 title_elems.push(data['short_score']);
612 if (last_move !== null) {
613 title_elems.push(last_move);
616 if (title_elems.length != 0) {
617 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
619 document.title = 'analysis.sesse.net';
623 if (data['tablebase'] == 1) {
624 $("#searchstats").text("Tablebase result");
625 } else if (data['nodes'] && data['nps'] && data['depth']) {
626 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
627 if (data['seldepth']) {
628 stats += ' (' + data['seldepth'] + ' selective)';
630 if (data['tbhits'] && data['tbhits'] > 0) {
631 if (data['tbhits'] == 1) {
632 stats += ', one Syzygy hit';
634 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
638 $("#searchstats").text(stats);
640 $("#searchstats").text("");
643 // Update the board itself.
644 fen = data['position']['fen'];
645 update_displayed_line();
647 if (data['position']['last_move_uci']) {
648 highlight_from = data['position']['last_move_uci'].substr(0, 2);
649 highlight_to = data['position']['last_move_uci'].substr(2, 2);
651 highlight_from = highlight_to = undefined;
655 // Print the history.
656 if (data['position']['history']) {
657 add_pv('start', data['position']['history'], data['position']['pretty_history'], 1, 'W', 8, true);
659 display_lines.push(null);
664 $("#pv").html(add_pv(data['position']['fen'], data['pv_uci'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
666 // Update the PV arrow.
668 if (data['pv_uci'].length >= 1) {
669 // draw a continuation arrow as long as it's the same piece
670 for (var i = 0; i < data['pv_uci'].length; i += 2) {
671 var from = data['pv_uci'][i].substr(0, 2);
672 var to = data['pv_uci'][i].substr(2,4);
673 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
674 interfering_arrow(from, to)) {
677 create_arrow(from, to, '#f66', 6, 20);
680 var alt_moves = find_nonstupid_moves(data, 30);
681 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
682 create_arrow(alt_moves[i].substr(0, 2),
683 alt_moves[i].substr(2, 2), '#f66', 1, 10);
687 // See if all semi-reasonable moves have only one possible response.
688 if (data['pv_uci'].length >= 2) {
689 var nonstupid_moves = find_nonstupid_moves(data, 300);
690 var response = data['pv_uci'][1];
691 for (var i = 0; i < nonstupid_moves.length; ++i) {
692 if (nonstupid_moves[i] == data['pv_uci'][0]) {
693 // ignore the PV move for refutation lines.
696 if (!data['refutation_lines'] ||
697 !data['refutation_lines'][nonstupid_moves[i]] ||
698 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
699 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
700 // Incomplete PV, abort.
701 response = undefined;
704 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
705 if (response !== this_response) {
706 // Different response depending on lines, abort.
707 response = undefined;
712 if (nonstupid_moves.length > 0 && response !== undefined) {
713 create_arrow(response.substr(0, 2),
714 response.substr(2, 2), '#66f', 6, 20);
718 // Update the refutation lines.
719 fen = data['position']['fen'];
720 move_num = data['position']['move_num'];
721 toplay = data['position']['toplay'];
722 refutation_lines = data['refutation_lines'];
723 update_refutation_lines();
726 setTimeout(function() { request_update(); }, 100);
730 * @param {boolean} sort_by_score
732 var resort_refutation_lines = function(sort_by_score) {
733 sort_refutation_lines_by_score = sort_by_score;
734 update_refutation_lines();
736 window['resort_refutation_lines'] = resort_refutation_lines;
739 * @param {boolean} truncate_history
741 var set_truncate_history = function(truncate_history) {
742 truncate_display_history = truncate_history;
743 update_refutation_lines();
745 window['set_truncate_history'] = set_truncate_history;
748 * @param {number} line_num
749 * @param {number} move_num
751 var show_line = function(line_num, move_num) {
752 if (line_num == -1) {
753 current_display_line = null;
754 current_display_move = null;
756 current_display_line = display_lines[line_num];
757 current_display_move = move_num;
759 update_displayed_line();
763 window['show_line'] = show_line;
765 var prev_move = function() {
766 if (current_display_move > -1) {
767 --current_display_move;
769 update_displayed_line();
771 window['prev_move'] = prev_move;
773 var next_move = function() {
774 if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
775 ++current_display_move;
777 update_displayed_line();
779 window['next_move'] = next_move;
781 var update_displayed_line = function() {
782 if (highlighted_move !== null) {
783 highlighted_move.removeClass('highlight');
785 if (current_display_line === null) {
786 $("#linenav").hide();
787 $("#linemsg").show();
792 $("#linenav").show();
793 $("#linemsg").hide();
795 if (current_display_move <= 0) {
796 $("#prevmove").html("Previous");
798 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
800 if (current_display_move == current_display_line.uci_pv.length - 1) {
801 $("#nextmove").html("Next");
803 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
806 hiddenboard.position(current_display_line.start_fen, false);
807 for (var i = 0; i <= current_display_move; ++i) {
808 var pos = hiddenboard.position();
809 var move = current_display_line.uci_pv[i];
810 var source = move.substr(0, 2);
811 var target = move.substr(2, 2);
812 var promo = move.substr(4, 1);
814 // Check if we need to do en passant.
815 var piece = pos[source];
816 if (piece == "wP" || piece == "bP") {
817 if (source.substr(0, 1) != target.substr(0, 1) &&
818 pos[target] === undefined) {
819 var ep_square = target.substr(0, 1) + source.substr(1, 1);
820 delete pos[ep_square];
821 hiddenboard.position(pos, false);
825 move = source + "-" + target;
826 hiddenboard.move(move, false);
827 pos = hiddenboard.position();
829 // Do promotion if needed.
831 pos[target] = pos[target].substr(0, 1) + promo.toUpperCase();
832 hiddenboard.position(pos, false);
835 // chessboard.js does not automatically move the rook on castling
836 // (issue #51; marked as won't fix), so update it ourselves.
837 if (move == "e1-g1" && hiddenboard.position().g1 == "wK") { // white O-O
838 hiddenboard.move("h1-f1", false);
839 } else if (move == "e1-c1" && hiddenboard.position().c1 == "wK") { // white O-O-O
840 hiddenboard.move("a1-d1", false);
841 } else if (move == "e8-g8" && hiddenboard.position().g8 == "bK") { // black O-O
842 hiddenboard.move("h8-f8", false);
843 } else if (move == "e8-c8" && hiddenboard.position().c8 == "bK") { // black O-O-O
844 hiddenboard.move("a8-d8", false);
848 highlighted_move = $("#automove" + current_display_line.line_number + "-" + current_display_move);
849 highlighted_move.addClass('highlight');
851 board.position(hiddenboard.position());
854 var init = function() {
855 unique = get_unique();
858 board = new window.ChessBoard('board', 'start');
859 hiddenboard = new window.ChessBoard('hiddenboard', 'start');
862 $(window).resize(function() {
867 $(window).keyup(function(event) {
868 if (event.which == 39) {
870 } else if (event.which == 37) {
875 $(document).ready(init);