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_dest = null;
21 function escape_html(string) {
22 return String(string).replace(/[&<>"']/g, function (s) {
27 var current_display_fen = function() {
28 if (move_override == 0) {
29 return 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1';
31 return fens[move_override - 1];
35 var update = function() {
37 var history = game.history({ verbose: true });
38 for (var i = 0; i < history.length; ++i) {
40 text += (i/2 + 1) + ". ";
42 if (i + 1 == move_override) {
43 text += '<strong>' + history[i].san + '</strong>';
45 text += '<a href="javascript:set_move(' + (i + 1) + ')">' + history[i].san + '</a>';
49 $('#gamehistory').html(text);
51 if (board.fen() != current_display_fen()) {
52 board.position(current_display_fen());
55 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
56 if (move_override > 0) {
57 var last_move = history[move_override - 1];
58 var highlight_from = last_move.from;
59 var highlight_to = last_move.to;
60 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
61 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
67 var get_history_url = function() {
68 var history = game.history({ verbose: true }).map(function(x) { return x.san; });
69 history.length = move_override;
70 return '/?' + history.join(',');
73 var fetch_analysis = function() {
74 var fen = current_display_fen();
76 url: "/opening-stats.pl?fen=" + encodeURIComponent(fen) +
77 ";includetransp=" + (includetransp ? 1 : 0)
78 }).done(function(data, textstatus, xhr) {
79 show_lines(data, game);
83 var add_td = function(tr, value) {
84 var td = document.createElement("td");
86 $(td).addClass("num");
96 [ "Move", TYPE_MOVE ],
97 [ "Games", TYPE_INTEGER ],
99 [ "CGames", TYPE_INTEGER ],
100 [ "Hum", TYPE_RATIO ],
101 [ "Win%", TYPE_RATIO ],
102 [ "WWin", TYPE_INTEGER ],
103 [ "%WW", TYPE_RATIO ],
104 [ "Bwin", TYPE_INTEGER ],
105 [ "%BW", TYPE_RATIO ],
106 [ "Draw", TYPE_INTEGER ],
107 [ "Draw%", TYPE_RATIO ],
108 [ "AvWElo", TYPE_FLOAT ],
109 [ "AvBElo", TYPE_FLOAT ],
110 [ "EloVar", TYPE_FLOAT ],
111 [ "AWin%", TYPE_RATIO ],
116 var show_lines = function(data, game) {
117 var moves = data['moves'];
118 $('#numviewers').text(data['opening']);
120 if (data['root_game']) {
121 var text = escape_html(data['root_game']['white']);
122 if (data['root_game']['white_elo']) {
123 text += " (" + escape_html(data['root_game']['white_elo']) + ")";
125 text += " – " + escape_html(data['root_game']['black']);
126 if (data['root_game']['black_elo']) {
127 text += " (" + escape_html(data['root_game']['black_elo']) + ")";
129 text += " " + escape_html(data['root_game']['result']).replace(/-/, "–") + "<br />";
130 if (data['root_game']['eco']) {
131 text += "[" + escape_html(data['root_game']['eco']) + "] ";
133 text += "(" + data['root_game']['moves'] + ") ";
134 text += escape_html(data['root_game']['event']) + " " + escape_html(data['root_game']['date']);
135 $('#gamesummary').html(text);
139 for (var i = 0; i < moves.length; ++i) {
142 total_num += parseInt(move['white']);
143 total_num += parseInt(move['draw']);
144 total_num += parseInt(move['black']);
148 var headings_tr = $("#headings");
150 for (var i = 0; i < headings.length; ++i) {
151 var th = document.createElement("th");
152 headings_tr.append(th);
153 $(th).text(headings[i][0]);
154 (function(new_sort_by) {
155 $(th).click(function() {
156 if (sort_by == new_sort_by) {
157 direction = -direction;
159 sort_by = new_sort_by;
162 show_lines(data, game);
168 var transpose_only = [];
169 for (var i = 0; i < moves.length; ++i) {
173 var white = parseInt(move['white']);
174 var draw = parseInt(move['draw']);
175 var black = parseInt(move['black']);
176 var computer = parseInt(move['computer']);
178 line.push(move['move']); // Move.
179 transpose_only.push(move['transpose_only']);
180 var num = white + draw + black;
181 line.push(num); // N.
182 line.push(num / total_num); // %.
183 line.push(computer); // CGames.
185 // Adjust so that the human index is 50% overall.
186 var exp = Math.log(0.5) / Math.log(data['computer_games'] / data['total_games']);
187 line.push(1.0 - Math.pow(computer / num, exp)); // Hum.
190 var white_win_ratio = (white + 0.5 * draw) / num;
191 var win_ratio = (move_override % 2 == 0) ? white_win_ratio : 1.0 - white_win_ratio;
192 line.push(win_ratio);
194 line.push(white); // WWin.
195 line.push(white / num); // %WW.
196 line.push(black); // BWin.
197 line.push(black / num); // %BW.
198 line.push(draw); // Draw.
199 line.push(draw / num); // %Draw.
201 if (move['num_elo'] >= 10) {
203 line.push(move['white_avg_elo']);
204 line.push(move['black_avg_elo']);
205 line.push(move['white_avg_elo'] - move['black_avg_elo']);
207 // Win% corrected for Elo.
208 var win_elo = -400.0 * Math.log(1.0 / white_win_ratio - 1.0) / Math.LN10;
209 win_elo -= (move['white_avg_elo'] - move['black_avg_elo']);
210 white_win_ratio = 1.0 / (1.0 + Math.pow(10, win_elo / -400.0));
211 win_ratio = (move_override % 2 == 0) ? white_win_ratio : 1.0 - white_win_ratio;
212 line.push(win_ratio);
222 lines.sort(function(a, b) { return direction * ( b[sort_by] - a[sort_by]); });
224 var tbl = $("#lines");
227 for (var i = 0; i < moves.length; ++i) {
229 var tr = document.createElement("tr");
231 if (line[0] === undefined) {
232 $(tr).addClass("totals");
233 } else if (transpose_only[i]) {
234 $(tr).addClass("transponly");
237 for (var j = 0; j < line.length; ++j) {
238 if (line[j] === null) {
240 } else if (headings[j][1] == TYPE_MOVE) {
241 var td = document.createElement("td");
243 $(td).addClass("move");
244 if (line[j] !== undefined) {
245 if (move_override % 2 == 0) {
246 $(td).text(((move_override / 2) + 1) + ". ");
248 $(td).text(((move_override / 2) + 0.5) + "…");
252 var move_a = document.createElement("a");
253 move_a.href = "javascript:make_move('" + line[j] + "')";
254 td.appendChild(move_a);
255 $(move_a).text(line[j]);
256 } else if (headings[j][1] == TYPE_INTEGER) {
257 add_td(tr, line[j] || 0);
258 } else if (headings[j][1] == TYPE_FLOAT) {
259 if (isNaN(line[j]) || !isFinite(line[j])) {
262 add_td(tr, line[j].toFixed(1));
265 if (isNaN(line[j]) || !isFinite(line[j])) {
268 add_td(tr, (100.0 * line[j]).toFixed(1) + "%");
277 var set_includetransp = function(value) {
278 includetransp = value;
281 window['set_includetransp'] = set_includetransp;
283 var make_move = function(move, do_update) {
284 var history = game.history({ verbose: true });
285 if (move_override < history.length && history[move_override].san == move) {
286 // User effectively only moved forward in history.
289 var moves = game.history();
290 // Truncate the history if needed.
291 if (move_override < moves.length) {
293 for (var i = 0; i < move_override; ++i) {
296 fens.length = move_override;
299 fens.push(game.fen());
303 if (do_update !== false) {
305 window.history.pushState(null, null, get_history_url());
308 window['make_move'] = make_move;
310 var prev_move = function() {
311 if (move_override > 0) {
314 window.history.replaceState(null, null, get_history_url());
317 window['prev_move'] = prev_move;
319 var next_move = function() {
320 if (move_override < game.history().length) {
323 window.history.replaceState(null, null, get_history_url());
326 window['next_move'] = next_move;
328 var set_move = function(n, do_update) {
330 if (do_update !== false) {
332 window.history.replaceState(null, null, get_history_url());
335 window['set_move'] = set_move;
337 // almost all of this stuff comes from the chessboard.js example page
338 var onDragStart = function(source, piece, position, orientation) {
339 var pseudogame = new Chess(current_display_fen());
340 if (pseudogame.game_over() === true ||
341 (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
342 (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
346 recommended_dest = null;
347 get_best_dest(pseudogame, source, function(dest) {
348 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
350 var squareEl = $('#board .square-' + dest);
351 squareEl.addClass('highlight1-32417');
353 recommended_dest = dest;
357 var get_best_dest = function(game, source, cb) {
358 var moves = game.moves({ square: source, verbose: true });
359 if (moves.length == 0) {
363 if (moves.length == 1) {
368 // More than one move. Ask the engine to disambiguate.
369 var uci_moves = moves.map(function(m) { return m.from + m.to; });
370 var when_engine_is_ready = function() {
371 engine_running = true;
372 stockfish.onmessage = function(event) {
373 var res = event.data.match(/^bestmove \S\S(\S\S)/);
375 engine_running = false;
376 if (engine_replacement_callback !== null) {
377 // We are no longer interested in this query,
378 // so just discard it and call this other callback.
379 engine_replacement_callback();
380 engine_replacement_callback = null;
386 stockfish.postMessage("position fen " + game.fen());
387 stockfish.postMessage("go depth 6 searchmoves " + uci_moves.join(" "));
389 if (engine_running) {
390 engine_replacement_callback = when_engine_is_ready;
392 when_engine_is_ready();
396 var onDrop = function(source, target) {
397 if (engine_running) {
398 // Snap end before the engine came back.
399 // Discard the result when it does.
400 engine_replacement_callback = function() {};
402 if (source == target) {
403 if (recommended_dest === null) {
406 // Accept the move. It will be changed in onSnapEnd.
410 // Suggestion not asked for.
411 recommended_dest = null;
414 // see if the move is legal
415 var pseudogame = new Chess(current_display_fen());
416 var move = pseudogame.move({
419 promotion: 'q' // NOTE: always promote to a queen for example simplicity
423 if (move === null) return 'snapback';
426 var onSnapEnd = function(source, target) {
427 if (source == target && recommended_dest !== null) {
428 target = recommended_dest;
430 recommended_dest = null;
431 var pseudogame = new Chess(current_display_fen());
432 var move = pseudogame.move({
435 promotion: 'q' // NOTE: always promote to a queen for example simplicity
438 make_move(pseudogame.history({ verbose: true }).pop().san);
441 var onpopstate = function() {
442 var old_moves = game.history({ verbose: true }).map(function(x) { return x.san; });
443 var new_moves = document.location.search.replace(/^\?/, "").split(",");
445 if (new_moves.length == 1 && new_moves[0] == "") {
449 var num_shared_moves;
450 for (num_shared_moves = 0; num_shared_moves < Math.min(old_moves.length, new_moves.length); ++num_shared_moves) {
451 if (old_moves[i] != new_moves[i]) {
456 set_move(num_shared_moves, false);
457 for (var i = num_shared_moves; i < new_moves.length; ++i) {
458 make_move(new_moves[i], false);
461 window.history.replaceState(null, null, get_history_url());
464 var init = function() {
466 board = new window.ChessBoard('board', {
469 onDragStart: onDragStart,
474 window.onpopstate = onpopstate;
477 $(window).keyup(function(event) {
478 if (event.which == 39) {
480 } else if (event.which == 37) {
487 $(document).ready(init);