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