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