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