-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1201 lines (1099 loc) · 43 KB
/
script.js
File metadata and controls
1201 lines (1099 loc) · 43 KB
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
(() => {
const STORAGE_KEY = 'shandoku-wife-edition-save-v1';
const THEME_KEY = 'shandoku-wife-edition-theme-v1';
const GRID_SIZE = 9;
const TOTAL_CELLS = GRID_SIZE * GRID_SIZE;
const HISTORY_LIMIT = 200;
const RIFT_COOLDOWN_MS = 12000;
const RIFT_STATUS_DELAY_MS = 950;
const RIFT_STATUS_DELAY_REDUCED_MOTION_MS = 500;
const RIFT_EVALUATE_DEBOUNCE_MS = 140;
const RIFT_NON_CONFLICT_CHECK_INTERVAL = 5;
const testParams = new URLSearchParams(window.location.search);
const isLocalHost = ['localhost','127.0.0.1','0.0.0.0'].includes(window.location.hostname);
const testHooksEnabled = testParams.get('testHooks') === '1' && isLocalHost;
const e2eModeEnabled = testParams.get('e2e') === '1' && (isLocalHost || navigator.webdriver);
const TEST_MODE = testHooksEnabled || e2eModeEnabled;
const boardEl = document.getElementById('board');
const statusEl = document.getElementById('status');
const difficultyEl = document.getElementById('difficulty');
const timeStat = document.getElementById('timeStat');
const errorStat = document.getElementById('errorStat');
const progressBar = document.getElementById('progressBar');
const notesModeBtn = document.getElementById('notesModeBtn');
const autoNotesBtn = document.getElementById('autoNotesBtn');
const themeBtn = document.getElementById('themeBtn');
const boardShellEl = document.querySelector('.board-shell');
const riftModal = document.getElementById('riftModal');
const riftTitleEl = document.getElementById('riftTitle');
const riftBodyEl = document.getElementById('riftBody');
const riftBackdrop = document.getElementById('riftBackdrop');
const riftReturnBtn = document.getElementById('riftReturnBtn');
const riftRestoreBtn = document.getElementById('riftRestoreBtn');
const riftFreshBtn = document.getElementById('riftFreshBtn');
const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
let selected = null;
let notesMode = false;
let autoCleanup = true;
let elapsed = 0;
let timerId = null;
let history = [];
let future = [];
let touchStart = null;
let startingGrid = null;
let grid = null;
let notes = null;
let lastSolvableSnapshot = null;
let boardWasSolvable = true;
let statusSequenceId = 0;
let interactionLocked = false;
let riftEvalTimer = null;
let movesSinceSolvabilityCheck = 0;
let riftState = {
active:false,
nodes:[],
hasTriggered:false,
cooldownUntil:0,
copyKey:'pattern'
};
let riftSequenceRunning = false;
let lastFocusedBeforeRiftModal = null;
const riftExtensionHooks = {
onTrigger:[],
onResolve:[]
};
const riftCopySets = {
pattern:{
title:'A seam in the pattern',
lines:['This puzzle cannot exist.','Looking for a way through…','Something opened.'],
fragment:'Not every wrong turn is failure. Some of them are doors.'
},
geometry:{
title:'The shape bent',
lines:['The grid lost coherence.','Re-threading the path…','A fracture node remains.'],
fragment:'You pushed the puzzle past logic, and it answered.'
},
lantern:{
title:'Between answers',
lines:['The pattern broke cleanly.','Listening for a softer route…','A quiet door is available.'],
fragment:'Some detours are where the gift is waiting.'
}
};
// ── Helpers ──────────────────────────────────────────────────────────────
function cloneGrid(g){ return g.map(row => row.slice()); }
function cloneNotes(src){ return src.map(row => row.map(s => new Set([...s]))); }
function vibrate(ms){ if(navigator.vibrate) navigator.vibrate(ms); }
// Returns candidates for a given board state (does not use global grid)
function candidatesForBoard(board, r, c){
if(board[r][c] !== 0) return [];
const used = new Set();
for(let i=0;i<GRID_SIZE;i++){
if(board[r][i]) used.add(board[r][i]);
if(board[i][c]) used.add(board[i][c]);
}
const br = Math.floor(r/3)*3, bc = Math.floor(c/3)*3;
for(let rr=br;rr<br+3;rr++) for(let cc=bc;cc<bc+3;cc++) if(board[rr][cc]) used.add(board[rr][cc]);
const out = [];
for(let n=1;n<=GRID_SIZE;n++) if(!used.has(n)) out.push(n);
return out;
}
// Candidates for current global grid
function candidatesFor(r, c){ return candidatesForBoard(grid, r, c); }
function countFilled(){
let n = 0;
for(let r=0;r<GRID_SIZE;r++) for(let c=0;c<GRID_SIZE;c++) if(grid[r][c]) n++;
return n;
}
function hasConflict(r, c){
const v = grid[r][c];
if(!v) return false;
for(let i=0;i<GRID_SIZE;i++) if(i!==c && grid[r][i]===v) return true;
for(let i=0;i<GRID_SIZE;i++) if(i!==r && grid[i][c]===v) return true;
const br=Math.floor(r/3)*3, bc=Math.floor(c/3)*3;
for(let rr=br;rr<br+3;rr++) for(let cc=bc;cc<bc+3;cc++) if((rr!==r||cc!==c)&&grid[rr][cc]===v) return true;
return false;
}
function countErrors(){
let n=0;
for(let r=0;r<GRID_SIZE;r++) for(let c=0;c<GRID_SIZE;c++) if(hasConflict(r,c)) n++;
return n;
}
function isSolved(){ return countFilled()===TOTAL_CELLS && countErrors()===0; }
function hasImmediateContradiction(board){
function hasDuplicate(values){
const seen=new Set();
for(const v of values){
if(!v) continue;
if(seen.has(v)) return true;
seen.add(v);
}
return false;
}
for(let r=0;r<GRID_SIZE;r++) if(hasDuplicate(board[r])) return true;
for(let c=0;c<GRID_SIZE;c++){
const column=Array.from({length:GRID_SIZE},(_,r)=>board[r][c]);
if(hasDuplicate(column)) return true;
}
for(let br=0;br<GRID_SIZE;br+=3){
for(let bc=0;bc<GRID_SIZE;bc+=3){
const block=[];
for(let r=br;r<br+3;r++){
for(let c=bc;c<bc+3;c++){
block.push(board[r][c]);
}
}
if(hasDuplicate(block)) return true;
}
}
return false;
}
function hasAnySolution(board){
if(hasImmediateContradiction(board)) return false;
const b=cloneGrid(board);
function search(){
let best=null;
for(let r=0;r<GRID_SIZE;r++){
for(let c=0;c<GRID_SIZE;c++){
if(b[r][c]===0){
const cand=candidatesForBoard(b,r,c);
if(cand.length===0) return false;
if(!best||cand.length<best.cand.length) best={r,c,cand};
}
}
}
if(!best) return true;
for(const n of best.cand){
b[best.r][best.c]=n;
if(search()) return true;
b[best.r][best.c]=0;
}
return false;
}
return search();
}
function isRelated(r, c){
if(!selected || (selected.r===r && selected.c===c)) return false;
return selected.r===r || selected.c===c ||
(Math.floor(selected.r/3)===Math.floor(r/3) && Math.floor(selected.c/3)===Math.floor(c/3));
}
function getPersistedElapsedTime(data){
return data?.elapsed ?? data?.timeElapsed ?? data?.timer ?? data?.timeSeconds;
}
function normalizeElapsed(value){
const parsed=Number(value);
if(!Number.isFinite(parsed) || parsed<0) return 0;
return Math.floor(parsed);
}
function normalizeBoolean(value, fallback=false){
if(typeof value === 'boolean') return value;
if(typeof value === 'string'){
const normalized=value.trim().toLowerCase();
if(normalized==='true') return true;
if(normalized==='false') return false;
}
if(value==null) return fallback;
return Boolean(value);
}
function formatTime(t){
const normalized=normalizeElapsed(t);
return `${String(Math.floor(normalized/60)).padStart(2,'0')}:${String(normalized%60).padStart(2,'0')}`;
}
// ── Notes ────────────────────────────────────────────────────────────────
function fillNotesAll(){
for(let r=0;r<GRID_SIZE;r++)
for(let c=0;c<GRID_SIZE;c++)
if(grid[r][c]===0) notes[r][c]=new Set(candidatesFor(r,c));
else notes[r][c].clear();
}
function autoCleanNotesAround(r, c, value){
if(!autoCleanup || !value) return;
for(let i=0;i<GRID_SIZE;i++){
if(i!==c) notes[r][i].delete(value);
if(i!==r) notes[i][c].delete(value);
}
const br=Math.floor(r/3)*3, bc=Math.floor(c/3)*3;
for(let rr=br;rr<br+3;rr++) for(let cc=bc;cc<bc+3;cc++) if(rr!==r||cc!==c) notes[rr][cc].delete(value);
notes[r][c].clear();
}
// ── History ───────────────────────────────────────────────────────────────
function pushHistory(){
history.push({
grid:cloneGrid(grid), notes:cloneNotes(notes),
selected:selected?{...selected}:null,
elapsed, notesMode, autoCleanup
});
if(history.length>HISTORY_LIMIT) history.shift();
future=[];
}
function restoreSnapshot(snap){
grid=cloneGrid(snap.grid); notes=cloneNotes(snap.notes);
selected=snap.selected?{...snap.selected}:null;
elapsed=snap.elapsed; notesMode=snap.notesMode; autoCleanup=snap.autoCleanup;
boardShellEl.classList.remove('victory-glow');
clearRiftVisualState();
render(); updateStats(); updateToggles(); saveGame();
captureLastSolvableSnapshot();
}
function undo(){
if(!history.length){ setStatus('Nothing to undo.'); return; }
future.push({grid:cloneGrid(grid),notes:cloneNotes(notes),selected:selected?{...selected}:null,elapsed,notesMode,autoCleanup});
restoreSnapshot(history.pop());
setStatus('Undid last move.');
}
function redo(){
if(!future.length){ setStatus('Nothing to redo.'); return; }
history.push({grid:cloneGrid(grid),notes:cloneNotes(notes),selected:selected?{...selected}:null,elapsed,notesMode,autoCleanup});
restoreSnapshot(future.pop());
setStatus('Redid move.');
}
// ── UI updates ────────────────────────────────────────────────────────────
const MIN_SPLASH_MS=TEST_MODE?0:800;
const splashShownAt=Date.now();
function hideSplash(){
const splash=document.getElementById('splash');
if(!splash) return;
const elapsed=Date.now()-splashShownAt;
const delay=Math.max(0,MIN_SPLASH_MS-elapsed);
setTimeout(()=>{
splash.classList.add('fade-out');
splash.addEventListener('transitionend',()=>splash.remove(),{once:true});
},delay);
}
function setStatus(msg){ statusEl.textContent=msg; }
function notifyRiftHook(name, payload){
const handlers = riftExtensionHooks[name] || [];
handlers.forEach(handler => {
try {
handler(payload);
} catch (error) {
console.error(`Rift extension hook "${name}" failed:`, error);
}
});
}
function setInteractionLocked(locked){
interactionLocked=locked;
boardShellEl.classList.toggle('rift-locked',locked);
}
function canInteractWithBoard(options={}){
if(interactionLocked) return false;
if(riftState.active){
if(options.showStatus!==false) setStatus('Resolve the rift first.');
return false;
}
return true;
}
function snapshotCurrentState(){
return {
grid:cloneGrid(grid),
notes:cloneNotes(notes),
selected:selected?{...selected}:null,
elapsed, notesMode, autoCleanup
};
}
function captureLastSolvableSnapshot(){
if(hasAnySolution(grid)){
lastSolvableSnapshot=snapshotCurrentState();
boardWasSolvable=true;
return true;
}
boardWasSolvable=false;
return false;
}
function markCurrentStateAsSolvable(){
lastSolvableSnapshot=snapshotCurrentState();
boardWasSolvable=true;
}
function serializeRiftState(){
return {
active:riftState.active,
nodes:riftState.nodes.slice(0,3),
hasTriggered:riftState.hasTriggered,
cooldownUntil:riftState.cooldownUntil,
copyKey:riftState.copyKey
};
}
function deserializeRiftState(savedRiftState={}){
const isRiftActive = !!savedRiftState.active;
return {
active:isRiftActive,
nodes:isRiftActive ? (savedRiftState.nodes||[]).slice(0,3) : [],
hasTriggered:!!savedRiftState.hasTriggered,
cooldownUntil:Number(savedRiftState.cooldownUntil)||0,
copyKey:savedRiftState.copyKey||'pattern'
};
}
function resetRiftState(){
riftState = { active:false, nodes:[], hasTriggered:false, cooldownUntil:0, copyKey:'pattern' };
riftSequenceRunning = false;
}
function applyPostMovePipeline({ origin='player-move', riftOptions={}, shouldEvaluateRift=true, shouldCaptureSolvable=false }={}){
render();
saveGame();
if(shouldCaptureSolvable) captureLastSolvableSnapshot();
if(shouldEvaluateRift) scheduleRiftEvaluation(origin, riftOptions);
}
function clearRiftVisualState(){
statusSequenceId++;
if(riftEvalTimer){ clearTimeout(riftEvalTimer); riftEvalTimer=null; }
riftState.active=false;
riftSequenceRunning=false;
riftState.nodes=[];
movesSinceSolvabilityCheck=0;
boardShellEl.classList.remove('rift-active','rift-glitch');
statusEl.classList.remove('rift-status');
riftModal.hidden=true;
setInteractionLocked(false);
}
function getRiftNodes(){
const conflicted=[];
for(let r=0;r<GRID_SIZE;r++){
for(let c=0;c<GRID_SIZE;c++){
if(hasConflict(r,c)) conflicted.push({r,c});
}
}
if(conflicted.length) return conflicted.slice(0,3);
for(let r=0;r<GRID_SIZE;r++){
for(let c=0;c<GRID_SIZE;c++){
if(grid[r][c]===0) return [{r,c}];
}
}
return [{r:4,c:4}];
}
async function runStatusSequence(lines){
const id=++statusSequenceId;
const fast=reducedMotion.matches;
for(const line of lines){
if(id!==statusSequenceId) return false;
setStatus(line);
await new Promise(resolve=>setTimeout(resolve,fast?RIFT_STATUS_DELAY_REDUCED_MOTION_MS:RIFT_STATUS_DELAY_MS));
}
return id===statusSequenceId;
}
function openRiftModal(){
const copy=riftCopySets[riftState.copyKey]||riftCopySets.pattern;
riftBodyEl.textContent=copy.fragment;
riftTitleEl.textContent=copy.title;
lastFocusedBeforeRiftModal = document.activeElement;
riftModal.hidden=false;
riftReturnBtn.focus();
}
async function triggerRiftEvent(){
if(riftState.active || riftSequenceRunning) return;
riftSequenceRunning=true;
riftState.hasTriggered=true;
riftState.cooldownUntil=Date.now()+RIFT_COOLDOWN_MS;
setInteractionLocked(true);
boardShellEl.classList.add('rift-active');
if(!reducedMotion.matches) boardShellEl.classList.add('rift-glitch');
statusEl.classList.add('rift-status');
vibrate([15,55,15]);
render();
const copy=riftCopySets[riftState.copyKey]||riftCopySets.pattern;
const complete=await runStatusSequence(copy.lines);
boardShellEl.classList.remove('rift-glitch');
if(!complete){
riftSequenceRunning=false;
return;
}
riftState.nodes=getRiftNodes();
riftState.active=true;
riftSequenceRunning=false;
setInteractionLocked(false);
render();
setStatus('Rift node found. Tap the marked cell.');
saveGame();
notifyRiftHook('onTrigger', { rift:serializeRiftState(), snapshot:snapshotCurrentState() });
}
function shouldEvaluateRift(origin='system', options={}){
if(origin!=='player-move') return false;
if(riftState.active||riftSequenceRunning) return false;
if(riftState.hasTriggered) return false;
if(Date.now()<riftState.cooldownUntil) return false;
// Explicit policy: evaluate immediately after conflict-introducing moves,
// otherwise only every N non-conflicting moves to reduce solver pressure.
if(!options.force){
if(options.conflictIntroduced){
movesSinceSolvabilityCheck=0;
} else {
movesSinceSolvabilityCheck++;
if(movesSinceSolvabilityCheck<RIFT_NON_CONFLICT_CHECK_INTERVAL) return false;
movesSinceSolvabilityCheck=0;
}
}
return true;
}
function shouldTriggerRiftFromSolvability(solvable){
if(solvable){
markCurrentStateAsSolvable();
return false;
}
return boardWasSolvable;
}
function evaluateRiftTrigger(origin='system', options={}){
if(!shouldEvaluateRift(origin, options)) return;
const solvable=hasAnySolution(grid);
if(shouldTriggerRiftFromSolvability(solvable)){
boardWasSolvable=false;
triggerRiftEvent();
}
}
function scheduleRiftEvaluation(origin='player-move', options={}){
if(riftEvalTimer) clearTimeout(riftEvalTimer);
riftEvalTimer=setTimeout(()=>{
riftEvalTimer=null;
evaluateRiftTrigger(origin, options);
},RIFT_EVALUATE_DEBOUNCE_MS);
}
function restoreRiftStateFromSave(data){
riftState=deserializeRiftState(data.riftState||{});
riftSequenceRunning=false;
if(riftState.active){
boardShellEl.classList.add('rift-active');
statusEl.classList.add('rift-status');
}
}
function updateStats(){
timeStat.textContent=formatTime(elapsed);
const errs=countErrors();
if(errs>0){
errorStat.textContent=`${errs} err`;
errorStat.hidden=false;
} else {
errorStat.hidden=true;
}
progressBar.style.width=`${Math.round(countFilled()/81*100)}%`;
}
function updateToggles(){
notesModeBtn.textContent=notesMode?'Notes On':'Notes Off';
notesModeBtn.classList.toggle('active',notesMode);
autoNotesBtn.textContent=autoCleanup?'Auto-clean On':'Auto-clean Off';
autoNotesBtn.classList.toggle('active',autoCleanup);
}
function updateDigitPad(){
const counts=new Array(10).fill(0);
for(let r=0;r<GRID_SIZE;r++)
for(let c=0;c<GRID_SIZE;c++)
if(grid[r][c]&&!hasConflict(r,c)) counts[grid[r][c]]++;
document.querySelectorAll('#digitPad button').forEach(btn=>{
const n=Number(btn.textContent);
if(n>=1&&n<=9){
const done=counts[n]===9;
btn.classList.toggle('completed',done);
btn.disabled=done;
}
});
}
function updateStatus(){
if(riftSequenceRunning) return;
if(riftState.active){ setStatus('Rift node found. Tap the marked cell.'); return; }
if(!selected){ setStatus('Tap a cell to select it, then tap a number.'); return; }
const {r,c}=selected;
const isFixed=startingGrid[r][c]!==0;
const value=grid[r][c];
const nc=notes[r][c].size;
if(isFixed){ setStatus('Starting number — this cell cannot be changed.'); return; }
if(notesMode&&!value){ setStatus(nc?`Notes mode on — ${nc} pencil mark${nc===1?'':'s'} here.`:'Notes mode on — tap numbers to toggle pencil marks.'); return; }
if(!value){ setStatus(nc?`Empty cell — ${nc} pencil mark${nc===1?'':'s'}.`:'Empty cell selected.'); return; }
if(hasConflict(r,c)) setStatus(`Conflict! This ${value} clashes with another in its row, column, or block.`);
else setStatus(`You placed a ${value} here.${autoCleanup?' Related notes cleaned up.':''}`);
}
function makeNotesNode(r, c){
const box=document.createElement('div');
box.className='notes';
for(let n=1;n<=9;n++){
const span=document.createElement('span');
span.textContent=notes[r][c].has(n)?String(n):'';
box.appendChild(span);
}
return box;
}
function render(){
boardEl.innerHTML='';
const fragment=document.createDocumentFragment();
const blocks=Array.from({length:9},()=>{
const div=document.createElement('div');
div.className='block';
return div;
});
for(let r=0;r<GRID_SIZE;r++){
for(let c=0;c<GRID_SIZE;c++){
const cell=document.createElement('button');
cell.type='button';
cell.className='cell';
cell.dataset.r=r;
cell.dataset.c=c;
const isFixed=startingGrid[r][c]!==0;
const isUser=!isFixed&&grid[r][c]!==0;
if(isFixed) cell.classList.add('fixed');
if(isUser) cell.classList.add('user');
if(isRelated(r,c)) cell.classList.add('related');
if(selected&&selected.r===r&&selected.c===c) cell.classList.add('selected');
if(hasConflict(r,c)) cell.classList.add('error');
const isRiftNode=riftState.active && riftState.nodes.some(node=>node.r===r&&node.c===c);
if(isRiftNode) cell.classList.add('rift-node');
cell.setAttribute('aria-label',`Row ${r+1} Column ${c+1}${grid[r][c]?`, value ${grid[r][c]}`:', empty'}${isRiftNode?', rift node':''}`);
if(grid[r][c]) cell.textContent=grid[r][c];
else if(notes[r][c].size) cell.appendChild(makeNotesNode(r,c));
cell.addEventListener('click',()=>{
if(interactionLocked) return;
if(isRiftNode){ openRiftModal(); return; }
if(riftState.active){ setStatus('The rift is still open. Tap the marked cell.'); return; }
selected={r,c}; render(); saveGame();
});
blocks[Math.floor(r/3)*3+Math.floor(c/3)].appendChild(cell);
}
}
blocks.forEach(block=>fragment.appendChild(block));
boardEl.appendChild(fragment);
updateStats(); updateToggles(); updateStatus(); updateDigitPad();
}
function celebrate(){
document.querySelectorAll('.cell').forEach(el=>{
el.classList.add('okflash');
setTimeout(()=>el.classList.remove('okflash'),450);
});
document.querySelector('.board-shell').classList.add('victory-glow');
vibrate([50,30,80]);
// eslint-disable-next-line no-console
console.log('game_won',{elapsed,difficulty:difficultyEl.value});
}
// ── Persistence ───────────────────────────────────────────────────────────
function saveGame(){
const encodedLastSolvable=lastSolvableSnapshot?{
...lastSolvableSnapshot,
notes:lastSolvableSnapshot.notes.map(row=>row.map(s=>[...s]))
}:null;
const payload={
grid, startingGrid,
notes:notes.map(row=>row.map(s=>[...s])),
selected, elapsed, notesMode, autoCleanup,
difficulty:difficultyEl.value,
lastSolvableSnapshot:encodedLastSolvable,
riftState:serializeRiftState()
};
try{
localStorage.setItem(STORAGE_KEY,JSON.stringify(payload));
} catch(e){
if(e instanceof DOMException && e.name==='QuotaExceededError'){
setStatus('Auto-save failed: storage quota exceeded.');
}
}
}
function applyLoadedData(data){
grid=data.grid;
startingGrid=data.startingGrid||data.grid.map(row=>row.slice());
notes=data.notes.map(row=>row.map(arr=>new Set(arr)));
selected=data.selected;
elapsed=normalizeElapsed(getPersistedElapsedTime(data));
notesMode=normalizeBoolean(data.notesMode,false);
autoCleanup=normalizeBoolean(data.autoCleanup,true);
difficultyEl.value=data.difficulty||'medium';
history=[]; future=[];
boardShellEl.classList.remove('victory-glow');
clearRiftVisualState();
if(data.lastSolvableSnapshot && data.lastSolvableSnapshot.grid && data.lastSolvableSnapshot.notes){
lastSolvableSnapshot={
...data.lastSolvableSnapshot,
grid:cloneGrid(data.lastSolvableSnapshot.grid),
notes:data.lastSolvableSnapshot.notes.map(row=>row.map(arr=>new Set(arr)))
};
} else {
lastSolvableSnapshot=null;
}
restoreRiftStateFromSave(data);
render(); startTimer(); hideSplash();
setStatus(riftState.active?'Rift node found. Tap the marked cell.':'Resumed saved game.');
boardWasSolvable=hasAnySolution(grid);
if(!lastSolvableSnapshot && boardWasSolvable) captureLastSolvableSnapshot();
}
// ── Theme ─────────────────────────────────────────────────────────────────
function applyTheme(theme){
document.body.classList.toggle('light',theme==='light');
document.documentElement.style.background=theme==='light'?'#eef2ff':'#0b1220';
themeBtn.textContent=`Theme: ${theme==='light'?'Light':'Dark'}`;
document.querySelector('meta[name="theme-color"]').setAttribute('content',theme==='light'?'#f8fafc':'#111827');
localStorage.setItem(THEME_KEY,theme);
}
function toggleTheme(){ applyTheme(document.body.classList.contains('light')?'dark':'light'); }
// ── Puzzle generation ─────────────────────────────────────────────────────
function shuffle(a){
const out=a.slice();
for(let i=out.length-1;i>0;i--){ const j=Math.floor(Math.random()*(i+1)); [out[i],out[j]]=[out[j],out[i]]; }
return out;
}
function createSolvedBoard(){
const base=3, side=base*base;
const pattern=(r,c)=>(base*(r%base)+Math.floor(r/base)+c)%side;
const rBase=[0,1,2];
const rowsOrder=shuffle(rBase).flatMap(g=>shuffle(rBase).map(r=>g*base+r));
const colsOrder=shuffle(rBase).flatMap(g=>shuffle(rBase).map(c=>g*base+c));
const nums=shuffle([1,2,3,4,5,6,7,8,9]);
return rowsOrder.map(r=>colsOrder.map(c=>nums[pattern(r,c)]));
}
function countSolutions(board, limit=2){
let count=0;
function solve(b){
let best=null;
for(let r=0;r<GRID_SIZE;r++){
for(let c=0;c<GRID_SIZE;c++){
if(b[r][c]===0){
const cand=candidatesForBoard(b,r,c);
if(cand.length===0) return;
if(!best||cand.length<best.cand.length) best={r,c,cand};
}
}
}
if(!best){ count++; return; }
for(const n of best.cand){
b[best.r][best.c]=n;
solve(b);
if(count>=limit) break;
b[best.r][best.c]=0;
}
b[best.r][best.c]=0;
}
solve(board.map(row=>row.slice()));
return count;
}
function makePuzzleFromSolved(solved, difficulty){
const removals={easy:40,medium:50,hard:56};
const target=removals[difficulty]||50;
const board=solved.map(r=>r.slice());
const cells=shuffle(Array.from({length:TOTAL_CELLS},(_,i)=>i));
let removed=0;
for(const idx of cells){
if(removed>=target) break;
const r=Math.floor(idx/GRID_SIZE), c=idx%GRID_SIZE;
const backup=board[r][c];
board[r][c]=0;
if(countSolutions(board,2)!==1) board[r][c]=backup;
else removed++;
}
return board;
}
// ── Game actions ──────────────────────────────────────────────────────────
function startTimer(){
if(timerId) clearInterval(timerId);
timerId=setInterval(()=>{ elapsed++; updateStats(); saveGame(); },1000);
}
function newGame(){
const solved=createSolvedBoard();
grid=makePuzzleFromSolved(solved,difficultyEl.value);
startingGrid=cloneGrid(grid);
notes=Array.from({length:GRID_SIZE},()=>Array.from({length:GRID_SIZE},()=>new Set()));
fillNotesAll();
selected=null; elapsed=0; notesMode=false; autoCleanup=true; history=[]; future=[];
boardShellEl.classList.remove('victory-glow');
clearRiftVisualState();
resetRiftState();
movesSinceSolvabilityCheck=0;
captureLastSolvableSnapshot();
render(); startTimer(); saveGame(); hideSplash();
setStatus(`New ${difficultyEl.value} Shandoku game loaded.`);
}
function placeNumber(n){
if(!canInteractWithBoard()) return;
if(!selected) return;
const {r,c}=selected;
if(startingGrid[r][c]!==0){ setStatus('That cell is a starting number.'); return; }
pushHistory();
if(notesMode){
if(grid[r][c]!==0){ history.pop(); setStatus('Clear the number first before adding notes.'); return; }
if(notes[r][c].has(n)) notes[r][c].delete(n); else notes[r][c].add(n);
vibrate(10);
applyPostMovePipeline({ shouldEvaluateRift:false }); return;
}
grid[r][c]=n;
notes[r][c].clear();
autoCleanNotesAround(r,c,n);
const introducedConflict=hasConflict(r,c);
applyPostMovePipeline({ riftOptions:{conflictIntroduced:introducedConflict} });
if(introducedConflict){
vibrate([10,50,10]);
const cellEl=boardEl.querySelector(`[data-r="${r}"][data-c="${c}"]`);
if(cellEl){ cellEl.classList.add('error-shake'); setTimeout(()=>cellEl.classList.remove('error-shake'),400); }
} else {
vibrate(10);
}
if(isSolved()){ setStatus('Solved. Nice work.'); celebrate(); }
}
function clearSelected(){
if(!canInteractWithBoard()) return;
if(!selected) return;
const {r,c}=selected;
if(startingGrid[r][c]!==0){ setStatus('Starting number — this cell cannot be changed.'); return; }
pushHistory();
grid[r][c]=0; notes[r][c].clear();
applyPostMovePipeline({ riftOptions:{conflictIntroduced:false} });
setStatus('Cell cleared.');
}
function jumpToNextEmpty(){
if(!canInteractWithBoard()) return false;
const startIndex=selected?selected.r*GRID_SIZE+selected.c:-1;
for(let offset=1;offset<=TOTAL_CELLS;offset++){
const idx=(startIndex+offset+TOTAL_CELLS)%TOTAL_CELLS;
const r=Math.floor(idx/9), c=idx%9;
if(grid[r][c]===0&&startingGrid[r][c]===0){
selected={r,c}; render(); saveGame();
setStatus('Jumped to next empty cell.');
return true;
}
}
setStatus('No empty cells remaining.');
return false;
}
function giveHint(){
if(!canInteractWithBoard()) return;
let best=null;
outer: for(let r=0;r<GRID_SIZE;r++){
for(let c=0;c<GRID_SIZE;c++){
if(grid[r][c]===0){
const cand=candidatesFor(r,c);
if(cand.length===1){ best={r,c,v:cand[0]}; break outer; }
if(!best&&cand.length) best={r,c,v:cand[0]};
}
}
}
if(!best){ setStatus('Board is already complete.'); return; }
selected={r:best.r,c:best.c};
render(); saveGame();
setStatus(`Hint: try a ${best.v} in this cell.`);
}
function checkBoard(){
if(!canInteractWithBoard()) return;
render();
if(isSolved()) setStatus('Everything checks out. Puzzle solved.');
else if(countErrors()===0) setStatus(`No conflicts found. ${TOTAL_CELLS-countFilled()} cells still empty.`);
else setStatus(`${countErrors()} conflicting cell(s) found. Red marks the exact conflicting cells.`);
}
function solveBoard(){
if(!canInteractWithBoard()) return;
pushHistory();
const b=cloneGrid(grid);
function solve(){
let best=null;
for(let r=0;r<GRID_SIZE;r++){
for(let c=0;c<GRID_SIZE;c++){
if(b[r][c]===0){
const cand=candidatesForBoard(b,r,c);
if(cand.length===0) return false;
if(!best||cand.length<best.cand.length) best={r,c,cand};
}
}
}
if(!best) return true;
for(const n of best.cand){
b[best.r][best.c]=n;
if(solve()) return true;
b[best.r][best.c]=0;
}
return false;
}
const ok=solve();
grid=b;
notes=Array.from({length:GRID_SIZE},()=>Array.from({length:GRID_SIZE},()=>new Set()));
applyPostMovePipeline({ shouldEvaluateRift:false, shouldCaptureSolvable:true });
if(ok) setStatus('Solved.');
else setStatus('Could not solve — fix the conflicts first.');
}
function moveSelection(dr, dc){
if(!canInteractWithBoard({showStatus:false})) return;
if(!selected) selected={r:0,c:0};
else selected={r:(selected.r+dr+GRID_SIZE)%GRID_SIZE, c:(selected.c+dc+GRID_SIZE)%GRID_SIZE};
render(); saveGame();
}
function restoreLastSolvableState(){
if(!lastSolvableSnapshot){
setStatus('No solvable snapshot available yet.');
return;
}
restoreSnapshot(lastSolvableSnapshot);
boardWasSolvable=true;
setStatus('Returned to the last solvable state.');
}
function closeRift(returnMessage='Rift closed.'){
clearRiftVisualState();
setStatus(returnMessage);
saveGame();
notifyRiftHook('onResolve', { message:returnMessage, rift:serializeRiftState(), snapshot:snapshotCurrentState() });
if(lastFocusedBeforeRiftModal && typeof lastFocusedBeforeRiftModal.focus === 'function'){
lastFocusedBeforeRiftModal.focus();
}
lastFocusedBeforeRiftModal = null;
}
function registerRiftExtension(extension={}){
const dispose = [];
Object.keys(riftExtensionHooks).forEach(hookName => {
const handler = extension[hookName];
if(typeof handler !== 'function') return;
riftExtensionHooks[hookName].push(handler);
dispose.push(()=>{
riftExtensionHooks[hookName] = riftExtensionHooks[hookName].filter(fn=>fn!==handler);
});
});
return () => dispose.forEach(fn=>fn());
}
function normalizeTestBoard(board, fallbackValue=0){
if(!Array.isArray(board)||board.length!==GRID_SIZE){
return Array.from({length:GRID_SIZE},()=>Array.from({length:GRID_SIZE},()=>fallbackValue));
}
return board.map(row=>{
if(!Array.isArray(row)||row.length!==GRID_SIZE) return Array.from({length:GRID_SIZE},()=>fallbackValue);
return row.map(value=>{
const n=Number(value);
if(Number.isInteger(n)&&n>=0&&n<=9) return n;
return fallbackValue;
});
});
}
function applyTestBoardState(payload={}){
const nextGrid=normalizeTestBoard(payload.grid,0);
const nextStartingGrid=normalizeTestBoard(payload.startingGrid,0);
grid=cloneGrid(nextGrid);
startingGrid=cloneGrid(nextStartingGrid);
notes=Array.from({length:GRID_SIZE},()=>Array.from({length:GRID_SIZE},()=>new Set()));
selected=(payload.selected&&Number.isInteger(payload.selected.r)&&Number.isInteger(payload.selected.c))
?{r:Math.max(0,Math.min(8,payload.selected.r)),c:Math.max(0,Math.min(8,payload.selected.c))}
:null;
elapsed=normalizeElapsed(payload.elapsed);
notesMode=normalizeBoolean(payload.notesMode,false);
autoCleanup=normalizeBoolean(payload.autoCleanup,true);
history=[]; future=[];
boardShellEl.classList.remove('victory-glow');
clearRiftVisualState();
riftState={active:false,sequenceRunning:false,nodes:[],hasTriggered:false,cooldownUntil:0,copyKey:'pattern'};
movesSinceSolvabilityCheck=0;
captureLastSolvableSnapshot();
render();
saveGame();
}
function exposeTestApi(){
Object.defineProperty(window,'__shandokuTest',{value:{
resetStorage(){
localStorage.removeItem(STORAGE_KEY);
},
setBoardState(payload){
applyTestBoardState(payload);
},
getState(){
return {
grid:cloneGrid(grid),
startingGrid:cloneGrid(startingGrid),
selected:selected?{...selected}:null,
notesMode,
autoCleanup,
errorCount:countErrors(),
status:statusEl.textContent
};
},
selectCell(r,c){
selected={r:Math.max(0,Math.min(8,r)),c:Math.max(0,Math.min(8,c))};
render();
saveGame();
},
placeNumber(n){
placeNumber(n);
},
newGame(){
newGame();
},
forceRift(payload={}){
const r=Number.isInteger(payload.r)?Math.max(0,Math.min(8,payload.r)):4;
const c=Number.isInteger(payload.c)?Math.max(0,Math.min(8,payload.c)):4;
clearRiftVisualState();
riftState.active=true;
riftState.sequenceRunning=false;
riftState.nodes=[{r,c}];
riftState.hasTriggered=true;
riftState.cooldownUntil=Date.now()+RIFT_COOLDOWN_MS;
boardShellEl.classList.add('rift-active');
statusEl.classList.add('rift-status');
render();
setStatus('Rift node found. Tap the marked cell.');
saveGame();
}
}, configurable:false, writable:false});
}