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 candidate_moves = [];
162 var chosen_index = null;
164 var find_computer_move = function() {
165 var fen = current_display_fen();
167 url: "/opening-stats.pl?fen=" + encodeURIComponent(fen) + ";includetransp=0"
168 }).done(function(data, textstatus, xhr) {
169 candidate_moves = [];
171 var moves = data['moves'];
172 var root_move = sort_move_by_frequency(moves, data);
174 var practice_minimum_move_fraction;
175 if (move_override > 20) {
176 practice_minimum_move_fraction = practice_minimum_move_fraction_move5;
178 practice_minimum_move_fraction = practice_minimum_move_fraction_start +
179 ((move_override-1)/10.0) * (practice_minimum_move_fraction_move5 - practice_minimum_move_fraction_start);
181 console.log(practice_minimum_move_fraction);
183 for (var i = 0; i < Math.min(moves.length, practice_top_moves_limit); ++i) {
185 if (i == 0 || move['fraction'] >= practice_minimum_move_fraction) {
186 candidate_moves.push(move);
190 // Pick one at random.
191 choose_move(Math.floor(Math.random() * candidate_moves.length));
195 var choose_move = function(idx) {
197 var chosen = candidate_moves[chosen_index];
198 $("#compmove").text(chosen['move']);
199 $("#compfraction").text((100.0 * chosen['fraction']).toFixed(1) + "%");
200 if (candidate_moves.length == 1) {
201 $("#comprank").text("only candidate move");
203 $("#comprank").text(format_ordinal(chosen_index + 1) + " out of " + candidate_moves.length + " candidate moves, j/k to switch");
205 make_move(chosen['move']);
208 var prev_variant = function() {
209 if (chosen_index !== null) {
211 choose_move((chosen_index + candidate_moves.length - 1) % candidate_moves.length);
215 var next_variant = function() {
216 if (chosen_index !== null) {
218 choose_move((chosen_index + 1) % candidate_moves.length);
222 // Add deried data and then sort moves to get the most common ones (in-place).
223 // Remove the root mode and return it. Currently usable for practice mode only!
224 var sort_move_by_frequency = function(moves, data)
226 var total_num = find_total_games(moves);
228 for (var i = 0; i < moves.length; ++i) {
230 calc_move_derived_data(move, total_num, data, (practice_side === 'W'));
232 root_move = (moves.splice(i, 1))[0];
236 moves.sort(function(a, b) { return b['num'] - a['num'] });
240 var add_td = function(tr, value) {
241 var td = document.createElement("td");
243 $(td).addClass("num");
247 var format_ordinal = function(x) {
248 var tens = Math.floor(x / 10) % 10;
253 if (ones == 1) return x + "st";
254 if (ones == 2) return x + "nd";
255 if (ones == 3) return x + "rd";
260 var format_fraction = function(x) {
261 return (100.0 * x).toFixed(1) + '%';
265 var TYPE_INTEGER = 1;
270 [ "Move", TYPE_MOVE ],
271 [ "Games", TYPE_INTEGER ],
273 [ "CGames", TYPE_INTEGER ],
274 [ "Hum", TYPE_RATIO ],
275 [ "Win%", TYPE_RATIO ],
276 [ "WWin", TYPE_INTEGER ],
277 [ "%WW", TYPE_RATIO ],
278 [ "Bwin", TYPE_INTEGER ],
279 [ "%BW", TYPE_RATIO ],
280 [ "Draw", TYPE_INTEGER ],
281 [ "Draw%", TYPE_RATIO ],
282 [ "AvWElo", TYPE_FLOAT ],
283 [ "AvBElo", TYPE_FLOAT ],
284 [ "EloVar", TYPE_FLOAT ],
285 [ "AWin%", TYPE_RATIO ],
290 var show_lines = function(data, game) {
291 var moves = data['moves'];
292 $('#numviewers').text(data['opening']);
294 if (data['root_game']) {
295 var text = escape_html(data['root_game']['white']);
296 if (data['root_game']['white_elo']) {
297 text += " (" + escape_html(data['root_game']['white_elo']) + ")";
299 text += " – " + escape_html(data['root_game']['black']);
300 if (data['root_game']['black_elo']) {
301 text += " (" + escape_html(data['root_game']['black_elo']) + ")";
303 text += " " + escape_html(data['root_game']['result']).replace(/-/, "–") + "<br />";
304 if (data['root_game']['eco']) {
305 text += "[" + escape_html(data['root_game']['eco']) + "] ";
307 text += "(" + data['root_game']['moves'] + ") ";
308 text += escape_html(data['root_game']['event']) + " " + escape_html(data['root_game']['date']);
309 $('#gamesummary').html(text);
312 var total_num = find_total_games(moves);
314 var headings_tr = $("#headings");
316 for (var i = 0; i < headings.length; ++i) {
317 var th = document.createElement("th");
318 headings_tr.append(th);
319 $(th).text(headings[i][0]);
320 (function(new_sort_by) {
321 $(th).click(function() {
322 if (sort_by == new_sort_by) {
323 direction = -direction;
325 sort_by = new_sort_by;
328 show_lines(data, game);
334 var transpose_only = [];
335 for (var i = 0; i < moves.length; ++i) {
339 calc_move_derived_data(move, total_num, data, (move_override % 2 == 0));
341 var white = move['white'];
342 var draw = move['draw'];
343 var black = move['black'];
344 var computer = move['computer'];
346 line.push(move['move']); // Move.
347 transpose_only.push(move['transpose_only']);
348 line.push(move['num']); // N.
349 line.push(move['fraction']); // %.
350 line.push(computer); // CGames.
351 line.push(move['human_index']); // Hum.
352 line.push(move['win_ratio']); // Win%.
354 line.push(white); // WWin.
355 line.push(white / move['num']); // %WW.
356 line.push(black); // BWin.
357 line.push(black / move['num']); // %BW.
358 line.push(draw); // Draw.
359 line.push(draw / move['num']); // %Draw.
361 if (move['num_elo'] >= 10) {
363 line.push(move['white_avg_elo']);
364 line.push(move['black_avg_elo']);
365 line.push(move['white_avg_elo'] - move['black_avg_elo']);
372 line.push(move['corrected_win_ratio'] || null);
376 lines.sort(function(a, b) { return direction * ( b[sort_by] - a[sort_by]); });
378 var tbl = $("#lines");
381 for (var i = 0; i < moves.length; ++i) {
383 var tr = document.createElement("tr");
385 if (line[0] === undefined) {
386 $(tr).addClass("totals");
387 } else if (transpose_only[i]) {
388 $(tr).addClass("transponly");
391 for (var j = 0; j < line.length; ++j) {
392 if (line[j] === null) {
394 } else if (headings[j][1] == TYPE_MOVE) {
395 var td = document.createElement("td");
397 $(td).addClass("move");
398 if (line[j] !== undefined) {
399 if (move_override % 2 == 0) {
400 $(td).text(((move_override / 2) + 1) + ". ");
402 $(td).text(((move_override / 2) + 0.5) + "…");
406 if (line[j] === '1-0' || line[j] === '1/2-1/2' || line[j] === '0-1') {
407 $(td).text($(td).text() + line[j]);
409 var move_a = document.createElement("a");
410 move_a.href = "javascript:make_move('" + line[j] + "')";
411 td.appendChild(move_a);
412 $(move_a).text(line[j]);
414 } else if (headings[j][1] == TYPE_INTEGER) {
415 add_td(tr, line[j] || 0);
416 } else if (headings[j][1] == TYPE_FLOAT) {
417 if (isNaN(line[j]) || !isFinite(line[j])) {
420 add_td(tr, line[j].toFixed(1));
423 if (isNaN(line[j]) || !isFinite(line[j])) {
426 add_td(tr, format_fraction(line[j]));
435 var find_total_games = function(moves) {
437 for (var i = 0; i < moves.length; ++i) {
440 total_num += move['white'];
441 total_num += move['draw'];
442 total_num += move['black'];
448 var calc_move_derived_data = function(move, total_num, data, is_white) {
449 var white = move['white'];
450 var draw = move['draw'];
451 var black = move['black'];
452 var computer = move['computer'];
454 var num = white + draw + black;
456 move['fraction'] = num / total_num;
458 // Adjust so that the human index is 50% overall.
459 var exp = Math.log(0.5) / Math.log(data['computer_games'] / data['total_games']);
460 move['human_index'] = 1.0 - Math.pow(computer / num, exp);
463 var white_win_ratio = (white + 0.5 * draw) / num;
464 var win_ratio = is_white ? white_win_ratio : 1.0 - white_win_ratio;
465 move['win_ratio'] = win_ratio;
467 if (move['num_elo'] >= 10) {
468 // Win% corrected for Elo.
469 var win_elo = -400.0 * Math.log(1.0 / white_win_ratio - 1.0) / Math.LN10;
470 win_elo -= (move['white_avg_elo'] - move['black_avg_elo']);
471 white_win_ratio = 1.0 / (1.0 + Math.pow(10, win_elo / -400.0));
472 win_ratio = is_white ? white_win_ratio : 1.0 - white_win_ratio;
473 move['corrected_win_ratio'] = win_ratio;
477 var set_includetransp = function(value) {
478 includetransp = value;
481 window['set_includetransp'] = set_includetransp;
483 var set_flipboard = function(value) {
484 board.orientation(value ? 'black' : 'white');
486 window['set_flipboard'] = set_flipboard;
488 var set_practice = function(value) {
489 practice_mode = value;
491 practice_side = (move_override % 2 == 0) ? 'W' : 'B';
492 find_last_move_score();
494 $("#practiceoutput").show();
495 document.getElementById("includetransp").checked = false;
496 set_includetransp(false);
499 $("#practiceoutput").hide();
503 window['set_practice'] = set_practice;
505 var make_move = function(move, do_update) {
506 var history = game.history({ verbose: true });
507 if (move_override < history.length && history[move_override].san == move) {
508 // User effectively only moved forward in history.
511 var moves = game.history();
512 // Truncate the history if needed.
513 if (move_override < moves.length) {
515 for (var i = 0; i < move_override; ++i) {
518 fens.length = move_override;
521 fens.push(game.fen());
525 if (do_update !== false) {
527 window.history.pushState(null, null, get_history_url());
530 window['make_move'] = make_move;
532 var prev_move = function() {
533 var moves_to_skip = practice_mode ? 2 : 1;
534 if (move_override >= moves_to_skip) {
535 move_override -= moves_to_skip;
537 window.history.replaceState(null, null, get_history_url());
540 window['prev_move'] = prev_move;
542 var next_move = function() {
543 if (move_override < game.history().length) {
546 window.history.replaceState(null, null, get_history_url());
549 window['next_move'] = next_move;
551 var set_move = function(n, do_update) {
553 if (do_update !== false) {
555 window.history.replaceState(null, null, get_history_url());
558 window['set_move'] = set_move;
560 // almost all of this stuff comes from the chessboard.js example page
561 var onDragStart = function(source, piece, position, orientation) {
562 var pseudogame = new Chess(current_display_fen());
563 if (pseudogame.game_over() === true ||
564 (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
565 (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
569 recommended_move = null;
570 get_best_dest(pseudogame, source, null, function(src, dest) {
571 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
573 var squareEl = $('#board .square-' + dest);
574 squareEl.addClass('highlight1-32417');
575 recommended_move = [src, dest];
580 var mousedownSquare = function(e) {
581 reverse_dragging_from = null;
582 var square = $(this).attr('data-square');
584 var pseudogame = new Chess(current_display_fen());
585 if (pseudogame.game_over() === true) {
589 // If the square is empty, or has a piece of the side not to move,
590 // we handle it. If not, normal piece dragging will take it.
591 var position = board.position();
592 if (!position.hasOwnProperty(square) ||
593 (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
594 (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
595 reverse_dragging_from = square;
596 get_best_dest(pseudogame, null, square, function(src, dest) {
598 var squareEl = $('#board .square-' + src);
599 squareEl.addClass('highlight1-32417');
600 squareEl = $('#board .square-' + dest);
601 squareEl.addClass('highlight1-32417');
602 recommended_move = [src, dest];
606 recommended_src = null;
610 var mouseupSquare = function(e) {
611 if (reverse_dragging_from === null) {
614 var source = $(this).attr('data-square');
615 var target = reverse_dragging_from;
616 reverse_dragging_from = null;
617 if (onDrop(source, target) !== 'snapback') {
618 onSnapEnd(source, target);
620 $("#board").find('.square-55d63').removeClass('highlight1-32417');
623 var get_best_dest = function(game, source, target, cb) {
624 var moves = game.moves({ verbose: true });
625 if (source !== null) {
626 moves = moves.filter(function(move) { return move.from == source; });
628 if (target !== null) {
629 moves = moves.filter(function(move) { return move.to == target; });
631 if (moves.length == 0) {
635 if (moves.length == 1) {
636 cb(moves[0].from, moves[0].to);
640 // More than one move. Ask the engine to disambiguate.
641 var uci_moves = moves.map(function(m) { return m.from + m.to; });
642 var when_engine_is_ready = function() {
643 engine_running = true;
644 stockfish.onmessage = function(event) {
645 var res = event.data.match(/^bestmove (\S\S)(\S\S)/);
647 engine_running = false;
648 if (engine_replacement_callback !== null) {
649 // We are no longer interested in this query,
650 // so just discard it and call this other callback.
651 engine_replacement_callback();
652 engine_replacement_callback = null;
658 stockfish.postMessage("position fen " + game.fen());
659 stockfish.postMessage("go depth 6 searchmoves " + uci_moves.join(" "));
661 if (engine_running) {
662 engine_replacement_callback = when_engine_is_ready;
664 when_engine_is_ready();
668 var onDrop = function(source, target) {
669 if (engine_running) {
670 // Snap end before the engine came back.
671 // Discard the result when it does.
672 engine_replacement_callback = function() {};
674 if (source == target) {
675 if (recommended_move === null) {
678 // Accept the move. It will be changed in onSnapEnd.
682 // Suggestion not asked for.
683 recommended_move = null;
686 // see if the move is legal
687 var pseudogame = new Chess(current_display_fen());
688 var move = pseudogame.move({
691 promotion: 'q' // NOTE: always promote to a queen for example simplicity
695 if (move === null) return 'snapback';
698 var onSnapEnd = function(source, target) {
699 if (source == target && recommended_move !== null) {
700 source = recommended_move[0];
701 target = recommended_move[1];
703 recommended_move = null;
704 var pseudogame = new Chess(current_display_fen());
705 var move = pseudogame.move({
708 promotion: 'q' // NOTE: always promote to a queen for example simplicity
711 make_move(pseudogame.history({ verbose: true }).pop().san);
714 var onpopstate = function() {
715 var old_moves = game.history({ verbose: true }).map(function(x) { return x.san; });
716 var new_moves = document.location.search.replace(/^\?/, "").split(",");
718 if (new_moves.length == 1 && new_moves[0] == "") {
722 var num_shared_moves;
723 for (num_shared_moves = 0; num_shared_moves < Math.min(old_moves.length, new_moves.length); ++num_shared_moves) {
724 if (old_moves[i] != new_moves[i]) {
729 set_move(num_shared_moves, false);
730 for (var i = num_shared_moves; i < new_moves.length; ++i) {
731 make_move(new_moves[i], false);
734 window.history.replaceState(null, null, get_history_url());
737 var init = function() {
739 board = new window.ChessBoard('board', {
742 onDragStart: onDragStart,
746 $("#board").on('mousedown', '.square-55d63', mousedownSquare);
747 $("#board").on('mouseup', '.square-55d63', mouseupSquare);
749 window.onpopstate = onpopstate;
753 $(window).keyup(function(event) {
754 if (event.which == 39) {
756 } else if (event.which == 37) {
758 } else if (event.which == 74) { // j
759 if (practice_mode) next_variant();
760 } else if (event.which == 75) { // k
761 if (practice_mode) prev_variant();
765 // Seemingly the web worker is not started before we send it a message.
766 stockfish.postMessage("uci");
769 $(document).ready(init);