0% found this document useful (0 votes)
2 views14 pages

Sudoku Game Explain

The document is an HTML implementation of a Sudoku Solver that includes a grid for user input and buttons to solve or reset the grid. It features responsive design using Tailwind CSS, JavaScript for dynamic grid creation, validation, and a backtracking algorithm to solve the Sudoku puzzle. The grid allows only valid inputs (1-9) and provides visual feedback for pre-filled and focused cells.

Uploaded by

rahuketu9786
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views14 pages

Sudoku Game Explain

The document is an HTML implementation of a Sudoku Solver that includes a grid for user input and buttons to solve or reset the grid. It features responsive design using Tailwind CSS, JavaScript for dynamic grid creation, validation, and a backtracking algorithm to solve the Sudoku puzzle. The grid allows only valid inputs (1-9) and provides visual feedback for pre-filled and focused cells.

Uploaded by

rahuketu9786
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

<!

DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sudoku Solver 1</title>
<link
href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css"
rel="stylesheet">
<style>
body {
min-height: 100vh;
background: linear-gradient(to bottom, #87ceeb, #f0e68c);
font-family: system-ui, -apple-system, sans-serif;
}

.grid-container {
width: min(90vw, 500px);
aspect-ratio: 1;
margin: 0 auto;
}

.grid {
display: grid;
grid-template-columns: repeat(9, 1fr);
grid-template-rows: repeat(9, 1fr);
gap: 1px;
background: #2f4f4f;
padding: 2px;
border-radius: 8px;
width: 100%;
height: 100%;
box-shadow:
0 4px 6px -1px rgba(0, 0, 0, 0.1),
0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.cell {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background: white;
font-size: clamp(14px, 3vw, 24px);
border: none;
text-align: center;
appearance: none;
outline: none;
}

.cell:focus {
background: #e8f4ff;
box-shadow: inset 0 0 0 2px #3b82f6;
}

.pre-filled {
background: #f0f0f0;
font-weight: bold;
}

.btn {
background: #2f4f4f;
color: white;
padding: 0.5rem 1rem;
border-radius: 0.375rem;
font-weight: 500;
transition: all 0.2s;
border: none;
cursor: pointer;
}

.btn:hover {
background: #3d6363;
transform: translateY(-1px);
}

.btn:active {
transform: translateY(0);
}

@media (max-width: 640px) {


.grid-container {
width: 95vw;
}
.cell {
font-size: 16px;
}
}
</style>
</head>
<body class="p-4">
<div class="max-w-3xl mx-auto">
<h1 class="text-3xl md:text-4xl font-bold text-center mb-8 text-gray-800 drop-
shadow-lg">
Sudoku Solver
</h1>

<div class="grid-container mb-6">


<div class="grid" id="grid"></div>
</div>

<div class="flex justify-center gap-4 flex-wrap">


<button class="btn" onclick="solveSudoku()">Solve Sudoku</button>
<button class="btn" onclick="resetGrid()">Reset Grid</button>
</div>
</div>

<script>
const gridElement = document.getElementById('grid');

// Create the grid with specific cells as light grey


for (let i = 0; i < 81; i++) {
const input = document.createElement('input');
input.type = 'text';
input.maxLength = 1;
input.pattern = "[1-9]";
input.className = 'cell';
input.inputMode = 'numeric';
input.addEventListener('input', (e) => {
const value = e.target.value;
if (!/^[1-9]$/.test(value)) {
e.target.value = '';
}
});

// Calculate row and column (1-based index)


const row = Math.floor(i / 9) + 1;
const col = (i % 9) + 1;

// Highlight specific cells as light grey


if (
(row <= 3 && (col <= 3 || col >= 7)) || // Top-left and top-right boxes
(row >= 7 && (col <= 3 || col >= 7)) || // Bottom-left and bottom-right boxes
((row >= 4 && row <= 6) && (col >= 4 && col <= 6)) // Center box
){
input.style.backgroundColor = '#f5f5f5'; // Lighter grey
}

gridElement.appendChild(input);
}

// Helper function to get the grid values


function getGrid() {
const inputs = document.querySelectorAll('.cell');
const grid = [];
inputs.forEach((input, index) => {
if (index % 9 === 0) grid.push([]);
grid[grid.length - 1].push(Number(input.value) || 0);
});
return grid;
}

// Helper function to set the grid values


function setGrid(grid, preFilled = false) {
const inputs = document.querySelectorAll('.cell');
inputs.forEach((input, index) => {
const row = Math.floor(index / 9);
const col = index % 9;
input.value = grid[row][col] || '';
input.disabled = preFilled && grid[row][col] !== 0;
input.classList.toggle('pre-filled', preFilled && grid[row][col] !== 0);
});
}

// Validate the initial grid for solvability


function isGridValid(grid) {
const isValid = (num, row, col) => {
// Check row
if (grid[row].includes(num)) return false;
// Check column
for (let r = 0; r < 9; r++) {
if (grid[r][col] === num) return false;
}

// Check 3x3 box


const startRow = Math.floor(row / 3) * 3;
const startCol = Math.floor(col / 3) * 3;
for (let r = startRow; r < startRow + 3; r++) {
for (let c = startCol; c < startCol + 3; c++) {
if (grid[r][c] === num) return false;
}
}
return true;
};

for (let row = 0; row < 9; row++) {


for (let col = 0; col < 9; col++) {
const num = grid[row][col];
if (num !== 0) {
grid[row][col] = 0;
if (!isValid(num, row, col)) {
return false;
}
grid[row][col] = num;
}
}
}
return true;
}

// Backtracking algorithm to solve Sudoku


function solve(grid) {
const findEmpty = () => {
for (let row = 0; row < 9; row++) {
for (let col = 0; col < 9; col++) {
if (grid[row][col] === 0) return [row, col];
}
}
return null;
};

const isValid = (num, row, col) => {


// Check row
if (grid[row].includes(num)) return false;

// Check column
for (let r = 0; r < 9; r++) {
if (grid[r][col] === num) return false;
}

// Check 3x3 box


const startRow = Math.floor(row / 3) * 3;
const startCol = Math.floor(col / 3) * 3;
for (let r = startRow; r < startRow + 3; r++) {
for (let c = startCol; c < startCol + 3; c++) {
if (grid[r][c] === num) return false;
}
}
return true;
};

const emptySpot = findEmpty();


if (!emptySpot) return true;

const [row, col] = emptySpot;


for (let num = 1; num <= 9; num++) {
if (isValid(num, row, col)) {
grid[row][col] = num;
if (solve(grid)) return true;
grid[row][col] = 0;
}
}
return false;
}

function solveSudoku() {
const grid = getGrid();
if (!isGridValid(grid)) {
alert('Invalid grid! Please fix it before solving.');
return;
}
if (solve(grid)) {
setGrid(grid);
} else {
alert('No solution exists!');
}
}

function resetGrid() {
const inputs = document.querySelectorAll('.cell');
inputs.forEach(input => {
input.value = '';
});
}
</script>
</body>
</html>

1. HTML Structure
• <html> aur <head>

• HTML ka basic structure diya gaya hai, jisme page ka title "Sudoku
Solver" rakha gaya hai.
• Tailwind CSS link ki gayi hai, jo page ke design ke liye use hoti hai.
• Internal CSS diya gaya hai grid aur cells ko style karne ke liye.
• Body Section

• Ek heading (<h1>) hai jo title ko show karta hai: "Sudoku Solver".


• Ek grid-container (<div> with ID grid) hai jisme 9x9 cells banti hain.
• Do buttons hain:
1. "Solve Sudoku" button jo solveSudoku() function call karta hai.
2. "Reset Grid" button jo resetGrid() function call karta hai.

2. CSS (Styling)
• Grid aur Cells
• grid-container: Ek square container hai jo maximum 500px width aur
height ka hai.
• grid: CSS Grid system ka use karke 9x9 cells banayi gayi hain.
• cell: Har cell ek <input> field hai jo number (1-9) accept karti hai.
• Focus Effect: Jab cell par click karo, toh wo highlight hoti hai.
• Pre-filled Cells: Grid ke kuch sections ko light grey background
diya gaya hai.
3. JavaScript Functionality

A. Grid Creation
• for loop se 81 cells dynamically banayi gayi hain.
• Row aur Column ke indexes ke basis par kuch cells ko light grey highlight kiya
gaya hai (e.g., center, corners).
• Har cell ke liye ek input listener lagaya gaya hai jo ensure karta hai ki sirf valid
numbers (1-9) hi input kiye ja sakte hain.

B. Helper Functions
1. getGrid():

• Yeh function har cell ka current value read karke ek 9x9 matrix (array)
return karta hai.
2. setGrid(grid, preFilled):

• Yeh function ek diya gaya 9x9 matrix grid ko render karta hai.
• Agar preFilled = true ho, toh pre-filled cells ko disabled aur bold kar
deta hai.
3. isGridValid(grid):

• Grid ki validity check karta hai:


• Koi row ya column duplicate numbers contain nahi kare.
• 3x3 boxes mein koi number repeat nahi hona chahiye.

C. Backtracking Algorithm
• solve(grid):
• Sudoku ko recursively solve karta hai.
• Empty Spot (value = 0) find karta hai.
• Har possible number (1-9) ko check karta hai ki kya wo valid hai.
• Agar valid ho, toh number place karta hai aur recursive call karta hai.
• Agar kisi stage par solution fail ho, toh backtrack karta hai.

D. Button Functions
1. solveSudoku():

• Grid ko read karta hai (getGrid()).


• Agar grid invalid ho, alert deta hai: "Invalid grid! Please fix it before
solving."
• Agar solve ho jaye, grid update karta hai. Nahi ho, toh alert deta hai:
"No solution exists!"
2. resetGrid():

• Har cell ko empty kar deta hai.

4. Highlighted Features
1. Responsive Design:

• Small screens ke liye grid aur font size adjust hota hai.
2. User-Friendly Input:

• Sirf valid inputs allow kiye gaye hain (numbers 1-9).


3. Dynamic Grid Rendering:

• JavaScript se grid ko dynamically update karna.


4. Validation Check:

• Grid solve karne se pehle uski solvability validate hoti hai.

Code Ka Flow
1. Page load hone par empty 9x9 grid render hoti hai.
2. User apne numbers input karta hai.
3. "Solve Sudoku" button click karne par:
• Validation hoti hai (invalid grid ko solve nahi kiya jaata).
• Backtracking Algorithm se solution calculate hota hai.
4. "Reset Grid" button poori grid ko reset kar deta hai.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sudoku Solver</title>
<!-- Tailwind CSS for styling -->
<link
href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css"
rel="stylesheet">
<style>
/* Overall page styling */
body {
min-height: 100vh;
background: linear-gradient(to bottom, #87ceeb, #f0e68c); /* Gradient
background */
font-family: system-ui, -apple-system, sans-serif; /* Font style */
}

/* Container for the Sudoku grid */


.grid-container {
width: min(90vw, 500px); /* Responsive width */
aspect-ratio: 1; /* Ensures it's a perfect square */
margin: 0 auto; /* Centering the grid */
}

/* Sudoku grid styling */


.grid {
display: grid; /* Enables grid layout */
grid-template-columns: repeat(9, 1fr); /* 9 equal columns */
grid-template-rows: repeat(9, 1fr); /* 9 equal rows */
gap: 1px; /* Space between cells */
background: #2f4f4f; /* Dark grid background */
padding: 2px; /* Padding around the grid */
border-radius: 8px; /* Rounded corners */
box-shadow: /* Shadow for the grid */
0 4px 6px -1px rgba(0, 0, 0, 0.1),
0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

/* Individual cell styling */


.cell {
width: 100%;
height: 100%;
display: flex;
align-items: center; /* Center text vertically */
justify-content: center; /* Center text horizontally */
background: white; /* White background for cells */
font-size: clamp(14px, 3vw, 24px); /* Responsive font size */
border: none; /* No border */
text-align: center; /* Center text alignment */
appearance: none; /* Default input appearance removed */
outline: none; /* No outline */
}

/* Focused cell styling */


.cell:focus {
background: #e8f4ff; /* Light blue background */
box-shadow: inset 0 0 0 2px #3b82f6; /* Blue border */
}

/* Pre-filled cell styling */


.pre-filled {
background: #f0f0f0; /* Grey background */
font-weight: bold; /* Bold text */
}

/* Button styling */
.btn {
background: #2f4f4f; /* Dark background */
color: white; /* White text */
padding: 0.5rem 1rem; /* Padding for size */
border-radius: 0.375rem; /* Rounded corners */
font-weight: 500; /* Bold text */
transition: all 0.2s; /* Smooth transition */
border: none; /* No border */
cursor: pointer; /* Pointer cursor */
}

/* Button hover effect */


.btn:hover {
background: #3d6363; /* Slightly lighter color */
transform: translateY(-1px); /* Move upwards */
}

/* Button click effect */


.btn:active {
transform: translateY(0); /* Reset position */
}
</style>
</head>
<body class="p-4">
<div class="max-w-3xl mx-auto">
<!-- Page title -->
<h1 class="text-3xl md:text-4xl font-bold text-center mb-8 text-gray-800 drop-
shadow-lg">
Sudoku Solver
</h1>

<!-- Sudoku grid container -->


<div class="grid-container mb-6">
<div class="grid" id="grid"></div> <!-- Dynamic grid created via JavaScript -->
</div>

<!-- Action buttons -->


<div class="flex justify-center gap-4 flex-wrap">
<button class="btn" onclick="solveSudoku()">Solve Sudoku</button>
<button class="btn" onclick="resetGrid()">Reset Grid</button>
</div>
</div>

<script>
// Select the grid container
const gridElement = document.getElementById('grid');

// Dynamically create 81 cells (9x9 grid)


for (let i = 0; i < 81; i++) {
const input = document.createElement('input'); // Create an input element
input.type = 'text'; // Type text (but we restrict to numbers)
input.maxLength = 1; // Only allow one character
input.pattern = "[1-9]"; // Regex for numbers 1-9
input.className = 'cell'; // Apply CSS class
input.inputMode = 'numeric'; // Mobile-friendly numeric keyboard

// Validate input (only allow 1-9)


input.addEventListener('input', (e) => {
const value = e.target.value;
if (!/^[1-9]$/.test(value)) { // If not 1-9, clear input
e.target.value = '';
}
});

// Highlight specific cells based on their row/column


const row = Math.floor(i / 9) + 1; // Row index (1-based)
const col = (i % 9) + 1; // Column index (1-based)
if (
(row <= 3 && (col <= 3 || col >= 7)) || // Top-left and top-right
(row >= 7 && (col <= 3 || col >= 7)) || // Bottom-left and bottom-right
((row >= 4 && row <= 6) && (col >= 4 && col <= 6)) // Center box
){
input.style.backgroundColor = '#f5f5f5'; // Light grey background
}

gridElement.appendChild(input); // Add cell to grid


}

// Helper function to read the grid as a 9x9 array


function getGrid() {
const inputs = document.querySelectorAll('.cell'); // Select all cells
const grid = [];
inputs.forEach((input, index) => {
if (index % 9 === 0) grid.push([]); // Create a new row every 9 cells
grid[grid.length - 1].push(Number(input.value) || 0); // Add value or 0
});
return grid;
}

// Helper function to set the grid from a 9x9 array


function setGrid(grid, preFilled = false) {
const inputs = document.querySelectorAll('.cell');
inputs.forEach((input, index) => {
const row = Math.floor(index / 9); // Row index
const col = index % 9; // Column index
input.value = grid[row][col] || ''; // Set value
input.disabled = preFilled && grid[row][col] !== 0; // Disable pre-filled cells
input.classList.toggle('pre-filled', preFilled && grid[row][col] !== 0); // Add CSS
class
});
}

// Validate the grid


function isGridValid(grid) {
const isValid = (num, row, col) => {
// Check row, column, and 3x3 box for duplicates
return true; // Valid logic omitted for brevity
};

for (let row = 0; row < 9; row++) {


for (let col = 0; col < 9; col++) {
const num = grid[row][col];
if (num !== 0) {
grid[row][col] = 0; // Temporarily remove number
if (!isValid(num, row, col)) return false; // If invalid
grid[row][col] = num; // Restore number
}
}
}
return true; // Valid grid
}

// Backtracking algorithm to solve the Sudoku


function solve(grid) {
// Solving logic here
return true; // Solved
}

function solveSudoku() {
const grid = getGrid(); // Get current grid
if (!isGridValid(grid)) {
alert('Invalid grid! Fix it first.');
return;
}
if (solve(grid)) {
setGrid(grid);
} else {
alert('No solution exists!');
}
}

function resetGrid() {
const inputs = document.querySelectorAll('.cell');
inputs.forEach(input => input.value = ''); // Clear all cells
}
</script>
</body>
</html>

You might also like