JSFiddle - React, Tailwind, and code Playground

by Prathameshsb

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>Sudoku Game</title>
</head>
<body>
    <div class="sudoku-container" id="sudoku-container"></div>
    <script src="script.js"></script>
</body>
</html>

CSS

.sudoku-container {
    display: grid;
    grid-template-columns: repeat(9, 1fr);
    grid-template-rows: repeat(9, 1fr);
    gap: 2px;
}

.cell {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 40px;
    width: 40px;
    border: 1px solid black;
    font-size: 18px;
}

.cell.filled {
    background-color: #e0e0e0;
}

JavaScript

const sudokuContainer = document.getElementById('sudoku-container');

const sudokuBoard = [
    [5, 3, 0, 0, 7, 0, 0, 0, 0],
    [6, 0, 0, 1, 9, 5, 0, 0, 0],
    [0, 9, 8, 0, 0, 0, 0, 6, 0],
    [8, 0, 0, 0, 6, 0, 0, 0, 3],
    [4, 0, 0, 8, 0, 3, 0, 0, 1],
    [7, 0, 0, 0, 2, 0, 0, 0, 6],
    [0, 6, 0, 0, 0, 0, 2, 8, 0],
    [0, 0, 0, 4, 1, 9, 0, 0, 5],
    [0, 0, 0, 0, 8, 0, 0, 7, 9]
];

function createSudokuBoard() {
    for (let i = 0; i < 9; i++) {
        for (let j = 0; j < 9; j++) {
            const cell = document.createElement('div');
            cell.classList.add('cell');
            if (sudokuBoard[i][j] !== 0) {
                cell.textContent = sudokuBoard[i][j];
                cell.classList.add('filled');
            } else {
                cell.addEventListener('input', handleCellInput);
            }
            sudokuContainer.appendChild(cell);
        }
    }
}

function handleCellInput(event) {
    const inputValue = parseInt(event.target.innerText);
    const row = Math.floor(event.target.parentElement.rowIndex);
    const col = event.target.cellIndex;

    // Check if input is valid (between 1 and 9)
    if (inputValue >= 1 && inputValue <= 9) {
        sudokuBoard[row][col] = inputValue;
    } else {
        event.target.innerText = '';
        sudokuBoard[row][col] = 0;
    }
}

createSudokuBoard();