]> git.sesse.net Git - remoteglot-book/blob - www/js/book.js
2cbbcec6dc00fe1df7a2439c6d845c670373dddc
[remoteglot-book] / www / js / book.js
1 (function() {
2
3 var board = null;
4 var game = new Chess();
5 var fens = [];  // Position after each.
6 var move_override = 0;
7 var includetransp = true;
8 var stockfish = new Worker('/js/stockfish.js');
9 var engine_running = false;
10 var engine_replacement_callback = null;
11 var recommended_move = null;
12 var reverse_dragging_from = null;
13 var practice_mode = false;
14 var practice_side = 'W';
15
16 // TODO: Make this configurable.
17 var practice_top_moves_limit = 5;
18 var practice_minimum_move_fraction_start = 0.05;
19 var practice_minimum_move_fraction_move5 = 0.30;
20
21 var entity_map = {
22         "&": "&",
23         "<": "&lt;",
24         ">": "&gt;",
25         '"': '&quot;',
26         "'": '&#39;',
27 };
28
29 function escape_html(string) {
30         return String(string).replace(/[&<>"']/g, function (s) {
31                 return entity_map[s];
32         });
33 }
34
35 var current_display_fen = function() {
36         return fen_before_move(move_override);
37 }
38
39 var fen_before_move = function(move_num) {
40         if (move_num == 0) {
41                 return 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1';
42         } else {
43                 return fens[move_num - 1];
44         }
45 }
46
47 var update = function() {
48         var text = "";
49         var history = game.history({ verbose: true });
50         for (var i = 0; i < history.length; ++i) {
51                 if (i % 2 == 0) {
52                         text += (i/2 + 1) + ". ";
53                 }
54                 if (i + 1 == move_override) {
55                         text += '<strong>' + history[i].san + '</strong>';
56                 } else {
57                         text += '<a href="javascript:set_move(' + (i + 1) + ')">' + history[i].san + '</a>';
58                 }
59                 text += " ";
60         }
61         $('#gamehistory').html(text);
62
63         if (board.fen() != current_display_fen()) {
64                 board.position(current_display_fen());
65         }
66
67         $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
68         if (move_override > 0) {
69                 var last_move = history[move_override - 1];
70                 var highlight_from = last_move.from;
71                 var highlight_to = last_move.to;
72                 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
73                 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
74         }
75
76         if (practice_mode) {
77                 find_last_move_score();
78                 var side_to_move = (move_override % 2 == 0) ? 'W' : 'B';
79                 if (side_to_move !== practice_side) {
80                         find_computer_move();
81                 }
82                 // Fall through to get the line name and such.
83         }
84
85         fetch_analysis();
86 }
87
88 var get_history_url = function() {
89         var history = game.history({ verbose: true }).map(function(x) { return x.san; });
90         history.length = move_override;
91         return '/?' + history.join(',');
92 }
93
94 var fetch_analysis = function() {
95         var fen = current_display_fen();
96         $.ajax({
97                 url: "/opening-stats.pl?fen=" + encodeURIComponent(fen) +
98                         ";includetransp=" + (includetransp ? 1 : 0)
99         }).done(function(data, textstatus, xhr) {
100                 show_lines(data, game);
101         });
102 }
103
104 var find_last_move_score = function() {
105         var history = game.history({ verbose: true });
106         var side_to_move = (move_override % 2 == 0) ? 'W' : 'B';
107         var move_num = (side_to_move === practice_side) ? (move_override - 2) : (move_override - 1);
108         if (move_num < 0) {
109                 $("#yourmove").text("(none)");
110                 $("#yourfraction").text("N/A");
111                 $("#yourrank").text("N/A");
112                 $("#yourawin").text("??.?%");
113                 $("#yourawindiff").text("+?.?%");
114                 return;
115         }
116
117         var chosen_move = history[move_num].san;
118         $("#yourmove").text(chosen_move);
119         $.ajax({
120                 url: "/opening-stats.pl?fen=" + encodeURIComponent(fen_before_move(move_num)) +
121                         ";includetransp=0"
122         }).done(function(data, textstatus, xhr) {
123                 var moves = data['moves'];
124                 var root_move = sort_move_by_frequency(moves, data);
125                 var your_move, your_index;
126
127                 for (var i = 0; i < moves.length; ++i) {
128                         var move = moves[i];
129                         if (move['move'] === chosen_move) {
130                                 your_move = move;
131                                 your_index = i;
132                         }
133                 }
134
135                 if (your_move) {
136                         $("#yourfraction").text(format_fraction(your_move['fraction']));
137                         $("#yourawin").text(format_fraction(your_move['corrected_win_ratio']));
138                         $("#yourrank").text(format_ordinal(your_index + 1) + ", based on " + root_move['num'] + " games");
139                         var diff = your_move['corrected_win_ratio'] - root_move['corrected_win_ratio'];
140                         $("#yourawindiff").css("color", "black");
141                         if (diff === 0) {
142                                 $("#yourawindiff").text("0.0%");
143                         } else if (diff > 0) {
144                                 $("#yourawindiff").text("+" + format_fraction(diff));
145                                 $("#yourawindiff").css("color", "green");
146                         } else {
147                                 $("#yourawindiff").text(format_fraction(diff));
148                                 if (diff < -0.02) {
149                                         $("#yourawindiff").css("color", "red");
150                                 }
151                         }
152                 } else {
153                         $("#yourfraction").text("??.?%");
154                         $("#yourrank").text("?th");
155                         $("#yourawin").text("??.?%");
156                         $("#yourawindiff").text("+?.?%");
157                 }
158         });
159 }
160
161 var find_computer_move = function() {
162         var fen = current_display_fen();
163         $.ajax({
164                 url: "/opening-stats.pl?fen=" + encodeURIComponent(fen) + ";includetransp=0"
165         }).done(function(data, textstatus, xhr) {
166                 var candidate_moves = [];
167
168                 var moves = data['moves'];
169                 var root_move = sort_move_by_frequency(moves, data);
170
171                 var practice_minimum_move_fraction;
172                 if (move_override > 20) {
173                         practice_minimum_move_fraction = practice_minimum_move_fraction_move5;
174                 } else {
175                         practice_minimum_move_fraction = practice_minimum_move_fraction_start +
176                                 ((move_override-1)/10.0) * (practice_minimum_move_fraction_move5 - practice_minimum_move_fraction_start);
177                 }
178                 console.log(practice_minimum_move_fraction);
179
180                 for (var i = 0; i < Math.min(moves.length, practice_top_moves_limit); ++i) {
181                         var move = moves[i];
182                         if (i == 0 || move['fraction'] >= practice_minimum_move_fraction) {
183                                 candidate_moves.push(move);
184                         }
185                 }
186
187                 // Pick one at random.
188                 var chosen_index = Math.floor(Math.random() * candidate_moves.length);
189                 var chosen = candidate_moves[chosen_index];
190                 $("#compmove").text(chosen['move']);
191                 $("#compfraction").text((100.0 * chosen['fraction']).toFixed(1) + "%");
192                 if (candidate_moves.length == 1) {
193                         $("#comprank").text("only candidate move");
194                 } else {
195                         $("#comprank").text(format_ordinal(chosen_index + 1) + " out of " + candidate_moves.length + " candidate moves");
196                 }
197                 make_move(chosen['move']);
198         });
199 }
200
201 // Add deried data and then sort moves to get the most common ones (in-place).
202 // Remove the root mode and return it. Currently usable for practice mode only!
203 var sort_move_by_frequency = function(moves, data)
204 {
205         var total_num = find_total_games(moves);
206         var root_move;
207         for (var i = 0; i < moves.length; ++i) {
208                 var move = moves[i];
209                 calc_move_derived_data(move, total_num, data, (practice_side === 'W'));
210                 if (!move['move']) {
211                         root_move = (moves.splice(i, 1))[0];
212                         --i;
213                 }
214         }
215         moves.sort(function(a, b) { return b['num'] - a['num'] });
216         return root_move;
217 }
218
219 var add_td = function(tr, value) {
220         var td = document.createElement("td");
221         tr.appendChild(td);
222         $(td).addClass("num");
223         $(td).text(value);
224 }
225
226 var format_ordinal = function(x) {
227         var tens = Math.floor(x / 10) % 10;
228         if (tens == 1) {
229                 return x + "th";
230         } else {
231                 var ones = x % 10;
232                 if (ones == 1) return x + "st";
233                 if (ones == 2) return x + "nd";
234                 if (ones == 3) return x + "rd";
235                 return x + "th";
236         }
237 }
238
239 var format_fraction = function(x) {
240         return (100.0 * x).toFixed(1) + '%';
241 }
242
243 var TYPE_MOVE = 0;
244 var TYPE_INTEGER = 1;
245 var TYPE_FLOAT = 2;
246 var TYPE_RATIO = 3;
247
248 var headings = [
249         [ "Move", TYPE_MOVE ],
250         [ "Games", TYPE_INTEGER ],
251         [ "%", TYPE_RATIO ],
252         [ "CGames", TYPE_INTEGER ],
253         [ "Hum", TYPE_RATIO ],
254         [ "Win%", TYPE_RATIO ],
255         [ "WWin", TYPE_INTEGER ],
256         [ "%WW", TYPE_RATIO ],
257         [ "Bwin", TYPE_INTEGER ],
258         [ "%BW", TYPE_RATIO ],
259         [ "Draw", TYPE_INTEGER ],
260         [ "Draw%", TYPE_RATIO ],
261         [ "AvWElo", TYPE_FLOAT ],
262         [ "AvBElo", TYPE_FLOAT ],
263         [ "EloVar", TYPE_FLOAT ],
264         [ "AWin%", TYPE_RATIO ],
265 ];
266 var sort_by = 1;
267 var direction = 1;
268
269 var show_lines = function(data, game) {
270         var moves = data['moves'];
271         $('#numviewers').text(data['opening']);
272
273         if (data['root_game']) {
274                 var text = escape_html(data['root_game']['white']);
275                 if (data['root_game']['white_elo']) {
276                         text += " (" + escape_html(data['root_game']['white_elo']) + ")";
277                 }
278                 text += " &ndash; " + escape_html(data['root_game']['black']);
279                 if (data['root_game']['black_elo']) {
280                         text += " (" + escape_html(data['root_game']['black_elo']) + ")";
281                 }
282                 text += " &nbsp;" + escape_html(data['root_game']['result']).replace(/-/, "&ndash;") + "<br />";
283                 if (data['root_game']['eco']) {
284                         text += "[" + escape_html(data['root_game']['eco']) + "] ";
285                 }
286                 text += "(" + data['root_game']['moves'] + ") ";
287                 text += escape_html(data['root_game']['event']) + " &nbsp;" + escape_html(data['root_game']['date']);
288                 $('#gamesummary').html(text);
289         }
290
291         var total_num = find_total_games(moves);
292
293         var headings_tr = $("#headings");
294         headings_tr.empty();
295         for (var i = 0; i < headings.length; ++i) {
296                 var th = document.createElement("th");
297                 headings_tr.append(th);
298                 $(th).text(headings[i][0]);
299                 (function(new_sort_by) {
300                         $(th).click(function() {
301                                 if (sort_by == new_sort_by) {
302                                         direction = -direction;
303                                 } else {
304                                         sort_by = new_sort_by;
305                                         direction = 1;
306                                 }
307                                 show_lines(data, game);
308                         });
309                 })(i);
310         }
311
312         var lines = [];
313         var transpose_only = [];
314         for (var i = 0; i < moves.length; ++i) {
315                 var move = moves[i];
316                 var line = [];
317
318                 calc_move_derived_data(move, total_num, data, (move_override % 2 == 0));
319
320                 var white = move['white'];
321                 var draw = move['draw'];
322                 var black = move['black'];
323                 var computer = move['computer'];
324
325                 line.push(move['move']);  // Move.
326                 transpose_only.push(move['transpose_only']);
327                 line.push(move['num']);  // N.
328                 line.push(move['fraction']);  // %.
329                 line.push(computer);  // CGames.
330                 line.push(move['human_index']);  // Hum.
331                 line.push(move['win_ratio']);  // Win%.
332
333                 line.push(white);                // WWin.
334                 line.push(white / move['num']);  // %WW.
335                 line.push(black);                // BWin.
336                 line.push(black / move['num']);  // %BW.
337                 line.push(draw);                 // Draw.
338                 line.push(draw / move['num']);   // %Draw.
339
340                 if (move['num_elo'] >= 10) {
341                         // Elo.
342                         line.push(move['white_avg_elo']);
343                         line.push(move['black_avg_elo']);
344                         line.push(move['white_avg_elo'] - move['black_avg_elo']);
345                 } else {
346                         line.push(null);
347                         line.push(null);
348                         line.push(null);
349                 }
350
351                 line.push(move['corrected_win_ratio'] || null);
352                 lines.push(line);
353         }
354
355         lines.sort(function(a, b) { return direction * ( b[sort_by] - a[sort_by]); });
356
357         var tbl = $("#lines");
358         tbl.empty();
359
360         for (var i = 0; i < moves.length; ++i) {
361                 var line = lines[i];
362                 var tr = document.createElement("tr");
363
364                 if (line[0] === undefined) {
365                         $(tr).addClass("totals");
366                 } else if (transpose_only[i]) {
367                         $(tr).addClass("transponly");
368                 }
369
370                 for (var j = 0; j < line.length; ++j) {
371                         if (line[j] === null) {
372                                 add_td(tr, "");
373                         } else if (headings[j][1] == TYPE_MOVE) {
374                                 var td = document.createElement("td");
375                                 tr.appendChild(td);
376                                 $(td).addClass("move");
377                                 if (line[j] !== undefined) {
378                                         if (move_override % 2 == 0) {
379                                                 $(td).text(((move_override / 2) + 1) + ". ");
380                                         } else {
381                                                 $(td).text(((move_override / 2) + 0.5) + "…");
382                                         }
383                                 }
384
385                                 if (line[j] === '1-0' || line[j] === '1/2-1/2' || line[j] === '0-1') {
386                                         $(td).text($(td).text() + line[j]);
387                                 } else {
388                                         var move_a = document.createElement("a");
389                                         move_a.href = "javascript:make_move('" + line[j] + "')";
390                                         td.appendChild(move_a);
391                                         $(move_a).text(line[j]);
392                                 }
393                         } else if (headings[j][1] == TYPE_INTEGER) {
394                                 add_td(tr, line[j] || 0);
395                         } else if (headings[j][1] == TYPE_FLOAT) {
396                                 if (isNaN(line[j]) || !isFinite(line[j])) {
397                                         add_td(tr, '');
398                                 } else {
399                                         add_td(tr, line[j].toFixed(1));
400                                 }
401                         } else {
402                                 if (isNaN(line[j]) || !isFinite(line[j])) {
403                                         add_td(tr, '');
404                                 } else {
405                                         add_td(tr, format_fraction(line[j]));
406                                 }
407                         }
408                 }
409
410                 tbl.append(tr);
411         }
412 }
413
414 var find_total_games = function(moves) {
415         var total_num = 0;
416         for (var i = 0; i < moves.length; ++i) {
417                 var move = moves[i];
418                 if (move['move']) {
419                         total_num += move['white'];
420                         total_num += move['draw'];
421                         total_num += move['black'];
422                 }
423         }
424         return total_num;
425 }
426
427 var calc_move_derived_data = function(move, total_num, data, is_white) {
428         var white = move['white'];
429         var draw = move['draw'];
430         var black = move['black'];
431         var computer = move['computer'];
432
433         var num = white + draw + black;
434         move['num'] = num;
435         move['fraction'] = num / total_num;
436
437         // Adjust so that the human index is 50% overall.
438         var exp = Math.log(0.5) / Math.log(data['computer_games'] / data['total_games']);
439         move['human_index'] = 1.0 - Math.pow(computer / num, exp);
440
441         // Win%.
442         var white_win_ratio = (white + 0.5 * draw) / num;
443         var win_ratio = is_white ? white_win_ratio : 1.0 - white_win_ratio;
444         move['win_ratio'] = win_ratio;
445
446         if (move['num_elo'] >= 10) {
447                 // Win% corrected for Elo.
448                 var win_elo = -400.0 * Math.log(1.0 / white_win_ratio - 1.0) / Math.LN10;
449                 win_elo -= (move['white_avg_elo'] - move['black_avg_elo']);
450                 white_win_ratio = 1.0 / (1.0 + Math.pow(10, win_elo / -400.0));
451                 win_ratio = is_white ? white_win_ratio : 1.0 - white_win_ratio;
452                 move['corrected_win_ratio'] = win_ratio;
453         }
454 };
455
456 var set_includetransp = function(value) {
457         includetransp = value;
458         update();
459 }
460 window['set_includetransp'] = set_includetransp;
461
462 var set_flipboard = function(value) {
463         board.orientation(value ? 'black' : 'white');
464 }
465 window['set_flipboard'] = set_flipboard;
466
467 var set_practice = function(value) {
468         practice_mode = value;
469         if (practice_mode) {
470                 practice_side = (move_override % 2 == 0) ? 'W' : 'B';
471                 find_last_move_score();
472                 $("#stats").hide();
473                 $("#practiceoutput").show();
474                 document.getElementById("includetransp").checked = false;
475         } else {
476                 $("#stats").show();
477                 $("#practiceoutput").hide();
478         }
479         update();
480 }
481 window['set_practice'] = set_practice;
482
483 var make_move = function(move, do_update) {
484         var history = game.history({ verbose: true });
485         if (move_override < history.length && history[move_override].san == move) {
486                 // User effectively only moved forward in history.
487                 ++move_override;
488         } else {
489                 var moves = game.history();
490                 // Truncate the history if needed.
491                 if (move_override < moves.length) {
492                         game = new Chess();
493                         for (var i = 0; i < move_override; ++i) {
494                                 game.move(moves[i]);
495                         }
496                         fens.length = move_override;
497                 }
498                 game.move(move);
499                 fens.push(game.fen());
500                 ++move_override;
501         }
502
503         if (do_update !== false) {
504                 update();
505                 window.history.pushState(null, null, get_history_url());
506         }
507 }
508 window['make_move'] = make_move;
509
510 var prev_move = function() {
511         var moves_to_skip = practice_mode ? 2 : 1;
512         if (move_override >= moves_to_skip) {
513                 move_override -= moves_to_skip;
514                 update();
515                 window.history.replaceState(null, null, get_history_url());
516         }
517 }
518 window['prev_move'] = prev_move;
519
520 var next_move = function() {
521         if (move_override < game.history().length) {
522                 ++move_override;
523                 update();
524                 window.history.replaceState(null, null, get_history_url());
525         }
526 }
527 window['next_move'] = next_move;
528
529 var set_move = function(n, do_update) {
530         move_override = n;
531         if (do_update !== false) {
532                 update();
533                 window.history.replaceState(null, null, get_history_url());
534         }
535 }
536 window['set_move'] = set_move;
537
538 // almost all of this stuff comes from the chessboard.js example page
539 var onDragStart = function(source, piece, position, orientation) {
540         var pseudogame = new Chess(current_display_fen());
541         if (pseudogame.game_over() === true ||
542             (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
543             (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
544                 return false;
545         }
546
547         recommended_move = null;
548         get_best_dest(pseudogame, source, null, function(src, dest) {
549                 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
550                 if (dest !== null) {
551                         var squareEl = $('#board .square-' + dest);
552                         squareEl.addClass('highlight1-32417');
553                         recommended_move = [src, dest];
554                 }
555         });
556 }
557
558 var mousedownSquare = function(e) {
559         reverse_dragging_from = null;
560         var square = $(this).attr('data-square');
561
562         var pseudogame = new Chess(current_display_fen());
563         if (pseudogame.game_over() === true) {
564                 return;
565         }
566
567         // If the square is empty, or has a piece of the side not to move,
568         // we handle it. If not, normal piece dragging will take it.
569         var position = board.position();
570         if (!position.hasOwnProperty(square) ||
571             (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
572             (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
573                 reverse_dragging_from = square;
574                 get_best_dest(pseudogame, null, square, function(src, dest) {
575                         if (src !== null) {
576                                 var squareEl = $('#board .square-' + src);
577                                 squareEl.addClass('highlight1-32417');
578                                 squareEl = $('#board .square-' + dest);
579                                 squareEl.addClass('highlight1-32417');
580                                 recommended_move = [src, dest];
581                         }
582                 });
583         } else {
584                 recommended_src = null;
585         }
586 }
587
588 var mouseupSquare = function(e) {
589         if (reverse_dragging_from === null) {
590                 return;
591         }
592         var source = $(this).attr('data-square');
593         var target = reverse_dragging_from;
594         reverse_dragging_from = null;
595         if (onDrop(source, target) !== 'snapback') {
596                 onSnapEnd(source, target);
597         }
598         $("#board").find('.square-55d63').removeClass('highlight1-32417');
599 }
600
601 var get_best_dest = function(game, source, target, cb) {
602         var moves = game.moves({ verbose: true });
603         if (source !== null) {
604                 moves = moves.filter(function(move) { return move.from == source; });
605         }
606         if (target !== null) {
607                 moves = moves.filter(function(move) { return move.to == target; });
608         }
609         if (moves.length == 0) {
610                 cb(null, null);
611                 return;
612         }
613         if (moves.length == 1) {
614                 cb(moves[0].from, moves[0].to);
615                 return;
616         }
617
618         // More than one move. Ask the engine to disambiguate.
619         var uci_moves = moves.map(function(m) { return m.from + m.to; });
620         var when_engine_is_ready = function() {
621                 engine_running = true;
622                 stockfish.onmessage = function(event) {
623                         var res = event.data.match(/^bestmove (\S\S)(\S\S)/);
624                         if (res !== null) {
625                                 engine_running = false;
626                                 if (engine_replacement_callback !== null) {
627                                         // We are no longer interested in this query,
628                                         // so just discard it and call this other callback.
629                                         engine_replacement_callback();
630                                         engine_replacement_callback = null;
631                                 } else {
632                                         cb(res[1], res[2]);
633                                 }
634                         }
635                 };
636                 stockfish.postMessage("position fen " + game.fen());
637                 stockfish.postMessage("go depth 6 searchmoves " + uci_moves.join(" "));
638         };
639         if (engine_running) {
640                 engine_replacement_callback = when_engine_is_ready;
641         } else {
642                 when_engine_is_ready();
643         }
644 }
645
646 var onDrop = function(source, target) {
647         if (engine_running) {
648                 // Snap end before the engine came back.
649                 // Discard the result when it does.
650                 engine_replacement_callback = function() {};
651         }
652         if (source == target) {
653                 if (recommended_move === null) {
654                         return 'snapback';
655                 } else {
656                         // Accept the move. It will be changed in onSnapEnd.
657                         return;
658                 }
659         } else {
660                 // Suggestion not asked for.
661                 recommended_move = null;
662         }
663
664         // see if the move is legal
665         var pseudogame = new Chess(current_display_fen());
666         var move = pseudogame.move({
667                 from: source,
668                 to: target,
669                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
670         });
671
672         // illegal move
673         if (move === null) return 'snapback';
674 }
675
676 var onSnapEnd = function(source, target) {
677         if (source == target && recommended_move !== null) {
678                 source = recommended_move[0];
679                 target = recommended_move[1];
680         }
681         recommended_move = null;
682         var pseudogame = new Chess(current_display_fen());
683         var move = pseudogame.move({
684                 from: source,
685                 to: target,
686                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
687         });
688
689         make_move(pseudogame.history({ verbose: true }).pop().san);
690 }
691
692 var onpopstate = function() {
693         var old_moves = game.history({ verbose: true }).map(function(x) { return x.san; });
694         var new_moves = document.location.search.replace(/^\?/, "").split(",");
695
696         if (new_moves.length == 1 && new_moves[0] == "") {
697                 new_moves = [];
698         }
699
700         var num_shared_moves;
701         for (num_shared_moves = 0; num_shared_moves < Math.min(old_moves.length, new_moves.length); ++num_shared_moves) {
702                 if (old_moves[i] != new_moves[i]) {
703                         break;
704                 }
705         }
706
707         set_move(num_shared_moves, false);
708         for (var i = num_shared_moves; i < new_moves.length; ++i) {
709                 make_move(new_moves[i], false);
710         }
711         update();
712         window.history.replaceState(null, null, get_history_url());
713 }
714
715 var init = function() {
716         // Create board.
717         board = new window.ChessBoard('board', {
718                 draggable: true,
719                 position: 'start',
720                 onDragStart: onDragStart,
721                 onDrop: onDrop,
722                 onSnapEnd: onSnapEnd
723         });
724         $("#board").on('mousedown', '.square-55d63', mousedownSquare);
725         $("#board").on('mouseup', '.square-55d63', mouseupSquare);
726
727         window.onpopstate = onpopstate;
728         onpopstate();
729         set_practice(false);
730
731         $(window).keyup(function(event) {
732                 if (event.which == 39) {
733                         next_move();
734                 } else if (event.which == 37) {
735                         prev_move();
736                 }
737         });
738
739         // Seemingly the web worker is not started before we send it a message.
740         stockfish.postMessage("uci");
741 }
742
743 $(document).ready(init);
744
745 })();