]> git.sesse.net Git - remoteglot-book/blob - www/js/book.js
36a9a26183b90c3797cd6ed982022653eb14a377
[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         var transpose_only = [];
161         for (var i = 0; i < moves.length; ++i) {
162                 var move = moves[i];
163                 var line = [];
164
165                 var white = parseInt(move['white']);
166                 var draw = parseInt(move['draw']);
167                 var black = parseInt(move['black']);
168
169                 line.push(move['move']);  // Move.
170                 transpose_only.push(move['transpose_only']);
171                 var num = white + draw + black;
172                 line.push(num);  // N.
173                 line.push(num / total_num);  // %.
174
175                 // Win%.
176                 var white_win_ratio = (white + 0.5 * draw) / num;
177                 var win_ratio = (game.turn() == 'w') ? white_win_ratio : 1.0 - white_win_ratio;
178                 line.push(win_ratio);
179
180                 line.push(white);        // WWin.
181                 line.push(white / num);  // %WW.
182                 line.push(black);        // BWin.
183                 line.push(black / num);  // %BW.
184                 line.push(draw);         // Draw.
185                 line.push(draw / num);   // %Draw.
186
187                 if (move['num_elo'] >= 10) {
188                         // Elo.
189                         line.push(move['white_avg_elo']);
190                         line.push(move['black_avg_elo']);
191                         line.push(move['white_avg_elo'] - move['black_avg_elo']);
192
193                         // Win% corrected for Elo.
194                         var win_elo = -400.0 * Math.log(1.0 / white_win_ratio - 1.0) / Math.LN10;
195                         win_elo -= (move['white_avg_elo'] - move['black_avg_elo']);
196                         white_win_ratio = 1.0 / (1.0 + Math.pow(10, win_elo / -400.0));
197                         win_ratio = (game.turn() == 'w') ? white_win_ratio : 1.0 - white_win_ratio;
198                         line.push(win_ratio);
199                 } else {
200                         line.push(null);
201                         line.push(null);
202                         line.push(null);
203                         line.push(null);
204                 }
205                 lines.push(line);
206         }
207
208         lines.sort(function(a, b) { return direction * ( b[sort_by] - a[sort_by]); });
209
210         var tbl = $("#lines");
211         tbl.empty();
212
213         for (var i = 0; i < moves.length; ++i) {
214                 var line = lines[i];
215                 var tr = document.createElement("tr");
216
217                 if (line[0] === undefined) {
218                         $(tr).addClass("totals");
219                 } else if (transpose_only[i]) {
220                         $(tr).addClass("transponly");
221                 }
222
223                 for (var j = 0; j < line.length; ++j) {
224                         if (line[j] === null) {
225                                 add_td(tr, "");
226                         } else if (headings[j][1] == TYPE_MOVE) {
227                                 var td = document.createElement("td");
228                                 tr.appendChild(td);
229                                 $(td).addClass("move");
230                                 if (line[j] !== undefined) {
231                                         if (move_override % 2 == 0) {
232                                                 $(td).text(((move_override / 2) + 1) + ". ");
233                                         } else {
234                                                 $(td).text(((move_override / 2) + 0.5) + "…");
235                                         }
236                                 }
237
238                                 var move_a = document.createElement("a");
239                                 move_a.href = "javascript:make_move('" + line[j] + "')";
240                                 td.appendChild(move_a);
241                                 $(move_a).text(line[j]);
242                         } else if (headings[j][1] == TYPE_INTEGER) {
243                                 add_td(tr, line[j]);
244                         } else if (headings[j][1] == TYPE_FLOAT) {
245                                 add_td(tr, line[j].toFixed(1));
246                         } else {
247                                 add_td(tr, (100.0 * line[j]).toFixed(1) + "%");
248                         }
249                 }
250
251                 tbl.append(tr);
252         }
253 }
254
255 var set_includetransp = function(value) {
256         includetransp = value;
257         update();
258 }
259 window['set_includetransp'] = set_includetransp;
260
261 var make_move = function(move) {
262         if (move_override < history.length && history[move_override] == move) {
263                 // User effectively only moved forward in history.
264                 ++move_override;
265         } else {
266                 history.length = move_override;
267                 history.push(move);
268                 move_override = history.length;
269         }
270         update();
271 }
272 window['make_move'] = make_move;
273
274 var prev_move = function() {
275         if (move_override > 0) {
276                 --move_override;
277                 update();
278         }
279 }
280 window['prev_move'] = prev_move;
281
282 var next_move = function() {
283         if (move_override < history.length) {
284                 ++move_override;
285                 update();
286         }
287 }
288 window['next_move'] = next_move;
289
290 var set_move = function(n) {
291         move_override = n;
292         update();
293 }
294 window['set_move'] = set_move;
295
296 // almost all of this stuff comes from the chessboard.js example page
297 var onDragStart = function(source, piece, position, orientation) {
298         var game = get_game();
299         if (game.game_over() === true ||
300             (game.turn() === 'w' && piece.search(/^b/) !== -1) ||
301             (game.turn() === 'b' && piece.search(/^w/) !== -1)) {
302                 return false;
303         }
304 }
305
306 var onDrop = function(source, target) {
307         // see if the move is legal
308         var game = get_game();
309         var move = game.move({
310                 from: source,
311                 to: target,
312                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
313         });
314
315         // illegal move
316         if (move === null) return 'snapback';
317
318         var new_history = game.history({ verbose: true });
319         history = [];
320         for (var i = 0; i < new_history.length; ++i) {
321                 history.push(new_history[i].san);
322         }
323         move_override = history.length;
324 };
325
326 // update the board position after the piece snap 
327 // for castling, en passant, pawn promotion
328 var onSnapEnd = function() {
329         var game = get_game();
330         board.position(game.fen());
331         update();
332 };
333
334 var init = function() {
335         // Create board.
336         board = new window.ChessBoard('board', {
337                 draggable: true,
338                 position: 'start',
339                 onDragStart: onDragStart,
340                 onDrop: onDrop,
341                 onSnapEnd: onSnapEnd
342         });
343         update();
344
345         $(window).keyup(function(event) {
346                 if (event.which == 39) {
347                         next_move();
348                 } else if (event.which == 37) {
349                         prev_move();
350                 }
351         });
352 }
353
354
355 $(document).ready(init);
356
357 })();