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_moves_by_common(moves, data);
125 var your_move, your_index;
127 for (var i = 0; i < moves.length; ++i) {
129 if (move['move'] === chosen_move) {
134 moves.sort(function(a, b) { return b['num'] - a['num'] });
137 $("#yourfraction").text(format_fraction(your_move['fraction']));
138 $("#yourawin").text(format_fraction(your_move['corrected_win_ratio']));
139 $("#yourrank").text(format_ordinal(your_index + 1) + ", based on " + root_move['num'] + " games");
140 var diff = your_move['corrected_win_ratio'] - root_move['corrected_win_ratio'];
141 $("#yourawindiff").css("color", "black");
143 $("#yourawindiff").text("0.0%");
144 } else if (diff > 0) {
145 $("#yourawindiff").text("+" + format_fraction(diff));
146 $("#yourawindiff").css("color", "green");
148 $("#yourawindiff").text(format_fraction(diff));
150 $("#yourawindiff").css("color", "red");
154 $("#yourfraction").text("??.?%");
155 $("#yourrank").text("?th");
156 $("#yourawin").text("??.?%");
157 $("#yourawindiff").text("+?.?%");
162 var find_computer_move = function() {
163 var fen = current_display_fen();
165 url: "/opening-stats.pl?fen=" + encodeURIComponent(fen) + ";includetransp=0"
166 }).done(function(data, textstatus, xhr) {
167 var candidate_moves = [];
169 var moves = data['moves'];
170 var root_move = sort_moves_by_common(moves, data);
172 var practice_minimum_move_fraction;
173 if (move_override > 20) {
174 practice_minimum_move_fraction = practice_minimum_move_fraction_move5;
176 practice_minimum_move_fraction = practice_minimum_move_fraction_start +
177 ((move_override-1)/10.0) * (practice_minimum_move_fraction_move5 - practice_minimum_move_fraction_start);
179 console.log(practice_minimum_move_fraction);
181 for (var i = 0; i < Math.min(moves.length, practice_top_moves_limit); ++i) {
183 if (i == 0 || move['fraction'] >= practice_minimum_move_fraction) {
184 candidate_moves.push(move);
188 // Pick one at random.
189 var chosen_index = Math.floor(Math.random() * candidate_moves.length);
190 var chosen = candidate_moves[chosen_index];
191 $("#compmove").text(chosen['move']);
192 $("#compfraction").text((100.0 * chosen['fraction']).toFixed(1) + "%");
193 if (candidate_moves.length == 1) {
194 $("#comprank").text("only candidate move");
196 $("#comprank").text(format_ordinal(chosen_index + 1) + " out of " + candidate_moves.length + " candidate moves");
198 make_move(chosen['move']);
202 // Add deried data and then sort moves to get the most common ones (in-place).
203 // Remove the root mode and return it. Currently usable for practice mode only!
204 var sort_moves_by_common = function(moves, data)
206 var total_num = find_total_games(moves);
208 for (var i = 0; i < moves.length; ++i) {
210 calc_move_derived_data(move, total_num, data, (practice_side === 'W'));
212 root_move = (moves.splice(i, 1))[0];
216 moves.sort(function(a, b) { return b['num'] - a['num'] });
220 var add_td = function(tr, value) {
221 var td = document.createElement("td");
223 $(td).addClass("num");
227 var format_ordinal = function(x) {
228 var tens = Math.floor(x / 10) % 10;
233 if (ones == 1) return x + "st";
234 if (ones == 2) return x + "nd";
235 if (ones == 3) return x + "rd";
240 var format_fraction = function(x) {
241 return (100.0 * x).toFixed(1) + '%';
245 var TYPE_INTEGER = 1;
250 [ "Move", TYPE_MOVE ],
251 [ "Games", TYPE_INTEGER ],
253 [ "CGames", TYPE_INTEGER ],
254 [ "Hum", TYPE_RATIO ],
255 [ "Win%", TYPE_RATIO ],
256 [ "WWin", TYPE_INTEGER ],
257 [ "%WW", TYPE_RATIO ],
258 [ "Bwin", TYPE_INTEGER ],
259 [ "%BW", TYPE_RATIO ],
260 [ "Draw", TYPE_INTEGER ],
261 [ "Draw%", TYPE_RATIO ],
262 [ "AvWElo", TYPE_FLOAT ],
263 [ "AvBElo", TYPE_FLOAT ],
264 [ "EloVar", TYPE_FLOAT ],
265 [ "AWin%", TYPE_RATIO ],
270 var show_lines = function(data, game) {
271 var moves = data['moves'];
272 $('#numviewers').text(data['opening']);
274 if (data['root_game']) {
275 var text = escape_html(data['root_game']['white']);
276 if (data['root_game']['white_elo']) {
277 text += " (" + escape_html(data['root_game']['white_elo']) + ")";
279 text += " – " + escape_html(data['root_game']['black']);
280 if (data['root_game']['black_elo']) {
281 text += " (" + escape_html(data['root_game']['black_elo']) + ")";
283 text += " " + escape_html(data['root_game']['result']).replace(/-/, "–") + "<br />";
284 if (data['root_game']['eco']) {
285 text += "[" + escape_html(data['root_game']['eco']) + "] ";
287 text += "(" + data['root_game']['moves'] + ") ";
288 text += escape_html(data['root_game']['event']) + " " + escape_html(data['root_game']['date']);
289 $('#gamesummary').html(text);
292 var total_num = find_total_games(moves);
294 var headings_tr = $("#headings");
296 for (var i = 0; i < headings.length; ++i) {
297 var th = document.createElement("th");
298 headings_tr.append(th);
299 $(th).text(headings[i][0]);
300 (function(new_sort_by) {
301 $(th).click(function() {
302 if (sort_by == new_sort_by) {
303 direction = -direction;
305 sort_by = new_sort_by;
308 show_lines(data, game);
314 var transpose_only = [];
315 for (var i = 0; i < moves.length; ++i) {
319 calc_move_derived_data(move, total_num, data, (move_override % 2 == 0));
321 var white = move['white'];
322 var draw = move['draw'];
323 var black = move['black'];
324 var computer = move['computer'];
326 line.push(move['move']); // Move.
327 transpose_only.push(move['transpose_only']);
328 line.push(move['num']); // N.
329 line.push(move['fraction']); // %.
330 line.push(computer); // CGames.
331 line.push(move['human_index']); // Hum.
332 line.push(move['win_ratio']); // Win%.
334 line.push(white); // WWin.
335 line.push(white / move['num']); // %WW.
336 line.push(black); // BWin.
337 line.push(black / move['num']); // %BW.
338 line.push(draw); // Draw.
339 line.push(draw / move['num']); // %Draw.
341 if (move['num_elo'] >= 10) {
343 line.push(move['white_avg_elo']);
344 line.push(move['black_avg_elo']);
345 line.push(move['white_avg_elo'] - move['black_avg_elo']);
352 line.push(move['corrected_win_ratio'] || null);
356 lines.sort(function(a, b) { return direction * ( b[sort_by] - a[sort_by]); });
358 var tbl = $("#lines");
361 for (var i = 0; i < moves.length; ++i) {
363 var tr = document.createElement("tr");
365 if (line[0] === undefined) {
366 $(tr).addClass("totals");
367 } else if (transpose_only[i]) {
368 $(tr).addClass("transponly");
371 for (var j = 0; j < line.length; ++j) {
372 if (line[j] === null) {
374 } else if (headings[j][1] == TYPE_MOVE) {
375 var td = document.createElement("td");
377 $(td).addClass("move");
378 if (line[j] !== undefined) {
379 if (move_override % 2 == 0) {
380 $(td).text(((move_override / 2) + 1) + ". ");
382 $(td).text(((move_override / 2) + 0.5) + "…");
386 if (line[j] === '1-0' || line[j] === '1/2-1/2' || line[j] === '0-1') {
387 $(td).text($(td).text() + line[j]);
389 var move_a = document.createElement("a");
390 move_a.href = "javascript:make_move('" + line[j] + "')";
391 td.appendChild(move_a);
392 $(move_a).text(line[j]);
394 } else if (headings[j][1] == TYPE_INTEGER) {
395 add_td(tr, line[j] || 0);
396 } else if (headings[j][1] == TYPE_FLOAT) {
397 if (isNaN(line[j]) || !isFinite(line[j])) {
400 add_td(tr, line[j].toFixed(1));
403 if (isNaN(line[j]) || !isFinite(line[j])) {
406 add_td(tr, format_fraction(line[j]));
415 var find_total_games = function(moves) {
417 for (var i = 0; i < moves.length; ++i) {
420 total_num += move['white'];
421 total_num += move['draw'];
422 total_num += move['black'];
428 var calc_move_derived_data = function(move, total_num, data, is_white) {
429 var white = move['white'];
430 var draw = move['draw'];
431 var black = move['black'];
432 var computer = move['computer'];
434 var num = white + draw + black;
436 move['fraction'] = num / total_num;
438 // Adjust so that the human index is 50% overall.
439 var exp = Math.log(0.5) / Math.log(data['computer_games'] / data['total_games']);
440 move['human_index'] = 1.0 - Math.pow(computer / num, exp);
443 var white_win_ratio = (white + 0.5 * draw) / num;
444 var win_ratio = is_white ? white_win_ratio : 1.0 - white_win_ratio;
445 move['win_ratio'] = win_ratio;
447 if (move['num_elo'] >= 10) {
448 // Win% corrected for Elo.
449 var win_elo = -400.0 * Math.log(1.0 / white_win_ratio - 1.0) / Math.LN10;
450 win_elo -= (move['white_avg_elo'] - move['black_avg_elo']);
451 white_win_ratio = 1.0 / (1.0 + Math.pow(10, win_elo / -400.0));
452 win_ratio = is_white ? white_win_ratio : 1.0 - white_win_ratio;
453 move['corrected_win_ratio'] = win_ratio;
457 var set_includetransp = function(value) {
458 includetransp = value;
461 window['set_includetransp'] = set_includetransp;
463 var set_flipboard = function(value) {
464 board.orientation(value ? 'black' : 'white');
466 window['set_flipboard'] = set_flipboard;
468 var set_practice = function(value) {
469 practice_mode = value;
471 practice_side = (move_override % 2 == 0) ? 'W' : 'B';
472 find_last_move_score();
474 $("#practiceoutput").show();
475 document.getElementById("includetransp").checked = 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);