Sudoku Generator

Generate unlimited free Sudoku puzzles with multiple difficulty levels. Play online with interactive features or print for offline solving. Perfect for beginners to experts with AI-powered hints and customizable options.

Grid Size
4ร—4
Beginner
9ร—9
Classic
Difficulty Level
Easy 45-50 clues
Medium 35-40 clues
Hard 25-30 clues
Expert 17-24 clues
Game Mode
Solve Online
Print Format
00:00
Difficulty: Easy
Grid Size: 9ร—9
Filled: 0/81
Errors: 0
0
Generated
0
Completed
--:--
Best Time
--:--
Average Time
0%
Success Rate

๐ŸŽฏ Try Sample Puzzles

๐ŸŽฒ Classic Sudoku
Traditional 9ร—9 puzzle for practice
๐ŸŒฑ Beginner Friendly
Easy 4ร—4 puzzle for newcomers
๐Ÿ”ฅ Expert Challenge
Hard puzzle for experienced players
๐Ÿ“… Daily Puzzle
Today's featured Sudoku challenge
โš–๏ธ Symmetric Pattern
Aesthetically balanced puzzle design
๐ŸŽฏ Minimal Clues
17-clue puzzle - ultimate challenge

๐Ÿง  Love Brain Training Games?

Discover premium puzzle books and brain training apps for mental fitness

โœจ Smart Nation's Core Infrastructure: WIA Code โœจ

DroneยทRobot delivery, autonomous driving, emergency rescue and more - Experience the future in 30 days, completely free for your nation!

Learn More About WIA Code

๐Ÿค– Choose Your AI Assistant

๐Ÿ’ฌ ChatGPT
Most versatile โ€ข Best for general tasks
๐Ÿง  Claude
Best reasoning โ€ข Perfect for analysis
โœจ Gemini FREE
Free daily limits โ€ข Built-in chat
`; printWindow.document.write(html); printWindow.document.close(); printWindow.print(); } // ========== CONTROL FUNCTIONS ========== function selectGridSize(size) { document.querySelectorAll('.grid-btn').forEach(btn => btn.classList.remove('active')); event.target.classList.add('active'); gameState.gridSize = size; document.getElementById('currentSize').textContent = `${size}ร—${size}`; // Reset number pad generateNumberPad(); } function selectDifficulty(difficulty) { document.querySelectorAll('.difficulty-btn').forEach(btn => btn.classList.remove('active')); event.target.classList.add('active'); gameState.difficulty = difficulty; document.getElementById('currentDifficulty').textContent = difficulty.charAt(0).toUpperCase() + difficulty.slice(1); } function selectMode(mode) { document.querySelectorAll('.control-group:last-child .grid-btn').forEach(btn => btn.classList.remove('active')); event.target.classList.add('active'); gameState.mode = mode; } function loadSamplePuzzle(type) { if (SAMPLE_PUZZLES[type]) { const sample = SAMPLE_PUZZLES[type]; gameState.currentPuzzle = copyGrid(sample.puzzle); gameState.solution = copyGrid(sample.solution); gameState.userGrid = copyGrid(sample.puzzle); gameState.gridSize = sample.size; gameState.difficulty = sample.difficulty; gameState.isCompleted = false; gameState.moves = []; gameState.errors = 0; // Update UI document.getElementById('currentSize').textContent = `${sample.size}ร—${sample.size}`; document.getElementById('currentDifficulty').textContent = sample.difficulty.charAt(0).toUpperCase() + sample.difficulty.slice(1); displayPuzzle(); resetTimer(); showNotification(`Loaded ${type} puzzle`, 'success'); } else { // Generate puzzle based on type if (type === 'daily') { generateNewPuzzle(); } else if (type === 'challenging') { gameState.difficulty = 'expert'; selectDifficulty('expert'); generateNewPuzzle(); } else { generateNewPuzzle(); } } } // ========== TIMER FUNCTIONS ========== function startTimer() { if (gameState.timer) return; gameState.startTime = Date.now(); gameState.timer = setInterval(updateTimer, 1000); } function stopTimer() { if (gameState.timer) { clearInterval(gameState.timer); gameState.timer = null; } } function resetTimer() { stopTimer(); gameState.startTime = null; document.getElementById('timer').textContent = '00:00'; } function updateTimer() { if (!gameState.startTime) return; const elapsed = Math.floor((Date.now() - gameState.startTime) / 1000); const minutes = Math.floor(elapsed / 60); const seconds = elapsed % 60; document.getElementById('timer').textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; } function getElapsedTime() { if (!gameState.startTime) return '00:00'; const elapsed = Math.floor((Date.now() - gameState.startTime) / 1000); const minutes = Math.floor(elapsed / 60); const seconds = elapsed % 60; return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; } // ========== STATISTICS FUNCTIONS ========== function updateStats(action) { const stats = gameState.stats; if (action === 'generated') { stats.totalGenerated++; } else if (action === 'completed') { stats.totalCompleted++; const time = Date.now() - gameState.startTime; stats.totalTime += time; const difficulty = gameState.difficulty; if (!stats.bestTimes[difficulty] || time < stats.bestTimes[difficulty]) { stats.bestTimes[difficulty] = time; } } // Save to localStorage localStorage.setItem('sudokuStats', JSON.stringify(stats)); // Update display updateStatsDisplay(); } function updateStatsDisplay() { const stats = gameState.stats; document.getElementById('totalPuzzles').textContent = stats.totalGenerated; document.getElementById('completedPuzzles').textContent = stats.totalCompleted; // Best time for current difficulty const bestTime = stats.bestTimes[gameState.difficulty]; document.getElementById('bestTime').textContent = bestTime ? formatTime(bestTime) : '--:--'; // Average time const avgTime = stats.totalCompleted > 0 ? stats.totalTime / stats.totalCompleted : 0; document.getElementById('averageTime').textContent = avgTime > 0 ? formatTime(avgTime) : '--:--'; // Success rate const successRate = stats.totalGenerated > 0 ? Math.round((stats.totalCompleted / stats.totalGenerated) * 100) : 0; document.getElementById('successRate').textContent = `${successRate}%`; } function formatTime(milliseconds) { const seconds = Math.floor(milliseconds / 1000); const minutes = Math.floor(seconds / 60); const remainingSeconds = seconds % 60; return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`; } function updateGameInfo() { const size = gameState.gridSize; const filled = countFilledCells(); const total = size * size; document.getElementById('filledCells').textContent = `${filled}/${total}`; document.getElementById('errorCount').textContent = gameState.errors; // Start timer if first move if (filled > countClues(gameState.currentPuzzle) && !gameState.timer && !gameState.isCompleted) { startTimer(); } } function countFilledCells() { return gameState.userGrid.flat().filter(cell => cell !== 0).length; } // ========== UTILITY FUNCTIONS ========== function showNotification(message, type = 'success') { const toast = document.createElement('div'); toast.className = `toast ${type}`; toast.textContent = message; document.body.appendChild(toast); setTimeout(() => { toast.remove(); }, 3000); } function showOTA() { const otaContainer = document.getElementById('otaContainer'); if (otaContainer && (otaContainer.style.display === 'none' || !otaContainer.style.display)) { otaContainer.style.display = 'block'; setTimeout(() => { const otaHeader = document.querySelector('.ota-header h3'); if (otaHeader) { otaHeader.style.animation = 'pulse 1s ease-in-out'; } }, 100); } } function trackEvent(eventName, data = {}) { if (typeof gtag !== 'undefined') { gtag('event', eventName, { 'event_category': TOOL_CONFIG.category, 'event_label': TOOL_CONFIG.name, ...data }); } } // ========== AI ASSISTANT FUNCTIONS ========== function openAIModal() { const modal = document.getElementById('aiModal'); modal.classList.add('show'); if (aiModalState.apiKey && aiModalState.currentView === 'gemini') { showGeminiChat(); } else { showAISelector(); } updateAPIKeyStatus(); } function closeAIModal() { const modal = document.getElementById('aiModal'); modal.classList.remove('show'); setTimeout(() => { aiModalState.currentView = 'selector'; showAISelector(); }, 300); } function showAISelector() { document.getElementById('aiModalTitle').textContent = 'Choose Your AI Assistant'; document.getElementById('aiSelector').style.display = 'flex'; document.getElementById('geminiChat').style.display = 'none'; document.getElementById('apiKeySetup').style.display = 'none'; aiModalState.currentView = 'selector'; } function showGeminiChat() { document.getElementById('aiModalTitle').innerHTML = 'โœจ Gemini AI Assistant'; document.getElementById('aiSelector').style.display = 'none'; document.getElementById('geminiChat').style.display = 'flex'; document.getElementById('apiKeySetup').style.display = 'none'; aiModalState.currentView = 'gemini'; const chatMessages = document.getElementById('chatMessages'); if (!chatMessages.innerHTML.trim()) { addMessage('assistant', `Hello! I'm here to help with Sudoku: โ€ข Solving strategies and techniques โ€ข Tips for different difficulty levels โ€ข Understanding Sudoku rules and logic โ€ข Improving your solving speed โ€ข Custom puzzle generation advice โ€ข WIA Code system questions What would you like to know about Sudoku?`); } } function showAPIKeySetup() { document.getElementById('aiModalTitle').textContent = 'Setup Gemini API'; document.getElementById('aiSelector').style.display = 'none'; document.getElementById('geminiChat').style.display = 'none'; document.getElementById('apiKeySetup').style.display = 'block'; aiModalState.currentView = 'setup'; } function selectAI(aiType) { switch(aiType) { case 'chatgpt': const toolContext = `I need help with Sudoku puzzles and solving strategies. I'm using the Sudoku Generator on WIA Code platform to practice different difficulty levels and improve my solving skills.`; const chatUrl = `https://chat.openai.com/?q=${encodeURIComponent(toolContext)}`; window.open(chatUrl, '_blank'); closeAIModal(); trackEvent('ai_selection', { ai_type: 'chatgpt' }); break; case 'claude': const claudeContext = `I need help with Sudoku puzzles and solving strategies. I'm using the Sudoku Generator on WIA Code platform to practice different difficulty levels and improve my solving skills.`; const claudeUrl = `https://claude.ai/chat?q=${encodeURIComponent(claudeContext)}`; window.open(claudeUrl, '_blank'); closeAIModal(); trackEvent('ai_selection', { ai_type: 'claude' }); break; case 'gemini': if (!aiModalState.apiKey) { showAPIKeySetup(); } else { showGeminiChat(); } trackEvent('ai_selection', { ai_type: 'gemini' }); break; } } function saveGeminiApiKey() { const apiKey = document.getElementById('geminiApiKeyInput').value.trim(); if (apiKey) { localStorage.setItem('geminiApiKey', apiKey); aiModalState.apiKey = apiKey; showGeminiChat(); updateAPIKeyStatus(); } else { alert('Please enter a valid API key'); } } function updateAPIKeyStatus() { const statusEl = document.getElementById('apiKeyStatus'); if (aiModalState.apiKey) { statusEl.innerHTML = 'Change API Key'; } else { statusEl.textContent = 'No API key set'; } } function addMessage(type, content) { const chatMessages = document.getElementById('chatMessages'); const messageDiv = document.createElement('div'); messageDiv.className = `message ${type}`; if (type === 'user') { messageDiv.innerHTML = `You: ${content}`; } else { messageDiv.innerHTML = `โœจ Gemini:
${content.replace(/\n/g, '
')}`; } chatMessages.appendChild(messageDiv); chatMessages.scrollTop = chatMessages.scrollHeight; } async function sendToGemini() { const input = document.getElementById('geminiInput'); const message = input.value.trim(); if (!message) return; addMessage('user', message); input.value = ''; const loadingMsg = document.createElement('div'); loadingMsg.className = 'message assistant'; loadingMsg.innerHTML = 'โœจ Gemini:
Thinking...'; loadingMsg.id = 'loading-message'; document.getElementById('chatMessages').appendChild(loadingMsg); try { const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=${aiModalState.apiKey}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ contents: [{ parts: [{ text: `Context: User is playing Sudoku puzzles on WIA Code Sudoku Generator. Current game state: - Grid size: ${gameState.gridSize}ร—${gameState.gridSize} - Difficulty: ${gameState.difficulty} - Progress: ${countFilledCells()}/${gameState.gridSize * gameState.gridSize} cells filled - Errors: ${gameState.errors} Sudoku rules: Fill grid so each row, column, and ${Math.sqrt(gameState.gridSize)}ร—${Math.sqrt(gameState.gridSize)} box contains numbers 1-${gameState.gridSize} exactly once. User question: ${message}` }] }], generationConfig: { temperature: 0.7, maxOutputTokens: 1000 } }) }); const data = await response.json(); document.getElementById('loading-message').remove(); if (data.candidates && data.candidates[0] && data.candidates[0].content) { const reply = data.candidates[0].content.parts[0].text; addMessage('assistant', reply); } else { addMessage('assistant', 'Sorry, I could not generate a response. Please try again.'); } } catch (error) { document.getElementById('loading-message')?.remove(); if (error.message.includes('API key')) { addMessage('error', 'Invalid API key. Please check your API key and try again.'); showAPIKeySetup(); } else { addMessage('error', 'Failed to connect to Gemini. Please check your internet connection and try again.'); } } } // ========== INITIALIZATION ========== document.addEventListener('DOMContentLoaded', function() { // Initialize game updateStatsDisplay(); generateNumberPad(); // Generate first puzzle generateNewPuzzle(); // Event listeners document.getElementById('aiBtn').addEventListener('click', openAIModal); document.getElementById('aiModal').addEventListener('click', function(e) { if (e.target === this) { closeAIModal(); } }); document.addEventListener('keydown', function(e) { if (e.key === 'Enter') { const geminiInput = document.getElementById('geminiInput'); if (document.activeElement === geminiInput) { sendToGemini(); } } if (e.key === 'Escape') { closeAIModal(); } // Number keys for number selection if (e.key >= '1' && e.key <= '9') { const num = parseInt(e.key); if (num <= gameState.gridSize) { selectNumber(num); } } if (e.key === '0' || e.key === 'Delete' || e.key === 'Backspace') { if (gameState.selectedCell && document.activeElement.tagName !== 'INPUT') { selectNumber(0); } } }); updateAPIKeyStatus(); updateCurrentYear(); updateToolCount(); trackEvent('page_view', { tool: TOOL_CONFIG.name, category: TOOL_CONFIG.category }); }); // ========== DYNAMIC TOOL COUNT ========== async function updateToolCount() { try { const response = await fetch('/api/tool-count.php'); const data = await response.json(); document.querySelectorAll('.dynamic-tools-count').forEach(el => { el.textContent = `${data.count}+ free online tools in 206 languages. No signup, no fees, just tools that work.`; }); document.querySelectorAll('.dynamic-count').forEach(el => { const prefix = el.getAttribute('data-text') || ''; const suffix = el.getAttribute('data-suffix') || ''; const icon = el.textContent.split(' ')[0] || ''; el.textContent = `${icon} ${prefix} ${data.count}+ ${suffix}`; }); } catch (error) { const fallbackCount = 333; document.querySelectorAll('.dynamic-tools-count').forEach(el => { el.textContent = `${fallbackCount}+ free online tools in 206 languages. No signup, no fees, just tools that work.`; }); document.querySelectorAll('.dynamic-count').forEach(el => { const prefix = el.getAttribute('data-text') || ''; const suffix = el.getAttribute('data-suffix') || ''; const icon = el.textContent.split(' ')[0] || ''; el.textContent = `${icon} ${prefix} ${fallbackCount}+ ${suffix}`; }); } } function updateCurrentYear() { const currentYear = new Date().getFullYear(); document.querySelectorAll('.current-year').forEach(el => { el.textContent = currentYear; }); } // ========== ANALYTICS ========== window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-XXXXXXXXX'); trackEvent('page_view', { tool: TOOL_CONFIG.name, category: TOOL_CONFIG.category });