Create a self-containing HTML file that produces a Sudoku puzzle generator and solver
- User
Create a self-containing HTML file that produces a Sudoku puzzle generator and solver
Assistant
Okay, here is a self-contained HTML file that includes HTML structure, CSS styles, and JavaScript logic to generate and solve Sudoku puzzles.
It uses a recursive backtracking algorithm for both generation (by generating a full valid grid and then removing cells while ensuring solvability) and solving.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Sudoku Generator & Solver</title> <style> body { font-family: sans-serif; display: flex; flex-direction: column; align-items: center; background-color: #f4f4f4; margin: 20px; } h1 { color: #333; margin-bottom: 20px; } #sudoku-container { margin-bottom: 20px; border: 3px solid #000; box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.3); } table { border-collapse: collapse; } td { border: 1px solid #bbb; width: 40px; height: 40px; padding: 0; text-align: center; vertical-align: middle; } /* Thicker borders for 3x3 blocks */ td:nth-child(3n) { border-right-width: 3px; } tr:nth-child(3n) td { border-bottom-width: 3px; } td:first-child { border-left-width: 3px; } tr:first-child td { border-top-width: 3px; } tr:last-child td { border-bottom-width: 3px; } td:last-child { border-right-width: 3px; } td input { width: 100%; height: 100%; box-sizing: border-box; border: none; text-align: center; font-size: 1.5em; color: #007bff; /* Color for user input */ background-color: transparent; padding: 0; margin: 0; -moz-appearance: textfield; /* Remove number input arrows */ } td input::-webkit-outer-spin-button, td input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } td input:disabled { color: #333; /* Color for generated clues */ font-weight: bold; background-color: #eee; } td input:focus { outline: 2px solid #007bff; background-color: #e9f5ff; } .controls { margin-bottom: 20px; display: flex; gap: 10px; align-items: center; } .controls label { margin-right: 5px; } button { padding: 10px 15px; font-size: 1em; cursor: pointer; border: none; border-radius: 5px; transition: background-color 0.3s ease; } button:hover { opacity: 0.9; } #generate-btn { background-color: #28a745; color: white; } #solve-btn { background-color: #ffc107; color: #333; } #clear-btn { background-color: #dc3545; color: white; } #message { margin-top: 10px; font-size: 1.1em; color: #555; min-height: 1.2em; /* Reserve space */ } </style> </head> <body> <h1>Sudoku Generator & Solver</h1> <div id="sudoku-container"> <table> <tbody> <!-- The grid will be generated here by JavaScript --> </tbody> </table> </div> <div class="controls"> <label for="difficulty">Difficulty:</label> <select id="difficulty"> <option value="easy">Easy</option> <option value="medium">Medium</option> <option value="hard">Hard</option> </select> <button id="generate-btn">Generate New Puzzle</button> <button id="solve-btn">Solve Puzzle</button> <button id="clear-btn">Clear Grid</button> </div> <div id="message"></div> <script> const GRID_SIZE = 9; const BLOCK_SIZE = 3; let currentBoard = []; // The current state of the board (user input + clues) let solutionBoard = []; // The solved state of the *generated* puzzle (used for comparison if needed, or just the target for solver) const gridBody = document.querySelector('#sudoku-container tbody'); const messageDiv = document.getElementById('message'); const generateBtn = document.getElementById('generate-btn'); const solveBtn = document.getElementById('solve-btn'); const clearBtn = document.getElementById('clear-btn'); const difficultySelect = document.getElementById('difficulty'); // --- UI Rendering and Interaction --- function createGridHTML() { gridBody.innerHTML = ''; // Clear existing grid for (let r = 0; r < GRID_SIZE; r++) { const row = document.createElement('tr'); for (let c = 0; c < GRID_SIZE; c++) { const cell = document.createElement('td'); const input = document.createElement('input'); input.type = 'text'; input.maxLength = 1; input.pattern = '\\d?'; // Allows digits 0-9 or empty // Add input validation input.addEventListener('input', function(e) { // Allow only digits 1-9 or empty const value = e.target.value.replace(/[^1-9]/g, ''); e.target.value = value; // Update internal board state (optional, but good for tracking user input) // readGridFromHTML(); // Could call this after each input or on solve/check }); input.addEventListener('focus', function(e) { messageDiv.textContent = ''; // Clear message on interaction }); cell.appendChild(input); row.appendChild(cell); } gridBody.appendChild(row); } } function readGridFromHTML() { const board = []; const rows = gridBody.querySelectorAll('tr'); rows.forEach((row, r) => { board[r] = []; const inputs = row.querySelectorAll('input'); inputs.forEach((input, c) => { const value = parseInt(input.value) || 0; // Use 0 for empty cells board[r][c] = value; }); }); return board; } function writeGridToHTML(board, setClues = false) { const rows = gridBody.querySelectorAll('tr'); board.forEach((rowData, r) => { const inputs = rows[r].querySelectorAll('input'); rowData.forEach((cellValue, c) => { const input = inputs[c]; if (cellValue === 0) { input.value = ''; input.disabled = false; input.classList.remove('clue'); } else { input.value = cellValue; if (setClues) { input.disabled = true; input.classList.add('clue'); } else { // If not setting clues, this is likely a solved state or user input // Only disable if it was originally a clue // (This logic might need refinement depending on flow - simple version disables only during initial setClues) if(input.classList.contains('clue')) { input.disabled = true; } else { input.disabled = false; } } } }); }); } function clearGridHTML() { const inputs = gridBody.querySelectorAll('input'); inputs.forEach(input => { input.value = ''; input.disabled = false; input.classList.remove('clue'); }); messageDiv.textContent = ''; currentBoard = Array(GRID_SIZE).fill(0).map(() => Array(GRID_SIZE).fill(0)); // Reset internal board } function showMessage(msg, isError = false) { messageDiv.textContent = msg; messageDiv.style.color = isError ? 'red' : '#555'; } // --- Sudoku Logic Helper Functions --- function isValid(board, row, col, num) { // Check row for (let c = 0; c < GRID_SIZE; c++) { if (board[row][c] === num) { return false; } } // Check column for (let r = 0; r < GRID_SIZE; r++) { if (board[r][col] === num) { return false; } } // Check 3x3 block const startRow = Math.floor(row / BLOCK_SIZE) * BLOCK_SIZE; const startCol = Math.floor(col / BLOCK_SIZE) * BLOCK_SIZE; for (let r = 0; r < BLOCK_SIZE; r++) { for (let c = 0; c < BLOCK_SIZE; c++) { if (board[startRow + r][startCol + c] === num) { return false; } } } return true; } function findEmpty(board) { for (let r = 0; r < GRID_SIZE; r++) { for (let c = 0; c < GRID_SIZE; c++) { if (board[r][c] === 0) { return [r, c]; } } } return null; // No empty cell found } function shuffleArray(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; // Swap elements } return array; } // --- Sudoku Solver --- function solveSudoku(board) { const emptySpot = findEmpty(board); if (!emptySpot) { return true; // Grid is solved } const [row, col] = emptySpot; const numbers = shuffleArray([1, 2, 3, 4, 5, 6, 7, 8, 9]); // For generation, use shuffled; for solving, sequential is fine for (let num of numbers) { if (isValid(board, row, col, num)) { board[row][col] = num; if (solveSudoku(board)) { return true; // Found a solution } // Backtrack board[row][col] = 0; } } return false; // No number worked for this cell } // Counts solutions by attempting to solve. Stops early if count > 1. // Returns the count of solutions found. function countSolutions(board) { const tempBoard = board.map(row => [...row]); // Work on a copy let count = 0; function solveAndCount(currentBoard) { const emptySpot = findEmpty(currentBoard); if (!emptySpot) { return 1; // Found one solution } const [row, col] = emptySpot; let solutionsFound = 0; for (let num = 1; num <= 9; num++) { if (isValid(currentBoard, row, col, num)) { currentBoard[row][col] = num; solutionsFound += solveAndCount(currentBoard); currentBoard[row][col] = 0; // Backtrack if (solutionsFound > 1) { return solutionsFound; // Stop early if multiple found } } } return solutionsFound; } // Initialize the recursive counting process return solveAndCount(tempBoard); } // --- Sudoku Generator --- function fillGrid(board) { const emptySpot = findEmpty(board); if (!emptySpot) { return true; // Grid is filled } const [row, col] = emptySpot; const numbers = shuffleArray([1, 2, 3, 4, 5, 6, 7, 8, 9]); for (let num of numbers) { if (isValid(board, row, col, num)) { board[row][col] = num; if (fillGrid(board)) { return true; // Found a way to fill the rest } // Backtrack board[row][col] = 0; } } return false; // Couldn't fill this cell } function generatePuzzle(difficulty = 'medium') { showMessage('Generating...', false); // Give the message time to render before the potentially long task setTimeout(() => { let solvedGrid = Array(GRID_SIZE).fill(0).map(() => Array(GRID_SIZE).fill(0)); // 1. Generate a complete, valid solution if (!fillGrid(solvedGrid)) { console.error("Failed to generate a full grid."); showMessage('Error generating puzzle', true); return; } solutionBoard = solvedGrid.map(row => [...row]); // Store the full solution currentBoard = solvedGrid.map(row => [...row]); // Start removing from a copy // 2. Determine number of cells to remove based on difficulty let cellsToRemove; switch (difficulty) { case 'easy': cellsToRemove = 35; break; // Example counts case 'medium': cellsToRemove = 45; break; case 'hard': cellsToRemove = 55; break; default: cellsToRemove = 45; } // 3. Randomly remove cells while ensuring unique solution const cells = []; for(let r = 0; r < GRID_SIZE; r++) { for(let c = 0; c < GRID_SIZE; c++) { cells.push({r, c}); } } shuffleArray(cells); let removedCount = 0; for (const {r, c} of cells) { if (removedCount >= cellsToRemove) break; const value = currentBoard[r][c]; if (value === 0) continue; // Already removed currentBoard[r][c] = 0; // Temporarily remove // Check if the puzzle still has a unique solution if (countSolutions(currentBoard) === 1) { removedCount++; } else { // If not unique or no solution, put the number back currentBoard[r][c] = value; } } // Ensure we removed at least the target number for hard, etc. // If not enough removals resulted in unique solution, just show what we got. // A more advanced generator would try different removal patterns. writeGridToHTML(currentBoard, true); // Display the puzzle, setting clues as disabled showMessage('Puzzle generated!', false); }, 10); // Small delay to update UI message first } // --- Event Handlers --- generateBtn.addEventListener('click', () => { const difficulty = difficultySelect.value; generatePuzzle(difficulty); }); solveBtn.addEventListener('click', () => { showMessage('Solving...', false); // Give the message time to render setTimeout(() => { const boardToSolve = readGridFromHTML(); // Get current state from UI // Prevent overwriting clues during solve attempt if user changed them // Create a true copy where original clues are fixed const solveAttemptBoard = Array(GRID_SIZE).fill(0).map(() => Array(GRID_SIZE).fill(0)); const inputs = gridBody.querySelectorAll('input'); inputs.forEach((input, index) => { const r = Math.floor(index / GRID_SIZE); const c = index % GRID_SIZE; if (input.classList.contains('clue') && input.value !== '') { solveAttemptBoard[r][c] = parseInt(input.value); } else if (input.value !== '') { solveAttemptBoard[r][c] = parseInt(input.value); } }); if (solveSudoku(solveAttemptBoard)) { writeGridToHTML(solveAttemptBoard, false); // Display the solved grid (don't set clues again) showMessage('Puzzle solved!', false); } else { showMessage('No solution found for the current grid.', true); } }, 10); }); clearBtn.addEventListener('click', clearGridHTML); // --- Initialization --- document.addEventListener('DOMContentLoaded', () => { createGridHTML(); generatePuzzle(difficultySelect.value); // Generate a puzzle on load }); </script> </body> </html>How it works:
- HTML Structure: Sets up the basic page, a container for the grid (
<table>), control buttons (<button>), a difficulty selector (<select>), and a message area (<div>). - CSS Styling: Styles the grid, cells, input fields (including specific styles for generated clues vs. user input), buttons, and the overall layout. It uses
border-collapseand targeted borders (:nth-child) to create the classic Sudoku look with thick lines for 3x3 blocks. - JavaScript Logic:
createGridHTML(): Dynamically builds the 9x9 table with<input type="text">elements inside each cell (<td>).readGridFromHTML(): Reads the current values from the HTML input fields into a 2D JavaScript array (using0for empty cells).writeGridToHTML(): Takes a 2D array and populates the HTML input fields. It can optionally disable inputs that represent generated clues.clearGridHTML(): Clears all input fields and enables them.isValid(board, row, col, num): A core helper function to check if placingnumat(row, col)is valid according to Sudoku rules (row, column, and 3x3 block).findEmpty(board): Finds the next empty cell (value 0) in the grid.shuffleArray(array): A standard Fisher-Yates shuffle to randomize numbers (important for generation).fillGrid(board): A recursive backtracking function used only during generation to create a complete and valid 9x9 Sudoku solution. It tries random numbers in empty cells and backtracks if a dead end is reached.solveSudoku(board): A standard recursive backtracking solver. It finds an empty cell, tries numbers 1-9, and recursively calls itself. If a number leads to a solution, it returns true; otherwise, it backtracks.countSolutions(board): A variation of the solver that counts how many distinct full solutions exist for a given puzzle state. It stops early if it finds more than one solution. This is crucial for generating puzzles that have a unique solution.generatePuzzle(difficulty):- Initializes an empty board.
- Calls
fillGridto create a full, valid solution. - Copies this solution.
- Based on the selected difficulty, it attempts to remove a certain number of cells.
- For each cell removal, it calls
countSolutions. If the puzzle still has exactly one solution after removal, the removal is kept; otherwise, the number is put back. - Finally, it displays the resulting puzzle (with 0s representing empty cells) in the HTML grid and disables the clue inputs.
solvePuzzle(): Reads the current state from the HTML grid (including user input), callssolveSudokuon a copy of this state, and updates the HTML grid with the result if a solution is found.- Event listeners are attached to the buttons and the difficulty selector.
DOMContentLoadedensures the grid is created and an initial puzzle is generated when the page loads.
This single file provides a functional Sudoku experience within your browser.
- HTML Structure: Sets up the basic page, a container for the grid (
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.