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