]> git.sesse.net Git - remoteglot-book/blob - www/js/book.js
Show number of computer games in the UI.
[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 get_history_url = function() {
64         var history = game.history({ verbose: true }).map(function(x) { return x.san; });
65         history.length = move_override;
66         return '/?' + history.join(',');
67 }
68
69 var fetch_analysis = function() {
70         var fen = current_display_fen();
71         $.ajax({
72                 url: "/opening-stats.pl?fen=" + encodeURIComponent(fen) +
73                         ";includetransp=" + (includetransp ? 1 : 0)
74         }).done(function(data, textstatus, xhr) {
75                 show_lines(data, game);
76         });
77 }
78
79 var add_td = function(tr, value) {
80         var td = document.createElement("td");
81         tr.appendChild(td);
82         $(td).addClass("num");
83         $(td).text(value);
84 }
85
86 var TYPE_MOVE = 0;
87 var TYPE_INTEGER = 1;
88 var TYPE_FLOAT = 2;
89 var TYPE_RATIO = 3;
90
91 var headings = [
92         [ "Move", TYPE_MOVE ],
93         [ "Games", TYPE_INTEGER ],
94         [ "%", TYPE_RATIO ],
95         [ "CGames", TYPE_INTEGER ],
96         [ "Comp%", TYPE_RATIO ],
97         [ "Win%", TYPE_RATIO ],
98         [ "WWin", TYPE_INTEGER ],
99         [ "%WW", TYPE_RATIO ],
100         [ "Bwin", TYPE_INTEGER ],
101         [ "%BW", TYPE_RATIO ],
102         [ "Draw", TYPE_INTEGER ],
103         [ "Draw%", TYPE_RATIO ],
104         [ "AvWElo", TYPE_FLOAT ],
105         [ "AvBElo", TYPE_FLOAT ],
106         [ "EloVar", TYPE_FLOAT ],
107         [ "AWin%", TYPE_RATIO ],
108 ];
109 var sort_by = 1;
110 var direction = 1;
111
112 var show_lines = function(data, game) {
113         var moves = data['moves'];
114         $('#numviewers').text(data['opening']);
115
116         if (data['root_game']) {
117                 var text = escape_html(data['root_game']['white']);
118                 if (data['root_game']['white_elo']) {
119                         text += " (" + escape_html(data['root_game']['white_elo']) + ")";
120                 }
121                 text += " &ndash; " + escape_html(data['root_game']['black']);
122                 if (data['root_game']['black_elo']) {
123                         text += " (" + escape_html(data['root_game']['black_elo']) + ")";
124                 }
125                 text += " &nbsp;" + escape_html(data['root_game']['result']).replace(/-/, "&ndash;") + "<br />";
126                 if (data['root_game']['eco']) {
127                         text += "[" + escape_html(data['root_game']['eco']) + "] ";
128                 }
129                 text += "(" + data['root_game']['moves'] + ") ";
130                 text += escape_html(data['root_game']['event']) + " &nbsp;" + escape_html(data['root_game']['date']);
131                 $('#gamesummary').html(text);
132         }
133
134         var total_num = 0;
135         for (var i = 0; i < moves.length; ++i) {
136                 var move = moves[i];
137                 if (move['move']) {
138                         total_num += parseInt(move['white']);
139                         total_num += parseInt(move['draw']);
140                         total_num += parseInt(move['black']);
141                 }
142         }
143
144         var headings_tr = $("#headings");
145         headings_tr.empty();
146         for (var i = 0; i < headings.length; ++i) {
147                 var th = document.createElement("th");
148                 headings_tr.append(th);
149                 $(th).text(headings[i][0]);
150                 (function(new_sort_by) {
151                         $(th).click(function() {
152                                 if (sort_by == new_sort_by) {
153                                         direction = -direction;
154                                 } else {
155                                         sort_by = new_sort_by;
156                                         direction = 1;
157                                 }
158                                 show_lines(data, game);
159                         });
160                 })(i);
161         }
162
163         var lines = [];
164         var transpose_only = [];
165         for (var i = 0; i < moves.length; ++i) {
166                 var move = moves[i];
167                 var line = [];
168
169                 var white = parseInt(move['white']);
170                 var draw = parseInt(move['draw']);
171                 var black = parseInt(move['black']);
172                 var computer = parseInt(move['computer']);
173
174                 line.push(move['move']);  // Move.
175                 transpose_only.push(move['transpose_only']);
176                 var num = white + draw + black;
177                 line.push(num);  // N.
178                 line.push(num / total_num);  // %.
179                 line.push(computer);  // CGames.
180                 line.push(computer / num);  // Comp%.
181
182                 // Win%.
183                 var white_win_ratio = (white + 0.5 * draw) / num;
184                 var win_ratio = (move_override % 2 == 0) ? white_win_ratio : 1.0 - white_win_ratio;
185                 line.push(win_ratio);
186
187                 line.push(white);        // WWin.
188                 line.push(white / num);  // %WW.
189                 line.push(black);        // BWin.
190                 line.push(black / num);  // %BW.
191                 line.push(draw);         // Draw.
192                 line.push(draw / num);   // %Draw.
193
194                 if (move['num_elo'] >= 10) {
195                         // Elo.
196                         line.push(move['white_avg_elo']);
197                         line.push(move['black_avg_elo']);
198                         line.push(move['white_avg_elo'] - move['black_avg_elo']);
199
200                         // Win% corrected for Elo.
201                         var win_elo = -400.0 * Math.log(1.0 / white_win_ratio - 1.0) / Math.LN10;
202                         win_elo -= (move['white_avg_elo'] - move['black_avg_elo']);
203                         white_win_ratio = 1.0 / (1.0 + Math.pow(10, win_elo / -400.0));
204                         win_ratio = (move_override % 2 == 0) ? white_win_ratio : 1.0 - white_win_ratio;
205                         line.push(win_ratio);
206                 } else {
207                         line.push(null);
208                         line.push(null);
209                         line.push(null);
210                         line.push(null);
211                 }
212                 lines.push(line);
213         }
214
215         lines.sort(function(a, b) { return direction * ( b[sort_by] - a[sort_by]); });
216
217         var tbl = $("#lines");
218         tbl.empty();
219
220         for (var i = 0; i < moves.length; ++i) {
221                 var line = lines[i];
222                 var tr = document.createElement("tr");
223
224                 if (line[0] === undefined) {
225                         $(tr).addClass("totals");
226                 } else if (transpose_only[i]) {
227                         $(tr).addClass("transponly");
228                 }
229
230                 for (var j = 0; j < line.length; ++j) {
231                         if (line[j] === null) {
232                                 add_td(tr, "");
233                         } else if (headings[j][1] == TYPE_MOVE) {
234                                 var td = document.createElement("td");
235                                 tr.appendChild(td);
236                                 $(td).addClass("move");
237                                 if (line[j] !== undefined) {
238                                         if (move_override % 2 == 0) {
239                                                 $(td).text(((move_override / 2) + 1) + ". ");
240                                         } else {
241                                                 $(td).text(((move_override / 2) + 0.5) + "…");
242                                         }
243                                 }
244
245                                 var move_a = document.createElement("a");
246                                 move_a.href = "javascript:make_move('" + line[j] + "')";
247                                 td.appendChild(move_a);
248                                 $(move_a).text(line[j]);
249                         } else if (headings[j][1] == TYPE_INTEGER) {
250                                 add_td(tr, line[j] || 0);
251                         } else if (headings[j][1] == TYPE_FLOAT) {
252                                 if (isNaN(line[j]) || !isFinite(line[j])) {
253                                         add_td(tr, '');
254                                 } else {
255                                         add_td(tr, line[j].toFixed(1));
256                                 }
257                         } else {
258                                 if (isNaN(line[j]) || !isFinite(line[j])) {
259                                         add_td(tr, '');
260                                 } else {
261                                         add_td(tr, (100.0 * line[j]).toFixed(1) + "%");
262                                 }
263                         }
264                 }
265
266                 tbl.append(tr);
267         }
268 }
269
270 var set_includetransp = function(value) {
271         includetransp = value;
272         update();
273 }
274 window['set_includetransp'] = set_includetransp;
275
276 var make_move = function(move, do_update) {
277         var history = game.history({ verbose: true });
278         if (move_override < history.length && history[move_override].san == move) {
279                 // User effectively only moved forward in history.
280                 ++move_override;
281         } else {
282                 var moves = game.history();
283                 // Truncate the history if needed.
284                 if (move_override < moves.length) {
285                         game = new Chess();
286                         for (var i = 0; i < move_override; ++i) {
287                                 game.move(moves[i]);
288                         }
289                         fens.length = move_override;
290                 }
291                 game.move(move);
292                 fens.push(game.fen());
293                 ++move_override;
294         }
295
296         if (do_update !== false) {
297                 update();
298                 window.history.pushState(null, null, get_history_url());
299         }
300 }
301 window['make_move'] = make_move;
302
303 var prev_move = function() {
304         if (move_override > 0) {
305                 --move_override;
306                 update();
307                 window.history.replaceState(null, null, get_history_url());
308         }
309 }
310 window['prev_move'] = prev_move;
311
312 var next_move = function() {
313         if (move_override < game.history().length) {
314                 ++move_override;
315                 update();
316                 window.history.replaceState(null, null, get_history_url());
317         }
318 }
319 window['next_move'] = next_move;
320
321 var set_move = function(n, do_update) {
322         move_override = n;
323         if (do_update !== false) {
324                 update();
325                 window.history.replaceState(null, null, get_history_url());
326         }
327 }
328 window['set_move'] = set_move;
329
330 // almost all of this stuff comes from the chessboard.js example page
331 var onDragStart = function(source, piece, position, orientation) {
332         var pseudogame = new Chess(current_display_fen());
333         if (pseudogame.game_over() === true ||
334             (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
335             (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
336                 return false;
337         }
338 }
339
340 var onDrop = function(source, target) {
341         // see if the move is legal
342         var pseudogame = new Chess(current_display_fen());
343         var move = pseudogame.move({
344                 from: source,
345                 to: target,
346                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
347         });
348
349         // illegal move
350         if (move === null) return 'snapback';
351 }
352
353 var onSnapEnd = function(source, target) {
354         var pseudogame = new Chess(current_display_fen());
355         var move = pseudogame.move({
356                 from: source,
357                 to: target,
358                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
359         });
360
361         make_move(pseudogame.history({ verbose: true }).pop().san);
362 }
363
364 var onpopstate = function() {
365         var old_moves = game.history({ verbose: true }).map(function(x) { return x.san; });
366         var new_moves = document.location.search.replace(/^\?/, "").split(",");
367
368         if (new_moves.length == 1 && new_moves[0] == "") {
369                 new_moves = [];
370         }
371
372         var num_shared_moves;
373         for (num_shared_moves = 0; num_shared_moves < Math.min(old_moves.length, new_moves.length); ++num_shared_moves) {
374                 if (old_moves[i] != new_moves[i]) {
375                         break;
376                 }
377         }
378
379         set_move(num_shared_moves, false);
380         for (var i = num_shared_moves; i < new_moves.length; ++i) {
381                 make_move(new_moves[i], false);
382         }
383         update();
384         window.history.replaceState(null, null, get_history_url());
385 }
386
387 var init = function() {
388         // Create board.
389         board = new window.ChessBoard('board', {
390                 draggable: true,
391                 position: 'start',
392                 onDragStart: onDragStart,
393                 onDrop: onDrop,
394                 onSnapEnd: onSnapEnd
395         });
396
397         window.onpopstate = onpopstate;
398         onpopstate();
399
400         $(window).keyup(function(event) {
401                 if (event.which == 39) {
402                         next_move();
403                 } else if (event.which == 37) {
404                         prev_move();
405                 }
406         });
407 }
408
409
410 $(document).ready(init);
411
412 })();