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