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