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