]> git.sesse.net Git - remoteglot-book/blob - www/js/book.js
Fix move numbering when navigating in history.
[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 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                 if (move['move']) {
101                         total_num += parseInt(move['white']);
102                         total_num += parseInt(move['draw']);
103                         total_num += parseInt(move['black']);
104                 }
105         }
106
107         var headings_tr = $("#headings");
108         headings_tr.empty();
109         for (var i = 0; i < headings.length; ++i) {
110                 var th = document.createElement("th");
111                 headings_tr.append(th);
112                 $(th).text(headings[i][0]);
113                 (function(new_sort_by) {
114                         $(th).click(function() {
115                                 if (sort_by == new_sort_by) {
116                                         direction = -direction;
117                                 } else {
118                                         sort_by = new_sort_by;
119                                         direction = 1;
120                                 }
121                                 show_lines(data, game);
122                         });
123                 })(i);
124         }
125
126         var lines = [];
127         for (var i = 0; i < moves.length; ++i) {
128                 var move = moves[i];
129                 var line = [];
130
131                 var white = parseInt(move['white']);
132                 var draw = parseInt(move['draw']);
133                 var black = parseInt(move['black']);
134
135                 line.push(move['move']);  // Move.
136                 var num = white + draw + black;
137                 line.push(num);  // N.
138                 line.push(num / total_num);  // %.
139
140                 // Win%.
141                 var white_win_ratio = (white + 0.5 * draw) / num;
142                 var win_ratio = (game.turn() == 'w') ? white_win_ratio : 1.0 - white_win_ratio;
143                 line.push(win_ratio);
144
145                 line.push(white);        // WWin.
146                 line.push(white / num);  // %WW.
147                 line.push(black);        // BWin.
148                 line.push(black / num);  // %BW.
149                 line.push(draw);         // Draw.
150                 line.push(draw / num);   // %Draw.
151
152                 if (move['num_elo'] >= 10) {
153                         // Elo.
154                         line.push(move['white_avg_elo']);
155                         line.push(move['black_avg_elo']);
156                         line.push(move['white_avg_elo'] - move['black_avg_elo']);
157
158                         // Win% corrected for Elo.
159                         var win_elo = -400.0 * Math.log(1.0 / white_win_ratio - 1.0) / Math.LN10;
160                         win_elo -= (move['white_avg_elo'] - move['black_avg_elo']);
161                         white_win_ratio = 1.0 / (1.0 + Math.pow(10, win_elo / -400.0));
162                         win_ratio = (game.turn() == 'w') ? white_win_ratio : 1.0 - white_win_ratio;
163                         line.push(win_ratio);
164                 } else {
165                         line.push(null);
166                         line.push(null);
167                         line.push(null);
168                         line.push(null);
169                 }
170                 lines.push(line);
171         }
172
173         lines.sort(function(a, b) { return direction * ( b[sort_by] - a[sort_by]); });
174
175         var tbl = $("#lines");
176         tbl.empty();
177
178         for (var i = 0; i < moves.length; ++i) {
179                 var line = lines[i];
180                 var tr = document.createElement("tr");
181
182                 if (line[0] === undefined) {
183                         $(tr).addClass("totals");
184                 }
185
186                 for (var j = 0; j < line.length; ++j) {
187                         if (line[j] === null) {
188                                 add_td(tr, "");
189                         } else if (headings[j][1] == TYPE_MOVE) {
190                                 var td = document.createElement("td");
191                                 tr.appendChild(td);
192                                 $(td).addClass("move");
193                                 if (line[j] !== undefined) {
194                                         if (move_override % 2 == 0) {
195                                                 $(td).text(((move_override / 2) + 1) + ". ");
196                                         } else {
197                                                 $(td).text(((move_override / 2) + 0.5) + ". …");
198                                         }
199                                 }
200
201                                 var move_a = document.createElement("a");
202                                 move_a.href = "javascript:make_move('" + line[j] + "')";
203                                 td.appendChild(move_a);
204                                 $(move_a).text(line[j]);
205                         } else if (headings[j][1] == TYPE_INTEGER) {
206                                 add_td(tr, line[j]);
207                         } else if (headings[j][1] == TYPE_FLOAT) {
208                                 add_td(tr, line[j].toFixed(1));
209                         } else {
210                                 add_td(tr, (100.0 * line[j]).toFixed(1) + "%");
211                         }
212                 }
213
214                 tbl.append(tr);
215         }
216 }
217
218 var make_move = function(move) {
219         history.length = move_override;
220         history.push(move);
221         move_override = history.length;
222         update();
223 }
224 window['make_move'] = make_move;
225
226 var prev_move = function() {
227         if (move_override > 0) {
228                 --move_override;
229                 update();
230         }
231 }
232 window['prev_move'] = prev_move;
233
234 var next_move = function() {
235         if (move_override < history.length) {
236                 ++move_override;
237                 update();
238         }
239 }
240 window['next_move'] = next_move;
241
242 // almost all of this stuff comes from the chessboard.js example page
243 var onDragStart = function(source, piece, position, orientation) {
244         var game = get_game();
245         if (game.game_over() === true ||
246             (game.turn() === 'w' && piece.search(/^b/) !== -1) ||
247             (game.turn() === 'b' && piece.search(/^w/) !== -1)) {
248                 return false;
249         }
250 }
251
252 var onDrop = function(source, target) {
253         // see if the move is legal
254         var game = get_game();
255         var move = game.move({
256                 from: source,
257                 to: target,
258                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
259         });
260
261         // illegal move
262         if (move === null) return 'snapback';
263
264         history = game.history({ verbose: true });
265         move_override = history.length;
266 };
267
268 // update the board position after the piece snap 
269 // for castling, en passant, pawn promotion
270 var onSnapEnd = function() {
271         var game = get_game();
272         board.position(game.fen());
273         fetch_analysis();
274 };
275
276 var init = function() {
277         // Create board.
278         board = new window.ChessBoard('board', {
279                 draggable: true,
280                 position: 'start',
281                 onDragStart: onDragStart,
282                 onDrop: onDrop,
283                 onSnapEnd: onSnapEnd
284         });
285         update();
286
287         $(window).keyup(function(event) {
288                 if (event.which == 39) {
289                         next_move();
290                 } else if (event.which == 37) {
291                         prev_move();
292                 }
293         });
294 }
295
296
297 $(document).ready(init);
298
299 })();