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 {!string|undefined} @private */
40 var highlight_from = undefined;
42 /** @type {!string|undefined} @private */
43 var highlight_to = undefined;
45 /** @type {!number} @private */
46 var unique = Math.random();
48 /** The current position on the board, represented as a FEN string.
56 * uci_pv: Array.<string>,
57 * pretty_pv: Array.<string>
61 /** @type {Array.<DisplayLine>}
64 var display_lines = [];
66 /** @type {?DisplayLine} @private */
67 var current_display_line = null;
69 /** @type {?number} @private */
70 var current_display_move = null;
72 var request_update = function() {
74 url: "http://analysis.sesse.net/analysis.pl?ims=" + ims + "&unique=" + unique
75 //url: "http://analysis.sesse.net:5000/analysis.pl?ims=" + ims + "&unique=" + unique
76 }).done(function(data, textstatus, xhr) {
77 ims = xhr.getResponseHeader('X-Remoteglot-Last-Modified');
78 var num_viewers = xhr.getResponseHeader('X-Remoteglot-Num-Viewers');
79 update_board(data, num_viewers);
81 // Wait ten seconds, then try again.
82 setTimeout(function() { request_update(); }, 10000);
86 var clear_arrows = function() {
87 for (var i = 0; i < arrows.length; ++i) {
89 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
95 occupied_by_arrows = [];
96 for (var y = 0; y < 8; ++y) {
97 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
101 var redraw_arrows = function() {
102 for (var i = 0; i < arrows.length; ++i) {
103 position_arrow(arrows[i]);
107 /** @param {!number} x
110 var sign = function(x) {
120 /** See if drawing this arrow on the board would cause unduly amount of confusion.
121 * @param {!string} from The square the arrow is from (e.g. e4).
122 * @param {!string} to The square the arrow is to (e.g. e4).
125 var interfering_arrow = function(from, to) {
126 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
127 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
128 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
129 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
131 occupied_by_arrows[from_row][from_col] = true;
133 // Knight move: Just check that we haven't been at the destination before.
134 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
135 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
136 return occupied_by_arrows[to_row][to_col];
139 // Sliding piece: Check if anything except the from-square is seen before.
140 var dx = sign(to_col - from_col);
141 var dy = sign(to_row - from_row);
147 if (occupied_by_arrows[y][x]) {
150 occupied_by_arrows[y][x] = true;
151 } while (x != to_col || y != to_row);
156 /** Find a point along the coordinate system given by the given line,
157 * <t> units forward from the start of the line, <u> units to the right of it.
158 * @param {!number} x1
159 * @param {!number} x2
160 * @param {!number} y1
161 * @param {!number} y2
164 * @return {!string} The point in "x y" form, suitable for SVG paths.
166 var point_from_start = function(x1, y1, x2, y2, t, u) {
170 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
174 var x = x1 + dx * t + dy * u;
175 var y = y1 + dy * t - dx * u;
179 /** Find a point along the coordinate system given by the given line,
180 * <t> units forward from the end of the line, <u> units to the right of it.
181 * @param {!number} x1
182 * @param {!number} x2
183 * @param {!number} y1
184 * @param {!number} y2
187 * @return {!string} The point in "x y" form, suitable for SVG paths.
189 var point_from_end = function(x1, y1, x2, y2, t, u) {
193 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
197 var x = x2 + dx * t + dy * u;
198 var y = y2 + dy * t - dx * u;
202 var position_arrow = function(arrow) {
204 arrow.svg.parentElement.removeChild(arrow.svg);
207 if (current_display_line !== null) {
211 var pos = $(".square-a8").position();
213 var zoom_factor = $("#board").width() / 400.0;
214 var line_width = arrow.line_width * zoom_factor;
215 var arrow_size = arrow.arrow_size * zoom_factor;
217 var square_width = $(".square-a8").width();
218 var from_y = (7 - arrow.from_row + 0.5)*square_width;
219 var to_y = (7 - arrow.to_row + 0.5)*square_width;
220 var from_x = (arrow.from_col + 0.5)*square_width;
221 var to_x = (arrow.to_col + 0.5)*square_width;
223 var SVG_NS = "http://www.w3.org/2000/svg";
224 var XHTML_NS = "http://www.w3.org/1999/xhtml";
225 var svg = document.createElementNS(SVG_NS, "svg");
226 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
227 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
228 svg.setAttribute("style", "position: absolute");
229 svg.setAttribute("position", "absolute");
230 svg.setAttribute("version", "1.1");
231 svg.setAttribute("class", "c1");
232 svg.setAttribute("xmlns", XHTML_NS);
240 var outline = document.createElementNS(SVG_NS, "path");
241 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));
242 outline.setAttribute("xmlns", XHTML_NS);
243 outline.setAttribute("stroke", "#666");
244 outline.setAttribute("stroke-width", line_width + 2);
245 outline.setAttribute("fill", "none");
246 svg.appendChild(outline);
248 var path = document.createElementNS(SVG_NS, "path");
249 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));
250 path.setAttribute("xmlns", XHTML_NS);
251 path.setAttribute("stroke", arrow.fg_color);
252 path.setAttribute("stroke-width", line_width);
253 path.setAttribute("fill", "none");
254 svg.appendChild(path);
256 // Then the arrow head.
257 var head = document.createElementNS(SVG_NS, "path");
258 head.setAttribute("d",
259 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
260 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
261 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
262 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
263 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
264 head.setAttribute("xmlns", XHTML_NS);
265 head.setAttribute("stroke", "#000");
266 head.setAttribute("stroke-width", "1");
267 head.setAttribute("fill", arrow.fg_color);
268 svg.appendChild(head);
270 $(svg).css({ top: pos.top, left: pos.left });
271 document.body.appendChild(svg);
276 * @param {!string} from_square
277 * @param {!string} to_square
278 * @param {!string} fg_color
279 * @param {number} line_width
280 * @param {number} arrow_size
282 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
283 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
284 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
285 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
286 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
294 line_width: line_width,
295 arrow_size: arrow_size,
299 position_arrow(arrow);
303 var compare_by_sort_key = function(refutation_lines, a, b) {
304 var ska = refutation_lines[a]['sort_key'];
305 var skb = refutation_lines[b]['sort_key'];
306 if (ska < skb) return -1;
307 if (ska > skb) return 1;
311 var compare_by_score = function(refutation_lines, a, b) {
312 var sa = parseInt(refutation_lines[b]['score_sort_key'], 10);
313 var sb = parseInt(refutation_lines[a]['score_sort_key'], 10);
318 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
319 * sorted by quality, descending.
321 * @param {!Object} data
322 * @param {number} margin The maximum number of centipawns worse than the
323 * best move can be and still be included.
324 * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
325 * moves, in score order.
327 var find_nonstupid_moves = function(data, margin) {
328 // First of all, if there are any moves that are more than 0.5 ahead of
329 // the primary move, the refutation lines are probably bunk, so just
331 var best_score = undefined;
332 var pv_score = undefined;
333 for (var move in data['refutation_lines']) {
334 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
335 if (move == data['pv_uci'][0]) {
338 if (best_score === undefined || score > best_score) {
341 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
346 if (best_score - pv_score > 50) {
350 // Now find all moves that are within “margin” of the best score.
351 // The PV move will always be first.
353 for (var move in data['refutation_lines']) {
354 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
355 if (move != data['pv_uci'][0] && best_score - score <= margin) {
359 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], a, b) });
360 moves.unshift(data['pv_uci'][0]);
369 var thousands = function(x) {
370 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
374 * @param {!string} fen
375 * @param {Array.<string>} uci_pv
376 * @param {Array.<string>} pretty_pv
377 * @param {number} move_num
378 * @param {!string} toplay
379 * @param {number=} opt_limit
380 * @param {boolean=} opt_showlast
382 var print_pv = function(fen, uci_pv, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
391 if (opt_limit && opt_showlast) {
392 // Truncate the PV at the beginning (instead of at the end).
393 // We assume here that toplay is 'W'.
395 i = pretty_pv.length - opt_limit;
400 } else if (toplay == 'B') {
401 var move = "<a class=\"move\" href=\"javascript:show_line(" + (display_lines.length - 1) + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
402 pv = move_num + '. … ' + move;
407 for ( ; i < pretty_pv.length; ++i) {
408 var move = "<a class=\"move\" href=\"javascript:show_line(" + (display_lines.length - 1) + ", " + i + ");\">" + pretty_pv[i] + "</a>";
411 if (i > opt_limit && !opt_showlast) {
417 pv += move_num + '. ' + move;
428 var update_highlight = function() {
429 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
430 if (current_display_line === null && highlight_from !== undefined && highlight_to !== undefined) {
431 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
432 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
436 var update_refutation_lines = function() {
440 if (display_lines.length > 1) {
441 display_lines = [ display_lines[0] ];
444 var tbl = $("#refutationlines");
448 for (var move in refutation_lines) {
451 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
452 moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
453 for (var i = 0; i < moves.length; ++i) {
454 var line = refutation_lines[moves[i]];
456 var tr = document.createElement("tr");
458 var move_td = document.createElement("td");
459 tr.appendChild(move_td);
460 $(move_td).addClass("move");
461 if (line['pv_uci'].length == 0) {
462 $(move_td).text(line['pretty_move']);
464 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
465 $(move_td).html(move);
468 var score_td = document.createElement("td");
469 tr.appendChild(score_td);
470 $(score_td).addClass("score");
471 $(score_td).text(line['pretty_score']);
473 var depth_td = document.createElement("td");
474 tr.appendChild(depth_td);
475 $(depth_td).addClass("depth");
476 $(depth_td).text("d" + line['depth']);
478 var pv_td = document.createElement("td");
479 tr.appendChild(pv_td);
480 $(pv_td).addClass("pv");
481 $(pv_td).html(print_pv(fen, line['pv_uci'], line['pv_pretty'], move_num, toplay, 10));
486 // Make one of the links clickable and the other nonclickable.
487 if (sort_refutation_lines_by_score) {
488 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
489 $("#sortbyscore1").html("<strong>Score</strong>");
491 $("#sortbyscore0").html("<strong>Move</strong>");
492 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
497 * @param {Object} data
498 * @param {number} num_viewers
500 var update_board = function(data, num_viewers) {
505 if (data['position']['player_w'] && data['position']['player_b']) {
506 headline = data['position']['player_w'] + '–' +
507 data['position']['player_b'] + ', analysis';
509 headline = 'Analysis';
511 if (data['position']['last_move'] !== 'none') {
512 headline += ' after '
513 if (data['position']['toplay'] == 'W') {
514 headline += (data['position']['move_num']-1) + '… ';
516 headline += data['position']['move_num'] + '. ';
518 headline += data['position']['last_move'];
521 $("#headline").text(headline);
523 if (num_viewers === null) {
524 $("#numviewers").text("");
525 } else if (num_viewers == 1) {
526 $("#numviewers").text("You are the only current viewer");
528 $("#numviewers").text(num_viewers + " current viewers");
532 if (data['id'] && data['id']['name'] !== null) {
533 $("#engineid").text(data['id']['name']);
537 if (data['score'] !== null) {
538 $("#score").text(data['score']);
542 if (data['nodes'] && data['nps'] && data['depth']) {
543 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
544 if (data['seldepth']) {
545 stats += ' (' + data['seldepth'] + ' selective)';
547 if (data['tbhits'] && data['tbhits'] > 0) {
548 if (data['tbhits'] == 1) {
549 stats += ', one Syzygy hit';
551 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
555 $("#searchstats").text(stats);
558 // Update the board itself.
559 fen = data['position']['fen'];
560 update_displayed_line();
562 if (data['position']['last_move_uci']) {
563 highlight_from = data['position']['last_move_uci'].substr(0, 2);
564 highlight_to = data['position']['last_move_uci'].substr(2, 4);
566 highlight_from = highlight_to = undefined;
570 // Print the history.
571 if (data['position']['history']) {
572 $("#history").html(print_pv('start', data['position']['history'], data['position']['pretty_history'], 1, 'W', 8, true));
574 $("#history").html("No history");
578 $("#pv").html(print_pv(data['position']['fen'], data['pv_uci'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
580 // Update the PV arrow.
582 if (data['pv_uci'].length >= 1) {
583 // draw a continuation arrow as long as it's the same piece
584 for (var i = 0; i < data['pv_uci'].length; i += 2) {
585 var from = data['pv_uci'][i].substr(0, 2);
586 var to = data['pv_uci'][i].substr(2,4);
587 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 4)) ||
588 interfering_arrow(from, to)) {
591 create_arrow(from, to, '#f66', 6, 20);
594 var alt_moves = find_nonstupid_moves(data, 30);
595 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
596 create_arrow(alt_moves[i].substr(0, 2),
597 alt_moves[i].substr(2, 4), '#f66', 1, 10);
601 // See if all semi-reasonable moves have only one possible response.
602 if (data['pv_uci'].length >= 2) {
603 var nonstupid_moves = find_nonstupid_moves(data, 300);
604 var response = data['pv_uci'][1];
605 for (var i = 0; i < nonstupid_moves.length; ++i) {
606 if (nonstupid_moves[i] == data['pv_uci'][0]) {
607 // ignore the PV move for refutation lines.
610 if (!data['refutation_lines'] ||
611 !data['refutation_lines'][nonstupid_moves[i]] ||
612 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
613 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
614 // Incomplete PV, abort.
615 response = undefined;
618 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
619 if (response !== this_response) {
620 // Different response depending on lines, abort.
621 response = undefined;
626 if (nonstupid_moves.length > 0 && response !== undefined) {
627 create_arrow(response.substr(0, 2),
628 response.substr(2, 4), '#66f', 6, 20);
632 // Update the refutation lines.
633 fen = data['position']['fen'];
634 move_num = data['position']['move_num'];
635 toplay = data['position']['toplay'];
636 refutation_lines = data['refutation_lines'];
637 update_refutation_lines();
640 setTimeout(function() { request_update(); }, 100);
644 * @param {boolean} sort_by_score
646 var resort_refutation_lines = function(sort_by_score) {
647 sort_refutation_lines_by_score = sort_by_score;
648 update_refutation_lines();
650 window['resort_refutation_lines'] = resort_refutation_lines;
653 * @param {number} line_num
654 * @param {number} move_num
656 var show_line = function(line_num, move_num) {
657 if (line_num == -1) {
658 current_display_line = null;
659 current_display_move = null;
661 current_display_line = display_lines[line_num];
662 current_display_move = move_num;
664 update_displayed_line();
668 window['show_line'] = show_line;
670 var prev_move = function() {
671 if (current_display_move > -1) {
672 --current_display_move;
674 update_displayed_line();
676 window['prev_move'] = prev_move;
678 var next_move = function() {
679 if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
680 ++current_display_move;
682 update_displayed_line();
684 window['next_move'] = next_move;
686 var update_displayed_line = function() {
687 if (current_display_line === null) {
688 $("#linenav").hide();
689 $("#linemsg").show();
694 $("#linenav").show();
695 $("#linemsg").hide();
697 if (current_display_move == 0) {
698 $("#prevmove").html("Previous");
700 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
702 if (current_display_move == current_display_line.uci_pv.length - 1) {
703 $("#nextmove").html("Next");
705 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
708 hiddenboard.position(current_display_line.start_fen, false);
709 for (var i = 0; i <= current_display_move; ++i) {
710 var move = current_display_line.uci_pv[i];
711 move = move.substr(0, 2) + "-" + move.substr(2, 4);
712 hiddenboard.move(move, false);
714 // chessboard.js does not automatically move the rook on castling
715 // (issue #51; marked as won't fix), so update it ourselves.
716 if (move == "e1-g1" && hiddenboard.position().g1 == "wK") { // white O-O
717 hiddenboard.move("h1-f1", false);
718 } else if (move == "e1-c1" && hiddenboard.position().c1 == "wK") { // white O-O-O
719 hiddenboard.move("a1-d1", false);
720 } else if (move == "e8-g8" && hiddenboard.position().g8 == "bK") { // black O-O
721 hiddenboard.move("h8-f8", false);
722 } else if (move == "e8-c8" && hiddenboard.position().c8 == "bK") { // black O-O-O
723 hiddenboard.move("a8-d8", false);
726 board.position(hiddenboard.position());
729 var init = function() {
731 board = new window.ChessBoard('board', 'start');
732 hiddenboard = new window.ChessBoard('hiddenboard', 'start');
735 $(window).resize(function() {
740 $(window).keyup(function(event) {
741 if (event.which == 39) {
743 } else if (event.which == 37) {
748 $(document).ready(init);