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