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