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