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);
140 for (var i = 0; i < moves.length; ++i) {
143 total_num += parseInt(move['white']);
144 total_num += parseInt(move['draw']);
145 total_num += parseInt(move['black']);
149 var headings_tr = $("#headings");
151 for (var i = 0; i < headings.length; ++i) {
152 var th = document.createElement("th");
153 headings_tr.append(th);
154 $(th).text(headings[i][0]);
155 (function(new_sort_by) {
156 $(th).click(function() {
157 if (sort_by == new_sort_by) {
158 direction = -direction;
160 sort_by = new_sort_by;
163 show_lines(data, game);
169 var transpose_only = [];
170 for (var i = 0; i < moves.length; ++i) {
174 var white = parseInt(move['white']);
175 var draw = parseInt(move['draw']);
176 var black = parseInt(move['black']);
177 var computer = parseInt(move['computer']);
179 line.push(move['move']); // Move.
180 transpose_only.push(move['transpose_only']);
181 var num = white + draw + black;
182 line.push(num); // N.
183 line.push(num / total_num); // %.
184 line.push(computer); // CGames.
186 // Adjust so that the human index is 50% overall.
187 var exp = Math.log(0.5) / Math.log(data['computer_games'] / data['total_games']);
188 line.push(1.0 - Math.pow(computer / num, exp)); // Hum.
191 var white_win_ratio = (white + 0.5 * draw) / num;
192 var win_ratio = (move_override % 2 == 0) ? white_win_ratio : 1.0 - white_win_ratio;
193 line.push(win_ratio);
195 line.push(white); // WWin.
196 line.push(white / num); // %WW.
197 line.push(black); // BWin.
198 line.push(black / num); // %BW.
199 line.push(draw); // Draw.
200 line.push(draw / num); // %Draw.
202 if (move['num_elo'] >= 10) {
204 line.push(move['white_avg_elo']);
205 line.push(move['black_avg_elo']);
206 line.push(move['white_avg_elo'] - move['black_avg_elo']);
208 // Win% corrected for Elo.
209 var win_elo = -400.0 * Math.log(1.0 / white_win_ratio - 1.0) / Math.LN10;
210 win_elo -= (move['white_avg_elo'] - move['black_avg_elo']);
211 white_win_ratio = 1.0 / (1.0 + Math.pow(10, win_elo / -400.0));
212 win_ratio = (move_override % 2 == 0) ? white_win_ratio : 1.0 - white_win_ratio;
213 line.push(win_ratio);
223 lines.sort(function(a, b) { return direction * ( b[sort_by] - a[sort_by]); });
225 var tbl = $("#lines");
228 for (var i = 0; i < moves.length; ++i) {
230 var tr = document.createElement("tr");
232 if (line[0] === undefined) {
233 $(tr).addClass("totals");
234 } else if (transpose_only[i]) {
235 $(tr).addClass("transponly");
238 for (var j = 0; j < line.length; ++j) {
239 if (line[j] === null) {
241 } else if (headings[j][1] == TYPE_MOVE) {
242 var td = document.createElement("td");
244 $(td).addClass("move");
245 if (line[j] !== undefined) {
246 if (move_override % 2 == 0) {
247 $(td).text(((move_override / 2) + 1) + ". ");
249 $(td).text(((move_override / 2) + 0.5) + "…");
253 if (line[j] === '1-0' || line[j] === '1/2-1/2' || line[j] === '0-1') {
254 $(td).text($(td).text() + line[j]);
256 var move_a = document.createElement("a");
257 move_a.href = "javascript:make_move('" + line[j] + "')";
258 td.appendChild(move_a);
259 $(move_a).text(line[j]);
261 } else if (headings[j][1] == TYPE_INTEGER) {
262 add_td(tr, line[j] || 0);
263 } else if (headings[j][1] == TYPE_FLOAT) {
264 if (isNaN(line[j]) || !isFinite(line[j])) {
267 add_td(tr, line[j].toFixed(1));
270 if (isNaN(line[j]) || !isFinite(line[j])) {
273 add_td(tr, (100.0 * line[j]).toFixed(1) + "%");
282 var set_includetransp = function(value) {
283 includetransp = value;
286 window['set_includetransp'] = set_includetransp;
288 var set_flipboard = function(value) {
289 board.orientation(value ? 'black' : 'white');
291 window['set_flipboard'] = set_flipboard;
293 var make_move = function(move, do_update) {
294 var history = game.history({ verbose: true });
295 if (move_override < history.length && history[move_override].san == move) {
296 // User effectively only moved forward in history.
299 var moves = game.history();
300 // Truncate the history if needed.
301 if (move_override < moves.length) {
303 for (var i = 0; i < move_override; ++i) {
306 fens.length = move_override;
309 fens.push(game.fen());
313 if (do_update !== false) {
315 window.history.pushState(null, null, get_history_url());
318 window['make_move'] = make_move;
320 var prev_move = function() {
321 if (move_override > 0) {
324 window.history.replaceState(null, null, get_history_url());
327 window['prev_move'] = prev_move;
329 var next_move = function() {
330 if (move_override < game.history().length) {
333 window.history.replaceState(null, null, get_history_url());
336 window['next_move'] = next_move;
338 var set_move = function(n, do_update) {
340 if (do_update !== false) {
342 window.history.replaceState(null, null, get_history_url());
345 window['set_move'] = set_move;
347 // almost all of this stuff comes from the chessboard.js example page
348 var onDragStart = function(source, piece, position, orientation) {
349 var pseudogame = new Chess(current_display_fen());
350 if (pseudogame.game_over() === true ||
351 (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
352 (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
356 recommended_move = null;
357 get_best_dest(pseudogame, source, null, function(src, dest) {
358 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
360 var squareEl = $('#board .square-' + dest);
361 squareEl.addClass('highlight1-32417');
362 recommended_move = [src, dest];
367 var mousedownSquare = function(e) {
368 reverse_dragging_from = null;
369 var square = $(this).attr('data-square');
371 var pseudogame = new Chess(current_display_fen());
372 if (pseudogame.game_over() === true) {
376 // If the square is empty, or has a piece of the side not to move,
377 // we handle it. If not, normal piece dragging will take it.
378 var position = board.position();
379 if (!position.hasOwnProperty(square) ||
380 (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
381 (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
382 reverse_dragging_from = square;
383 get_best_dest(pseudogame, null, square, function(src, dest) {
385 var squareEl = $('#board .square-' + src);
386 squareEl.addClass('highlight1-32417');
387 squareEl = $('#board .square-' + dest);
388 squareEl.addClass('highlight1-32417');
389 recommended_move = [src, dest];
393 recommended_src = null;
397 var mouseupSquare = function(e) {
398 if (reverse_dragging_from === null) {
401 var source = $(this).attr('data-square');
402 var target = reverse_dragging_from;
403 reverse_dragging_from = null;
404 if (onDrop(source, target) !== 'snapback') {
405 onSnapEnd(source, target);
407 $("#board").find('.square-55d63').removeClass('highlight1-32417');
410 var get_best_dest = function(game, source, target, cb) {
411 var moves = game.moves({ verbose: true });
412 if (source !== null) {
413 moves = moves.filter(function(move) { return move.from == source; });
415 if (target !== null) {
416 moves = moves.filter(function(move) { return move.to == target; });
418 if (moves.length == 0) {
422 if (moves.length == 1) {
423 cb(moves[0].from, moves[0].to);
427 // More than one move. Ask the engine to disambiguate.
428 var uci_moves = moves.map(function(m) { return m.from + m.to; });
429 var when_engine_is_ready = function() {
430 engine_running = true;
431 stockfish.onmessage = function(event) {
432 var res = event.data.match(/^bestmove (\S\S)(\S\S)/);
434 engine_running = false;
435 if (engine_replacement_callback !== null) {
436 // We are no longer interested in this query,
437 // so just discard it and call this other callback.
438 engine_replacement_callback();
439 engine_replacement_callback = null;
445 stockfish.postMessage("position fen " + game.fen());
446 stockfish.postMessage("go depth 6 searchmoves " + uci_moves.join(" "));
448 if (engine_running) {
449 engine_replacement_callback = when_engine_is_ready;
451 when_engine_is_ready();
455 var onDrop = function(source, target) {
456 if (engine_running) {
457 // Snap end before the engine came back.
458 // Discard the result when it does.
459 engine_replacement_callback = function() {};
461 if (source == target) {
462 if (recommended_move === null) {
465 // Accept the move. It will be changed in onSnapEnd.
469 // Suggestion not asked for.
470 recommended_move = null;
473 // see if the move is legal
474 var pseudogame = new Chess(current_display_fen());
475 var move = pseudogame.move({
478 promotion: 'q' // NOTE: always promote to a queen for example simplicity
482 if (move === null) return 'snapback';
485 var onSnapEnd = function(source, target) {
486 if (source == target && recommended_move !== null) {
487 source = recommended_move[0];
488 target = recommended_move[1];
490 recommended_move = null;
491 var pseudogame = new Chess(current_display_fen());
492 var move = pseudogame.move({
495 promotion: 'q' // NOTE: always promote to a queen for example simplicity
498 make_move(pseudogame.history({ verbose: true }).pop().san);
501 var onpopstate = function() {
502 var old_moves = game.history({ verbose: true }).map(function(x) { return x.san; });
503 var new_moves = document.location.search.replace(/^\?/, "").split(",");
505 if (new_moves.length == 1 && new_moves[0] == "") {
509 var num_shared_moves;
510 for (num_shared_moves = 0; num_shared_moves < Math.min(old_moves.length, new_moves.length); ++num_shared_moves) {
511 if (old_moves[i] != new_moves[i]) {
516 set_move(num_shared_moves, false);
517 for (var i = num_shared_moves; i < new_moves.length; ++i) {
518 make_move(new_moves[i], false);
521 window.history.replaceState(null, null, get_history_url());
524 var init = function() {
526 board = new window.ChessBoard('board', {
529 onDragStart: onDragStart,
533 $("#board").on('mousedown', '.square-55d63', mousedownSquare);
534 $("#board").on('mouseup', '.square-55d63', mouseupSquare);
536 window.onpopstate = onpopstate;
539 $(window).keyup(function(event) {
540 if (event.which == 39) {
542 } else if (event.which == 37) {
547 // Seemingly the web worker is not started before we send it a message.
548 stockfish.postMessage("uci");
551 $(document).ready(init);