]> git.sesse.net Git - remoteglot-book/blob - www/js/book.js
854d6ad6e86fb7f233b88604cefbef9bb31f2317
[remoteglot-book] / www / js / book.js
1 (function() {
2
3 var board = null;
4 var history = [];
5 var move_override = 0;
6 var includetransp = true;
7
8 var entity_map = {
9         "&": "&",
10         "<": "&lt;",
11         ">": "&gt;",
12         '"': '&quot;',
13         "'": '&#39;',
14 };
15
16 function escape_html(string) {
17         return String(string).replace(/[&<>"']/g, function (s) {
18                 return entity_map[s];
19         });
20 }
21
22 var get_game = function(skip_last_move) {
23         var moves_to_drop = 0;
24         if (skip_last_move === true) {
25                 moves_to_drop = 1;
26         }
27
28         var game = new Chess();
29         for (var i = 0; i < move_override - moves_to_drop; ++i) {
30                 game.move(history[i]);
31         }
32         return game;
33 }
34
35 var update = function() {
36         var text = "";
37         for (var i = 0; i < history.length; ++i) {
38                 if (i % 2 == 0) {
39                         text += (i/2 + 1) + ". ";
40                 }
41                 if (i + 1 == move_override) {
42                         text += '<strong>' + history[i] + '</strong>';
43                 } else {
44                         text += '<a href="javascript:set_move(' + (i + 1) + ')">' + history[i] + '</a>';
45                 }
46                 text += " ";
47         }
48         $('#gamehistory').html(text);
49
50         var game = get_game();
51         board.position(game.fen());
52
53         var all_moves = game.history({ verbose: true });
54         if (all_moves.length > 0) {
55                 var last_move = all_moves.pop();
56                 var highlight_from = last_move.from;
57                 var highlight_to = last_move.to;
58                 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
59                 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
60                 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
61         }
62
63         fetch_analysis();
64 }
65
66 var fetch_analysis = function() {
67         var game = get_game();
68         var fen = game.fen();
69         $.ajax({
70                 url: "/opening-stats.pl?fen=" + encodeURIComponent(fen) +
71                         ";includetransp=" + (includetransp ? 1 : 0)
72         }).done(function(data, textstatus, xhr) {
73                 show_lines(data, game);
74         });
75 }
76
77 var add_td = function(tr, value) {
78         var td = document.createElement("td");
79         tr.appendChild(td);
80         $(td).addClass("num");
81         $(td).text(value);
82 }
83
84 var TYPE_MOVE = 0;
85 var TYPE_INTEGER = 1;
86 var TYPE_FLOAT = 2;
87 var TYPE_RATIO = 3;
88
89 var headings = [
90         [ "Move", TYPE_MOVE ],
91         [ "Games", TYPE_INTEGER ],
92         [ "%", TYPE_RATIO ],
93         [ "Win%", TYPE_RATIO ],
94         [ "WWin", TYPE_INTEGER ],
95         [ "%WW", TYPE_RATIO ],
96         [ "Bwin", TYPE_INTEGER ],
97         [ "%BW", TYPE_RATIO ],
98         [ "Draw", TYPE_INTEGER ],
99         [ "Draw%", TYPE_RATIO ],
100         [ "AvWElo", TYPE_FLOAT ],
101         [ "AvBElo", TYPE_FLOAT ],
102         [ "EloVar", TYPE_FLOAT ],
103         [ "AWin%", TYPE_RATIO ],
104 ];
105 var sort_by = 1;
106 var direction = 1;
107
108 var show_lines = function(data, game) {
109         var moves = data['moves'];
110         $('#numviewers').text(data['opening']);
111
112         if (data['root_game']) {
113                 var text = escape_html(data['root_game']['white']);
114                 if (data['root_game']['white_elo']) {
115                         text += " (" + escape_html(data['root_game']['white_elo']) + ")";
116                 }
117                 text += " &ndash; " + escape_html(data['root_game']['black']);
118                 if (data['root_game']['black_elo']) {
119                         text += " (" + escape_html(data['root_game']['black_elo']) + ")";
120                 }
121                 text += " &nbsp;" + escape_html(data['root_game']['result']).replace(/-/, "&ndash;") + "<br />";
122                 if (data['root_game']['eco']) {
123                         text += "[" + escape_html(data['root_game']['eco']) + "] ";
124                 }
125                 text += "(" + data['root_game']['moves'] + ") ";
126                 text += escape_html(data['root_game']['event']) + " &nbsp;" + escape_html(data['root_game']['date']);
127                 $('#gamesummary').html(text);
128         }
129
130         var total_num = 0;
131         for (var i = 0; i < moves.length; ++i) {
132                 var move = moves[i];
133                 if (move['move']) {
134                         total_num += parseInt(move['white']);
135                         total_num += parseInt(move['draw']);
136                         total_num += parseInt(move['black']);
137                 }
138         }
139
140         var headings_tr = $("#headings");
141         headings_tr.empty();
142         for (var i = 0; i < headings.length; ++i) {
143                 var th = document.createElement("th");
144                 headings_tr.append(th);
145                 $(th).text(headings[i][0]);
146                 (function(new_sort_by) {
147                         $(th).click(function() {
148                                 if (sort_by == new_sort_by) {
149                                         direction = -direction;
150                                 } else {
151                                         sort_by = new_sort_by;
152                                         direction = 1;
153                                 }
154                                 show_lines(data, game);
155                         });
156                 })(i);
157         }
158
159         var lines = [];
160         for (var i = 0; i < moves.length; ++i) {
161                 var move = moves[i];
162                 var line = [];
163
164                 var white = parseInt(move['white']);
165                 var draw = parseInt(move['draw']);
166                 var black = parseInt(move['black']);
167
168                 line.push(move['move']);  // Move.
169                 var num = white + draw + black;
170                 line.push(num);  // N.
171                 line.push(num / total_num);  // %.
172
173                 // Win%.
174                 var white_win_ratio = (white + 0.5 * draw) / num;
175                 var win_ratio = (game.turn() == 'w') ? white_win_ratio : 1.0 - white_win_ratio;
176                 line.push(win_ratio);
177
178                 line.push(white);        // WWin.
179                 line.push(white / num);  // %WW.
180                 line.push(black);        // BWin.
181                 line.push(black / num);  // %BW.
182                 line.push(draw);         // Draw.
183                 line.push(draw / num);   // %Draw.
184
185                 if (move['num_elo'] >= 10) {
186                         // Elo.
187                         line.push(move['white_avg_elo']);
188                         line.push(move['black_avg_elo']);
189                         line.push(move['white_avg_elo'] - move['black_avg_elo']);
190
191                         // Win% corrected for Elo.
192                         var win_elo = -400.0 * Math.log(1.0 / white_win_ratio - 1.0) / Math.LN10;
193                         win_elo -= (move['white_avg_elo'] - move['black_avg_elo']);
194                         white_win_ratio = 1.0 / (1.0 + Math.pow(10, win_elo / -400.0));
195                         win_ratio = (game.turn() == 'w') ? white_win_ratio : 1.0 - white_win_ratio;
196                         line.push(win_ratio);
197                 } else {
198                         line.push(null);
199                         line.push(null);
200                         line.push(null);
201                         line.push(null);
202                 }
203                 lines.push(line);
204         }
205
206         lines.sort(function(a, b) { return direction * ( b[sort_by] - a[sort_by]); });
207
208         var tbl = $("#lines");
209         tbl.empty();
210
211         for (var i = 0; i < moves.length; ++i) {
212                 var line = lines[i];
213                 var tr = document.createElement("tr");
214
215                 if (line[0] === undefined) {
216                         $(tr).addClass("totals");
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         if (move_override < history.length && history[move_override] == move) {
259                 // User effectively only moved forward in history.
260                 ++move_override;
261         } else {
262                 history.length = move_override;
263                 history.push(move);
264                 move_override = history.length;
265         }
266         update();
267 }
268 window['make_move'] = make_move;
269
270 var prev_move = function() {
271         if (move_override > 0) {
272                 --move_override;
273                 update();
274         }
275 }
276 window['prev_move'] = prev_move;
277
278 var next_move = function() {
279         if (move_override < history.length) {
280                 ++move_override;
281                 update();
282         }
283 }
284 window['next_move'] = next_move;
285
286 var set_move = function(n) {
287         move_override = n;
288         update();
289 }
290 window['set_move'] = set_move;
291
292 // almost all of this stuff comes from the chessboard.js example page
293 var onDragStart = function(source, piece, position, orientation) {
294         var game = get_game();
295         if (game.game_over() === true ||
296             (game.turn() === 'w' && piece.search(/^b/) !== -1) ||
297             (game.turn() === 'b' && piece.search(/^w/) !== -1)) {
298                 return false;
299         }
300 }
301
302 var onDrop = function(source, target) {
303         // see if the move is legal
304         var game = get_game();
305         var move = game.move({
306                 from: source,
307                 to: target,
308                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
309         });
310
311         // illegal move
312         if (move === null) return 'snapback';
313
314         var new_history = game.history({ verbose: true });
315         history = [];
316         for (var i = 0; i < new_history.length; ++i) {
317                 history.push(new_history[i].san);
318         }
319         move_override = history.length;
320 };
321
322 // update the board position after the piece snap 
323 // for castling, en passant, pawn promotion
324 var onSnapEnd = function() {
325         var game = get_game();
326         board.position(game.fen());
327         update();
328 };
329
330 var init = function() {
331         // Create board.
332         board = new window.ChessBoard('board', {
333                 draggable: true,
334                 position: 'start',
335                 onDragStart: onDragStart,
336                 onDrop: onDrop,
337                 onSnapEnd: onSnapEnd
338         });
339         update();
340
341         $(window).keyup(function(event) {
342                 if (event.which == 39) {
343                         next_move();
344                 } else if (event.which == 37) {
345                         prev_move();
346                 }
347         });
348 }
349
350
351 $(document).ready(init);
352
353 })();