]> git.sesse.net Git - remoteglot-book/blob - www/js/book.js
Support reverse-dragging, also with engine suggestions.
[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                                 var move_a = document.createElement("a");
254                                 move_a.href = "javascript:make_move('" + line[j] + "')";
255                                 td.appendChild(move_a);
256                                 $(move_a).text(line[j]);
257                         } else if (headings[j][1] == TYPE_INTEGER) {
258                                 add_td(tr, line[j] || 0);
259                         } else if (headings[j][1] == TYPE_FLOAT) {
260                                 if (isNaN(line[j]) || !isFinite(line[j])) {
261                                         add_td(tr, '');
262                                 } else {
263                                         add_td(tr, line[j].toFixed(1));
264                                 }
265                         } else {
266                                 if (isNaN(line[j]) || !isFinite(line[j])) {
267                                         add_td(tr, '');
268                                 } else {
269                                         add_td(tr, (100.0 * line[j]).toFixed(1) + "%");
270                                 }
271                         }
272                 }
273
274                 tbl.append(tr);
275         }
276 }
277
278 var set_includetransp = function(value) {
279         includetransp = value;
280         update();
281 }
282 window['set_includetransp'] = set_includetransp;
283
284 var make_move = function(move, do_update) {
285         var history = game.history({ verbose: true });
286         if (move_override < history.length && history[move_override].san == move) {
287                 // User effectively only moved forward in history.
288                 ++move_override;
289         } else {
290                 var moves = game.history();
291                 // Truncate the history if needed.
292                 if (move_override < moves.length) {
293                         game = new Chess();
294                         for (var i = 0; i < move_override; ++i) {
295                                 game.move(moves[i]);
296                         }
297                         fens.length = move_override;
298                 }
299                 game.move(move);
300                 fens.push(game.fen());
301                 ++move_override;
302         }
303
304         if (do_update !== false) {
305                 update();
306                 window.history.pushState(null, null, get_history_url());
307         }
308 }
309 window['make_move'] = make_move;
310
311 var prev_move = function() {
312         if (move_override > 0) {
313                 --move_override;
314                 update();
315                 window.history.replaceState(null, null, get_history_url());
316         }
317 }
318 window['prev_move'] = prev_move;
319
320 var next_move = function() {
321         if (move_override < game.history().length) {
322                 ++move_override;
323                 update();
324                 window.history.replaceState(null, null, get_history_url());
325         }
326 }
327 window['next_move'] = next_move;
328
329 var set_move = function(n, do_update) {
330         move_override = n;
331         if (do_update !== false) {
332                 update();
333                 window.history.replaceState(null, null, get_history_url());
334         }
335 }
336 window['set_move'] = set_move;
337
338 // almost all of this stuff comes from the chessboard.js example page
339 var onDragStart = function(source, piece, position, orientation) {
340         var pseudogame = new Chess(current_display_fen());
341         if (pseudogame.game_over() === true ||
342             (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
343             (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
344                 return false;
345         }
346
347         recommended_move = null;
348         get_best_dest(pseudogame, source, null, function(src, dest) {
349                 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
350                 if (dest !== null) {
351                         var squareEl = $('#board .square-' + dest);
352                         squareEl.addClass('highlight1-32417');
353                         recommended_move = [src, dest];
354                 }
355         });
356 }
357
358 var mousedownSquare = function(e) {
359         reverse_dragging_from = null;
360         var square = $(this).attr('data-square');
361
362         var pseudogame = new Chess(current_display_fen());
363         if (pseudogame.game_over() === true) {
364                 return;
365         }
366
367         // If the square is empty, or has a piece of the side not to move,
368         // we handle it. If not, normal piece dragging will take it.
369         var position = board.position();
370         if (!position.hasOwnProperty(square) ||
371             (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
372             (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
373                 reverse_dragging_from = square;
374                 get_best_dest(pseudogame, null, square, function(src, dest) {
375                         if (src !== null) {
376                                 var squareEl = $('#board .square-' + src);
377                                 squareEl.addClass('highlight1-32417');
378                                 squareEl = $('#board .square-' + dest);
379                                 squareEl.addClass('highlight1-32417');
380                                 recommended_move = [src, dest];
381                         }
382                 });
383         } else {
384                 recommended_src = null;
385         }
386 }
387
388 var mouseupSquare = function(e) {
389         if (reverse_dragging_from === null) {
390                 return;
391         }
392         var source = $(this).attr('data-square');
393         var target = reverse_dragging_from;
394         reverse_dragging_from = null;
395         if (onDrop(source, target) !== 'snapback') {
396                 onSnapEnd(source, target);
397         }
398         $("#board").find('.square-55d63').removeClass('highlight1-32417');
399 }
400
401 var get_best_dest = function(game, source, target, cb) {
402         var moves = game.moves({ verbose: true });
403         if (source !== null) {
404                 moves = moves.filter(function(move) { return move.from == source; });
405         }
406         if (target !== null) {
407                 moves = moves.filter(function(move) { return move.to == target; });
408         }
409         if (moves.length == 0) {
410                 cb(null, null);
411                 return;
412         }
413         if (moves.length == 1) {
414                 cb(moves[0].from, moves[0].to);
415                 return;
416         }
417
418         // More than one move. Ask the engine to disambiguate.
419         var uci_moves = moves.map(function(m) { return m.from + m.to; });
420         var when_engine_is_ready = function() {
421                 engine_running = true;
422                 stockfish.onmessage = function(event) {
423                         var res = event.data.match(/^bestmove (\S\S)(\S\S)/);
424                         if (res !== null) {
425                                 engine_running = false;
426                                 if (engine_replacement_callback !== null) {
427                                         // We are no longer interested in this query,
428                                         // so just discard it and call this other callback.
429                                         engine_replacement_callback();
430                                         engine_replacement_callback = null;
431                                 } else {
432                                         cb(res[1], res[2]);
433                                 }
434                         }
435                 };
436                 stockfish.postMessage("position fen " + game.fen());
437                 stockfish.postMessage("go depth 6 searchmoves " + uci_moves.join(" "));
438         };
439         if (engine_running) {
440                 engine_replacement_callback = when_engine_is_ready;
441         } else {
442                 when_engine_is_ready();
443         }
444 }
445
446 var onDrop = function(source, target) {
447         if (engine_running) {
448                 // Snap end before the engine came back.
449                 // Discard the result when it does.
450                 engine_replacement_callback = function() {};
451         }
452         if (source == target) {
453                 if (recommended_move === null) {
454                         return 'snapback';
455                 } else {
456                         // Accept the move. It will be changed in onSnapEnd.
457                         return;
458                 }
459         } else {
460                 // Suggestion not asked for.
461                 recommended_move = null;
462         }
463
464         // see if the move is legal
465         var pseudogame = new Chess(current_display_fen());
466         var move = pseudogame.move({
467                 from: source,
468                 to: target,
469                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
470         });
471
472         // illegal move
473         if (move === null) return 'snapback';
474 }
475
476 var onSnapEnd = function(source, target) {
477         if (source == target && recommended_move !== null) {
478                 source = recommended_move[0];
479                 target = recommended_move[1];
480         }
481         recommended_move = null;
482         var pseudogame = new Chess(current_display_fen());
483         var move = pseudogame.move({
484                 from: source,
485                 to: target,
486                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
487         });
488
489         make_move(pseudogame.history({ verbose: true }).pop().san);
490 }
491
492 var onpopstate = function() {
493         var old_moves = game.history({ verbose: true }).map(function(x) { return x.san; });
494         var new_moves = document.location.search.replace(/^\?/, "").split(",");
495
496         if (new_moves.length == 1 && new_moves[0] == "") {
497                 new_moves = [];
498         }
499
500         var num_shared_moves;
501         for (num_shared_moves = 0; num_shared_moves < Math.min(old_moves.length, new_moves.length); ++num_shared_moves) {
502                 if (old_moves[i] != new_moves[i]) {
503                         break;
504                 }
505         }
506
507         set_move(num_shared_moves, false);
508         for (var i = num_shared_moves; i < new_moves.length; ++i) {
509                 make_move(new_moves[i], false);
510         }
511         update();
512         window.history.replaceState(null, null, get_history_url());
513 }
514
515 var init = function() {
516         // Create board.
517         board = new window.ChessBoard('board', {
518                 draggable: true,
519                 position: 'start',
520                 onDragStart: onDragStart,
521                 onDrop: onDrop,
522                 onSnapEnd: onSnapEnd
523         });
524         $("#board").on('mousedown', '.square-55d63', mousedownSquare);
525         $("#board").on('mouseup', '.square-55d63', mouseupSquare);
526
527         window.onpopstate = onpopstate;
528         onpopstate();
529
530         $(window).keyup(function(event) {
531                 if (event.which == 39) {
532                         next_move();
533                 } else if (event.which == 37) {
534                         prev_move();
535                 }
536         });
537 }
538
539
540 $(document).ready(init);
541
542 })();