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