Sure! Below is a complete HTML file that implements a non-interactive Sudoku game as per your specifications. The game randomly generates a Sudoku puzzle, displays both the unsolved (left side) and solved (right side) versions on an HTML canvas, and includes a button to download the solved Sudoku as a PNG image.
Features:
- Random Sudoku Generation: Uses a backtracking algorithm to generate a complete Sudoku solution and then removes a number of cells to create the puzzle.
- Canvas Rendering: Displays the unsolved and solved Sudoku grids side by side on an HTML canvas.
- Download Functionality: Provides a button that allows users to download the solved Sudoku grid as a PNG image.
Implementation Details:
-
Sudoku Generation:
- A backtracking algorithm generates a complete, valid Sudoku grid.
- A certain number of cells are cleared from the complete grid to create the puzzle. You can adjust the difficulty by changing the number of cells removed.
-
Canvas Drawing:
- The Sudoku grids are drawn on a single canvas, with the unsolved puzzle on the left and the complete solution on the right.
- The grids are styled with thick lines for 3x3 subgrids and thin lines for individual cells.
-
Download Button:
- When clicked, the download button creates a temporary canvas containing only the solved Sudoku grid and triggers a download of this image as a PNG file.
Complete HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Random Sudoku Game</title>
<style>
body {
text-align: center;
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
canvas {
border: 2px solid #000;
margin-top: 20px;
}
#downloadBtn {
margin-top: 20px;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Random Sudoku Game</h1>
<canvas id="sudokuCanvas" width="700" height="350"></canvas>
<br>
<button id="downloadBtn">Download Solved Sudoku as PNG</button>
<script>
// Utility function to shuffle an array
function shuffle(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]];
}
return array;
}
// Function to generate a complete Sudoku grid using backtracking
function generateSudoku() {
const grid = Array.from({ length: 9 }, () => Array(9).fill(0));
function isValid(grid, row, col, num) {
for (let x = 0; x < 9; x++) {
if (grid[row][x] === num || grid[x][col] === num) {
return false;
}
}
const startRow = Math.floor(row / 3) * 3;
const startCol = Math.floor(col / 3) * 3;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (grid[startRow + i][startCol + j] === num) {
return false;
}
}
}
return true;
}
function fillGrid(grid) {
for (let row = 0; row < 9; row++) {
for (let col = 0; col < 9; col++) {
if (grid[row][col] === 0) {
const numbers = shuffle([1,2,3,4,5,6,7,8,9]);
for (let num of numbers) {
if (isValid(grid, row, col, num)) {
grid[row][col] = num;
if (fillGrid(grid)) {
return true;
}
grid[row][col] = 0;
}
}
return false;
}
}
}
return true;
}
fillGrid(grid);
return grid;
}
// Function to create a puzzle by removing numbers from the complete grid
function createPuzzle(grid, removeCount = 40) {
const puzzle = grid.map(row => row.slice());
let attempts = removeCount;
while (attempts > 0) {
const row = Math.floor(Math.random() * 9);
const col = Math.floor(Math.random() * 9);
if (puzzle[row][col] !== 0) {
puzzle[row][col] = 0;
attempts--;
}
}
return puzzle;
}
// Function to draw a Sudoku grid on a canvas context
function drawSudoku(ctx, grid, xOffset, yOffset, cellSize, isPuzzle = false) {
ctx.strokeStyle = '#000';
ctx.lineWidth = 1;
// Draw cells
for (let i = 0; i <= 9; i++) {
// Thicker lines for 3x3 grids
if (i % 3 === 0) {
ctx.lineWidth = 3;
} else {
ctx.lineWidth = 1;
}
// Vertical lines
ctx.beginPath();
ctx.moveTo(xOffset + i * cellSize, yOffset);
ctx.lineTo(xOffset + i * cellSize, yOffset + 9 * cellSize);
ctx.stroke();
// Horizontal lines
ctx.beginPath();
ctx.moveTo(xOffset, yOffset + i * cellSize);
ctx.lineTo(xOffset + 9 * cellSize, yOffset + i * cellSize);
ctx.stroke();
}
// Set text properties
ctx.font = `${cellSize / 1.5}px Arial`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = '#000';
// Fill numbers
for (let row = 0; row < 9; row++) {
for (let col = 0; col < 9; col++) {
const num = grid[row][col];
if (num !== 0) {
ctx.fillText(num, xOffset + col * cellSize + cellSize / 2, yOffset + row * cellSize + cellSize / 2);
}
}
}
}
// Main function to initialize the Sudoku game
function initSudoku() {
const canvas = document.getElementById('sudokuCanvas');
const ctx = canvas.getContext('2d');
// Generate complete Sudoku solution
const solution = generateSudoku();
// Create puzzle by removing numbers
const puzzle = createPuzzle(solution, 40); // Adjust removeCount for difficulty
// Define cell size and offsets
const cellSize = 30;
const padding = 20;
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw Puzzle (Left Side)
drawSudoku(ctx, puzzle, padding, padding, cellSize, true);
// Draw Solution (Right Side)
drawSudoku(ctx, solution, padding + 9 * cellSize + padding, padding, cellSize, false);
// Store solution for download
canvas.dataset.solution = JSON.stringify(solution);
}
// Function to download the solved Sudoku as PNG
function downloadSolution() {
const canvas = document.getElementById('sudokuCanvas');
const solution = JSON.parse(canvas.dataset.solution);
// Create a temporary canvas for the solution
const tempCanvas = document.createElement('canvas');
const cellSize = 30;
const padding = 20;
tempCanvas.width = 9 * cellSize + 2 * padding;
tempCanvas.height = 9 * cellSize + 2 * padding;
const ctx = tempCanvas.getContext('2d');
// Fill background
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, tempCanvas.width, tempCanvas.height);
// Draw Sudoku
drawSudoku(ctx, solution, padding, padding, cellSize, false);
// Create a link to download the image
const link = document.createElement('a');
link.download = 'solved_sudoku.png';
link.href = tempCanvas.toDataURL();
link.click();
}
// Initialize Sudoku on page load
window.onload = initSudoku;
// Add event listener to download button
document.getElementById('downloadBtn').addEventListener('click', downloadSolution);
</script>
</body>
</html>
How It Works:
-
Sudoku Generation:
- The
generateSudoku function creates a complete Sudoku grid using a backtracking algorithm. It fills the grid randomly to ensure different puzzles each time.
- The
createPuzzle function removes a specified number of cells from the complete grid to create the puzzle. By default, it removes 40 cells, but you can adjust this number to increase or decrease the difficulty.
-
Drawing on Canvas:
- The
drawSudoku function takes a grid and draws it on the canvas. It handles drawing the grid lines (with thicker lines for the 3x3 subgrids) and the numbers.
- The canvas is split into two sections:
- Left Side: Displays the puzzle with some cells removed.
- Right Side: Displays the complete solved Sudoku grid.
-
Download Functionality:
- When the "Download Solved Sudoku as PNG" button is clicked, the
downloadSolution function creates a temporary canvas, draws the solved Sudoku on it, and triggers a download of the image.
-
Initialization:
- Upon loading the page (
window.onload = initSudoku;), a new Sudoku puzzle is generated and drawn on the canvas.
Customization:
-
Difficulty Level:
- To make the puzzle easier or harder, adjust the
removeCount parameter in the createPuzzle function. A higher number of removed cells makes the puzzle harder.
-
Styling:
- You can modify the CSS within the
<style> tags to change the appearance of the canvas and button to better fit your preferences or website theme.
Usage:
-
Viewing the Puzzle and Solution:
- Open the HTML file in a web browser. You'll see the unsolved puzzle on the left and the complete solution on the right.
-
Downloading the Solution:
- Click the "Download Solved Sudoku as PNG" button to download an image of the solved Sudoku grid.
Feel free to integrate this code into your website or modify it further to suit your needs!