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 {!number} @private */
49 var unique = Math.random();
51 /** The current position on the board, represented as a FEN string.
59 * uci_pv: Array.<string>,
60 * pretty_pv: Array.<string>
64 /** @type {Array.<DisplayLine>}
67 var display_lines = [];
69 /** @type {?DisplayLine} @private */
70 var current_display_line = null;
72 /** @type {?number} @private */
73 var current_display_move = null;
75 var request_update = function() {
77 url: "http://analysis.sesse.net/analysis.pl?ims=" + ims + "&unique=" + unique
78 //url: "http://analysis.sesse.net:5000/analysis.pl?ims=" + ims + "&unique=" + unique
79 }).done(function(data, textstatus, xhr) {
80 ims = xhr.getResponseHeader('X-Remoteglot-Last-Modified');
81 var num_viewers = xhr.getResponseHeader('X-Remoteglot-Num-Viewers');
82 update_board(data, num_viewers);
84 // Wait ten seconds, then try again.
85 setTimeout(function() { request_update(); }, 10000);
89 var clear_arrows = function() {
90 for (var i = 0; i < arrows.length; ++i) {
92 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
98 occupied_by_arrows = [];
99 for (var y = 0; y < 8; ++y) {
100 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
104 var redraw_arrows = function() {
105 for (var i = 0; i < arrows.length; ++i) {
106 position_arrow(arrows[i]);
110 /** @param {!number} x
113 var sign = function(x) {
123 /** See if drawing this arrow on the board would cause unduly amount of confusion.
124 * @param {!string} from The square the arrow is from (e.g. e4).
125 * @param {!string} to The square the arrow is to (e.g. e4).
128 var interfering_arrow = function(from, to) {
129 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
130 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
131 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
132 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
134 occupied_by_arrows[from_row][from_col] = true;
136 // Knight move: Just check that we haven't been at the destination before.
137 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
138 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
139 return occupied_by_arrows[to_row][to_col];
142 // Sliding piece: Check if anything except the from-square is seen before.
143 var dx = sign(to_col - from_col);
144 var dy = sign(to_row - from_row);
150 if (occupied_by_arrows[y][x]) {
153 occupied_by_arrows[y][x] = true;
154 } while (x != to_col || y != to_row);
159 /** Find a point along the coordinate system given by the given line,
160 * <t> units forward from the start of the line, <u> units to the right of it.
161 * @param {!number} x1
162 * @param {!number} x2
163 * @param {!number} y1
164 * @param {!number} y2
167 * @return {!string} The point in "x y" form, suitable for SVG paths.
169 var point_from_start = function(x1, y1, x2, y2, t, u) {
173 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
177 var x = x1 + dx * t + dy * u;
178 var y = y1 + dy * t - dx * u;
182 /** Find a point along the coordinate system given by the given line,
183 * <t> units forward from the end of the line, <u> units to the right of it.
184 * @param {!number} x1
185 * @param {!number} x2
186 * @param {!number} y1
187 * @param {!number} y2
190 * @return {!string} The point in "x y" form, suitable for SVG paths.
192 var point_from_end = function(x1, y1, x2, y2, t, u) {
196 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
200 var x = x2 + dx * t + dy * u;
201 var y = y2 + dy * t - dx * u;
205 var position_arrow = function(arrow) {
207 arrow.svg.parentElement.removeChild(arrow.svg);
210 if (current_display_line !== null) {
214 var pos = $(".square-a8").position();
216 var zoom_factor = $("#board").width() / 400.0;
217 var line_width = arrow.line_width * zoom_factor;
218 var arrow_size = arrow.arrow_size * zoom_factor;
220 var square_width = $(".square-a8").width();
221 var from_y = (7 - arrow.from_row + 0.5)*square_width;
222 var to_y = (7 - arrow.to_row + 0.5)*square_width;
223 var from_x = (arrow.from_col + 0.5)*square_width;
224 var to_x = (arrow.to_col + 0.5)*square_width;
226 var SVG_NS = "http://www.w3.org/2000/svg";
227 var XHTML_NS = "http://www.w3.org/1999/xhtml";
228 var svg = document.createElementNS(SVG_NS, "svg");
229 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
230 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
231 svg.setAttribute("style", "position: absolute");
232 svg.setAttribute("position", "absolute");
233 svg.setAttribute("version", "1.1");
234 svg.setAttribute("class", "c1");
235 svg.setAttribute("xmlns", XHTML_NS);
243 var outline = document.createElementNS(SVG_NS, "path");
244 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));
245 outline.setAttribute("xmlns", XHTML_NS);
246 outline.setAttribute("stroke", "#666");
247 outline.setAttribute("stroke-width", line_width + 2);
248 outline.setAttribute("fill", "none");
249 svg.appendChild(outline);
251 var path = document.createElementNS(SVG_NS, "path");
252 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));
253 path.setAttribute("xmlns", XHTML_NS);
254 path.setAttribute("stroke", arrow.fg_color);
255 path.setAttribute("stroke-width", line_width);
256 path.setAttribute("fill", "none");
257 svg.appendChild(path);
259 // Then the arrow head.
260 var head = document.createElementNS(SVG_NS, "path");
261 head.setAttribute("d",
262 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
263 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
264 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
265 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
266 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
267 head.setAttribute("xmlns", XHTML_NS);
268 head.setAttribute("stroke", "#000");
269 head.setAttribute("stroke-width", "1");
270 head.setAttribute("fill", arrow.fg_color);
271 svg.appendChild(head);
273 $(svg).css({ top: pos.top, left: pos.left });
274 document.body.appendChild(svg);
279 * @param {!string} from_square
280 * @param {!string} to_square
281 * @param {!string} fg_color
282 * @param {number} line_width
283 * @param {number} arrow_size
285 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
286 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
287 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
288 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
289 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
297 line_width: line_width,
298 arrow_size: arrow_size,
302 position_arrow(arrow);
306 var compare_by_sort_key = function(refutation_lines, a, b) {
307 var ska = refutation_lines[a]['sort_key'];
308 var skb = refutation_lines[b]['sort_key'];
309 if (ska < skb) return -1;
310 if (ska > skb) return 1;
314 var compare_by_score = function(refutation_lines, a, b) {
315 var sa = parseInt(refutation_lines[b]['score_sort_key'], 10);
316 var sb = parseInt(refutation_lines[a]['score_sort_key'], 10);
321 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
322 * sorted by quality, descending.
324 * @param {!Object} data
325 * @param {number} margin The maximum number of centipawns worse than the
326 * best move can be and still be included.
327 * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
328 * moves, in score order.
330 var find_nonstupid_moves = function(data, margin) {
331 // First of all, if there are any moves that are more than 0.5 ahead of
332 // the primary move, the refutation lines are probably bunk, so just
334 var best_score = undefined;
335 var pv_score = undefined;
336 for (var move in data['refutation_lines']) {
337 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
338 if (move == data['pv_uci'][0]) {
341 if (best_score === undefined || score > best_score) {
344 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
349 if (best_score - pv_score > 50) {
353 // Now find all moves that are within “margin” of the best score.
354 // The PV move will always be first.
356 for (var move in data['refutation_lines']) {
357 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
358 if (move != data['pv_uci'][0] && best_score - score <= margin) {
362 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], a, b) });
363 moves.unshift(data['pv_uci'][0]);
372 var thousands = function(x) {
373 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
377 * @param {!string} fen
378 * @param {Array.<string>} uci_pv
379 * @param {Array.<string>} pretty_pv
380 * @param {number} move_num
381 * @param {!string} toplay
382 * @param {number=} opt_limit
383 * @param {boolean=} opt_showlast
385 var add_pv = function(fen, uci_pv, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
391 return print_pv(display_lines.length - 1, pretty_pv, move_num, toplay, opt_limit, opt_showlast);
395 * @param {number} line_num
396 * @param {Array.<string>} pretty_pv
397 * @param {number} move_num
398 * @param {!string} toplay
399 * @param {number=} opt_limit
400 * @param {boolean=} opt_showlast
402 var print_pv = function(line_num, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
405 if (opt_limit && opt_showlast) {
406 // Truncate the PV at the beginning (instead of at the end).
407 // We assume here that toplay is 'W'. We also assume that if
408 // opt_showlast is set, then it is the history, and thus,
409 // the UI should be to expand the history.
410 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
411 i = pretty_pv.length - opt_limit;
416 } else if (toplay == 'B') {
417 var move = "<a class=\"move\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
418 pv = move_num + '. … ' + move;
423 for ( ; i < pretty_pv.length; ++i) {
424 var move = "<a class=\"move\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
427 if (i > opt_limit && !opt_showlast) {
433 pv += move_num + '. ' + move;
444 var update_highlight = function() {
445 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
446 if (current_display_line === null && highlight_from !== undefined && highlight_to !== undefined) {
447 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
448 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
452 var update_history = function() {
453 if (display_lines[0] === null) {
454 $("#history").html("No history");
455 } else if (truncate_display_history) {
456 $("#history").html(print_pv(0, display_lines[0].pretty_pv, 1, 'W', 8, true));
459 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
460 print_pv(0, display_lines[0].pretty_pv, 1, 'W'));
465 * @param {!boolean} truncate_history
467 var collapse_history = function(truncate_history) {
468 truncate_display_history = truncate_history;
471 window['collapse_history'] = collapse_history;
473 var update_refutation_lines = function() {
477 if (display_lines.length > 1) {
478 display_lines = [ display_lines[0] ];
481 var tbl = $("#refutationlines");
485 for (var move in refutation_lines) {
488 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
489 moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
490 for (var i = 0; i < moves.length; ++i) {
491 var line = refutation_lines[moves[i]];
493 var tr = document.createElement("tr");
495 var move_td = document.createElement("td");
496 tr.appendChild(move_td);
497 $(move_td).addClass("move");
498 if (line['pv_uci'].length == 0) {
499 $(move_td).text(line['pretty_move']);
501 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
502 $(move_td).html(move);
505 var score_td = document.createElement("td");
506 tr.appendChild(score_td);
507 $(score_td).addClass("score");
508 $(score_td).text(line['pretty_score']);
510 var depth_td = document.createElement("td");
511 tr.appendChild(depth_td);
512 $(depth_td).addClass("depth");
513 $(depth_td).text("d" + line['depth']);
515 var pv_td = document.createElement("td");
516 tr.appendChild(pv_td);
517 $(pv_td).addClass("pv");
518 $(pv_td).html(add_pv(fen, line['pv_uci'], line['pv_pretty'], move_num, toplay, 10));
523 // Make one of the links clickable and the other nonclickable.
524 if (sort_refutation_lines_by_score) {
525 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
526 $("#sortbyscore1").html("<strong>Score</strong>");
528 $("#sortbyscore0").html("<strong>Move</strong>");
529 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
534 * @param {Object} data
535 * @param {number} num_viewers
537 var update_board = function(data, num_viewers) {
542 if (data['position']['player_w'] && data['position']['player_b']) {
543 headline = data['position']['player_w'] + '–' +
544 data['position']['player_b'] + ', analysis';
546 headline = 'Analysis';
548 if (data['position']['last_move'] !== 'none') {
549 headline += ' after '
550 if (data['position']['toplay'] == 'W') {
551 headline += (data['position']['move_num']-1) + '… ';
553 headline += data['position']['move_num'] + '. ';
555 headline += data['position']['last_move'];
558 $("#headline").text(headline);
560 if (num_viewers === null) {
561 $("#numviewers").text("");
562 } else if (num_viewers == 1) {
563 $("#numviewers").text("You are the only current viewer");
565 $("#numviewers").text(num_viewers + " current viewers");
569 if (data['id'] && data['id']['name'] !== null) {
570 $("#engineid").text(data['id']['name']);
574 if (data['score'] !== null) {
575 $("#score").text(data['score']);
579 if (data['nodes'] && data['nps'] && data['depth']) {
580 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
581 if (data['seldepth']) {
582 stats += ' (' + data['seldepth'] + ' selective)';
584 if (data['tbhits'] && data['tbhits'] > 0) {
585 if (data['tbhits'] == 1) {
586 stats += ', one Syzygy hit';
588 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
592 $("#searchstats").text(stats);
595 // Update the board itself.
596 fen = data['position']['fen'];
597 update_displayed_line();
599 if (data['position']['last_move_uci']) {
600 highlight_from = data['position']['last_move_uci'].substr(0, 2);
601 highlight_to = data['position']['last_move_uci'].substr(2, 4);
603 highlight_from = highlight_to = undefined;
607 // Print the history.
608 if (data['position']['history']) {
609 add_pv('start', data['position']['history'], data['position']['pretty_history'], 1, 'W', 8, true);
611 displayed_lines.push(null);
616 $("#pv").html(add_pv(data['position']['fen'], data['pv_uci'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
618 // Update the PV arrow.
620 if (data['pv_uci'].length >= 1) {
621 // draw a continuation arrow as long as it's the same piece
622 for (var i = 0; i < data['pv_uci'].length; i += 2) {
623 var from = data['pv_uci'][i].substr(0, 2);
624 var to = data['pv_uci'][i].substr(2,4);
625 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 4)) ||
626 interfering_arrow(from, to)) {
629 create_arrow(from, to, '#f66', 6, 20);
632 var alt_moves = find_nonstupid_moves(data, 30);
633 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
634 create_arrow(alt_moves[i].substr(0, 2),
635 alt_moves[i].substr(2, 4), '#f66', 1, 10);
639 // See if all semi-reasonable moves have only one possible response.
640 if (data['pv_uci'].length >= 2) {
641 var nonstupid_moves = find_nonstupid_moves(data, 300);
642 var response = data['pv_uci'][1];
643 for (var i = 0; i < nonstupid_moves.length; ++i) {
644 if (nonstupid_moves[i] == data['pv_uci'][0]) {
645 // ignore the PV move for refutation lines.
648 if (!data['refutation_lines'] ||
649 !data['refutation_lines'][nonstupid_moves[i]] ||
650 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
651 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
652 // Incomplete PV, abort.
653 response = undefined;
656 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
657 if (response !== this_response) {
658 // Different response depending on lines, abort.
659 response = undefined;
664 if (nonstupid_moves.length > 0 && response !== undefined) {
665 create_arrow(response.substr(0, 2),
666 response.substr(2, 4), '#66f', 6, 20);
670 // Update the refutation lines.
671 fen = data['position']['fen'];
672 move_num = data['position']['move_num'];
673 toplay = data['position']['toplay'];
674 refutation_lines = data['refutation_lines'];
675 update_refutation_lines();
678 setTimeout(function() { request_update(); }, 100);
682 * @param {boolean} sort_by_score
684 var resort_refutation_lines = function(sort_by_score) {
685 sort_refutation_lines_by_score = sort_by_score;
686 update_refutation_lines();
688 window['resort_refutation_lines'] = resort_refutation_lines;
691 * @param {boolean} truncate_history
693 var set_truncate_history = function(truncate_history) {
694 truncate_display_history = truncate_history;
695 update_refutation_lines();
697 window['set_truncate_history'] = set_truncate_history;
700 * @param {number} line_num
701 * @param {number} move_num
703 var show_line = function(line_num, move_num) {
704 if (line_num == -1) {
705 current_display_line = null;
706 current_display_move = null;
708 current_display_line = display_lines[line_num];
709 current_display_move = move_num;
711 update_displayed_line();
715 window['show_line'] = show_line;
717 var prev_move = function() {
718 if (current_display_move > -1) {
719 --current_display_move;
721 update_displayed_line();
723 window['prev_move'] = prev_move;
725 var next_move = function() {
726 if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
727 ++current_display_move;
729 update_displayed_line();
731 window['next_move'] = next_move;
733 var update_displayed_line = function() {
734 if (current_display_line === null) {
735 $("#linenav").hide();
736 $("#linemsg").show();
741 $("#linenav").show();
742 $("#linemsg").hide();
744 if (current_display_move == 0) {
745 $("#prevmove").html("Previous");
747 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
749 if (current_display_move == current_display_line.uci_pv.length - 1) {
750 $("#nextmove").html("Next");
752 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
755 hiddenboard.position(current_display_line.start_fen, false);
756 for (var i = 0; i <= current_display_move; ++i) {
757 var move = current_display_line.uci_pv[i];
758 move = move.substr(0, 2) + "-" + move.substr(2, 4);
759 hiddenboard.move(move, false);
761 // chessboard.js does not automatically move the rook on castling
762 // (issue #51; marked as won't fix), so update it ourselves.
763 if (move == "e1-g1" && hiddenboard.position().g1 == "wK") { // white O-O
764 hiddenboard.move("h1-f1", false);
765 } else if (move == "e1-c1" && hiddenboard.position().c1 == "wK") { // white O-O-O
766 hiddenboard.move("a1-d1", false);
767 } else if (move == "e8-g8" && hiddenboard.position().g8 == "bK") { // black O-O
768 hiddenboard.move("h8-f8", false);
769 } else if (move == "e8-c8" && hiddenboard.position().c8 == "bK") { // black O-O-O
770 hiddenboard.move("a8-d8", false);
773 board.position(hiddenboard.position());
776 var init = function() {
778 board = new window.ChessBoard('board', 'start');
779 hiddenboard = new window.ChessBoard('hiddenboard', 'start');
782 $(window).resize(function() {
787 $(window).keyup(function(event) {
788 if (event.which == 39) {
790 } else if (event.which == 37) {
795 $(document).ready(init);