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