-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterface.js
1010 lines (828 loc) · 28.9 KB
/
interface.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// A minimal UI for Sudoku, an A/B experiment lab for 6.831.
// This file intentionally exposes its names to global scope to
// simplify testing, so you can directly manipulate the state
// from the console. For example, set the selected number:
// setcurnumber(3)
// or retrieve, modify, and set the state:
// state=currentstate(); state.answer[0]=3+1; commitstate(state);
/////////////////////////////////////////////////////////////////////////////
// Constants and global state
/////////////////////////////////////////////////////////////////////////////
// Initialize algorithm.js: we use a 2x2x2x2-sized sudoku game.
// This sets up the constants Sudoku.N = 4, Sudoku.S = 16, Sudoku.B = 2.
Sudoku.init(2);
var DISABLE_CONTEXTMENU = false; // Enables context menus.
var USE_LOCAL_STORAGE = true; // Enables saving state to localStorage.
var SYMMETRIC_PUZZLES = false; // Allows asymmetric puzzles.
// This app uses url-based state to support deep linking. That means
// almost all the application state is stored in the URL, which allows
// the user to bookmark the page to save and share the screen they see.
// It also allows browser's "back" button to work for undo.
//
// The url, therefore, is the main global state variable:
//
// state = currentstate(); will read the current state from the URL.
// commitstate(state); will save state to the URL (and localStorage),
//
// If you remember (e.g., log) the URL string, you will be able to
// recreate most of the game state by linking back to it.
//
// The only UI state which is not saved in the hash are the variables
// below having to do with transient visual effects such as selection,
// focus, and the visible timer.
var starttime = (new Date).getTime(); // t=0 for the visible timer.
var runningtime = false; // true if the timer is running.
var visiblefocus = null; // location of a blue focus rect.
var curnumber = null; // currently selected number.
/////////////////////////////////////////////////////////////////////////////
// Page and Game Set-up
/////////////////////////////////////////////////////////////////////////////
// The main entry point: runs when the page is finished loading.
$(function () {
var sinit;
// Generate static HTML such as the number palette.
setup_screen();
if (window.location.hash && (sinit = currentstate()).seed) {
// If the URL contains game state, adjust the time and log an event.
starttime = (new Date).getTime() - sinit.elapsed;
$(document).trigger('log', ['linkgame', { seed: sinit.seed }]);
saveseed(sinit.seed);
} else {
// For a bare URL, modify the url to have a game (generated or loaded).
setupgame(0);
}
// Render the current state of the game based on the URL.
redraw();
// Re-render whenever the URL hash changes.
$(window).bind('hashchange', function () {
redraw();
});
// Set the selected number to the 'eraser'.
setcurnumber(0);
// Show the instructions to the user
if (currentstate().seed == 1) {
showpopup('#intro');
}
});
// This function generates or loads (from localStorage) puzzle #X,
// and makes it the current puzzle.
function setupgame(seed) {
// If no seed is given, remember the last seed or take the default 1.
if (!seed) { seed = loadseed(); }
// Log an event for the new game.
$(document).trigger('log', ['setupgame', { seed: seed }]);
// Remember this is the last seed played.
saveseed(seed);
// If there is already a saved game for this seed, load it.
if (loadgame(storagename(seed))) { return; }
// Otherwise generate one: make it quickly, and make it symmetric.
var quick = false;
var puzzle = Sudoku.makepuzzle(seed, quick, SYMMETRIC_PUZZLES);
// Remember the moment this game was created as gentime.
var gentime = (new Date).getTime();
// Commit the game state to the URL.
commitstate({
puzzle: puzzle,
seed: seed,
answer: [],
work: [],
elapsed: 0,
gentime: gentime,
});
}
/////////////////////////////////////////////////////////////////////////////
// URL hash state management
/////////////////////////////////////////////////////////////////////////////
// Retrieve current state from URL.
function currentstate() {
return decodeboardstate(gethashdata());
}
// Save state in URL and localstorage.
function commitstate(state) {
// Automatically update elapsed time unless already solved.
var now = (new Date).getTime();
if (state.gentime > starttime) {
starttime = state.gentime;
}
if (!victorious(state) || !victorious(currentstate())) {
state.elapsed = (now - starttime);
}
// Update the url (may trigger a redraw).
sethashdata(encodeboardstate(state));
// Save the state in localStorage also.
savestate(storagename(state.seed), state);
hidepopups();
checkUpdateOnEvent();
}
// Parses a url-parameter-style string after the current URL hash parts.
function gethashdata() {
var result = {};
window.location.hash.replace(/^\W*/, '').split('&').forEach(function (pair) {
if (pair === '') return;
var parts = pair.split('=');
result[parts[0]] = parts[1] && decodeURIComponent(
parts[1].replace(/\+/g, ' '));
});
return result;
}
// Sets a url-parameter-style string as the hash part of a url.
function sethashdata(data) {
if (!window.location.hash && window.history.replaceState) {
// Overwrite a hashless history entry.
window.history.replaceState(null, null, '#' + $.param(data));
} else {
// If there is already a hash, create a history entry as usual.
window.location.hash = $.param(data);
}
}
/////////////////////////////////////////////////////////////////////////////
// State serialization
/////////////////////////////////////////////////////////////////////////////
// Encodes the game state as a set of scalars, suitable for storing in a URL.
function encodeboardstate(state) {
// puzzle: a list of N^2 nulls and numbers from 0-(N-1) for given numbers.
var result = {
puzzle: encodepuzzle(state.puzzle)
}
// answer: a list of N^2 nulls and numbers from 0-(N-1) for written numbers.
if ('answer' in state) { result.answer = encodepuzzle(state.answer); }
// work: a list of N^2 bitmasks from 0-(2^N-1) for small numbers.
if ('work' in state) { result.work = arraytobase64(state.work); }
// seed: the puzzle number; 1 is the first page puzzle.
if ('seed' in state) { result.seed = state.seed; }
// gentime: when the puzzle was created, unix time milliseconds.
if ('gentime' in state) { result.gentime = state.gentime; }
// elapsed: number of milliseconds the user has actively spent on the puzzle.
if ('elapsed' in state) { result.elapsed = state.elapsed; }
if ('currFocus' in state) { result.currFocus = state.currFocus; }
// size: 2 for 4x4 boards, 3 for 9x9 boards.
result.size = Sudoku.B;
return result;
}
// Decodes game state from a set of scalars, e.g., from a URL.
function decodeboardstate(data) {
if ('size' in data) {
// Do not load state from an incompatible size.
if (Sudoku.B != data.size) {
data = {}
}
}
var puzzle = decodepuzzle('puzzle' in data ? data.puzzle : '');
var answer = decodepuzzle('answer' in data ? data.answer : '');
var work = base64toarray('work' in data ? data.work : '');
var result = {
puzzle: puzzle,
answer: answer,
work: work
};
if ('seed' in data) { result.seed = data.seed; }
if ('gentime' in data) { result.gentime = data.gentime; }
if ('currFocus' in data) { result.currFocus = data.currFocus; }
if ('elapsed' in data) { result.elapsed = data.elapsed; }
return result;
}
/////////////////////////////////////////////////////////////////////////////
// Render game state
/////////////////////////////////////////////////////////////////////////////
// Redraws the sudoku board. If 'pos' is passed, only that square is drawn.
function redraw(givenstate, pos) {
var state = givenstate ? givenstate : currentstate();
var startpos = 0;
var endpos = Sudoku.S;
if (typeof pos != 'undefined') { startpos = pos; endpos = pos + 1; }
var puzzle = state.puzzle;
var answer = state.answer;
var work = state.work;
var victory = victorious(state);
var seed = state.seed;
// Set the title of the puzzle.
var title = seed ? ('Puzzle #' + seed) : 'Custom Puzzle';
$('#grade').html(title);
// Show appropriate victory UI.
if (victory) {
runningtime = false;
$('.timer').text(formatelapsed(state.elapsed));
// here victory
} else {
$('#victory').css('display', 'none');
}
// Render timer UI
$('.progress').css('display', victory ? 'none' : 'inline');
$('.finished').css('display', victory ? 'inline' : 'none');
if (!victory) {
$('.timer').text(formatelapsed((new Date).getTime() - starttime));
}
// Hide the timer for puzzle #1.
$('.timescore').css({
visibility: state.seed == 1 && !victory
? 'hidden' : 'visible'
});
// If the timer should be running but it is not, get it going.
if (!victory && !runningtime) {
runningtime = true;
updatetime();
}
// Run through the sudoku board and render each square.
for (var j = startpos; j < endpos; j++) {
if (puzzle[j] !== null) {
// Render a given-number in bold from the "puzzle" state.
$("#sn" + j).attr('class', 'sudoku-given').html(puzzle[j] + 1);
} else {
if (answer[j] !== null || work[j] == 0) {
// Render an answered-number in pencil from the "answer" state.
$("#sn" + j).attr('class', 'sudoku-answer').html(
answer[j] === null ? ' ' : handglyph(answer[j] + 1));
} else {
// Render a grid of mini-numbers from the "work" state.
var text = '<table class="sudoku-work-table">';
for (var n = 0; n < Sudoku.N; n++) {
if (n % Sudoku.B == 0) { text += '<tr>'; }
text += '<td><div>' +
((work[j] & (1 << n)) ? handglyph(n + 1) : ' ') +
'</div></td>';
if (n % Sudoku.B == Sudoku.B - 1) { text += '</tr>'; }
}
text += '</table>'
$("#sn" + j).attr('class', 'sudoku-work').html(text);
}
}
}
}
// Makes a handwritten number, handling a glyph substitution.
function handglyph(text) {
// The "1" doesn't look as one-like as the capital-I in Handlee.
if ('' + text === '1') { return 'I'; }
return text;
}
/////////////////////////////////////////////////////////////////////////////
// Number palette interactions
/////////////////////////////////////////////////////////////////////////////
// We always use "on" so we can bind events to elements which do not exist
// at the beginning of the program when we are setting up binding.
//
// Read http://api.jquery.com/on/#direct-and-delegated-events
// to understand why we are doing this.
// Clicks in the number palette.
$(document).on('click', 'td.numberkey-cell', function (ev) {
console.log("number clicked");
var num = parseInt($(this).attr('id').substr(2));
setcurnumber(num);
ev.stopPropagation();
});
// keyboard number input only
$(document).keypress(function (e) {
let state = currentstate();
//let cell = document.getElementById("sc" + state.currFocus);
let pos = parseInt(state.currFocus);
if (state.puzzle[pos] !== null) return;
if (e.which == 49) {
setcurnumber(1);
state.answer[pos] = 0;
state.work[pos] = 0;
}
else if (e.which == 50) {
setcurnumber(2);
state.answer[pos] = 1;
state.work[pos] = 1;
}
else if (e.which == 51) {
setcurnumber(3);
state.answer[pos] = 2;
state.work[pos] = 2;
}
else if (e.which == 52) {
setcurnumber(4);
state.answer[pos] = 3;
state.work[pos] = 3;
}
// Immediate redraw of just the keyed cell.
redraw(state, pos);
// Commit state after a timeout
setTimeout(function () {
commitstate(state);
}, 0);
$(document).trigger('log', ['keyboard_input', {
cellNumber : state.currFocus,
inputNumber: state.answer[pos] + 1
}]);
});
document.onkeydown = function (e) {
let state = currentstate();
let cell = null;
let allCells = document.getElementsByClassName("sudoku-cell");
function clearFocus() {
for (let i = 0; i < allCells.length; i++) {
let border = $(allCells[i]).find('div.sudoku-border');
border.toggleClass('focus', false);
}
}
let oldState = state.currFocus;
let movement = e.key;
switch (e.key) {
case 'ArrowUp':
// up arrow
if (parseInt(state.currFocus) >= 4) {
clearFocus();
cell = document.getElementById("sc" + (parseInt(state.currFocus) - 4));
state.currFocus = parseInt(state.currFocus) - 4;
}
break;
case 'ArrowDown':
// down arrow
if (parseInt(state.currFocus) <= 11) {
clearFocus();
cell = document.getElementById("sc" + (parseInt(state.currFocus) + 4));
state.currFocus = parseInt(state.currFocus) + 4;
}
break;
case 'ArrowLeft':
// left arrow
if (!(parseInt(state.currFocus) == 0 || parseInt(state.currFocus) == 4 || parseInt(state.currFocus) == 8 || parseInt(state.currFocus) == 12)) {
clearFocus();
cell = document.getElementById("sc" + (parseInt(state.currFocus) - 1));
state.currFocus = parseInt(state.currFocus) - 1;
}
break;
case 'ArrowRight':
// right arrow
if (!(parseInt(state.currFocus) == 3 || parseInt(state.currFocus) == 7 || parseInt(state.currFocus) == 11 || parseInt(state.currFocus) == 15)) {
clearFocus();
cell = document.getElementById("sc" + (parseInt(state.currFocus) + 1));
state.currFocus = parseInt(state.currFocus) + 1;
}
break;
case 'Delete':
state.answer[parseInt(state.currFocus)] = null;
state.work[parseInt(state.currFocus)] = 0;
break;
}
if (cell) {
$(cell).find('div.sudoku-border').toggleClass('focus', true);
}
// state.currFocus = parseInt(this.id.substring(2));
commitstate(state);
$(document).trigger('log', ['Arrow_movement', {
movement : movement,
previousState : oldState,
newState : state.currFocus
}]);
};
// Clicks outside other regions set the number palette to 'eraser'.
$(document).on('click', function (ev) {
if (!$(ev.target).is('a,input')) {
setcurnumber(0);
}
hidepopups();
});
/////////////////////////////////////////////////////////////////////////////
// Suoku board interactions
/////////////////////////////////////////////////////////////////////////////
// Mouse entering a sudoku cell sets visible focus.
$(document).on('mouseenter', 'td.sudoku-cell', function (ev) {
let state = currentstate();
state.currFocus = parseInt(this.id.substring(2));
let allCells = document.getElementsByClassName("sudoku-cell");
for (let i = 0; i < allCells.length; i++) {
let border = $(allCells[i]).find('div.sudoku-border');
border.toggleClass('focus', false);
}
console.log();
commitstate(state);
$(this).find('div.sudoku-border').toggleClass('focus', true);
setvisiblefocus(this);
ev.stopPropagation();
});
// Mouse leaving a sudoku cell sets visible focus.
$(document).on('mouseleave', 'td.sudoku-cell', function (ev) {
// $(this).find('div.sudoku-border').toggleClass('focus', false);
// setvisiblefocus(null);
//ev.stopPropagation();
});
// Defeats right-click context menu.
if (DISABLE_CONTEXTMENU) {
$(document).on('contextmenu', function (ev) {
ev.preventDefault();
ev.stopPropagation();
});
}
// Handle sudoku cell clicks on mousedown.
$(document).on('mousedown', 'td.sudoku-cell', function (ev) {
ev.preventDefault();
hidepopups();
var pos = parseInt($(this).attr('id').substr(2));
var state = currentstate();
// Ignore the click if the square is given in the puzzle.
if (state.puzzle[pos] !== null) return;
// Internally we store "1" as "0".
var num = curnumber - 1;
if (num == -1) {
// Erase this square.
state.answer[pos] = null;
state.work[pos] = 0;
} else if (isalt(ev)) {
// Undiscoverable: write small numbers if ctrl is pressed.
state.answer[pos] = null;
state.work[pos] ^= (1 << num);
} else {
// Set the number
state.answer[pos] = num;
state.work[pos] = 0;
// Update elapsed time immediately, to avoid flicker upon victory.
if (victorious(state)) {
var now = (new Date).getTime();
if (state.gentime > starttime) {
starttime = state.gentime;
}
state.elapsed = (now - starttime);
// Log the exact moment, along with the elapsed time in ms.
$(document).trigger('log', ['victory', {
elapsed: state.elapsed,
seed: currentstate().seed
}]);
}
}
// Immediate redraw of just the keyed cell.
redraw(state, pos);
// Clear the current number.
setcurnumber(0);
// Commit state after a timeout
setTimeout(function () {
commitstate(state);
}, 0);
});
// Defeats normal sudoku-cell click-handling on mouseup.
$(document).on('click', 'td.sudoku-cell', function (ev) {
ev.stopPropagation();
});
// Detects if a modifier key is pressed.
function isalt(ev) {
return (ev.which == 3) || (ev.ctrlKey) || (ev.shiftKey);
}
/////////////////////////////////////////////////////////////////////////////
// Next/Previous game handling
/////////////////////////////////////////////////////////////////////////////
// Handles the next button.
$(document).on('click', '#nextbutton', function (ev) {
flippage(1);
});
// Handles the previous button.
$(document).on('click', '#prevbutton', function (ev) {
flippage(-1);
});
// Increments or decrements the seed, then sets up that game.
function flippage(skip) {
var state = currentstate();
var seed = parseInt(state.seed);
if (seed >= 1 && seed <= 1e9) {
savestate(storagename(seed), state);
}
seed += skip;
if (!(seed >= 1 && seed <= 1e9)) {
seed = 1;
}
setupgame(seed);
}
/////////////////////////////////////////////////////////////////////////////
// Clear/Check game handling
/////////////////////////////////////////////////////////////////////////////
// Clear the answers.
$(document).on('click', '#clearbutton', function (ev) {
hidepopups();
var state = currentstate();
var cleared = {
puzzle: state.puzzle, seed: state.seed,
answer: [], work: [], gentime: (new Date).getTime()
};
commitstate(cleared);
});
function checkUpdateOnEvent(){
hidepopups();
var state = currentstate();
var sofar = boardsofar(state);
let boardStatus = 'start';
const victory = '#victory';
const ok = '#ok';
const errors = '#errors';
// Check for conflicts.
var conflicts = SudokuHint.conflicts(sofar);
if (conflicts.length == 0) {
// We are all good so far - and maybe have a win.
boardStatus = countfilled(sofar) == Sudoku.S ? victory : ok;
showpopup(boardStatus);
} else {
// Oops - there is some mistake.
boardStatus = errors;
showpopup(errors);
}
$(document).trigger('log', ['current_board_status', {
boardStates : boardStatus,
timePassed : boardStatus == '#victory' ? formatelapsed((new Date).getTime() - starttime) : formatelapsed(state.elapsed)
}]);
// $('.timer').text(formatelapsed(state.elapsed));
// // here victory
// } else {
// $('#victory').css('display', 'none');
// }
// // Render timer UI
// $('.progress').css('display', victory ? 'none' : 'inline');
// $('.finished').css('display', victory ? 'inline' : 'none');
// if (!victory) {
// $('.timer').text(formatelapsed((new Date).getTime() - starttime));
}
// Depressing the "check" button.
function checkUpdate(ev){
hidepopups();
var state = currentstate();
var sofar = boardsofar(state);
// Check for conflicts.
var conflicts = SudokuHint.conflicts(sofar);
if (conflicts.length == 0) {
// We are all good so far - and maybe have a win.
showpopup(countfilled(sofar) == Sudoku.S ? '#victory' : '#ok');
} else {
// Oops - there is some mistake.
showpopup('#errors');
}
ev.stopPropagation();
}
$(document).on('mousedown touchstart', '#checkbutton', function (ev) {
// hidepopups();
// var state = currentstate();
// var sofar = boardsofar(state);
// // Check for conflicts.
// var conflicts = SudokuHint.conflicts(sofar);
// if (conflicts.length == 0) {
// // We are all good so far - and maybe have a win.
// showpopup(countfilled(sofar) == Sudoku.S ? '#victory' : '#ok');
// } else {
// // Oops - there is some mistake.
// showpopup('#errors');
// }
// ev.stopPropagation();
console.log("ev");
console.log(ev);
checkUpdate(ev)
});
// Releasing the "check" button.
$(document).on('mouseup mouseleave touchend', '#checkbutton', function () {
if ($('#victory').css('display') != 'none') {
return;
}
hidepopups();
var state = currentstate();
redraw(state);
});
// Defeat normal click handliing for the "check" button.
$(document).on('click', '#checkbutton', function (ev) {
if ($('#victory').css('display') != 'none') {
ev.stopPropagation();
}
});
/////////////////////////////////////////////////////////////////////////////
// Transient UI: popups, focus, selection, timer
/////////////////////////////////////////////////////////////////////////////
// Move the focus rectangle.
function setvisiblefocus(kf) {
if (visiblefocus !== null) {
$(visiblefocus).find('div.sudoku-border').toggleClass('focus', false);
}
visiblefocus = kf;
if (visiblefocus !== null) {
$(visiblefocus).find('div.sudoku-border').toggleClass('focus', true);
}
}
// Set the currently-selected number. Zero is the eraser.
function setcurnumber(num) {
$('td.numberkey-cell').toggleClass('selected', false);
$('#nk' + num).toggleClass('selected', true);
curnumber = num;
}
// Dismiss popup messages.
function hidepopups() {
$('div.sudoku-popup').css('display', 'none');
}
function hidepopupsStatus() {
$('div.sudoku-popup').css('display', 'none');
}
// Unhide the popup with a given id.
function showpopup(id) {
var velt = $(id);
var telt = $('table.sudoku');
var position = telt.offset();
position.left += (telt.outerWidth() - velt.outerWidth()) / 2;
position.top += (telt.outerHeight() - velt.outerHeight()) / 3;
velt.css({
display: 'block',
left: position.left,
top: position.top
});
}
// Format timer text.
function formatelapsed(elapsed) {
if (!(elapsed >= 0)) { return '-'; }
var seconds = Math.floor(elapsed / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
seconds -= minutes * 60;
minutes -= hours * 60;
var formatted = minutes + ':' + (seconds < 10 ? '0' : '') + seconds;
if (hours > 0) {
formattted = hours + ':' + (minutes < 10 ? '0' : '') + formatted;
}
return formatted;
}
// The countdown timer redraws itself using this function.
function updatetime() {
if (runningtime && $('.timer').is(':visible')) {
$('.timer').text(formatelapsed((new Date).getTime() - starttime));
setTimeout(updatetime,
1001 - (((new Date).getTime() - starttime) % 1000));
} else {
runningtime = false;
}
}
/////////////////////////////////////////////////////////////////////////////
// Win conditions
/////////////////////////////////////////////////////////////////////////////
// Returns an array with one entry per puzzle square, containing
// null for any unfilled square, and a number from 0-(N-1) for any
// square that was filled by the user or given as part of the puzzle.
function boardsofar(state) {
var sofar = state.puzzle.slice();
for (var j = 0; j < Sudoku.S; j++) {
if (state.answer[j] !== null) sofar[j] = state.answer[j];
}
return sofar;
}
// Counts the number of squares that have been filled in, total.
function countfilled(board) {
var count = 0;
for (var j = 0; j < Sudoku.S; j++) {
if (board[j] !== null) count += 1;
}
return count;
}
// Checks for victory.
function victorious(state) {
var sofar = boardsofar(state);
if (countfilled(sofar) != Sudoku.S) return false;
if (SudokuHint.conflicts(sofar).length != 0) return false;
return true;
}
/////////////////////////////////////////////////////////////////////////////
// localStorage handling
/////////////////////////////////////////////////////////////////////////////
// The localStorage key used for this game.
function storagename(seed) {
return 'sudoku' + location.pathname.replace(/[\W]+/g, '-') + '-' + seed;
}
// Tries to load a saved game from a localStorage key, then commits
// the state to the URL (triggering a re-render). False if not found.
function loadgame(name) {
var state = loadstate(name);
if (!state) return false;
if (!state.puzzle || !state.puzzle.length) return false;
if ('elapsed' in state) {
starttime = (new Date).getTime() - state.elapsed;
}
commitstate(state);
return true;
}
// Loads JSON data from localStorage, or null if not found.
function loadstate(name) {
if (!USE_LOCAL_STORAGE ||
!('localStorage' in window) || !('JSON' in window) ||
!(name in window.localStorage)) {
return null;
}
var data = localStorage[name];
var state = JSON.parse(data);
return state;
}
// Saves the passed data to a localStorage key as JSON.
function savestate(name, state) {
if (!USE_LOCAL_STORAGE ||
!('localStorage' in window) || !('JSON' in window)) {
return;
}
localStorage[name] = JSON.stringify(state);
}
// Remembers the last saved seed.
function loadseed() {
return loadstate(storagename('seed')) || 1;
}
// Saves the seed being played.
function saveseed(seed) {
savestate(storagename('seed'), seed);
}
/////////////////////////////////////////////////////////////////////////////
// Simple string serialization for number arrays
/////////////////////////////////////////////////////////////////////////////
// Encodes an sparse array of small integers as a short string.
function encodepuzzle(puzzle) {
if (!puzzle) return '';
var result = [];
for (var j = 0; j < puzzle.length; j++) {
result.push(puzzle[j] === null ? 0 : puzzle[j] + 1);
}
return result.join('');
}
// Decodes an array that was encoded by encodepuzzle.
function decodepuzzle(str) {
var puzzle = [];
var c = 0;
for (var j = 0; j < str.length; j++) {
var num = str.charCodeAt(j) - '0'.charCodeAt(0);
puzzle.push(num == 0 ? null : (num - 1));
}
for (; j < Sudoku.S; j++) {
puzzle.push(null);
}
return puzzle;
}
// Encodes a nubmer less that 4096 in base64.
function shorttobase64(int18) {
return base64chars[(int18 >> 6) & 63] +
base64chars[int18 & 63];
}
// Decodes a nubmer less that 4096 in base64.
function base64toshort(base64, index) {
return (base64chars.indexOf(base64.charAt(index)) << 6) +
base64chars.indexOf(base64.charAt(index + 1));
}
// Encodes an array of numbers less than 4096 in base64, skipping end zeros.
function arraytobase64(numbers) {
var result = [];
for (var end = numbers.length; end > 0; end--) {
if (numbers[end - 1]) break;
}
for (var j = 0; j < end; j++) {
result.push(shorttobase64(numbers[j]));
}
return result.join('');
}
// Decodes an array of numbers less than 4096 in base64, padding end zeros.
function base64toarray(base64) {
var result = [];
for (var j = 0; j + 1 < base64.length; j += 2) {
result.push(base64toshort(base64, j));
}
for (j /= 2; j < Sudoku.S; j++) {
result.push(0);
}
return result;
}
// Constant to set up for use by encoders above.
var base64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz" +
"0123456789" +
"-_";
/////////////////////////////////////////////////////////////////////////////
// Static HTML construction.
/////////////////////////////////////////////////////////////////////////////
// Generates HTML for a not-filled-in NxN Sudoku table.
// The function redraw() will fill this in based on the current state.
function boardhtml() {
var text = "<table class=sudoku id=grid cellpadding=1px>\n";
text += "<tr><td colspan=13 class=sudoku-border>" +
"<img class=sudoku-border></td></tr>\n";
for (var y = 0; y < Sudoku.N; y++) {
text += "<tr>"
text += "<td class=sudoku-border></td>"
for (var x = 0; x < Sudoku.N; x++) {
var c = y * Sudoku.N + x;
text += "<td class=sudoku-cell id=sc" + c + ">" +
"<div class=sudoku-border>" +
"<div class=sudoku-number id=sn" + c + ">" +
" </div></div>";
if (x % Sudoku.B == Sudoku.B - 1) text += "<td class=sudoku-border></td>";
}
text += "</tr>\n";
if (y % Sudoku.B == Sudoku.B - 1) {
text += "<tr><td colspan=13 class=sudoku-border>" +
"<img class=sudoku-border></td></tr>\n";
}
}
text += "<tr><td colspan=" + Sudoku.N + " id=caption></td></tr>\n";
text += "</table>\n";
return text;
}
// Generates HTML for the number palette from 1 to N, plus an eraser.
function numberkeyhtml() {
var result = '<table class=numberkey>';
for (var j = 1; j <= Sudoku.N; ++j) {
result += '<tr><td class=numberkey-cell id=nk' + j + '>' +
'<div class="sudoku-answer nk' + j + '">' +
handglyph(j) + '</div></td></tr>';
}
result += '<tr><td class=numberkey-cell id=nk0>' +
'<div class="eraser nk0">' +
'</div></td></tr>';
result += '</table>';
return result;