]> git.sesse.net Git - remoteglot-book/blob - www/js/book.js
Show immediate end results as moves.
[remoteglot-book] / www / js / book.js
1 (function() {
2
3 var board = null;
4 var game = new Chess();
5 var fens = [];
6 var move_override = 0;
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
14 var entity_map = {
15         "&": "&",
16         "<": "&lt;",
17         ">": "&gt;",
18         '"': '&quot;',
19         "'": '&#39;',
20 };
21
22 function escape_html(string) {
23         return String(string).replace(/[&<>"']/g, function (s) {
24                 return entity_map[s];
25         });
26 }
27
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';
31         } else {
32                 return fens[move_override - 1];
33         }
34 }
35
36 var update = function() {
37         var text = "";
38         var history = game.history({ verbose: true });
39         for (var i = 0; i < history.length; ++i) {
40                 if (i % 2 == 0) {
41                         text += (i/2 + 1) + ". ";
42                 }
43                 if (i + 1 == move_override) {
44                         text += '<strong>' + history[i].san + '</strong>';
45                 } else {
46                         text += '<a href="javascript:set_move(' + (i + 1) + ')">' + history[i].san + '</a>';
47                 }
48                 text += " ";
49         }
50         $('#gamehistory').html(text);
51
52         if (board.fen() != current_display_fen()) {
53                 board.position(current_display_fen());
54         }
55
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');
63         }
64
65         fetch_analysis();
66 }
67
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(',');
72 }
73
74 var fetch_analysis = function() {
75         var fen = current_display_fen();
76         $.ajax({
77                 url: "/opening-stats.pl?fen=" + encodeURIComponent(fen) +
78                         ";includetransp=" + (includetransp ? 1 : 0)
79         }).done(function(data, textstatus, xhr) {
80                 show_lines(data, game);
81         });
82 }
83
84 var add_td = function(tr, value) {
85         var td = document.createElement("td");
86         tr.appendChild(td);
87         $(td).addClass("num");
88         $(td).text(value);
89 }
90
91 var TYPE_MOVE = 0;
92 var TYPE_INTEGER = 1;
93 var TYPE_FLOAT = 2;
94 var TYPE_RATIO = 3;
95
96 var headings = [
97         [ "Move", TYPE_MOVE ],
98         [ "Games", TYPE_INTEGER ],
99         [ "%", TYPE_RATIO ],
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 ],
113 ];
114 var sort_by = 1;
115 var direction = 1;
116
117 var show_lines = function(data, game) {
118         var moves = data['moves'];
119         $('#numviewers').text(data['opening']);
120
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']) + ")";
125                 }
126                 text += " &ndash; " + escape_html(data['root_game']['black']);
127                 if (data['root_game']['black_elo']) {
128                         text += " (" + escape_html(data['root_game']['black_elo']) + ")";
129                 }
130                 text += " &nbsp;" + escape_html(data['root_game']['result']).replace(/-/, "&ndash;") + "<br />";
131                 if (data['root_game']['eco']) {
132                         text += "[" + escape_html(data['root_game']['eco']) + "] ";
133                 }
134                 text += "(" + data['root_game']['moves'] + ") ";
135                 text += escape_html(data['root_game']['event']) + " &nbsp;" + escape_html(data['root_game']['date']);
136                 $('#gamesummary').html(text);
137         }
138
139         var total_num = 0;
140         for (var i = 0; i < moves.length; ++i) {
141                 var move = moves[i];
142                 if (move['move']) {
143                         total_num += parseInt(move['white']);
144                         total_num += parseInt(move['draw']);
145                         total_num += parseInt(move['black']);
146                 }
147         }
148
149         var headings_tr = $("#headings");
150         headings_tr.empty();
151         for (var i = 0; i < headings.length; ++i) {
152                 var th = document.createElement("th");
153                 headings_tr.append(th);
154                 $(th).text(headings[i][0]);
155                 (function(new_sort_by) {
156                         $(th).click(function() {
157                                 if (sort_by == new_sort_by) {
158                                         direction = -direction;
159                                 } else {
160                                         sort_by = new_sort_by;
161                                         direction = 1;
162                                 }
163                                 show_lines(data, game);
164                         });
165                 })(i);
166         }
167
168         var lines = [];
169         var transpose_only = [];
170         for (var i = 0; i < moves.length; ++i) {
171                 var move = moves[i];
172                 var line = [];
173
174                 var white = parseInt(move['white']);
175                 var draw = parseInt(move['draw']);
176                 var black = parseInt(move['black']);
177                 var computer = parseInt(move['computer']);
178
179                 line.push(move['move']);  // Move.
180                 transpose_only.push(move['transpose_only']);
181                 var num = white + draw + black;
182                 line.push(num);  // N.
183                 line.push(num / total_num);  // %.
184                 line.push(computer);  // CGames.
185
186                 // Adjust so that the human index is 50% overall.
187                 var exp = Math.log(0.5) / Math.log(data['computer_games'] / data['total_games']);
188                 line.push(1.0 - Math.pow(computer / num, exp));  // Hum.
189
190                 // Win%.
191                 var white_win_ratio = (white + 0.5 * draw) / num;
192                 var win_ratio = (move_override % 2 == 0) ? white_win_ratio : 1.0 - white_win_ratio;
193                 line.push(win_ratio);
194
195                 line.push(white);        // WWin.
196                 line.push(white / num);  // %WW.
197                 line.push(black);        // BWin.
198                 line.push(black / num);  // %BW.
199                 line.push(draw);         // Draw.
200                 line.push(draw / num);   // %Draw.
201
202                 if (move['num_elo'] >= 10) {
203                         // Elo.
204                         line.push(move['white_avg_elo']);
205                         line.push(move['black_avg_elo']);
206                         line.push(move['white_avg_elo'] - move['black_avg_elo']);
207
208                         // Win% corrected for Elo.
209                         var win_elo = -400.0 * Math.log(1.0 / white_win_ratio - 1.0) / Math.LN10;
210                         win_elo -= (move['white_avg_elo'] - move['black_avg_elo']);
211                         white_win_ratio = 1.0 / (1.0 + Math.pow(10, win_elo / -400.0));
212                         win_ratio = (move_override % 2 == 0) ? white_win_ratio : 1.0 - white_win_ratio;
213                         line.push(win_ratio);
214                 } else {
215                         line.push(null);
216                         line.push(null);
217                         line.push(null);
218                         line.push(null);
219                 }
220                 lines.push(line);
221         }
222
223         lines.sort(function(a, b) { return direction * ( b[sort_by] - a[sort_by]); });
224
225         var tbl = $("#lines");
226         tbl.empty();
227
228         for (var i = 0; i < moves.length; ++i) {
229                 var line = lines[i];
230                 var tr = document.createElement("tr");
231
232                 if (line[0] === undefined) {
233                         $(tr).addClass("totals");
234                 } else if (transpose_only[i]) {
235                         $(tr).addClass("transponly");
236                 }
237
238                 for (var j = 0; j < line.length; ++j) {
239                         if (line[j] === null) {
240                                 add_td(tr, "");
241                         } else if (headings[j][1] == TYPE_MOVE) {
242                                 var td = document.createElement("td");
243                                 tr.appendChild(td);
244                                 $(td).addClass("move");
245                                 if (line[j] !== undefined) {
246                                         if (move_override % 2 == 0) {
247                                                 $(td).text(((move_override / 2) + 1) + ". ");
248                                         } else {
249                                                 $(td).text(((move_override / 2) + 0.5) + "…");
250                                         }
251                                 }
252
253                                 if (line[j] === '1-0' || line[j] === '1/2-1/2' || line[j] === '0-1') {
254                                         $(td).text($(td).text() + line[j]);
255                                 } else {
256                                         var move_a = document.createElement("a");
257                                         move_a.href = "javascript:make_move('" + line[j] + "')";
258                                         td.appendChild(move_a);
259                                         $(move_a).text(line[j]);
260                                 }
261                         } else if (headings[j][1] == TYPE_INTEGER) {
262                                 add_td(tr, line[j] || 0);
263                         } else if (headings[j][1] == TYPE_FLOAT) {
264                                 if (isNaN(line[j]) || !isFinite(line[j])) {
265                                         add_td(tr, '');
266                                 } else {
267                                         add_td(tr, line[j].toFixed(1));
268                                 }
269                         } else {
270                                 if (isNaN(line[j]) || !isFinite(line[j])) {
271                                         add_td(tr, '');
272                                 } else {
273                                         add_td(tr, (100.0 * line[j]).toFixed(1) + "%");
274                                 }
275                         }
276                 }
277
278                 tbl.append(tr);
279         }
280 }
281
282 var set_includetransp = function(value) {
283         includetransp = value;
284         update();
285 }
286 window['set_includetransp'] = set_includetransp;
287
288 var set_flipboard = function(value) {
289         board.orientation(value ? 'black' : 'white');
290 }
291 window['set_flipboard'] = set_flipboard;
292
293 var make_move = function(move, do_update) {
294         var history = game.history({ verbose: true });
295         if (move_override < history.length && history[move_override].san == move) {
296                 // User effectively only moved forward in history.
297                 ++move_override;
298         } else {
299                 var moves = game.history();
300                 // Truncate the history if needed.
301                 if (move_override < moves.length) {
302                         game = new Chess();
303                         for (var i = 0; i < move_override; ++i) {
304                                 game.move(moves[i]);
305                         }
306                         fens.length = move_override;
307                 }
308                 game.move(move);
309                 fens.push(game.fen());
310                 ++move_override;
311         }
312
313         if (do_update !== false) {
314                 update();
315                 window.history.pushState(null, null, get_history_url());
316         }
317 }
318 window['make_move'] = make_move;
319
320 var prev_move = function() {
321         if (move_override > 0) {
322                 --move_override;
323                 update();
324                 window.history.replaceState(null, null, get_history_url());
325         }
326 }
327 window['prev_move'] = prev_move;
328
329 var next_move = function() {
330         if (move_override < game.history().length) {
331                 ++move_override;
332                 update();
333                 window.history.replaceState(null, null, get_history_url());
334         }
335 }
336 window['next_move'] = next_move;
337
338 var set_move = function(n, do_update) {
339         move_override = n;
340         if (do_update !== false) {
341                 update();
342                 window.history.replaceState(null, null, get_history_url());
343         }
344 }
345 window['set_move'] = set_move;
346
347 // almost all of this stuff comes from the chessboard.js example page
348 var onDragStart = function(source, piece, position, orientation) {
349         var pseudogame = new Chess(current_display_fen());
350         if (pseudogame.game_over() === true ||
351             (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
352             (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
353                 return false;
354         }
355
356         recommended_move = null;
357         get_best_dest(pseudogame, source, null, function(src, dest) {
358                 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
359                 if (dest !== null) {
360                         var squareEl = $('#board .square-' + dest);
361                         squareEl.addClass('highlight1-32417');
362                         recommended_move = [src, dest];
363                 }
364         });
365 }
366
367 var mousedownSquare = function(e) {
368         reverse_dragging_from = null;
369         var square = $(this).attr('data-square');
370
371         var pseudogame = new Chess(current_display_fen());
372         if (pseudogame.game_over() === true) {
373                 return;
374         }
375
376         // If the square is empty, or has a piece of the side not to move,
377         // we handle it. If not, normal piece dragging will take it.
378         var position = board.position();
379         if (!position.hasOwnProperty(square) ||
380             (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
381             (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
382                 reverse_dragging_from = square;
383                 get_best_dest(pseudogame, null, square, function(src, dest) {
384                         if (src !== null) {
385                                 var squareEl = $('#board .square-' + src);
386                                 squareEl.addClass('highlight1-32417');
387                                 squareEl = $('#board .square-' + dest);
388                                 squareEl.addClass('highlight1-32417');
389                                 recommended_move = [src, dest];
390                         }
391                 });
392         } else {
393                 recommended_src = null;
394         }
395 }
396
397 var mouseupSquare = function(e) {
398         if (reverse_dragging_from === null) {
399                 return;
400         }
401         var source = $(this).attr('data-square');
402         var target = reverse_dragging_from;
403         reverse_dragging_from = null;
404         if (onDrop(source, target) !== 'snapback') {
405                 onSnapEnd(source, target);
406         }
407         $("#board").find('.square-55d63').removeClass('highlight1-32417');
408 }
409
410 var get_best_dest = function(game, source, target, cb) {
411         var moves = game.moves({ verbose: true });
412         if (source !== null) {
413                 moves = moves.filter(function(move) { return move.from == source; });
414         }
415         if (target !== null) {
416                 moves = moves.filter(function(move) { return move.to == target; });
417         }
418         if (moves.length == 0) {
419                 cb(null, null);
420                 return;
421         }
422         if (moves.length == 1) {
423                 cb(moves[0].from, moves[0].to);
424                 return;
425         }
426
427         // More than one move. Ask the engine to disambiguate.
428         var uci_moves = moves.map(function(m) { return m.from + m.to; });
429         var when_engine_is_ready = function() {
430                 engine_running = true;
431                 stockfish.onmessage = function(event) {
432                         var res = event.data.match(/^bestmove (\S\S)(\S\S)/);
433                         if (res !== null) {
434                                 engine_running = false;
435                                 if (engine_replacement_callback !== null) {
436                                         // We are no longer interested in this query,
437                                         // so just discard it and call this other callback.
438                                         engine_replacement_callback();
439                                         engine_replacement_callback = null;
440                                 } else {
441                                         cb(res[1], res[2]);
442                                 }
443                         }
444                 };
445                 stockfish.postMessage("position fen " + game.fen());
446                 stockfish.postMessage("go depth 6 searchmoves " + uci_moves.join(" "));
447         };
448         if (engine_running) {
449                 engine_replacement_callback = when_engine_is_ready;
450         } else {
451                 when_engine_is_ready();
452         }
453 }
454
455 var onDrop = function(source, target) {
456         if (engine_running) {
457                 // Snap end before the engine came back.
458                 // Discard the result when it does.
459                 engine_replacement_callback = function() {};
460         }
461         if (source == target) {
462                 if (recommended_move === null) {
463                         return 'snapback';
464                 } else {
465                         // Accept the move. It will be changed in onSnapEnd.
466                         return;
467                 }
468         } else {
469                 // Suggestion not asked for.
470                 recommended_move = null;
471         }
472
473         // see if the move is legal
474         var pseudogame = new Chess(current_display_fen());
475         var move = pseudogame.move({
476                 from: source,
477                 to: target,
478                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
479         });
480
481         // illegal move
482         if (move === null) return 'snapback';
483 }
484
485 var onSnapEnd = function(source, target) {
486         if (source == target && recommended_move !== null) {
487                 source = recommended_move[0];
488                 target = recommended_move[1];
489         }
490         recommended_move = null;
491         var pseudogame = new Chess(current_display_fen());
492         var move = pseudogame.move({
493                 from: source,
494                 to: target,
495                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
496         });
497
498         make_move(pseudogame.history({ verbose: true }).pop().san);
499 }
500
501 var onpopstate = function() {
502         var old_moves = game.history({ verbose: true }).map(function(x) { return x.san; });
503         var new_moves = document.location.search.replace(/^\?/, "").split(",");
504
505         if (new_moves.length == 1 && new_moves[0] == "") {
506                 new_moves = [];
507         }
508
509         var num_shared_moves;
510         for (num_shared_moves = 0; num_shared_moves < Math.min(old_moves.length, new_moves.length); ++num_shared_moves) {
511                 if (old_moves[i] != new_moves[i]) {
512                         break;
513                 }
514         }
515
516         set_move(num_shared_moves, false);
517         for (var i = num_shared_moves; i < new_moves.length; ++i) {
518                 make_move(new_moves[i], false);
519         }
520         update();
521         window.history.replaceState(null, null, get_history_url());
522 }
523
524 var init = function() {
525         // Create board.
526         board = new window.ChessBoard('board', {
527                 draggable: true,
528                 position: 'start',
529                 onDragStart: onDragStart,
530                 onDrop: onDrop,
531                 onSnapEnd: onSnapEnd
532         });
533         $("#board").on('mousedown', '.square-55d63', mousedownSquare);
534         $("#board").on('mouseup', '.square-55d63', mouseupSquare);
535
536         window.onpopstate = onpopstate;
537         onpopstate();
538
539         $(window).keyup(function(event) {
540                 if (event.which == 39) {
541                         next_move();
542                 } else if (event.which == 37) {
543                         prev_move();
544                 }
545         });
546
547         // Seemingly the web worker is not started before we send it a message.
548         stockfish.postMessage("uci");
549 }
550
551 $(document).ready(init);
552
553 })();