-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
53 lines (47 loc) · 1.62 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
// Initialize empty Sudoku grid
let grid = Array(9).fill().map(() => Array(9).fill(0));
// Function to render the Sudoku grid
function renderGrid() {
const sudokuGrid = document.getElementById('sudoku-grid');
sudokuGrid.innerHTML = ''; // Clear previous grid
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
const cell = document.createElement('input');
cell.className = 'sudoku-cell';
cell.type = 'text';
cell.maxLength = 1;
cell.value = grid[i][j] === 0 ? '' : grid[i][j];
cell.dataset.highlight = grid[i][j] !== 0;
cell.oninput = () => validateInput(cell, i, j);
sudokuGrid.appendChild(cell);
}
}
}
// Function to validate Sudoku input (numbers only 1-9)
function validateInput(cell, row, col) {
const value = cell.value;
if (value >= 1 && value <= 9) {
grid[row][col] = parseInt(value);
} else {
cell.value = ''; // Clear invalid input
grid[row][col] = 0;
}
}
// Function to generate a random Sudoku grid
function generateSudoku() {
// Reset grid to empty
grid = Array(9).fill().map(() => Array(9).fill(0));
// Simple random number filling (you can implement Sudoku puzzle generation logic here)
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
if (Math.random() > 0.7) {
grid[i][j] = Math.floor(Math.random() * 9) + 1;
}
}
}
renderGrid();
}
// On page load, render an empty grid
window.onload = () => {
generateSudoku();
};