-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
626 lines (502 loc) · 17.5 KB
/
script.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
let puzzle, activeDir = 'across', activeIdx = null, timerSecs = 0;
let timerInterval;
let puzzleCompleted = false;
let answerGrid = [];
const dateOptions = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
};
window.onload = async () => {
try {
puzzle = await (await fetch('puzzle.json')).json();
console.log(puzzle);
buildAnswerGrid();
buildPuzzleGrid();
buildClues();
startTimer();
document.getElementById('toggle-dir').addEventListener('click', () => {
if (activeIdx !== null) {
activeDir = activeDir === 'across' ? 'down' : 'across';
highlightFrom(activeIdx);
}
});
const now = new Date();
let dateString = now.toLocaleDateString('en-US', dateOptions);
if (puzzle.date && puzzle.date !== ""){
dateString = puzzle.date;
}
document.getElementById('date').textContent = dateString;
let authorString = `By ${puzzle.author}`;
if (puzzle.editor && puzzle.editor !== "")
authorString += ` ● Edited by ${puzzle.editor}`
document.getElementById('creator').textContent = authorString;
document.getElementById('rebus').addEventListener('click', () => console.log('Rebus clicked'));
document.getElementById('clear').addEventListener('click', clearPuzzle);
document.getElementById('reveal').addEventListener('click', revealSquare);
document.getElementById('check').addEventListener('click', checkSquare);
document.getElementById('pause').addEventListener('click', handlePause);
document.addEventListener('keydown', handleKeydown);
} catch (error) {
console.error('Error loading puzzle:', error);
}
};
function buildAnswerGrid() {
answerGrid = Array(puzzle.rows).fill().map(() => Array(puzzle.cols).fill(''));
for (let row = 0; row < puzzle.rows; row++){
let rowStringIdx = 0;
for (let col = 0; col < puzzle.cols; col++) {
if (isBlackCell(row, col)) continue;
const entry = puzzle.across[row];
if (rowStringIdx >= entry.answer.length) continue;
answerGrid[row][col] = entry.answer.charAt(rowStringIdx);
rowStringIdx++;
}
}
}
function findPositionForClue(direction, index) {
const clue = puzzle[direction][index];
const clueNum = getClueNumberFromIndex(direction, index);
if (clueNum === null)
return { row: -1, col: -1 };
for (let r = 0; r < puzzle.rows; r++) {
for (let c = 0; c < puzzle.cols; c++) {
const num = getClueNumber(r, c);
if (num === clueNum) {
return { row: r, col: c };
}
}
}
return { row: -1, col: -1 };
}
function getClueNumberFromIndex(direction, index) {
let acrossCount = 0;
let downCount = 0;
let clueNumbers = [];
for (let r = 0; r < puzzle.rows; r++) {
for (let c = 0; c < puzzle.cols; c++) {
if (isBlackCell(r, c)) continue;
const startAcross = c === 0 || isBlackCell(r, c-1);
const startDown = r === 0 || isBlackCell(r-1, c);
if (startAcross || startDown) {
const clueNumber = clueNumbers.length + 1;
clueNumbers.push(clueNumber);
if (startAcross) acrossCount++;
if (startDown) downCount++;
if (direction === 'across' && startAcross && acrossCount === index + 1) {
return clueNumber;
}
if (direction === 'down' && startDown && downCount === index + 1) {
return clueNumber;
}
}
}
}
return null;
}
function clearPuzzle(e) {
clearHighlighting();
document.querySelectorAll('input')
.forEach(c => c.value = "");
}
function checkSquare(e) {
const input = document.querySelector(`input[data-idx='${activeIdx}']`);
const {r, c} = idxToRC(activeIdx);
const expected = answerGrid[r][c];
if (input.value && input.value === expected)
input.classList.add('correct');
else
input.classList.add('incorrect');
}
function revealSquare(e) {
const input = document.querySelector(`input[data-idx='${activeIdx}']`);
const {r, c} = idxToRC(activeIdx);
const answer = answerGrid[r][c];
if (input.classList.contains('incorrect'))
input.classList.remove('incorrect');
input.value = answer;
input.classList.add('correct');
setTimeout(checkPuzzleCompletion, 300);
}
function clearHighlighting(e) {
document.querySelectorAll('.cell.selected, .cell.active')
.forEach(c => c.classList.remove('selected','active'));
document.querySelectorAll('#across-list li, #down-list li')
.forEach(li => li.classList.remove('active', 'highlighted'));
}
function handlePause(e) {
if (!timerInterval) {
// Restart timer
startTimer();
const existingOverlay = document.querySelector('.pause-overlay');
if (existingOverlay) {
document.body.removeChild(existingOverlay);
}
} else {
// Pause the timer
clearInterval(timerInterval);
timerInterval = null;
// Create pause overlay
const overlay = document.createElement('div');
overlay.className = 'popup-overlay';
const messageBox = document.createElement('div');
messageBox.className = 'popup-message';
const heading = document.createElement('h2');
heading.textContent = 'Timer Paused';
const timeMsg = document.createElement('p');
const m = Math.floor(timerSecs / 60), s = String(timerSecs % 60).padStart(2, '0');
timeMsg.textContent = `Puzzle stopped at ${m}:${s}`;
const continueBtn = document.createElement('button');
continueBtn.textContent = 'Continue';
continueBtn.addEventListener('click', () => {
document.body.removeChild(overlay);
startTimer();
});
messageBox.appendChild(heading);
messageBox.appendChild(timeMsg);
messageBox.appendChild(continueBtn);
overlay.appendChild(messageBox);
document.body.appendChild(overlay);
}
}
function handleKeydown(e) {
if (!activeIdx) return;
if (e.key === 'ArrowRight') {
e.preventDefault();
moveInDirection(0, 1);
} else if (e.key === 'ArrowLeft') {
e.preventDefault();
moveInDirection(0, -1);
} else if (e.key === 'ArrowDown') {
e.preventDefault();
moveInDirection(1, 0);
} else if (e.key === 'ArrowUp') {
e.preventDefault();
moveInDirection(-1, 0);
} else if (e.key === 'Enter') {
e.preventDefault();
moveToNextClue();
}
}
function moveToNextClue() {
let currentClueIndex = -1;
const entriesInCurrentDirection = puzzle[activeDir];
// Find the active clue in the current direction
for (let i = 0; i < entriesInCurrentDirection.length; i++) {
const position = findPositionForClue(activeDir, i);
const clueIdx = position.row * puzzle.cols + position.col;
const clueCells = getEntryCells(clueIdx);
if (clueCells.includes(activeIdx)) {
currentClueIndex = i;
break;
}
}
if (currentClueIndex !== -1) {
// Move to the next clue in the current direction
const nextClueIndex = (currentClueIndex + 1) % entriesInCurrentDirection.length;
const nextPosition = findPositionForClue(activeDir, nextClueIndex);
const nextClueIdx = nextPosition.row * puzzle.cols + nextPosition.col;
// Highlight the new clue and focus on its first cell
activeIdx = nextClueIdx;
highlightFrom(nextClueIdx);
document.querySelector(`input[data-idx='${nextClueIdx}']`).focus();
}
}
function moveToPreviousClue() {
let currentClueIndex = -1;
const entriesInCurrentDirection = puzzle[activeDir];
// Find the active clue in the current direction
for (let i = 0; i < entriesInCurrentDirection.length; i++){
const position = findPositionForClue(activeDir, i);
const clueIdx = position.row * puzzle.cols + position.col;
const clueCells = getEntryCells(clueIdx);
if (clueCells.includes(activeIdx)){
currentClueIndex = i;
break;
}
}
if (currentClueIndex === -1) return;
let prevClueIndex = (currentClueIndex - 1) % entriesInCurrentDirection.length;
// Wrap around to last clue
if (prevClueIndex === -1)
prevClueIndex = entriesInCurrentDirection.length - 1;
const prevCluePosition = findPositionForClue(activeDir, prevClueIndex);
if (prevCluePosition.row === -1) return;
const prevClueStartIdx = rcToIdx(prevCluePosition.row, prevCluePosition.col);
const prevClueLength = getEntryCells(prevClueStartIdx).length;
if (activeDir === 'across'){
prevCluePosition.col += prevClueLength - 1;
}
else {
prevCluePosition.row += prevClueLength - 1;
}
const prevClueEndIdx = rcToIdx(prevCluePosition.row, prevCluePosition.col);
activeIdx = prevClueEndIdx;
highlightFrom(prevClueEndIdx);
document.querySelector(`input[data-idx='${prevClueEndIdx}']`).focus();
}
function moveInDirection(dr, dc) {
if (activeIdx === null) return;
const { r, c } = idxToRC(activeIdx);
const newR = r + dr;
const newC = c + dc;
// Check bounds and black cells
if (newR >= 0 && newR < puzzle.rows &&
newC >= 0 && newC < puzzle.cols &&
!isBlackCell(newR, newC)) {
const newIdx = newR * puzzle.cols + newC;
highlightFrom(newIdx);
document.querySelector(`input[data-idx='${newIdx}']`).focus();
}
}
function buildPuzzleGrid() {
const grid = document.getElementById('grid');
grid.innerHTML = '';
grid.style.gridTemplateColumns = `repeat(${puzzle.cols},1fr)`;
for (let r = 0; r < puzzle.rows; r++) {
for (let c = 0; c < puzzle.cols; c++) {
const idx = rcToIdx(r, c);
const cell = document.createElement('div');
cell.className = 'cell';
if (puzzle.grid[idx].black){
cell.classList.add('black');
}
else {
const num = getClueNumber(r, c);
if (num) {
const n = document.createElement('div');
n.className = 'number';
n.textContent = num;
cell.appendChild(n);
}
const inp = document.createElement('input');
inp.maxLength = 1;
inp.dataset.idx = idx;
inp.addEventListener('input', onInput);
inp.addEventListener('keydown', handleBackspace);
cell.addEventListener('click', () => onCellClick(idx));
cell.appendChild(inp);
}
grid.appendChild(cell);
}
}
// Initialize the first active cell
if (puzzle.across.length > 0) {
const firstPosition = findPositionForClue('across', 0);
const firstIdx = firstPosition.row * puzzle.cols + firstPosition.col;
setTimeout(() => {
highlightFrom(firstIdx);
}, 100);
}
}
function handleBackspace(e) {
if (e.key !== "Backspace") return;
if (e.target.value && !e.target.classList.contains('correct')) {
e.target.value = '';
}
else {
moveCursor(-1);
e.preventDefault();
}
}
function onInput(e) {
// Only move forward if a character was actually entered
if (!e.target.value) return;
if (e.target.classList.contains('incorrect'))
e.target.classList.remove('incorrect');
e.target.value = e.target.value.toUpperCase();
moveCursor(1);
// Check if puzzle is complete after input
setTimeout(checkPuzzleCompletion, 300);
}
function buildClues() {
['across','down'].forEach(dir => {
const ul = document.getElementById(dir + '-list');
ul.innerHTML = '';
puzzle[dir].forEach((clue, index) => {
const position = findPositionForClue(dir, index);
const clueNum = getClueNumberFromIndex(dir, index);
const li = document.createElement('li');
li.innerHTML = `<strong>${clueNum}.</strong> ${clue.clue}`;
li.dataset.dir = dir;
li.dataset.num = clueNum;
li.dataset.idx = position.row * puzzle.cols + position.col;
li.addEventListener('click', () => {
activeDir = dir;
highlightFrom(parseInt(li.dataset.idx));
});
ul.appendChild(li);
});
});
}
function onCellClick(idx) {
// If clicking the same cell, toggle direction but keep cell selected
if (activeIdx === idx) {
activeDir = activeDir === 'across' ? 'down' : 'across';
} else {
// If clicking a new cell, switch to that cell
activeIdx = idx;
}
highlightFrom(idx);
document.querySelector(`input[data-idx='${idx}']`).focus();
}
function moveCursor(delta) {
if (activeIdx === null) return;
const cells = getEntryCells(activeIdx);
const pos = cells.indexOf(activeIdx);
const newPos = pos + delta;
if (newPos >= 0 && newPos < cells.length) {
const newCell = cells[newPos];
document.querySelector(`input[data-idx='${newCell}']`).focus();
highlightFrom(newCell);
} else if (delta > 0 && newPos >= cells.length) {
moveToNextClue();
}
else if (delta < 0 && newPos < 0) {
moveToPreviousClue();
}
}
function highlightFrom(idx) {
clearHighlighting();
// Highlight the selected cell
const selCell = document.querySelector(`input[data-idx='${idx}']`).parentElement;
selCell.classList.add('selected');
// Highlight other cells in the entry
const cells = getEntryCells(idx);
cells.forEach(i => {
if (i !== idx) {
const cellElement = document.querySelector(`input[data-idx='${i}']`).parentElement;
cellElement.classList.add('active');
}
});
activeIdx = idx;
// Find the clue that contains this cell
const entries = puzzle[activeDir];
for (let i = 0; i < entries.length; i++) {
const position = findPositionForClue(activeDir, i);
const clueIdx = position.row * puzzle.cols + position.col;
const clueCells = getEntryCells(clueIdx);
if (clueCells.includes(idx)) {
// This is our active clue
const clueNum = getClueNumberFromIndex(activeDir, i);
const clueElement = document.querySelector(`#${activeDir}-list li[data-num='${clueNum}']`);
if (clueElement) {
clueElement.classList.add('active');
// Scroll the clue into view if needed
clueElement.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
break;
}
}
}
function getEntryCells(startIdx) {
const { r, c } = idxToRC(startIdx);
// step back to entry start
let rr = r, cc = c;
while (rr >= 0 && cc >= 0 && !isBlackCell(rr, cc)) {
if (activeDir === 'across') cc--; else rr--;
}
if (activeDir === 'across') cc++; else rr++;
// collect full entry
const cells = [];
while (rr < puzzle.rows && cc < puzzle.cols && !isBlackCell(rr, cc)) {
cells.push(rr * puzzle.cols + cc);
if (activeDir === 'across') cc++; else rr++;
}
return cells;
}
function isBlackCell(r, c) {
if (r < 0 || c < 0 || r >= puzzle.rows || c >= puzzle.cols) return true;
const idx = rcToIdx(r, c);
return puzzle.grid[idx].black;
}
function getClueNumber(r, c) {
// We need to determine if this cell starts an across or down entry
if (isBlackCell(r, c)) return null;
const startAcross = c === 0 || isBlackCell(r, c-1);
const startDown = r === 0 || isBlackCell(r-1, c);
if (!startAcross && !startDown) return null;
// Count all the clue numbers up to this point
let clueNumber = 1;
for (let rr = 0; rr < puzzle.rows; rr++) {
for (let cc = 0; cc < puzzle.cols; cc++) {
if (rr === r && cc === c) return clueNumber;
if (!isBlackCell(rr, cc)) {
const sa = cc === 0 || isBlackCell(rr, cc-1);
const sd = rr === 0 || isBlackCell(rr-1, cc);
if (sa || sd) clueNumber++;
}
}
}
return null;
}
function startTimer() {
const el = document.getElementById('timer');
timerInterval = setInterval(() => {
if (!puzzleCompleted) {
timerSecs++;
const m = Math.floor(timerSecs / 60), s = String(timerSecs % 60).padStart(2, '0');
el.firstChild.textContent = `${m}:${s}`;
}
}, 1000);
}
function checkPuzzleCompletion() {
if (puzzleCompleted) return false;
for (let r = 0; r < puzzle.rows; r++) {
for (let c = 0; c < puzzle.cols; c++) {
if (isBlackCell(r, c)) continue;
const idx = rcToIdx(r, c);
const input = document.querySelector(`input[data-idx='${idx}']`);
const expectedValue = answerGrid[r][c];
if (!input || input.value !== expectedValue) {
return false;
}
}
}
showVictoryScreen();
return true;
}
function showVictoryScreen() {
puzzleCompleted = true;
const overlay = document.createElement('div');
overlay.className = 'popup-overlay';
const messageBox = document.createElement('div');
messageBox.className = 'popup-message';
const heading = document.createElement('h2');
heading.textContent = 'Congratulations!';
const timeMsg = document.createElement('p');
const m = Math.floor(timerSecs / 60), s = String(timerSecs % 60).padStart(2, '0');
timeMsg.textContent = `You completed the puzzle in ${m}:${s}`;
const closeBtn = document.createElement('button');
closeBtn.textContent = 'Close';
closeBtn.addEventListener('click', () => {
document.body.removeChild(overlay);
});
messageBox.appendChild(heading);
messageBox.appendChild(timeMsg);
messageBox.appendChild(closeBtn);
overlay.appendChild(messageBox);
document.body.appendChild(overlay);
if (puzzle.highlight_prom_text)
highlightPromposal();
}
function highlightPromposal() {
let promStartingPos = 4;
activeDir = 'down';
clearHighlighting();
const promCell = document.querySelector(`input[data-idx='${promStartingPos}']`).parentElement;
promCell.classList.add('selected');
// Highlight all cells in prom
const cells = getEntryCells(promStartingPos);
cells.forEach(i => {
const cellElement = document.querySelector(`input[data-idx='${i}']`).parentElement;
cellElement.classList.add('selected');
});
}
function rcToIdx(r, c) {
return r * puzzle.cols + c;
}
function idxToRC(idx) {
return { r: Math.floor(idx / puzzle.cols), c: idx % puzzle.cols };
}