]> git.sesse.net Git - remoteglot-book/blob - www/js/book.js
a100fc85afc1e48fd9953a16b4936bc23e23a9d7
[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 fetch_analysis = function() {
64         var fen = current_display_fen();
65         $.ajax({
66                 url: "/opening-stats.pl?fen=" + encodeURIComponent(fen) +
67                         ";includetransp=" + (includetransp ? 1 : 0)
68         }).done(function(data, textstatus, xhr) {
69                 show_lines(data, game);
70         });
71 }
72
73 var add_td = function(tr, value) {
74         var td = document.createElement("td");
75         tr.appendChild(td);
76         $(td).addClass("num");
77         $(td).text(value);
78 }
79
80 var TYPE_MOVE = 0;
81 var TYPE_INTEGER = 1;
82 var TYPE_FLOAT = 2;
83 var TYPE_RATIO = 3;
84
85 var headings = [
86         [ "Move", TYPE_MOVE ],
87         [ "Games", TYPE_INTEGER ],
88         [ "%", TYPE_RATIO ],
89         [ "Win%", TYPE_RATIO ],
90         [ "WWin", TYPE_INTEGER ],
91         [ "%WW", TYPE_RATIO ],
92         [ "Bwin", TYPE_INTEGER ],
93         [ "%BW", TYPE_RATIO ],
94         [ "Draw", TYPE_INTEGER ],
95         [ "Draw%", TYPE_RATIO ],
96         [ "AvWElo", TYPE_FLOAT ],
97         [ "AvBElo", TYPE_FLOAT ],
98         [ "EloVar", TYPE_FLOAT ],
99         [ "AWin%", TYPE_RATIO ],
100 ];
101 var sort_by = 1;
102 var direction = 1;
103
104 var show_lines = function(data, game) {
105         var moves = data['moves'];
106         $('#numviewers').text(data['opening']);
107
108         if (data['root_game']) {
109                 var text = escape_html(data['root_game']['white']);
110                 if (data['root_game']['white_elo']) {
111                         text += " (" + escape_html(data['root_game']['white_elo']) + ")";
112                 }
113                 text += " &ndash; " + escape_html(data['root_game']['black']);
114                 if (data['root_game']['black_elo']) {
115                         text += " (" + escape_html(data['root_game']['black_elo']) + ")";
116                 }
117                 text += " &nbsp;" + escape_html(data['root_game']['result']).replace(/-/, "&ndash;") + "<br />";
118                 if (data['root_game']['eco']) {
119                         text += "[" + escape_html(data['root_game']['eco']) + "] ";
120                 }
121                 text += "(" + data['root_game']['moves'] + ") ";
122                 text += escape_html(data['root_game']['event']) + " &nbsp;" + escape_html(data['root_game']['date']);
123                 $('#gamesummary').html(text);
124         }
125
126         var total_num = 0;
127         for (var i = 0; i < moves.length; ++i) {
128                 var move = moves[i];
129                 if (move['move']) {
130                         total_num += parseInt(move['white']);
131                         total_num += parseInt(move['draw']);
132                         total_num += parseInt(move['black']);
133                 }
134         }
135
136         var headings_tr = $("#headings");
137         headings_tr.empty();
138         for (var i = 0; i < headings.length; ++i) {
139                 var th = document.createElement("th");
140                 headings_tr.append(th);
141                 $(th).text(headings[i][0]);
142                 (function(new_sort_by) {
143                         $(th).click(function() {
144                                 if (sort_by == new_sort_by) {
145                                         direction = -direction;
146                                 } else {
147                                         sort_by = new_sort_by;
148                                         direction = 1;
149                                 }
150                                 show_lines(data, game);
151                         });
152                 })(i);
153         }
154
155         var lines = [];
156         var transpose_only = [];
157         for (var i = 0; i < moves.length; ++i) {
158                 var move = moves[i];
159                 var line = [];
160
161                 var white = parseInt(move['white']);
162                 var draw = parseInt(move['draw']);
163                 var black = parseInt(move['black']);
164
165                 line.push(move['move']);  // Move.
166                 transpose_only.push(move['transpose_only']);
167                 var num = white + draw + black;
168                 line.push(num);  // N.
169                 line.push(num / total_num);  // %.
170
171                 // Win%.
172                 var white_win_ratio = (white + 0.5 * draw) / num;
173                 var win_ratio = (move_override % 2 == 0) ? white_win_ratio : 1.0 - white_win_ratio;
174                 line.push(win_ratio);
175
176                 line.push(white);        // WWin.
177                 line.push(white / num);  // %WW.
178                 line.push(black);        // BWin.
179                 line.push(black / num);  // %BW.
180                 line.push(draw);         // Draw.
181                 line.push(draw / num);   // %Draw.
182
183                 if (move['num_elo'] >= 10) {
184                         // Elo.
185                         line.push(move['white_avg_elo']);
186                         line.push(move['black_avg_elo']);
187                         line.push(move['white_avg_elo'] - move['black_avg_elo']);
188
189                         // Win% corrected for Elo.
190                         var win_elo = -400.0 * Math.log(1.0 / white_win_ratio - 1.0) / Math.LN10;
191                         win_elo -= (move['white_avg_elo'] - move['black_avg_elo']);
192                         white_win_ratio = 1.0 / (1.0 + Math.pow(10, win_elo / -400.0));
193                         win_ratio = (move_override % 2 == 0) ? white_win_ratio : 1.0 - white_win_ratio;
194                         line.push(win_ratio);
195                 } else {
196                         line.push(null);
197                         line.push(null);
198                         line.push(null);
199                         line.push(null);
200                 }
201                 lines.push(line);
202         }
203
204         lines.sort(function(a, b) { return direction * ( b[sort_by] - a[sort_by]); });
205
206         var tbl = $("#lines");
207         tbl.empty();
208
209         for (var i = 0; i < moves.length; ++i) {
210                 var line = lines[i];
211                 var tr = document.createElement("tr");
212
213                 if (line[0] === undefined) {
214                         $(tr).addClass("totals");
215                 } else if (transpose_only[i]) {
216                         $(tr).addClass("transponly");
217                 }
218
219                 for (var j = 0; j < line.length; ++j) {
220                         if (line[j] === null) {
221                                 add_td(tr, "");
222                         } else if (headings[j][1] == TYPE_MOVE) {
223                                 var td = document.createElement("td");
224                                 tr.appendChild(td);
225                                 $(td).addClass("move");
226                                 if (line[j] !== undefined) {
227                                         if (move_override % 2 == 0) {
228                                                 $(td).text(((move_override / 2) + 1) + ". ");
229                                         } else {
230                                                 $(td).text(((move_override / 2) + 0.5) + "…");
231                                         }
232                                 }
233
234                                 var move_a = document.createElement("a");
235                                 move_a.href = "javascript:make_move('" + line[j] + "')";
236                                 td.appendChild(move_a);
237                                 $(move_a).text(line[j]);
238                         } else if (headings[j][1] == TYPE_INTEGER) {
239                                 add_td(tr, line[j]);
240                         } else if (headings[j][1] == TYPE_FLOAT) {
241                                 add_td(tr, line[j].toFixed(1));
242                         } else {
243                                 add_td(tr, (100.0 * line[j]).toFixed(1) + "%");
244                         }
245                 }
246
247                 tbl.append(tr);
248         }
249 }
250
251 var set_includetransp = function(value) {
252         includetransp = value;
253         update();
254 }
255 window['set_includetransp'] = set_includetransp;
256
257 var make_move = function(move) {
258         var history = game.history({ verbose: true });
259         if (move_override < history.length && history[move_override].san == move) {
260                 // User effectively only moved forward in history.
261                 ++move_override;
262         } else {
263                 var moves = game.history();
264                 // Truncate the history if needed.
265                 if (move_override < moves.length) {
266                         game = new Chess();
267                         for (var i = 0; i < move_override; ++i) {
268                                 game.move(moves[i]);
269                         }
270                         fens.length = move_override;
271                 }
272                 game.move(move);
273                 fens.push(game.fen());
274                 ++move_override;
275         }
276         update();
277 }
278 window['make_move'] = make_move;
279
280 var prev_move = function() {
281         if (move_override > 0) {
282                 --move_override;
283                 update();
284         }
285 }
286 window['prev_move'] = prev_move;
287
288 var next_move = function() {
289         if (move_override < game.history().length) {
290                 ++move_override;
291                 update();
292         }
293 }
294 window['next_move'] = next_move;
295
296 var set_move = function(n) {
297         move_override = n;
298         update();
299 }
300 window['set_move'] = set_move;
301
302 // almost all of this stuff comes from the chessboard.js example page
303 var onDragStart = function(source, piece, position, orientation) {
304         var pseudogame = new Chess(current_display_fen());
305         if (pseudogame.game_over() === true ||
306             (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
307             (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
308                 return false;
309         }
310 }
311
312 var onDrop = function(source, target) {
313         // see if the move is legal
314         var pseudogame = new Chess(current_display_fen());
315         var move = pseudogame.move({
316                 from: source,
317                 to: target,
318                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
319         });
320
321         // illegal move
322         if (move === null) return 'snapback';
323 }
324
325 var onSnapEnd = function(source, target) {
326         var pseudogame = new Chess(current_display_fen());
327         var move = pseudogame.move({
328                 from: source,
329                 to: target,
330                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
331         });
332
333         make_move(pseudogame.history({ verbose: true }).pop().san);
334 }
335
336 var init = function() {
337         // Create board.
338         board = new window.ChessBoard('board', {
339                 draggable: true,
340                 position: 'start',
341                 onDragStart: onDragStart,
342                 onDrop: onDrop,
343                 onSnapEnd: onSnapEnd
344         });
345         update();
346
347         $(window).keyup(function(event) {
348                 if (event.which == 39) {
349                         next_move();
350                 } else if (event.which == 37) {
351                         prev_move();
352                 }
353         });
354 }
355
356
357 $(document).ready(init);
358
359 })();