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