-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
542 lines (450 loc) · 15 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
function possible(board, y, x, n) {
for (let i = 0; i < 9; i++) {
if (board[y][i] === n || board[i][x] === n) {
return false;
}
}
const xSquare = Math.floor(x / 3) * 3;
const ySquare = Math.floor(y / 3) * 3;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (board[ySquare + i][xSquare + j] === n) {
return false;
}
}
}
return true;
}
function solvesudoku(board) {
const solutions = [];
function backtrack(board, y, x) {
if (y === 9) {
solutions.push(JSON.parse(JSON.stringify(board)));
return;
}
if (board[y][x] !== 0) {
if (x === 8) {
backtrack(board, y + 1, 0);
} else {
backtrack(board, y, x + 1);
}
return;
}
for (let n = 1; n <= 9; n++) {
if (possible(board, y, x, n)) {
board[y][x] = n;
if (x === 8) {
backtrack(board, y + 1, 0);
} else {
backtrack(board, y, x + 1);
}
board[y][x] = 0;
}
}
}
backtrack(board, 0, 0);
return solutions;
}
// sudoku problem generator program ____
// |
// \/
function shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
function isValid(board, row, col, num) {
for (let i = 0; i < 9; i++) {
if (board[row][i] === num || board[i][col] === num) {
return false;
}
}
const boxRow = Math.floor(row / 3) * 3;
const boxCol = Math.floor(col / 3) * 3;
for (let i = boxRow; i < boxRow + 3; i++) {
for (let j = boxCol; j < boxCol + 3; j++) {
if (board[i][j] === num) {
return false;
}
}
}
return true;
}
function generateSudoku() {
const board = Array(9).fill().map(() => Array(9).fill(0));
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
shuffle(nums);
for (let i = 0; i < 9; i++) {
board[0][i] = nums[i];
}
function fill(row, col) {
if (col === 9) {
col = 0;
row++;
}
if (row === 9) {
return true;
}
if (board[row][col] !== 0) {
return fill(row, col + 1);
}
shuffle(nums);
for (let i = 0; i < 9; i++) {
if (isValid(board, row, col, nums[i])) {
board[row][col] = nums[i];
if (fill(row, col + 1)) {
return true;
}
board[row][col] = 0;
}
}
return false;
}
fill(1, 0);
return board;
}
function removeValues(board, vals) {
const newBoard = board.map(row => row.slice());
while (vals > 0) {
const row = Math.floor(Math.random() * 9);
const col = Math.floor(Math.random() * 9);
if (newBoard[row][col] !== 0) {
newBoard[row][col] = 0;
vals--;
}
}
return newBoard;
}
function generateSudokuPuzzle(difficulty) {
const solved = generateSudoku();
const n = difficulty === 'easy' ? 45 : difficulty === 'medium' ? 40 : 35;
const puzzle = removeValues(solved, n);
return puzzle;
}
// Example usage
//<div class='cell'><input type='text' id='" + (count + 2) + "' class='input'></div>
let variable = [0];
let z = -1;
let z2 = false;
for (var i = 1; i <= 81; i++) {
while (true) {
z = Math.floor((Math.random() * 81) + 1);
for (let x of variable) {
if (x == z) {
z2 = true;
}
}
if (z2 == false) {
break;
}
z2 = false;
}
variable.push(z);
document.getElementById("main").innerHTML = document.getElementById("main").innerHTML + `<input type="number" value="" id="${i}" class="input" oninput="this.value = this.value.slice(-1); checkInputValidity()" style="--i:${z}" readonly="true">`;
}
// adding margin to create 3x3 grid effect
for (let i = 1; i <= 81; i++) {
let x = document.getElementById(i.toString());
if (i % 9 == 3 || i % 9 == 6) {
x.style.marginRight = ".4rem";
}
if ((i >= 19 && i <= 27) || (i >= 46 && i <= 54)) {
x.style.marginBottom = ".6rem";
}
}
const timer = () => {
let sec = 0;
let min = 0;
var timeid = setInterval(() => {
sec += 1;
if (sec > 59) {
min += 1;
sec = 0;
}
let inmin = document.getElementById("time_min");
let insec = document.getElementById("time_sec");
inmin.innerHTML = (min < 10 ? "0" + min : min);
insec.innerHTML = (sec < 10 ? "0" + sec : sec);
if (min >= 2 && (sec == 10 || sec == 20 || sec == 30 || sec == 40 || sec == 50 || sec == 59)) {
if (score > 0) {
score -= 2;
document.getElementById("score").innerHTML = (score < 10 ? "0" + score : score);
if (score <= 20) {
document.getElementById("score").style.color = "red"
}
}
}
}, 1000);
return timeid;
}
var level = "not-set";
var ques;
var solution;
var id;
var timeid;
var score = 100;
document.getElementById("score").innerHTML = score;
const checkValidity = (board, row, col, num) => {
// Check the row
for (let i = 0; i < 9; i++) {
if (board[row][i] === num && i !== col) {
return false;
}
}
// Check the column
for (let i = 0; i < 9; i++) {
if (board[i][col] === num && i !== row) {
return false;
}
}
// Check the 3x3 box
const boxRow = Math.floor(row / 3) * 3;
const boxCol = Math.floor(col / 3) * 3;
for (let i = boxRow; i < boxRow + 3; i++) {
for (let j = boxCol; j < boxCol + 3; j++) {
if (board[i][j] === num && (i !== row || j !== col)) {
return false;
}
}
}
return true;
};
const checkInputValidity = () => {
const userBoard = Array(9).fill().map(() => Array(9).fill(0));
let count = 1;
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
const elem = document.getElementById(count.toString());
if (elem) {
userBoard[i][j] = elem.value;
}
else {
userBoard[i][j] = 0;
}
count += 1;
}
}
count = 1;
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
const elem = document.getElementById(count.toString());
if (!elem.readOnly && !checkValidity(userBoard, i, j, userBoard[i][j])) {
elem.style.color = "red";
}
else {
elem.style.color = "white";
}
count += 1;
}
}
}
// checksudoku function
const checksudoku = () => {
let x = 1;
let possible = true;
let usersolution = [
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
];
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
let value = document.getElementById(x.toString()).value;
usersolution[i][j] = Number.parseInt(value);
if (isNaN(usersolution[i][j])) {
possible = false;
break;
}
x += 1;
}
if (!possible) {
break;
}
}
if (possible) {
for (x = 0; x < solution.length; x++) {
let yes = true;
ans = solution[x];
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
if (ans[i][j] != usersolution[i][j]) {
yes = false;
}
}
}
if (yes == true) {
return true;
}
}
}
else {
return false;
}
}
//answer
function answer() {
if (confirm("do you really want to give up!!")) {
if (level == "not-set") {
alert("please start a game first!!");
}
else {
clearInterval(id);
clearInterval(timeid);
let ans = solution[0];
console.log("this is just one solution, There may be more solutions possible");
document.getElementById("score").innerHTML = "00";
let x = 1;
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
document.getElementById(x.toString()).value = ans[i][j];
document.getElementById(x.toString()).readOnly = true;
x += 1;
}
}
checkInputValidity();
}
for (let i = 0; i < 3; i++) {
document.getElementsByClassName("label")[i].setAttribute("onclick", "return true;");
}
document.getElementById("start").setAttribute("onclick", "start()");
}
}
//check answer
const interval = () => {
id = setInterval(() => {
if (document.activeElement.className == "input") {
if (checksudoku()) {
clearInterval(id);
let currentscore = Number.parseInt(document.getElementById("score").innerHTML);
try {
let name = localStorage.getItem("name");
let score = Number.parseInt(localStorage.getItem("score"));
if (isNaN(score)) {
throw "not a number";
}
else {
if (score < currentscore) {
alert(`congractulations, you beats the high score !!.....\nyour score = ${currentscore}\nhigh score = ${score}\n\nyour name = ${name}`);
localStorage.setItem("score", currentscore);
}
else {
alert(`congractulation you win!....\nyour score = ${currentscore}\nhigh score = ${score}\n\nyour name = ${name}`);
}
}
} catch (err) {
console.log("no user found in local storage");
let name = prompt(`congractulation you win!....\nyour score = ${currentscore}\n\nEnter your name: `);
localStorage.setItem("name", name);
localStorage.setItem("score", currentscore);
}
window.location.reload();
}
}
}, 500);
return id;
}
function start() {
timeid = timer();
for (let i = 0; i < 3; i++) {
document.getElementsByClassName("label")[i].setAttribute("onclick", "return false;");
}
if (document.getElementById("easy").checked) {
level = 'easy';
ques = generateSudokuPuzzle('easy');
}
else if (document.getElementById("medium").checked) {
level = 'medium';
ques = generateSudokuPuzzle('medium');
}
else {
level = 'hard';
ques = generateSudokuPuzzle('hard');
}
let x = 0;
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
if (ques[i][j].toString() != '0') {
document.getElementById((x + 1).toString()).value = ques[i][j];
document.getElementById((x + 1).toString()).readOnly = true;
document.getElementById((x + 1).toString()).style.backgroundColor = "#0b1c49";
}
else {
document.getElementById((x + 1).toString()).readOnly = false;
document.getElementById((x + 1).toString()).style.backgroundColor = "#0f2a72";
document.getElementById((x + 1).toString()).value = '';
}
x += 1;
}
}
interval();
solution = solvesudoku(ques);
document.getElementById("start").removeAttribute("onclick");
// console.log(solution.map(e => "" + e));
}
function replay() {
clearInterval(timeid);
clearInterval(id);
for (var i = 1; i <= 81; i++) {
document.getElementById(i.toString()).value = '';
document.getElementById(i.toString()).style.backgroundColor = "#0f2a72";
document.getElementById(i.toString()).readOnly = false;
}
start();
}
// const MoveFocus = (event) => {
// const element = event.target;
// let id = element.id;
// if (element.tagName === 'INPUT' && element.type === 'number' && (event.key === 'ArrowUp' || event.key === 'ArrowDown')) {
// event.preventDefault();
// }
// if (element.tagName === 'INPUT' && element.type === 'number') {
// if (event.key === 'ArrowUp') {
// document.getElementById(id - 9).focus();
// }
// else if (event.key === 'ArrowDown') {
// document.getElementById(id + 9).focus();
// }
// else if (event.key === 'ArrowLeft') {
// document.getElementById(id - 1).focus();
// }
// else if (event.key === 'ArrowRight') {
// document.getElementById(id + 1).focus();
// }
// }
// }
function moveFocusByArrowKey(event) {
if (event.target.tagName === 'INPUT' && event.target.type === 'number' && event.key.startsWith('Arrow')) {
event.preventDefault();
const currentElement = document.activeElement;
const cellNumber = parseInt(currentElement.id);
let newCellNumber;
switch (event.key) {
case 'ArrowUp':
newCellNumber = Math.max(1, cellNumber - 9);
break;
case 'ArrowDown':
newCellNumber = Math.min(81, cellNumber + 9);
break;
case 'ArrowLeft':
newCellNumber = Math.max(1, cellNumber - 1);
break;
case 'ArrowRight':
newCellNumber = Math.min(81, cellNumber + 1);
break;
default:
return;
}
const newElement = document.getElementById(`${newCellNumber}`);
if (newElement) {
newElement.focus();
}
}
}
document.addEventListener('keydown', moveFocusByArrowKey);