4 var game = new Chess();
5 var fens = []; // Position after each.
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;
13 var practice_mode = false;
14 var practice_side = 'W';
16 // TODO: Make this configurable.
17 var practice_top_moves_limit = 5;
18 var practice_minimum_move_fraction_start = 0.05;
19 var practice_minimum_move_fraction_move5 = 0.30;
29 function escape_html(string) {
30 return String(string).replace(/[&<>"']/g, function (s) {
35 var current_display_fen = function() {
36 return fen_before_move(move_override);
39 var fen_before_move = function(move_num) {
41 return 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1';
43 return fens[move_num - 1];
47 var update = function() {
49 var history = game.history({ verbose: true });
50 for (var i = 0; i < history.length; ++i) {
52 text += (i/2 + 1) + ". ";
54 if (i + 1 == move_override) {
55 text += '<strong>' + history[i].san + '</strong>';
57 text += '<a href="javascript:set_move(' + (i + 1) + ')">' + history[i].san + '</a>';
61 $('#gamehistory').html(text);
63 if (board.fen() != current_display_fen()) {
64 board.position(current_display_fen());
67 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
68 if (move_override > 0) {
69 var last_move = history[move_override - 1];
70 var highlight_from = last_move.from;
71 var highlight_to = last_move.to;
72 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
73 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
77 find_last_move_score();
78 var side_to_move = (move_override % 2 == 0) ? 'W' : 'B';
79 if (side_to_move !== practice_side) {
82 // Fall through to get the line name and such.
88 var get_history_url = function() {
89 var history = game.history({ verbose: true }).map(function(x) { return x.san; });
90 history.length = move_override;
91 return '/?' + history.join(',');
94 var fetch_analysis = function() {
95 var fen = current_display_fen();
97 url: "/opening-stats.pl?fen=" + encodeURIComponent(fen) +
98 ";includetransp=" + (includetransp ? 1 : 0)
99 }).done(function(data, textstatus, xhr) {
100 show_lines(data, game);
104 var find_last_move_score = function() {
105 var history = game.history({ verbose: true });
106 var side_to_move = (move_override % 2 == 0) ? 'W' : 'B';
107 var move_num = (side_to_move === practice_side) ? (move_override - 2) : (move_override - 1);
109 $("#yourmove").text("(none)");
110 $("#yourfraction").text("N/A");
111 $("#yourrank").text("N/A");
112 $("#yourawin").text("??.?%");
113 $("#yourawindiff").text("+?.?%");
117 var chosen_move = history[move_num].san;
118 $("#yourmove").text(chosen_move);
120 url: "/opening-stats.pl?fen=" + encodeURIComponent(fen_before_move(move_num)) +
122 }).done(function(data, textstatus, xhr) {
123 var moves = data['moves'];
124 var root_move = sort_move_by_frequency(moves, data);
125 var your_move, your_index;
127 for (var i = 0; i < moves.length; ++i) {
129 if (move['move'] === chosen_move) {
136 $("#yourfraction").text(format_fraction(your_move['fraction']));
137 $("#yourawin").text(format_fraction(your_move['corrected_win_ratio']));
138 $("#yourrank").text(format_ordinal(your_index + 1) + ", based on " + root_move['num'] + " games");
139 var diff = your_move['corrected_win_ratio'] - root_move['corrected_win_ratio'];
140 $("#yourawindiff").css("color", "black");
142 $("#yourawindiff").text("0.0%");
143 } else if (diff > 0) {
144 $("#yourawindiff").text("+" + format_fraction(diff));
145 $("#yourawindiff").css("color", "green");
147 $("#yourawindiff").text(format_fraction(diff));
149 $("#yourawindiff").css("color", "red");
153 $("#yourfraction").text("??.?%");
154 $("#yourrank").text("?th");
155 $("#yourawin").text("??.?%");
156 $("#yourawindiff").text("+?.?%");
161 var find_computer_move = function() {
162 var fen = current_display_fen();
164 url: "/opening-stats.pl?fen=" + encodeURIComponent(fen) + ";includetransp=0"
165 }).done(function(data, textstatus, xhr) {
166 var candidate_moves = [];
168 var moves = data['moves'];
169 var root_move = sort_move_by_frequency(moves, data);
171 var practice_minimum_move_fraction;
172 if (move_override > 20) {
173 practice_minimum_move_fraction = practice_minimum_move_fraction_move5;
175 practice_minimum_move_fraction = practice_minimum_move_fraction_start +
176 ((move_override-1)/10.0) * (practice_minimum_move_fraction_move5 - practice_minimum_move_fraction_start);
178 console.log(practice_minimum_move_fraction);
180 for (var i = 0; i < Math.min(moves.length, practice_top_moves_limit); ++i) {
182 if (i == 0 || move['fraction'] >= practice_minimum_move_fraction) {
183 candidate_moves.push(move);
187 // Pick one at random.
188 var chosen_index = Math.floor(Math.random() * candidate_moves.length);
189 var chosen = candidate_moves[chosen_index];
190 $("#compmove").text(chosen['move']);
191 $("#compfraction").text((100.0 * chosen['fraction']).toFixed(1) + "%");
192 if (candidate_moves.length == 1) {
193 $("#comprank").text("only candidate move");
195 $("#comprank").text(format_ordinal(chosen_index + 1) + " out of " + candidate_moves.length + " candidate moves");
197 make_move(chosen['move']);
201 // Add deried data and then sort moves to get the most common ones (in-place).
202 // Remove the root mode and return it. Currently usable for practice mode only!
203 var sort_move_by_frequency = function(moves, data)
205 var total_num = find_total_games(moves);
207 for (var i = 0; i < moves.length; ++i) {
209 calc_move_derived_data(move, total_num, data, (practice_side === 'W'));
211 root_move = (moves.splice(i, 1))[0];
215 moves.sort(function(a, b) { return b['num'] - a['num'] });
219 var add_td = function(tr, value) {
220 var td = document.createElement("td");
222 $(td).addClass("num");
226 var format_ordinal = function(x) {
227 var tens = Math.floor(x / 10) % 10;
232 if (ones == 1) return x + "st";
233 if (ones == 2) return x + "nd";
234 if (ones == 3) return x + "rd";
239 var format_fraction = function(x) {
240 return (100.0 * x).toFixed(1) + '%';
244 var TYPE_INTEGER = 1;
249 [ "Move", TYPE_MOVE ],
250 [ "Games", TYPE_INTEGER ],
252 [ "CGames", TYPE_INTEGER ],
253 [ "Hum", TYPE_RATIO ],
254 [ "Win%", TYPE_RATIO ],
255 [ "WWin", TYPE_INTEGER ],
256 [ "%WW", TYPE_RATIO ],
257 [ "Bwin", TYPE_INTEGER ],
258 [ "%BW", TYPE_RATIO ],
259 [ "Draw", TYPE_INTEGER ],
260 [ "Draw%", TYPE_RATIO ],
261 [ "AvWElo", TYPE_FLOAT ],
262 [ "AvBElo", TYPE_FLOAT ],
263 [ "EloVar", TYPE_FLOAT ],
264 [ "AWin%", TYPE_RATIO ],
269 var show_lines = function(data, game) {
270 var moves = data['moves'];
271 $('#numviewers').text(data['opening']);
273 if (data['root_game']) {
274 var text = escape_html(data['root_game']['white']);
275 if (data['root_game']['white_elo']) {
276 text += " (" + escape_html(data['root_game']['white_elo']) + ")";
278 text += " – " + escape_html(data['root_game']['black']);
279 if (data['root_game']['black_elo']) {
280 text += " (" + escape_html(data['root_game']['black_elo']) + ")";
282 text += " " + escape_html(data['root_game']['result']).replace(/-/, "–") + "<br />";
283 if (data['root_game']['eco']) {
284 text += "[" + escape_html(data['root_game']['eco']) + "] ";
286 text += "(" + data['root_game']['moves'] + ") ";
287 text += escape_html(data['root_game']['event']) + " " + escape_html(data['root_game']['date']);
288 $('#gamesummary').html(text);
291 var total_num = find_total_games(moves);
293 var headings_tr = $("#headings");
295 for (var i = 0; i < headings.length; ++i) {
296 var th = document.createElement("th");
297 headings_tr.append(th);
298 $(th).text(headings[i][0]);
299 (function(new_sort_by) {
300 $(th).click(function() {
301 if (sort_by == new_sort_by) {
302 direction = -direction;
304 sort_by = new_sort_by;
307 show_lines(data, game);
313 var transpose_only = [];
314 for (var i = 0; i < moves.length; ++i) {
318 calc_move_derived_data(move, total_num, data, (move_override % 2 == 0));
320 var white = move['white'];
321 var draw = move['draw'];
322 var black = move['black'];
323 var computer = move['computer'];
325 line.push(move['move']); // Move.
326 transpose_only.push(move['transpose_only']);
327 line.push(move['num']); // N.
328 line.push(move['fraction']); // %.
329 line.push(computer); // CGames.
330 line.push(move['human_index']); // Hum.
331 line.push(move['win_ratio']); // Win%.
333 line.push(white); // WWin.
334 line.push(white / move['num']); // %WW.
335 line.push(black); // BWin.
336 line.push(black / move['num']); // %BW.
337 line.push(draw); // Draw.
338 line.push(draw / move['num']); // %Draw.
340 if (move['num_elo'] >= 10) {
342 line.push(move['white_avg_elo']);
343 line.push(move['black_avg_elo']);
344 line.push(move['white_avg_elo'] - move['black_avg_elo']);
351 line.push(move['corrected_win_ratio'] || null);
355 lines.sort(function(a, b) { return direction * ( b[sort_by] - a[sort_by]); });
357 var tbl = $("#lines");
360 for (var i = 0; i < moves.length; ++i) {
362 var tr = document.createElement("tr");
364 if (line[0] === undefined) {
365 $(tr).addClass("totals");
366 } else if (transpose_only[i]) {
367 $(tr).addClass("transponly");
370 for (var j = 0; j < line.length; ++j) {
371 if (line[j] === null) {
373 } else if (headings[j][1] == TYPE_MOVE) {
374 var td = document.createElement("td");
376 $(td).addClass("move");
377 if (line[j] !== undefined) {
378 if (move_override % 2 == 0) {
379 $(td).text(((move_override / 2) + 1) + ". ");
381 $(td).text(((move_override / 2) + 0.5) + "…");
385 if (line[j] === '1-0' || line[j] === '1/2-1/2' || line[j] === '0-1') {
386 $(td).text($(td).text() + line[j]);
388 var move_a = document.createElement("a");
389 move_a.href = "javascript:make_move('" + line[j] + "')";
390 td.appendChild(move_a);
391 $(move_a).text(line[j]);
393 } else if (headings[j][1] == TYPE_INTEGER) {
394 add_td(tr, line[j] || 0);
395 } else if (headings[j][1] == TYPE_FLOAT) {
396 if (isNaN(line[j]) || !isFinite(line[j])) {
399 add_td(tr, line[j].toFixed(1));
402 if (isNaN(line[j]) || !isFinite(line[j])) {
405 add_td(tr, format_fraction(line[j]));
414 var find_total_games = function(moves) {
416 for (var i = 0; i < moves.length; ++i) {
419 total_num += move['white'];
420 total_num += move['draw'];
421 total_num += move['black'];
427 var calc_move_derived_data = function(move, total_num, data, is_white) {
428 var white = move['white'];
429 var draw = move['draw'];
430 var black = move['black'];
431 var computer = move['computer'];
433 var num = white + draw + black;
435 move['fraction'] = num / total_num;
437 // Adjust so that the human index is 50% overall.
438 var exp = Math.log(0.5) / Math.log(data['computer_games'] / data['total_games']);
439 move['human_index'] = 1.0 - Math.pow(computer / num, exp);
442 var white_win_ratio = (white + 0.5 * draw) / num;
443 var win_ratio = is_white ? white_win_ratio : 1.0 - white_win_ratio;
444 move['win_ratio'] = win_ratio;
446 if (move['num_elo'] >= 10) {
447 // Win% corrected for Elo.
448 var win_elo = -400.0 * Math.log(1.0 / white_win_ratio - 1.0) / Math.LN10;
449 win_elo -= (move['white_avg_elo'] - move['black_avg_elo']);
450 white_win_ratio = 1.0 / (1.0 + Math.pow(10, win_elo / -400.0));
451 win_ratio = is_white ? white_win_ratio : 1.0 - white_win_ratio;
452 move['corrected_win_ratio'] = win_ratio;
456 var set_includetransp = function(value) {
457 includetransp = value;
460 window['set_includetransp'] = set_includetransp;
462 var set_flipboard = function(value) {
463 board.orientation(value ? 'black' : 'white');
465 window['set_flipboard'] = set_flipboard;
467 var set_practice = function(value) {
468 practice_mode = value;
470 practice_side = (move_override % 2 == 0) ? 'W' : 'B';
471 find_last_move_score();
473 $("#practiceoutput").show();
474 document.getElementById("includetransp").checked = false;
475 set_includetransp(false);
478 $("#practiceoutput").hide();
482 window['set_practice'] = set_practice;
484 var make_move = function(move, do_update) {
485 var history = game.history({ verbose: true });
486 if (move_override < history.length && history[move_override].san == move) {
487 // User effectively only moved forward in history.
490 var moves = game.history();
491 // Truncate the history if needed.
492 if (move_override < moves.length) {
494 for (var i = 0; i < move_override; ++i) {
497 fens.length = move_override;
500 fens.push(game.fen());
504 if (do_update !== false) {
506 window.history.pushState(null, null, get_history_url());
509 window['make_move'] = make_move;
511 var prev_move = function() {
512 var moves_to_skip = practice_mode ? 2 : 1;
513 if (move_override >= moves_to_skip) {
514 move_override -= moves_to_skip;
516 window.history.replaceState(null, null, get_history_url());
519 window['prev_move'] = prev_move;
521 var next_move = function() {
522 if (move_override < game.history().length) {
525 window.history.replaceState(null, null, get_history_url());
528 window['next_move'] = next_move;
530 var set_move = function(n, do_update) {
532 if (do_update !== false) {
534 window.history.replaceState(null, null, get_history_url());
537 window['set_move'] = set_move;
539 // almost all of this stuff comes from the chessboard.js example page
540 var onDragStart = function(source, piece, position, orientation) {
541 var pseudogame = new Chess(current_display_fen());
542 if (pseudogame.game_over() === true ||
543 (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
544 (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
548 recommended_move = null;
549 get_best_dest(pseudogame, source, null, function(src, dest) {
550 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
552 var squareEl = $('#board .square-' + dest);
553 squareEl.addClass('highlight1-32417');
554 recommended_move = [src, dest];
559 var mousedownSquare = function(e) {
560 reverse_dragging_from = null;
561 var square = $(this).attr('data-square');
563 var pseudogame = new Chess(current_display_fen());
564 if (pseudogame.game_over() === true) {
568 // If the square is empty, or has a piece of the side not to move,
569 // we handle it. If not, normal piece dragging will take it.
570 var position = board.position();
571 if (!position.hasOwnProperty(square) ||
572 (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
573 (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
574 reverse_dragging_from = square;
575 get_best_dest(pseudogame, null, square, function(src, dest) {
577 var squareEl = $('#board .square-' + src);
578 squareEl.addClass('highlight1-32417');
579 squareEl = $('#board .square-' + dest);
580 squareEl.addClass('highlight1-32417');
581 recommended_move = [src, dest];
585 recommended_src = null;
589 var mouseupSquare = function(e) {
590 if (reverse_dragging_from === null) {
593 var source = $(this).attr('data-square');
594 var target = reverse_dragging_from;
595 reverse_dragging_from = null;
596 if (onDrop(source, target) !== 'snapback') {
597 onSnapEnd(source, target);
599 $("#board").find('.square-55d63').removeClass('highlight1-32417');
602 var get_best_dest = function(game, source, target, cb) {
603 var moves = game.moves({ verbose: true });
604 if (source !== null) {
605 moves = moves.filter(function(move) { return move.from == source; });
607 if (target !== null) {
608 moves = moves.filter(function(move) { return move.to == target; });
610 if (moves.length == 0) {
614 if (moves.length == 1) {
615 cb(moves[0].from, moves[0].to);
619 // More than one move. Ask the engine to disambiguate.
620 var uci_moves = moves.map(function(m) { return m.from + m.to; });
621 var when_engine_is_ready = function() {
622 engine_running = true;
623 stockfish.onmessage = function(event) {
624 var res = event.data.match(/^bestmove (\S\S)(\S\S)/);
626 engine_running = false;
627 if (engine_replacement_callback !== null) {
628 // We are no longer interested in this query,
629 // so just discard it and call this other callback.
630 engine_replacement_callback();
631 engine_replacement_callback = null;
637 stockfish.postMessage("position fen " + game.fen());
638 stockfish.postMessage("go depth 6 searchmoves " + uci_moves.join(" "));
640 if (engine_running) {
641 engine_replacement_callback = when_engine_is_ready;
643 when_engine_is_ready();
647 var onDrop = function(source, target) {
648 if (engine_running) {
649 // Snap end before the engine came back.
650 // Discard the result when it does.
651 engine_replacement_callback = function() {};
653 if (source == target) {
654 if (recommended_move === null) {
657 // Accept the move. It will be changed in onSnapEnd.
661 // Suggestion not asked for.
662 recommended_move = null;
665 // see if the move is legal
666 var pseudogame = new Chess(current_display_fen());
667 var move = pseudogame.move({
670 promotion: 'q' // NOTE: always promote to a queen for example simplicity
674 if (move === null) return 'snapback';
677 var onSnapEnd = function(source, target) {
678 if (source == target && recommended_move !== null) {
679 source = recommended_move[0];
680 target = recommended_move[1];
682 recommended_move = null;
683 var pseudogame = new Chess(current_display_fen());
684 var move = pseudogame.move({
687 promotion: 'q' // NOTE: always promote to a queen for example simplicity
690 make_move(pseudogame.history({ verbose: true }).pop().san);
693 var onpopstate = function() {
694 var old_moves = game.history({ verbose: true }).map(function(x) { return x.san; });
695 var new_moves = document.location.search.replace(/^\?/, "").split(",");
697 if (new_moves.length == 1 && new_moves[0] == "") {
701 var num_shared_moves;
702 for (num_shared_moves = 0; num_shared_moves < Math.min(old_moves.length, new_moves.length); ++num_shared_moves) {
703 if (old_moves[i] != new_moves[i]) {
708 set_move(num_shared_moves, false);
709 for (var i = num_shared_moves; i < new_moves.length; ++i) {
710 make_move(new_moves[i], false);
713 window.history.replaceState(null, null, get_history_url());
716 var init = function() {
718 board = new window.ChessBoard('board', {
721 onDragStart: onDragStart,
725 $("#board").on('mousedown', '.square-55d63', mousedownSquare);
726 $("#board").on('mouseup', '.square-55d63', mouseupSquare);
728 window.onpopstate = onpopstate;
732 $(window).keyup(function(event) {
733 if (event.which == 39) {
735 } else if (event.which == 37) {
740 // Seemingly the web worker is not started before we send it a message.
741 stockfish.postMessage("uci");
744 $(document).ready(init);