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