4 var game = new Chess();
7 var includetransp = true;
8 var stockfish = new Worker('/js/stockfish.js');
9 var engine_running = false;
10 var engine_replacement_callback = null;
11 var recommended_move = null;
12 var reverse_dragging_from = null;
22 function escape_html(string) {
23 return String(string).replace(/[&<>"']/g, function (s) {
28 var current_display_fen = function() {
29 if (move_override == 0) {
30 return 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1';
32 return fens[move_override - 1];
36 var update = function() {
38 var history = game.history({ verbose: true });
39 for (var i = 0; i < history.length; ++i) {
41 text += (i/2 + 1) + ". ";
43 if (i + 1 == move_override) {
44 text += '<strong>' + history[i].san + '</strong>';
46 text += '<a href="javascript:set_move(' + (i + 1) + ')">' + history[i].san + '</a>';
50 $('#gamehistory').html(text);
52 if (board.fen() != current_display_fen()) {
53 board.position(current_display_fen());
56 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
57 if (move_override > 0) {
58 var last_move = history[move_override - 1];
59 var highlight_from = last_move.from;
60 var highlight_to = last_move.to;
61 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
62 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
68 var get_history_url = function() {
69 var history = game.history({ verbose: true }).map(function(x) { return x.san; });
70 history.length = move_override;
71 return '/?' + history.join(',');
74 var fetch_analysis = function() {
75 var fen = current_display_fen();
77 url: "/opening-stats.pl?fen=" + encodeURIComponent(fen) +
78 ";includetransp=" + (includetransp ? 1 : 0)
79 }).done(function(data, textstatus, xhr) {
80 show_lines(data, game);
84 var add_td = function(tr, value) {
85 var td = document.createElement("td");
87 $(td).addClass("num");
97 [ "Move", TYPE_MOVE ],
98 [ "Games", TYPE_INTEGER ],
100 [ "CGames", TYPE_INTEGER ],
101 [ "Hum", TYPE_RATIO ],
102 [ "Win%", TYPE_RATIO ],
103 [ "WWin", TYPE_INTEGER ],
104 [ "%WW", TYPE_RATIO ],
105 [ "Bwin", TYPE_INTEGER ],
106 [ "%BW", TYPE_RATIO ],
107 [ "Draw", TYPE_INTEGER ],
108 [ "Draw%", TYPE_RATIO ],
109 [ "AvWElo", TYPE_FLOAT ],
110 [ "AvBElo", TYPE_FLOAT ],
111 [ "EloVar", TYPE_FLOAT ],
112 [ "AWin%", TYPE_RATIO ],
117 var show_lines = function(data, game) {
118 var moves = data['moves'];
119 $('#numviewers').text(data['opening']);
121 if (data['root_game']) {
122 var text = escape_html(data['root_game']['white']);
123 if (data['root_game']['white_elo']) {
124 text += " (" + escape_html(data['root_game']['white_elo']) + ")";
126 text += " – " + escape_html(data['root_game']['black']);
127 if (data['root_game']['black_elo']) {
128 text += " (" + escape_html(data['root_game']['black_elo']) + ")";
130 text += " " + escape_html(data['root_game']['result']).replace(/-/, "–") + "<br />";
131 if (data['root_game']['eco']) {
132 text += "[" + escape_html(data['root_game']['eco']) + "] ";
134 text += "(" + data['root_game']['moves'] + ") ";
135 text += escape_html(data['root_game']['event']) + " " + escape_html(data['root_game']['date']);
136 $('#gamesummary').html(text);
139 var total_num = find_total_games(moves);
141 var headings_tr = $("#headings");
143 for (var i = 0; i < headings.length; ++i) {
144 var th = document.createElement("th");
145 headings_tr.append(th);
146 $(th).text(headings[i][0]);
147 (function(new_sort_by) {
148 $(th).click(function() {
149 if (sort_by == new_sort_by) {
150 direction = -direction;
152 sort_by = new_sort_by;
155 show_lines(data, game);
161 var transpose_only = [];
162 for (var i = 0; i < moves.length; ++i) {
166 var white = move['white'];
167 var draw = move['draw'];
168 var black = move['black'];
169 var computer = move['computer'];
171 line.push(move['move']); // Move.
172 transpose_only.push(move['transpose_only']);
173 var num = white + draw + black;
174 line.push(num); // N.
175 line.push(num / total_num); // %.
176 line.push(computer); // CGames.
178 // Adjust so that the human index is 50% overall.
179 var exp = Math.log(0.5) / Math.log(data['computer_games'] / data['total_games']);
180 line.push(1.0 - Math.pow(computer / num, exp)); // Hum.
183 var white_win_ratio = (white + 0.5 * draw) / num;
184 var win_ratio = (move_override % 2 == 0) ? white_win_ratio : 1.0 - white_win_ratio;
185 line.push(win_ratio);
187 line.push(white); // WWin.
188 line.push(white / num); // %WW.
189 line.push(black); // BWin.
190 line.push(black / num); // %BW.
191 line.push(draw); // Draw.
192 line.push(draw / num); // %Draw.
194 if (move['num_elo'] >= 10) {
196 line.push(move['white_avg_elo']);
197 line.push(move['black_avg_elo']);
198 line.push(move['white_avg_elo'] - move['black_avg_elo']);
200 // Win% corrected for Elo.
201 var win_elo = -400.0 * Math.log(1.0 / white_win_ratio - 1.0) / Math.LN10;
202 win_elo -= (move['white_avg_elo'] - move['black_avg_elo']);
203 white_win_ratio = 1.0 / (1.0 + Math.pow(10, win_elo / -400.0));
204 win_ratio = (move_override % 2 == 0) ? white_win_ratio : 1.0 - white_win_ratio;
205 line.push(win_ratio);
215 lines.sort(function(a, b) { return direction * ( b[sort_by] - a[sort_by]); });
217 var tbl = $("#lines");
220 for (var i = 0; i < moves.length; ++i) {
222 var tr = document.createElement("tr");
224 if (line[0] === undefined) {
225 $(tr).addClass("totals");
226 } else if (transpose_only[i]) {
227 $(tr).addClass("transponly");
230 for (var j = 0; j < line.length; ++j) {
231 if (line[j] === null) {
233 } else if (headings[j][1] == TYPE_MOVE) {
234 var td = document.createElement("td");
236 $(td).addClass("move");
237 if (line[j] !== undefined) {
238 if (move_override % 2 == 0) {
239 $(td).text(((move_override / 2) + 1) + ". ");
241 $(td).text(((move_override / 2) + 0.5) + "…");
245 if (line[j] === '1-0' || line[j] === '1/2-1/2' || line[j] === '0-1') {
246 $(td).text($(td).text() + line[j]);
248 var move_a = document.createElement("a");
249 move_a.href = "javascript:make_move('" + line[j] + "')";
250 td.appendChild(move_a);
251 $(move_a).text(line[j]);
253 } else if (headings[j][1] == TYPE_INTEGER) {
254 add_td(tr, line[j] || 0);
255 } else if (headings[j][1] == TYPE_FLOAT) {
256 if (isNaN(line[j]) || !isFinite(line[j])) {
259 add_td(tr, line[j].toFixed(1));
262 if (isNaN(line[j]) || !isFinite(line[j])) {
265 add_td(tr, (100.0 * line[j]).toFixed(1) + "%");
274 var find_total_games = function(moves) {
276 for (var i = 0; i < moves.length; ++i) {
279 total_num += move['white'];
280 total_num += move['draw'];
281 total_num += move['black'];
287 var set_includetransp = function(value) {
288 includetransp = value;
291 window['set_includetransp'] = set_includetransp;
293 var set_flipboard = function(value) {
294 board.orientation(value ? 'black' : 'white');
296 window['set_flipboard'] = set_flipboard;
298 var make_move = function(move, do_update) {
299 var history = game.history({ verbose: true });
300 if (move_override < history.length && history[move_override].san == move) {
301 // User effectively only moved forward in history.
304 var moves = game.history();
305 // Truncate the history if needed.
306 if (move_override < moves.length) {
308 for (var i = 0; i < move_override; ++i) {
311 fens.length = move_override;
314 fens.push(game.fen());
318 if (do_update !== false) {
320 window.history.pushState(null, null, get_history_url());
323 window['make_move'] = make_move;
325 var prev_move = function() {
326 if (move_override > 0) {
329 window.history.replaceState(null, null, get_history_url());
332 window['prev_move'] = prev_move;
334 var next_move = function() {
335 if (move_override < game.history().length) {
338 window.history.replaceState(null, null, get_history_url());
341 window['next_move'] = next_move;
343 var set_move = function(n, do_update) {
345 if (do_update !== false) {
347 window.history.replaceState(null, null, get_history_url());
350 window['set_move'] = set_move;
352 // almost all of this stuff comes from the chessboard.js example page
353 var onDragStart = function(source, piece, position, orientation) {
354 var pseudogame = new Chess(current_display_fen());
355 if (pseudogame.game_over() === true ||
356 (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
357 (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
361 recommended_move = null;
362 get_best_dest(pseudogame, source, null, function(src, dest) {
363 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
365 var squareEl = $('#board .square-' + dest);
366 squareEl.addClass('highlight1-32417');
367 recommended_move = [src, dest];
372 var mousedownSquare = function(e) {
373 reverse_dragging_from = null;
374 var square = $(this).attr('data-square');
376 var pseudogame = new Chess(current_display_fen());
377 if (pseudogame.game_over() === true) {
381 // If the square is empty, or has a piece of the side not to move,
382 // we handle it. If not, normal piece dragging will take it.
383 var position = board.position();
384 if (!position.hasOwnProperty(square) ||
385 (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
386 (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
387 reverse_dragging_from = square;
388 get_best_dest(pseudogame, null, square, function(src, dest) {
390 var squareEl = $('#board .square-' + src);
391 squareEl.addClass('highlight1-32417');
392 squareEl = $('#board .square-' + dest);
393 squareEl.addClass('highlight1-32417');
394 recommended_move = [src, dest];
398 recommended_src = null;
402 var mouseupSquare = function(e) {
403 if (reverse_dragging_from === null) {
406 var source = $(this).attr('data-square');
407 var target = reverse_dragging_from;
408 reverse_dragging_from = null;
409 if (onDrop(source, target) !== 'snapback') {
410 onSnapEnd(source, target);
412 $("#board").find('.square-55d63').removeClass('highlight1-32417');
415 var get_best_dest = function(game, source, target, cb) {
416 var moves = game.moves({ verbose: true });
417 if (source !== null) {
418 moves = moves.filter(function(move) { return move.from == source; });
420 if (target !== null) {
421 moves = moves.filter(function(move) { return move.to == target; });
423 if (moves.length == 0) {
427 if (moves.length == 1) {
428 cb(moves[0].from, moves[0].to);
432 // More than one move. Ask the engine to disambiguate.
433 var uci_moves = moves.map(function(m) { return m.from + m.to; });
434 var when_engine_is_ready = function() {
435 engine_running = true;
436 stockfish.onmessage = function(event) {
437 var res = event.data.match(/^bestmove (\S\S)(\S\S)/);
439 engine_running = false;
440 if (engine_replacement_callback !== null) {
441 // We are no longer interested in this query,
442 // so just discard it and call this other callback.
443 engine_replacement_callback();
444 engine_replacement_callback = null;
450 stockfish.postMessage("position fen " + game.fen());
451 stockfish.postMessage("go depth 6 searchmoves " + uci_moves.join(" "));
453 if (engine_running) {
454 engine_replacement_callback = when_engine_is_ready;
456 when_engine_is_ready();
460 var onDrop = function(source, target) {
461 if (engine_running) {
462 // Snap end before the engine came back.
463 // Discard the result when it does.
464 engine_replacement_callback = function() {};
466 if (source == target) {
467 if (recommended_move === null) {
470 // Accept the move. It will be changed in onSnapEnd.
474 // Suggestion not asked for.
475 recommended_move = null;
478 // see if the move is legal
479 var pseudogame = new Chess(current_display_fen());
480 var move = pseudogame.move({
483 promotion: 'q' // NOTE: always promote to a queen for example simplicity
487 if (move === null) return 'snapback';
490 var onSnapEnd = function(source, target) {
491 if (source == target && recommended_move !== null) {
492 source = recommended_move[0];
493 target = recommended_move[1];
495 recommended_move = null;
496 var pseudogame = new Chess(current_display_fen());
497 var move = pseudogame.move({
500 promotion: 'q' // NOTE: always promote to a queen for example simplicity
503 make_move(pseudogame.history({ verbose: true }).pop().san);
506 var onpopstate = function() {
507 var old_moves = game.history({ verbose: true }).map(function(x) { return x.san; });
508 var new_moves = document.location.search.replace(/^\?/, "").split(",");
510 if (new_moves.length == 1 && new_moves[0] == "") {
514 var num_shared_moves;
515 for (num_shared_moves = 0; num_shared_moves < Math.min(old_moves.length, new_moves.length); ++num_shared_moves) {
516 if (old_moves[i] != new_moves[i]) {
521 set_move(num_shared_moves, false);
522 for (var i = num_shared_moves; i < new_moves.length; ++i) {
523 make_move(new_moves[i], false);
526 window.history.replaceState(null, null, get_history_url());
529 var init = function() {
531 board = new window.ChessBoard('board', {
534 onDragStart: onDragStart,
538 $("#board").on('mousedown', '.square-55d63', mousedownSquare);
539 $("#board").on('mouseup', '.square-55d63', mouseupSquare);
541 window.onpopstate = onpopstate;
544 $(window).keyup(function(event) {
545 if (event.which == 39) {
547 } else if (event.which == 37) {
552 // Seemingly the web worker is not started before we send it a message.
553 stockfish.postMessage("uci");
556 $(document).ready(init);