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 */
52 var unique = Math.random();
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 request_update = function() {
81 url: "http://analysis.sesse.net/analysis.pl?ims=" + ims + "&unique=" + unique
82 //url: "http://analysis.sesse.net:5000/analysis.pl?ims=" + ims + "&unique=" + unique
83 }).done(function(data, textstatus, xhr) {
84 ims = xhr.getResponseHeader('X-Remoteglot-Last-Modified');
85 var num_viewers = xhr.getResponseHeader('X-Remoteglot-Num-Viewers');
86 update_board(data, num_viewers);
88 // Wait ten seconds, then try again.
89 setTimeout(function() { request_update(); }, 10000);
93 var clear_arrows = function() {
94 for (var i = 0; i < arrows.length; ++i) {
96 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
102 occupied_by_arrows = [];
103 for (var y = 0; y < 8; ++y) {
104 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
108 var redraw_arrows = function() {
109 for (var i = 0; i < arrows.length; ++i) {
110 position_arrow(arrows[i]);
114 /** @param {!number} x
117 var sign = function(x) {
127 /** See if drawing this arrow on the board would cause unduly amount of confusion.
128 * @param {!string} from The square the arrow is from (e.g. e4).
129 * @param {!string} to The square the arrow is to (e.g. e4).
132 var interfering_arrow = function(from, to) {
133 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
134 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
135 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
136 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
138 occupied_by_arrows[from_row][from_col] = true;
140 // Knight move: Just check that we haven't been at the destination before.
141 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
142 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
143 return occupied_by_arrows[to_row][to_col];
146 // Sliding piece: Check if anything except the from-square is seen before.
147 var dx = sign(to_col - from_col);
148 var dy = sign(to_row - from_row);
154 if (occupied_by_arrows[y][x]) {
157 occupied_by_arrows[y][x] = true;
158 } while (x != to_col || y != to_row);
163 /** Find a point along the coordinate system given by the given line,
164 * <t> units forward from the start of the line, <u> units to the right of it.
165 * @param {!number} x1
166 * @param {!number} x2
167 * @param {!number} y1
168 * @param {!number} y2
171 * @return {!string} The point in "x y" form, suitable for SVG paths.
173 var point_from_start = function(x1, y1, x2, y2, t, u) {
177 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
181 var x = x1 + dx * t + dy * u;
182 var y = y1 + dy * t - dx * u;
186 /** Find a point along the coordinate system given by the given line,
187 * <t> units forward from the end of the line, <u> units to the right of it.
188 * @param {!number} x1
189 * @param {!number} x2
190 * @param {!number} y1
191 * @param {!number} y2
194 * @return {!string} The point in "x y" form, suitable for SVG paths.
196 var point_from_end = function(x1, y1, x2, y2, t, u) {
200 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
204 var x = x2 + dx * t + dy * u;
205 var y = y2 + dy * t - dx * u;
209 var position_arrow = function(arrow) {
211 arrow.svg.parentElement.removeChild(arrow.svg);
214 if (current_display_line !== null) {
218 var pos = $(".square-a8").position();
220 var zoom_factor = $("#board").width() / 400.0;
221 var line_width = arrow.line_width * zoom_factor;
222 var arrow_size = arrow.arrow_size * zoom_factor;
224 var square_width = $(".square-a8").width();
225 var from_y = (7 - arrow.from_row + 0.5)*square_width;
226 var to_y = (7 - arrow.to_row + 0.5)*square_width;
227 var from_x = (arrow.from_col + 0.5)*square_width;
228 var to_x = (arrow.to_col + 0.5)*square_width;
230 var SVG_NS = "http://www.w3.org/2000/svg";
231 var XHTML_NS = "http://www.w3.org/1999/xhtml";
232 var svg = document.createElementNS(SVG_NS, "svg");
233 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
234 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
235 svg.setAttribute("style", "position: absolute");
236 svg.setAttribute("position", "absolute");
237 svg.setAttribute("version", "1.1");
238 svg.setAttribute("class", "c1");
239 svg.setAttribute("xmlns", XHTML_NS);
247 var outline = document.createElementNS(SVG_NS, "path");
248 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));
249 outline.setAttribute("xmlns", XHTML_NS);
250 outline.setAttribute("stroke", "#666");
251 outline.setAttribute("stroke-width", line_width + 2);
252 outline.setAttribute("fill", "none");
253 svg.appendChild(outline);
255 var path = document.createElementNS(SVG_NS, "path");
256 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));
257 path.setAttribute("xmlns", XHTML_NS);
258 path.setAttribute("stroke", arrow.fg_color);
259 path.setAttribute("stroke-width", line_width);
260 path.setAttribute("fill", "none");
261 svg.appendChild(path);
263 // Then the arrow head.
264 var head = document.createElementNS(SVG_NS, "path");
265 head.setAttribute("d",
266 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
267 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
268 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
269 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
270 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
271 head.setAttribute("xmlns", XHTML_NS);
272 head.setAttribute("stroke", "#000");
273 head.setAttribute("stroke-width", "1");
274 head.setAttribute("fill", arrow.fg_color);
275 svg.appendChild(head);
277 $(svg).css({ top: pos.top, left: pos.left });
278 document.body.appendChild(svg);
283 * @param {!string} from_square
284 * @param {!string} to_square
285 * @param {!string} fg_color
286 * @param {number} line_width
287 * @param {number} arrow_size
289 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
290 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
291 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
292 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
293 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
301 line_width: line_width,
302 arrow_size: arrow_size,
306 position_arrow(arrow);
310 var compare_by_sort_key = function(refutation_lines, a, b) {
311 var ska = refutation_lines[a]['sort_key'];
312 var skb = refutation_lines[b]['sort_key'];
313 if (ska < skb) return -1;
314 if (ska > skb) return 1;
318 var compare_by_score = function(refutation_lines, a, b) {
319 var sa = parseInt(refutation_lines[b]['score_sort_key'], 10);
320 var sb = parseInt(refutation_lines[a]['score_sort_key'], 10);
325 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
326 * sorted by quality, descending.
328 * @param {!Object} data
329 * @param {number} margin The maximum number of centipawns worse than the
330 * best move can be and still be included.
331 * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
332 * moves, in score order.
334 var find_nonstupid_moves = function(data, margin) {
335 // First of all, if there are any moves that are more than 0.5 ahead of
336 // the primary move, the refutation lines are probably bunk, so just
338 var best_score = undefined;
339 var pv_score = undefined;
340 for (var move in data['refutation_lines']) {
341 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
342 if (move == data['pv_uci'][0]) {
345 if (best_score === undefined || score > best_score) {
348 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
353 if (best_score - pv_score > 50) {
357 // Now find all moves that are within “margin” of the best score.
358 // The PV move will always be first.
360 for (var move in data['refutation_lines']) {
361 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
362 if (move != data['pv_uci'][0] && best_score - score <= margin) {
366 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], a, b) });
367 moves.unshift(data['pv_uci'][0]);
376 var thousands = function(x) {
377 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
381 * @param {!string} fen
382 * @param {Array.<string>} uci_pv
383 * @param {Array.<string>} pretty_pv
384 * @param {number} move_num
385 * @param {!string} toplay
386 * @param {number=} opt_limit
387 * @param {boolean=} opt_showlast
389 var add_pv = function(fen, uci_pv, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
393 pretty_pv: pretty_pv,
394 line_number: display_lines.length
396 return print_pv(display_lines.length - 1, pretty_pv, move_num, toplay, opt_limit, opt_showlast);
400 * @param {number} line_num
401 * @param {Array.<string>} pretty_pv
402 * @param {number} move_num
403 * @param {!string} toplay
404 * @param {number=} opt_limit
405 * @param {boolean=} opt_showlast
407 var print_pv = function(line_num, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
410 if (opt_limit && opt_showlast) {
411 // Truncate the PV at the beginning (instead of at the end).
412 // We assume here that toplay is 'W'. We also assume that if
413 // opt_showlast is set, then it is the history, and thus,
414 // the UI should be to expand the history.
415 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
416 i = pretty_pv.length - opt_limit;
421 } else if (toplay == 'B') {
422 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
423 pv = move_num + '. … ' + move;
428 for ( ; i < pretty_pv.length; ++i) {
429 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
432 if (i > opt_limit && !opt_showlast) {
438 pv += move_num + '. ' + move;
449 var update_highlight = function() {
450 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
451 if (current_display_line === null && highlight_from !== undefined && highlight_to !== undefined) {
452 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
453 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
457 var update_history = function() {
458 if (display_lines[0] === null) {
459 $("#history").html("No history");
460 } else if (truncate_display_history) {
461 $("#history").html(print_pv(0, display_lines[0].pretty_pv, 1, 'W', 8, true));
464 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
465 print_pv(0, display_lines[0].pretty_pv, 1, 'W'));
470 * @param {!boolean} truncate_history
472 var collapse_history = function(truncate_history) {
473 truncate_display_history = truncate_history;
476 window['collapse_history'] = collapse_history;
478 var update_refutation_lines = function() {
482 if (display_lines.length > 2) {
483 display_lines = [ display_lines[0], display_lines[1] ];
486 var tbl = $("#refutationlines");
490 for (var move in refutation_lines) {
493 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
494 moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
495 for (var i = 0; i < moves.length; ++i) {
496 var line = refutation_lines[moves[i]];
498 var tr = document.createElement("tr");
500 var move_td = document.createElement("td");
501 tr.appendChild(move_td);
502 $(move_td).addClass("move");
503 if (line['pv_uci'].length == 0) {
504 $(move_td).text(line['pretty_move']);
506 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
507 $(move_td).html(move);
510 var score_td = document.createElement("td");
511 tr.appendChild(score_td);
512 $(score_td).addClass("score");
513 $(score_td).text(line['pretty_score']);
515 var depth_td = document.createElement("td");
516 tr.appendChild(depth_td);
517 $(depth_td).addClass("depth");
518 $(depth_td).text("d" + line['depth']);
520 var pv_td = document.createElement("td");
521 tr.appendChild(pv_td);
522 $(pv_td).addClass("pv");
523 $(pv_td).html(add_pv(fen, line['pv_uci'], line['pv_pretty'], move_num, toplay, 10));
528 // Make one of the links clickable and the other nonclickable.
529 if (sort_refutation_lines_by_score) {
530 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
531 $("#sortbyscore1").html("<strong>Score</strong>");
533 $("#sortbyscore0").html("<strong>Move</strong>");
534 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
539 * @param {Object} data
540 * @param {number} num_viewers
542 var update_board = function(data, num_viewers) {
547 if (data['position']['player_w'] && data['position']['player_b']) {
548 headline = data['position']['player_w'] + '–' +
549 data['position']['player_b'] + ', analysis';
551 headline = 'Analysis';
553 if (data['position']['last_move'] !== 'none') {
554 headline += ' after '
555 if (data['position']['toplay'] == 'W') {
556 headline += (data['position']['move_num']-1) + '… ';
558 headline += data['position']['move_num'] + '. ';
560 headline += data['position']['last_move'];
563 $("#headline").text(headline);
565 if (num_viewers === null) {
566 $("#numviewers").text("");
567 } else if (num_viewers == 1) {
568 $("#numviewers").text("You are the only current viewer");
570 $("#numviewers").text(num_viewers + " current viewers");
574 if (data['id'] && data['id']['name'] !== null) {
575 $("#engineid").text(data['id']['name']);
579 if (data['score'] !== null) {
580 $("#score").text(data['score']);
584 if (data['nodes'] && data['nps'] && data['depth']) {
585 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
586 if (data['seldepth']) {
587 stats += ' (' + data['seldepth'] + ' selective)';
589 if (data['tbhits'] && data['tbhits'] > 0) {
590 if (data['tbhits'] == 1) {
591 stats += ', one Syzygy hit';
593 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
597 $("#searchstats").text(stats);
600 // Update the board itself.
601 fen = data['position']['fen'];
602 update_displayed_line();
604 if (data['position']['last_move_uci']) {
605 highlight_from = data['position']['last_move_uci'].substr(0, 2);
606 highlight_to = data['position']['last_move_uci'].substr(2, 2);
608 highlight_from = highlight_to = undefined;
612 // Print the history.
613 if (data['position']['history']) {
614 add_pv('start', data['position']['history'], data['position']['pretty_history'], 1, 'W', 8, true);
616 display_lines.push(null);
621 $("#pv").html(add_pv(data['position']['fen'], data['pv_uci'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
623 // Update the PV arrow.
625 if (data['pv_uci'].length >= 1) {
626 // draw a continuation arrow as long as it's the same piece
627 for (var i = 0; i < data['pv_uci'].length; i += 2) {
628 var from = data['pv_uci'][i].substr(0, 2);
629 var to = data['pv_uci'][i].substr(2,4);
630 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
631 interfering_arrow(from, to)) {
634 create_arrow(from, to, '#f66', 6, 20);
637 var alt_moves = find_nonstupid_moves(data, 30);
638 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
639 create_arrow(alt_moves[i].substr(0, 2),
640 alt_moves[i].substr(2, 2), '#f66', 1, 10);
644 // See if all semi-reasonable moves have only one possible response.
645 if (data['pv_uci'].length >= 2) {
646 var nonstupid_moves = find_nonstupid_moves(data, 300);
647 var response = data['pv_uci'][1];
648 for (var i = 0; i < nonstupid_moves.length; ++i) {
649 if (nonstupid_moves[i] == data['pv_uci'][0]) {
650 // ignore the PV move for refutation lines.
653 if (!data['refutation_lines'] ||
654 !data['refutation_lines'][nonstupid_moves[i]] ||
655 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
656 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
657 // Incomplete PV, abort.
658 response = undefined;
661 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
662 if (response !== this_response) {
663 // Different response depending on lines, abort.
664 response = undefined;
669 if (nonstupid_moves.length > 0 && response !== undefined) {
670 create_arrow(response.substr(0, 2),
671 response.substr(2, 2), '#66f', 6, 20);
675 // Update the refutation lines.
676 fen = data['position']['fen'];
677 move_num = data['position']['move_num'];
678 toplay = data['position']['toplay'];
679 refutation_lines = data['refutation_lines'];
680 update_refutation_lines();
683 setTimeout(function() { request_update(); }, 100);
687 * @param {boolean} sort_by_score
689 var resort_refutation_lines = function(sort_by_score) {
690 sort_refutation_lines_by_score = sort_by_score;
691 update_refutation_lines();
693 window['resort_refutation_lines'] = resort_refutation_lines;
696 * @param {boolean} truncate_history
698 var set_truncate_history = function(truncate_history) {
699 truncate_display_history = truncate_history;
700 update_refutation_lines();
702 window['set_truncate_history'] = set_truncate_history;
705 * @param {number} line_num
706 * @param {number} move_num
708 var show_line = function(line_num, move_num) {
709 if (line_num == -1) {
710 current_display_line = null;
711 current_display_move = null;
713 current_display_line = display_lines[line_num];
714 current_display_move = move_num;
716 update_displayed_line();
720 window['show_line'] = show_line;
722 var prev_move = function() {
723 if (current_display_move > -1) {
724 --current_display_move;
726 update_displayed_line();
728 window['prev_move'] = prev_move;
730 var next_move = function() {
731 if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
732 ++current_display_move;
734 update_displayed_line();
736 window['next_move'] = next_move;
738 var update_displayed_line = function() {
739 if (highlighted_move !== null) {
740 highlighted_move.removeClass('highlight');
742 if (current_display_line === null) {
743 $("#linenav").hide();
744 $("#linemsg").show();
749 $("#linenav").show();
750 $("#linemsg").hide();
752 if (current_display_move == 0) {
753 $("#prevmove").html("Previous");
755 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
757 if (current_display_move == current_display_line.uci_pv.length - 1) {
758 $("#nextmove").html("Next");
760 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
763 hiddenboard.position(current_display_line.start_fen, false);
764 for (var i = 0; i <= current_display_move; ++i) {
765 var move = current_display_line.uci_pv[i];
766 move = move.substr(0, 2) + "-" + move.substr(2, 2);
767 hiddenboard.move(move, false);
769 // chessboard.js does not automatically move the rook on castling
770 // (issue #51; marked as won't fix), so update it ourselves.
771 if (move == "e1-g1" && hiddenboard.position().g1 == "wK") { // white O-O
772 hiddenboard.move("h1-f1", false);
773 } else if (move == "e1-c1" && hiddenboard.position().c1 == "wK") { // white O-O-O
774 hiddenboard.move("a1-d1", false);
775 } else if (move == "e8-g8" && hiddenboard.position().g8 == "bK") { // black O-O
776 hiddenboard.move("h8-f8", false);
777 } else if (move == "e8-c8" && hiddenboard.position().c8 == "bK") { // black O-O-O
778 hiddenboard.move("a8-d8", false);
782 highlighted_move = $("#automove" + current_display_line.line_number + "-" + current_display_move);
783 highlighted_move.addClass('highlight');
785 board.position(hiddenboard.position());
788 var init = function() {
790 board = new window.ChessBoard('board', 'start');
791 hiddenboard = new window.ChessBoard('hiddenboard', 'start');
794 $(window).resize(function() {
799 $(window).keyup(function(event) {
800 if (event.which == 39) {
802 } else if (event.which == 37) {
807 $(document).ready(init);