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 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(move['num']); // N.
176 line.push(move['fraction']); // %.
177 line.push(computer); // CGames.
178 line.push(move['human_index']); // Hum.
179 line.push(move['win_ratio']); // Win%.
181 line.push(white); // WWin.
182 line.push(white / move['num']); // %WW.
183 line.push(black); // BWin.
184 line.push(black / move['num']); // %BW.
185 line.push(draw); // Draw.
186 line.push(draw / move['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(move['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) {
276 var white = move['white'];
277 var draw = move['draw'];
278 var black = move['black'];
279 var computer = move['computer'];
281 var num = white + draw + black;
283 move['fraction'] = num / total_num;
285 // Adjust so that the human index is 50% overall.
286 var exp = Math.log(0.5) / Math.log(data['computer_games'] / data['total_games']);
287 move['human_index'] = 1.0 - Math.pow(computer / num, exp);
290 var white_win_ratio = (white + 0.5 * draw) / num;
291 var win_ratio = is_white ? white_win_ratio : 1.0 - white_win_ratio;
292 move['win_ratio'] = win_ratio;
294 if (move['num_elo'] >= 10) {
295 // Win% corrected for Elo.
296 var win_elo = -400.0 * Math.log(1.0 / white_win_ratio - 1.0) / Math.LN10;
297 win_elo -= (move['white_avg_elo'] - move['black_avg_elo']);
298 white_win_ratio = 1.0 / (1.0 + Math.pow(10, win_elo / -400.0));
299 win_ratio = is_white ? white_win_ratio : 1.0 - white_win_ratio;
300 move['corrected_win_ratio'] = win_ratio;
304 var set_includetransp = function(value) {
305 includetransp = value;
308 window['set_includetransp'] = set_includetransp;
310 var set_flipboard = function(value) {
311 board.orientation(value ? 'black' : 'white');
313 window['set_flipboard'] = set_flipboard;
315 var make_move = function(move, do_update) {
316 var history = game.history({ verbose: true });
317 if (move_override < history.length && history[move_override].san == move) {
318 // User effectively only moved forward in history.
321 var moves = game.history();
322 // Truncate the history if needed.
323 if (move_override < moves.length) {
325 for (var i = 0; i < move_override; ++i) {
328 fens.length = move_override;
331 fens.push(game.fen());
335 if (do_update !== false) {
337 window.history.pushState(null, null, get_history_url());
340 window['make_move'] = make_move;
342 var prev_move = function() {
343 if (move_override > 0) {
346 window.history.replaceState(null, null, get_history_url());
349 window['prev_move'] = prev_move;
351 var next_move = function() {
352 if (move_override < game.history().length) {
355 window.history.replaceState(null, null, get_history_url());
358 window['next_move'] = next_move;
360 var set_move = function(n, do_update) {
362 if (do_update !== false) {
364 window.history.replaceState(null, null, get_history_url());
367 window['set_move'] = set_move;
369 // almost all of this stuff comes from the chessboard.js example page
370 var onDragStart = function(source, piece, position, orientation) {
371 var pseudogame = new Chess(current_display_fen());
372 if (pseudogame.game_over() === true ||
373 (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
374 (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
378 recommended_move = null;
379 get_best_dest(pseudogame, source, null, function(src, dest) {
380 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
382 var squareEl = $('#board .square-' + dest);
383 squareEl.addClass('highlight1-32417');
384 recommended_move = [src, dest];
389 var mousedownSquare = function(e) {
390 reverse_dragging_from = null;
391 var square = $(this).attr('data-square');
393 var pseudogame = new Chess(current_display_fen());
394 if (pseudogame.game_over() === true) {
398 // If the square is empty, or has a piece of the side not to move,
399 // we handle it. If not, normal piece dragging will take it.
400 var position = board.position();
401 if (!position.hasOwnProperty(square) ||
402 (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
403 (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
404 reverse_dragging_from = square;
405 get_best_dest(pseudogame, null, square, function(src, dest) {
407 var squareEl = $('#board .square-' + src);
408 squareEl.addClass('highlight1-32417');
409 squareEl = $('#board .square-' + dest);
410 squareEl.addClass('highlight1-32417');
411 recommended_move = [src, dest];
415 recommended_src = null;
419 var mouseupSquare = function(e) {
420 if (reverse_dragging_from === null) {
423 var source = $(this).attr('data-square');
424 var target = reverse_dragging_from;
425 reverse_dragging_from = null;
426 if (onDrop(source, target) !== 'snapback') {
427 onSnapEnd(source, target);
429 $("#board").find('.square-55d63').removeClass('highlight1-32417');
432 var get_best_dest = function(game, source, target, cb) {
433 var moves = game.moves({ verbose: true });
434 if (source !== null) {
435 moves = moves.filter(function(move) { return move.from == source; });
437 if (target !== null) {
438 moves = moves.filter(function(move) { return move.to == target; });
440 if (moves.length == 0) {
444 if (moves.length == 1) {
445 cb(moves[0].from, moves[0].to);
449 // More than one move. Ask the engine to disambiguate.
450 var uci_moves = moves.map(function(m) { return m.from + m.to; });
451 var when_engine_is_ready = function() {
452 engine_running = true;
453 stockfish.onmessage = function(event) {
454 var res = event.data.match(/^bestmove (\S\S)(\S\S)/);
456 engine_running = false;
457 if (engine_replacement_callback !== null) {
458 // We are no longer interested in this query,
459 // so just discard it and call this other callback.
460 engine_replacement_callback();
461 engine_replacement_callback = null;
467 stockfish.postMessage("position fen " + game.fen());
468 stockfish.postMessage("go depth 6 searchmoves " + uci_moves.join(" "));
470 if (engine_running) {
471 engine_replacement_callback = when_engine_is_ready;
473 when_engine_is_ready();
477 var onDrop = function(source, target) {
478 if (engine_running) {
479 // Snap end before the engine came back.
480 // Discard the result when it does.
481 engine_replacement_callback = function() {};
483 if (source == target) {
484 if (recommended_move === null) {
487 // Accept the move. It will be changed in onSnapEnd.
491 // Suggestion not asked for.
492 recommended_move = null;
495 // see if the move is legal
496 var pseudogame = new Chess(current_display_fen());
497 var move = pseudogame.move({
500 promotion: 'q' // NOTE: always promote to a queen for example simplicity
504 if (move === null) return 'snapback';
507 var onSnapEnd = function(source, target) {
508 if (source == target && recommended_move !== null) {
509 source = recommended_move[0];
510 target = recommended_move[1];
512 recommended_move = null;
513 var pseudogame = new Chess(current_display_fen());
514 var move = pseudogame.move({
517 promotion: 'q' // NOTE: always promote to a queen for example simplicity
520 make_move(pseudogame.history({ verbose: true }).pop().san);
523 var onpopstate = function() {
524 var old_moves = game.history({ verbose: true }).map(function(x) { return x.san; });
525 var new_moves = document.location.search.replace(/^\?/, "").split(",");
527 if (new_moves.length == 1 && new_moves[0] == "") {
531 var num_shared_moves;
532 for (num_shared_moves = 0; num_shared_moves < Math.min(old_moves.length, new_moves.length); ++num_shared_moves) {
533 if (old_moves[i] != new_moves[i]) {
538 set_move(num_shared_moves, false);
539 for (var i = num_shared_moves; i < new_moves.length; ++i) {
540 make_move(new_moves[i], false);
543 window.history.replaceState(null, null, get_history_url());
546 var init = function() {
548 board = new window.ChessBoard('board', {
551 onDragStart: onDragStart,
555 $("#board").on('mousedown', '.square-55d63', mousedownSquare);
556 $("#board").on('mouseup', '.square-55d63', mouseupSquare);
558 window.onpopstate = onpopstate;
561 $(window).keyup(function(event) {
562 if (event.which == 39) {
564 } else if (event.which == 37) {
569 // Seemingly the web worker is not started before we send it a message.
570 stockfish.postMessage("uci");
573 $(document).ready(init);