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