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 derived = calc_move_derived_data(move, total_num, data, (move_override % 2 == 0));
168 var white = move['white'];
169 var draw = move['draw'];
170 var black = move['black'];
171 var computer = move['computer'];
173 line.push(move['move']); // Move.
174 transpose_only.push(move['transpose_only']);
175 line.push(derived['num']); // N.
176 line.push(derived['fraction']); // %.
177 line.push(computer); // CGames.
178 line.push(derived['human_index']); // Hum.
179 line.push(derived['win_ratio']); // Win%.
181 line.push(white); // WWin.
182 line.push(white / derived['num']); // %WW.
183 line.push(black); // BWin.
184 line.push(black / derived['num']); // %BW.
185 line.push(draw); // Draw.
186 line.push(draw / derived['num']); // %Draw.
188 if (move['num_elo'] >= 10) {
190 line.push(move['white_avg_elo']);
191 line.push(move['black_avg_elo']);
192 line.push(move['white_avg_elo'] - move['black_avg_elo']);
199 line.push(derived['corrected_win_ratio'] || null);
203 lines.sort(function(a, b) { return direction * ( b[sort_by] - a[sort_by]); });
205 var tbl = $("#lines");
208 for (var i = 0; i < moves.length; ++i) {
210 var tr = document.createElement("tr");
212 if (line[0] === undefined) {
213 $(tr).addClass("totals");
214 } else if (transpose_only[i]) {
215 $(tr).addClass("transponly");
218 for (var j = 0; j < line.length; ++j) {
219 if (line[j] === null) {
221 } else if (headings[j][1] == TYPE_MOVE) {
222 var td = document.createElement("td");
224 $(td).addClass("move");
225 if (line[j] !== undefined) {
226 if (move_override % 2 == 0) {
227 $(td).text(((move_override / 2) + 1) + ". ");
229 $(td).text(((move_override / 2) + 0.5) + "…");
233 if (line[j] === '1-0' || line[j] === '1/2-1/2' || line[j] === '0-1') {
234 $(td).text($(td).text() + line[j]);
236 var move_a = document.createElement("a");
237 move_a.href = "javascript:make_move('" + line[j] + "')";
238 td.appendChild(move_a);
239 $(move_a).text(line[j]);
241 } else if (headings[j][1] == TYPE_INTEGER) {
242 add_td(tr, line[j] || 0);
243 } else if (headings[j][1] == TYPE_FLOAT) {
244 if (isNaN(line[j]) || !isFinite(line[j])) {
247 add_td(tr, line[j].toFixed(1));
250 if (isNaN(line[j]) || !isFinite(line[j])) {
253 add_td(tr, (100.0 * line[j]).toFixed(1) + "%");
262 var find_total_games = function(moves) {
264 for (var i = 0; i < moves.length; ++i) {
267 total_num += move['white'];
268 total_num += move['draw'];
269 total_num += move['black'];
275 var calc_move_derived_data = function(move, total_num, data, is_white) {
277 var white = move['white'];
278 var draw = move['draw'];
279 var black = move['black'];
280 var computer = move['computer'];
282 var num = white + draw + black;
283 derived['num'] = num;
284 derived['fraction'] = num / total_num;
286 // Adjust so that the human index is 50% overall.
287 var exp = Math.log(0.5) / Math.log(data['computer_games'] / data['total_games']);
288 derived['human_index'] = 1.0 - Math.pow(computer / num, exp);
291 var white_win_ratio = (white + 0.5 * draw) / num;
292 var win_ratio = is_white ? white_win_ratio : 1.0 - white_win_ratio;
293 derived['win_ratio'] = win_ratio;
295 if (move['num_elo'] >= 10) {
296 // Win% corrected for Elo.
297 var win_elo = -400.0 * Math.log(1.0 / white_win_ratio - 1.0) / Math.LN10;
298 win_elo -= (move['white_avg_elo'] - move['black_avg_elo']);
299 white_win_ratio = 1.0 / (1.0 + Math.pow(10, win_elo / -400.0));
300 win_ratio = is_white ? white_win_ratio : 1.0 - white_win_ratio;
301 derived['corrected_win_ratio'] = win_ratio;
307 var set_includetransp = function(value) {
308 includetransp = value;
311 window['set_includetransp'] = set_includetransp;
313 var set_flipboard = function(value) {
314 board.orientation(value ? 'black' : 'white');
316 window['set_flipboard'] = set_flipboard;
318 var make_move = function(move, do_update) {
319 var history = game.history({ verbose: true });
320 if (move_override < history.length && history[move_override].san == move) {
321 // User effectively only moved forward in history.
324 var moves = game.history();
325 // Truncate the history if needed.
326 if (move_override < moves.length) {
328 for (var i = 0; i < move_override; ++i) {
331 fens.length = move_override;
334 fens.push(game.fen());
338 if (do_update !== false) {
340 window.history.pushState(null, null, get_history_url());
343 window['make_move'] = make_move;
345 var prev_move = function() {
346 if (move_override > 0) {
349 window.history.replaceState(null, null, get_history_url());
352 window['prev_move'] = prev_move;
354 var next_move = function() {
355 if (move_override < game.history().length) {
358 window.history.replaceState(null, null, get_history_url());
361 window['next_move'] = next_move;
363 var set_move = function(n, do_update) {
365 if (do_update !== false) {
367 window.history.replaceState(null, null, get_history_url());
370 window['set_move'] = set_move;
372 // almost all of this stuff comes from the chessboard.js example page
373 var onDragStart = function(source, piece, position, orientation) {
374 var pseudogame = new Chess(current_display_fen());
375 if (pseudogame.game_over() === true ||
376 (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
377 (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
381 recommended_move = null;
382 get_best_dest(pseudogame, source, null, function(src, dest) {
383 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
385 var squareEl = $('#board .square-' + dest);
386 squareEl.addClass('highlight1-32417');
387 recommended_move = [src, dest];
392 var mousedownSquare = function(e) {
393 reverse_dragging_from = null;
394 var square = $(this).attr('data-square');
396 var pseudogame = new Chess(current_display_fen());
397 if (pseudogame.game_over() === true) {
401 // If the square is empty, or has a piece of the side not to move,
402 // we handle it. If not, normal piece dragging will take it.
403 var position = board.position();
404 if (!position.hasOwnProperty(square) ||
405 (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
406 (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
407 reverse_dragging_from = square;
408 get_best_dest(pseudogame, null, square, function(src, dest) {
410 var squareEl = $('#board .square-' + src);
411 squareEl.addClass('highlight1-32417');
412 squareEl = $('#board .square-' + dest);
413 squareEl.addClass('highlight1-32417');
414 recommended_move = [src, dest];
418 recommended_src = null;
422 var mouseupSquare = function(e) {
423 if (reverse_dragging_from === null) {
426 var source = $(this).attr('data-square');
427 var target = reverse_dragging_from;
428 reverse_dragging_from = null;
429 if (onDrop(source, target) !== 'snapback') {
430 onSnapEnd(source, target);
432 $("#board").find('.square-55d63').removeClass('highlight1-32417');
435 var get_best_dest = function(game, source, target, cb) {
436 var moves = game.moves({ verbose: true });
437 if (source !== null) {
438 moves = moves.filter(function(move) { return move.from == source; });
440 if (target !== null) {
441 moves = moves.filter(function(move) { return move.to == target; });
443 if (moves.length == 0) {
447 if (moves.length == 1) {
448 cb(moves[0].from, moves[0].to);
452 // More than one move. Ask the engine to disambiguate.
453 var uci_moves = moves.map(function(m) { return m.from + m.to; });
454 var when_engine_is_ready = function() {
455 engine_running = true;
456 stockfish.onmessage = function(event) {
457 var res = event.data.match(/^bestmove (\S\S)(\S\S)/);
459 engine_running = false;
460 if (engine_replacement_callback !== null) {
461 // We are no longer interested in this query,
462 // so just discard it and call this other callback.
463 engine_replacement_callback();
464 engine_replacement_callback = null;
470 stockfish.postMessage("position fen " + game.fen());
471 stockfish.postMessage("go depth 6 searchmoves " + uci_moves.join(" "));
473 if (engine_running) {
474 engine_replacement_callback = when_engine_is_ready;
476 when_engine_is_ready();
480 var onDrop = function(source, target) {
481 if (engine_running) {
482 // Snap end before the engine came back.
483 // Discard the result when it does.
484 engine_replacement_callback = function() {};
486 if (source == target) {
487 if (recommended_move === null) {
490 // Accept the move. It will be changed in onSnapEnd.
494 // Suggestion not asked for.
495 recommended_move = null;
498 // see if the move is legal
499 var pseudogame = new Chess(current_display_fen());
500 var move = pseudogame.move({
503 promotion: 'q' // NOTE: always promote to a queen for example simplicity
507 if (move === null) return 'snapback';
510 var onSnapEnd = function(source, target) {
511 if (source == target && recommended_move !== null) {
512 source = recommended_move[0];
513 target = recommended_move[1];
515 recommended_move = null;
516 var pseudogame = new Chess(current_display_fen());
517 var move = pseudogame.move({
520 promotion: 'q' // NOTE: always promote to a queen for example simplicity
523 make_move(pseudogame.history({ verbose: true }).pop().san);
526 var onpopstate = function() {
527 var old_moves = game.history({ verbose: true }).map(function(x) { return x.san; });
528 var new_moves = document.location.search.replace(/^\?/, "").split(",");
530 if (new_moves.length == 1 && new_moves[0] == "") {
534 var num_shared_moves;
535 for (num_shared_moves = 0; num_shared_moves < Math.min(old_moves.length, new_moves.length); ++num_shared_moves) {
536 if (old_moves[i] != new_moves[i]) {
541 set_move(num_shared_moves, false);
542 for (var i = num_shared_moves; i < new_moves.length; ++i) {
543 make_move(new_moves[i], false);
546 window.history.replaceState(null, null, get_history_url());
549 var init = function() {
551 board = new window.ChessBoard('board', {
554 onDragStart: onDragStart,
558 $("#board").on('mousedown', '.square-55d63', mousedownSquare);
559 $("#board").on('mouseup', '.square-55d63', mouseupSquare);
561 window.onpopstate = onpopstate;
564 $(window).keyup(function(event) {
565 if (event.which == 39) {
567 } else if (event.which == 37) {
572 // Seemingly the web worker is not started before we send it a message.
573 stockfish.postMessage("uci");
576 $(document).ready(init);