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 = false;
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
381 var print_pv = function(fen, uci_pv, pretty_pv, move_num, toplay, opt_limit) {
391 var move = "<a class=\"move\" href=\"javascript:show_line(" + (display_lines.length - 1) + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
392 pv = move_num + '. … ' + move;
397 for ( ; i < pretty_pv.length; ++i) {
398 var move = "<a class=\"move\" href=\"javascript:show_line(" + (display_lines.length - 1) + ", " + i + ");\">" + pretty_pv[i] + "</a>";
407 pv += move_num + '. ' + move;
418 var update_highlight = function() {
419 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
420 if (current_display_line === null && highlight_from !== undefined && highlight_to !== undefined) {
421 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
422 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
426 var update_refutation_lines = function() {
430 if (display_lines.length > 1) {
431 display_lines = [ display_lines[0] ];
434 var tbl = $("#refutationlines");
438 for (var move in refutation_lines) {
441 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
442 moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
443 for (var i = 0; i < moves.length; ++i) {
444 var line = refutation_lines[moves[i]];
446 var tr = document.createElement("tr");
448 var move_td = document.createElement("td");
449 tr.appendChild(move_td);
450 $(move_td).addClass("move");
451 if (line['pv_uci'].length == 0) {
452 $(move_td).text(line['pretty_move']);
454 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
455 $(move_td).html(move);
458 var score_td = document.createElement("td");
459 tr.appendChild(score_td);
460 $(score_td).addClass("score");
461 $(score_td).text(line['pretty_score']);
463 var depth_td = document.createElement("td");
464 tr.appendChild(depth_td);
465 $(depth_td).addClass("depth");
466 $(depth_td).text("d" + line['depth']);
468 var pv_td = document.createElement("td");
469 tr.appendChild(pv_td);
470 $(pv_td).addClass("pv");
471 $(pv_td).html(print_pv(fen, line['pv_uci'], line['pv_pretty'], move_num, toplay, 10));
476 // Make one of the links clickable and the other nonclickable.
477 if (sort_refutation_lines_by_score) {
478 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
479 $("#sortbyscore1").html("<strong>Score</strong>");
481 $("#sortbyscore0").html("<strong>Move</strong>");
482 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
487 * @param {Object} data
488 * @param {number} num_viewers
490 var update_board = function(data, num_viewers) {
494 var headline = 'Analysis';
495 if (data['position']['last_move'] !== 'none') {
496 headline += ' after '
497 if (data['position']['toplay'] == 'W') {
498 headline += (data['position']['move_num']-1) + '… ';
500 headline += data['position']['move_num'] + '. ';
502 headline += data['position']['last_move'];
505 $("#headline").text(headline);
507 if (num_viewers === null) {
508 $("#numviewers").text("");
509 } else if (num_viewers == 1) {
510 $("#numviewers").text("You are the only current viewer");
512 $("#numviewers").text(num_viewers + " current viewers");
516 if (data['score'] !== null) {
517 $("#score").text(data['score']);
521 if (data['nodes'] && data['nps'] && data['depth']) {
522 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
523 if (data['seldepth']) {
524 stats += ' (' + data['seldepth'] + ' selective)';
526 if (data['tbhits'] && data['tbhits'] > 0) {
527 if (data['tbhits'] == 1) {
528 stats += ', one Nalimov hit';
530 stats += ', ' + data['tbhits'] + ' Nalimov hits';
534 $("#searchstats").text(stats);
537 // Update the board itself.
538 fen = data['position']['fen'];
539 update_displayed_line();
541 if (data['position']['last_move_uci']) {
542 highlight_from = data['position']['last_move_uci'].substr(0, 2);
543 highlight_to = data['position']['last_move_uci'].substr(2, 4);
545 highlight_from = highlight_to = undefined;
550 $("#pv").html(print_pv(data['position']['fen'], data['pv_uci'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
552 // Update the PV arrow.
554 if (data['pv_uci'].length >= 1) {
555 // draw a continuation arrow as long as it's the same piece
556 for (var i = 0; i < data['pv_uci'].length; i += 2) {
557 var from = data['pv_uci'][i].substr(0, 2);
558 var to = data['pv_uci'][i].substr(2,4);
559 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 4)) ||
560 interfering_arrow(from, to)) {
563 create_arrow(from, to, '#f66', 6, 20);
566 var alt_moves = find_nonstupid_moves(data, 30);
567 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
568 create_arrow(alt_moves[i].substr(0, 2),
569 alt_moves[i].substr(2, 4), '#f66', 1, 10);
573 // See if all semi-reasonable moves have only one possible response.
574 if (data['pv_uci'].length >= 2) {
575 var nonstupid_moves = find_nonstupid_moves(data, 300);
576 var response = data['pv_uci'][1];
577 for (var i = 0; i < nonstupid_moves.length; ++i) {
578 if (nonstupid_moves[i] == data['pv_uci'][0]) {
579 // ignore the PV move for refutation lines.
582 if (!data['refutation_lines'] ||
583 !data['refutation_lines'][nonstupid_moves[i]] ||
584 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
585 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
586 // Incomplete PV, abort.
587 response = undefined;
590 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
591 if (response !== this_response) {
592 // Different response depending on lines, abort.
593 response = undefined;
598 if (nonstupid_moves.length > 0 && response !== undefined) {
599 create_arrow(response.substr(0, 2),
600 response.substr(2, 4), '#66f', 6, 20);
604 // Update the refutation lines.
605 fen = data['position']['fen'];
606 move_num = data['position']['move_num'];
607 toplay = data['position']['toplay'];
608 refutation_lines = data['refutation_lines'];
609 update_refutation_lines();
612 setTimeout(function() { request_update(); }, 100);
616 * @param {boolean} sort_by_score
618 var resort_refutation_lines = function(sort_by_score) {
619 sort_refutation_lines_by_score = sort_by_score;
620 update_refutation_lines();
622 window['resort_refutation_lines'] = resort_refutation_lines;
625 * @param {number} line_num
626 * @param {number} move_num
628 var show_line = function(line_num, move_num) {
629 if (line_num == -1) {
630 current_display_line = null;
631 current_display_move = null;
633 current_display_line = display_lines[line_num];
634 current_display_move = move_num;
636 update_displayed_line();
640 window['show_line'] = show_line;
642 var prev_move = function() {
643 --current_display_move;
644 update_displayed_line();
646 window['prev_move'] = prev_move;
648 var next_move = function() {
649 ++current_display_move;
650 update_displayed_line();
652 window['next_move'] = prev_move;
654 var update_displayed_line = function() {
655 if (current_display_line === null) {
656 $("#linenav").hide();
657 $("#linemsg").show();
662 $("#linenav").show();
663 $("#linemsg").hide();
665 if (current_display_move == 0) {
666 $("#prevmove").html("Previous");
668 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
670 if (current_display_move == current_display_line.uci_pv.length - 1) {
671 $("#nextmove").html("Next");
673 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
676 hiddenboard.position(current_display_line.start_fen, false);
677 for (var i = 0; i <= current_display_move; ++i) {
678 var move = current_display_line.uci_pv[i];
679 move = move.substr(0, 2) + "-" + move.substr(2, 4);
680 hiddenboard.move(move, false);
682 board.position(hiddenboard.position());
685 var init = function() {
687 board = new window.ChessBoard('board', 'start');
688 hiddenboard = new window.ChessBoard('hiddenboard', 'start');
691 $(window).resize(function() {
697 $(document).ready(init);