Spaces:
Running

GAF1 / sudoku.html
IndividualGamer's picture
Rename sudoku-portrait-numpad.html to sudoku.html
229ab22 verified
Raw History Blame Contribute Delete
22.2 kB
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
<title>Sudoku Game & Solver</title>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
-webkit-tap-highlight-color: transparent;
}
html, body {
width: 100%;
min-height: 100dvh;
overflow-x: hidden;
background-color: #f4f4f9;
color: #222;
font-family: system-ui, -apple-system, sans-serif;
user-select: none;
}
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
padding: max(8px, env(safe-area-inset-top)) 10px max(10px, env(safe-area-inset-bottom)) 10px;
}
h2 {
font-size: clamp(1.1rem, 4.5vw, 1.35rem);
margin-bottom: 8px;
text-align: center;
line-height: 1.2;
}
.header-controls {
width: 100%;
max-width: min(400px, calc(100vw - 20px));
margin-bottom: 8px;
display: flex;
gap: 5px;
justify-content: space-between;
align-items: center;
}
select, button {
padding: 7px 8px;
font-size: clamp(12px, 3.3vw, 14px);
border-radius: 6px;
border: 1px solid #ccc;
cursor: pointer;
}
select {
background-color: #fff;
flex: 1;
max-width: 100px;
}
.timer-box {
background-color: #fff;
border: 1px solid #ccc;
border-radius: 6px;
padding: 6px 8px;
font-size: clamp(12px, 3.4vw, 14px);
font-weight: 700;
font-variant-numeric: tabular-nums;
color: #212529;
text-align: center;
min-width: 74px;
display: flex;
align-items: center;
justify-content: center;
gap: 3px;
}
.btn-sound {
background-color: #fff;
border: 1px solid #ccc;
color: #212529;
padding: 6px 9px;
font-size: clamp(13px, 3.6vw, 15px);
min-width: 36px;
display: flex;
align-items: center;
justify-content: center;
}
.btn-sound.muted {
background-color: #e9ecef;
color: #6c757d;
}
button {
border: none;
color: white;
font-weight: 600;
transition: transform 0.05s, opacity 0.15s;
}
button:active {
transform: scale(0.96);
opacity: 0.85;
}
.btn-new { background-color: #198754; flex: 1.2; white-space: nowrap; }
.btn-hint { background-color: #f59e0b; color: #000; }
.btn-solve { background-color: #0d6efd; }
.btn-clear { background-color: #dc3545; }
/* Papan Sudoku 9x9 berbasis Div (Tanpa Keyboard Sistem) */
.grid {
width: 100%;
max-width: min(390px, calc(100vw - 20px), calc(100dvh - 245px));
aspect-ratio: 1 / 1;
display: grid;
grid-template-columns: repeat(9, 1fr);
grid-template-rows: repeat(9, 1fr);
border: 3px solid #222;
background-color: #fff;
box-shadow: 0 4px 10px rgba(0,0,0,0.1);
}
.cell {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
font-size: clamp(16px, 4.8vw, 22px);
font-weight: bold;
border: 1px solid #ccc;
color: #0d6efd;
background-color: #fff;
cursor: pointer;
}
/* Garis tebal pembatas kotak 3x3 */
.cell:nth-child(3n) { border-right: 2px solid #222; }
.cell:nth-child(9n) { border-right: none; }
.border-bottom { border-bottom: 2px solid #222 !important; }
/* Sorotan sel aktif & baris/kolom terkait */
.related-cell {
background-color: #eef5ff;
}
.same-number {
background-color: #d0e3ff;
}
.selected-cell {
background-color: #bbdefb !important;
outline: 2px solid #0d6efd;
outline-offset: -2px;
z-index: 2;
}
/* Status Warna Kotak */
.fixed-cell {
background-color: #e9ecef;
color: #212529;
}
.fixed-cell.related-cell {
background-color: #dde4ec;
}
.fixed-cell.same-number {
background-color: #cbd7e6;
}
.hint-cell {
background-color: #fff3cd;
color: #b45309;
}
.error-cell {
background-color: #f8d7da !important;
color: #842029 !important;
}
#status {
width: 100%;
max-width: min(390px, calc(100vw - 20px));
margin-top: 6px;
font-size: clamp(12px, 3.3vw, 14px);
font-weight: bold;
min-height: 19px;
text-align: center;
padding: 0 4px;
}
/* Numpad Virtual 1-9 + Hapus */
.numpad {
width: 100%;
max-width: min(390px, calc(100vw - 20px));
margin-top: 6px;
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 6px;
}
.num-btn {
background-color: #ffffff;
color: #0d6efd;
border: 1.5px solid #cbd5e1;
border-radius: 8px;
padding: 10px 0;
font-size: clamp(17px, 4.8vw, 21px);
font-weight: 700;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}
.num-btn:active {
background-color: #e3f2fd;
border-color: #0d6efd;
}
.num-btn.erase-btn {
background-color: #fee2e2;
color: #dc2626;
border-color: #fca5a5;
font-size: clamp(15px, 4.2vw, 18px);
}
.controls {
width: 100%;
max-width: min(390px, calc(100vw - 20px));
margin-top: 8px;
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 6px;
}
.controls button {
flex: 1 1 30%;
min-width: 85px;
padding: 8px 6px;
}
</style>
</head>
<body>
<h2>Sudoku Game & Solver</h2>
<div class="header-controls">
<select id="difficulty">
<option value="30">Mudah</option>
<option value="42" selected>Sedang</option>
<option value="52">Sulit</option>
</select>
<div class="timer-box" id="timer">⏱️ 00:00</div>
<button class="btn-sound" id="sound-toggle" onclick="toggleSound()" title="Suara Aktif">🔊</button>
<button class="btn-new" onclick="startNewGame()">Permainan Baru</button>
</div>
<div class="grid" id="sudoku-grid"></div>
<div id="status"></div>
<!-- Numpad Virtual di Layar -->
<div class="numpad">
<button class="num-btn" onclick="inputNumber(1)">1</button>
<button class="num-btn" onclick="inputNumber(2)">2</button>
<button class="num-btn" onclick="inputNumber(3)">3</button>
<button class="num-btn" onclick="inputNumber(4)">4</button>
<button class="num-btn" onclick="inputNumber(5)">5</button>
<button class="num-btn" onclick="inputNumber(6)">6</button>
<button class="num-btn" onclick="inputNumber(7)">7</button>
<button class="num-btn" onclick="inputNumber(8)">8</button>
<button class="num-btn" onclick="inputNumber(9)">9</button>
<button class="num-btn erase-btn" onclick="inputNumber(0)" title="Hapus Angka">⌫</button>
</div>
<div class="controls">
<button class="btn-hint" onclick="giveHint()">💡 Hint</button>
<button class="btn-solve" onclick="solveAll()">Selesaikan</button>
<button class="btn-clear" onclick="clearBoard()">Mode Kosong</button>
</div>
<script>
const gridElement = document.getElementById('sudoku-grid');
const statusElement = document.getElementById('status');
const timerElement = document.getElementById('timer');
const soundToggleBtn = document.getElementById('sound-toggle');
let solutionBoard = [];
let selectedCell = null;
let secondsElapsed = 0;
let timerInterval = null;
let soundEnabled = true;
let audioCtx = null;
function initAudio() {
if (!audioCtx) {
const AudioContext = window.AudioContext || window.webkitAudioContext;
if (AudioContext) {
audioCtx = new AudioContext();
}
}
if (audioCtx && audioCtx.state === 'suspended') {
audioCtx.resume();
}
}
function toggleSound() {
soundEnabled = !soundEnabled;
if (soundEnabled) {
soundToggleBtn.textContent = '🔊';
soundToggleBtn.title = 'Suara Aktif';
soundToggleBtn.classList.remove('muted');
playSound('correct');
} else {
soundToggleBtn.textContent = '🔇';
soundToggleBtn.title = 'Suara Dimatikan';
soundToggleBtn.classList.add('muted');
}
}
function playSound(type) {
if (!soundEnabled) return;
initAudio();
if (!audioCtx) return;
const now = audioCtx.currentTime;
if (type === 'select') {
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
osc.type = 'sine';
osc.frequency.setValueAtTime(420, now);
gain.gain.setValueAtTime(0.05, now);
gain.gain.exponentialRampToValueAtTime(0.001, now + 0.04);
osc.connect(gain);
gain.connect(audioCtx.destination);
osc.start(now);
osc.stop(now + 0.04);
} else if (type === 'correct') {
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
osc.type = 'sine';
osc.frequency.setValueAtTime(587.33, now);
osc.frequency.exponentialRampToValueAtTime(880, now + 0.08);
gain.gain.setValueAtTime(0.15, now);
gain.gain.exponentialRampToValueAtTime(0.001, now + 0.14);
osc.connect(gain);
gain.connect(audioCtx.destination);
osc.start(now);
osc.stop(now + 0.14);
} else if (type === 'wrong') {
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
osc.type = 'sawtooth';
osc.frequency.setValueAtTime(160, now);
osc.frequency.linearRampToValueAtTime(110, now + 0.22);
gain.gain.setValueAtTime(0.18, now);
gain.gain.exponentialRampToValueAtTime(0.001, now + 0.24);
osc.connect(gain);
gain.connect(audioCtx.destination);
osc.start(now);
osc.stop(now + 0.24);
} else if (type === 'win') {
const notes = [523.25, 659.25, 783.99, 1046.50];
notes.forEach((freq, idx) => {
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
osc.type = 'triangle';
const startTime = now + idx * 0.11;
const duration = idx === notes.length - 1 ? 0.45 : 0.15;
osc.frequency.setValueAtTime(freq, startTime);
gain.gain.setValueAtTime(0.2, startTime);
gain.gain.exponentialRampToValueAtTime(0.001, startTime + duration);
osc.connect(gain);
gain.connect(audioCtx.destination);
osc.start(startTime);
osc.stop(startTime + duration);
});
}
}
function formatTime(totalSeconds) {
const mins = Math.floor(totalSeconds / 60).toString().padStart(2, '0');
const secs = (totalSeconds % 60).toString().padStart(2, '0');
return `${mins}:${secs}`;
}
function startTimer() {
stopTimer();
secondsElapsed = 0;
timerElement.textContent = '⏱️ 00:00';
timerInterval = setInterval(() => {
secondsElapsed++;
timerElement.textContent = `⏱️ ${formatTime(secondsElapsed)}`;
}, 1000);
}
function stopTimer() {
if (timerInterval !== null) {
clearInterval(timerInterval);
timerInterval = null;
}
}
function resetTimer() {
stopTimer();
secondsElapsed = 0;
timerElement.textContent = '⏱️ 00:00';
}
// 1. Inisialisasi 81 kotak berbasis DIV agar tidak memicu keyboard HP
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
const cell = document.createElement('div');
cell.classList.add('cell');
cell.dataset.row = r;
cell.dataset.col = c;
cell.dataset.locked = 'false';
if (r === 2 || r === 5) cell.classList.add('border-bottom');
cell.addEventListener('click', () => {
selectCell(cell);
playSound('select');
});
gridElement.appendChild(cell);
}
}
function selectCell(cell) {
selectedCell = cell;
updateHighlights();
}
function updateHighlights() {
const cells = document.querySelectorAll('#sudoku-grid .cell');
cells.forEach(c => c.classList.remove('selected-cell', 'related-cell', 'same-number'));
if (!selectedCell) return;
const selRow = parseInt(selectedCell.dataset.row);
const selCol = parseInt(selectedCell.dataset.col);
const selBoxRow = Math.floor(selRow / 3);
const selBoxCol = Math.floor(selCol / 3);
const selVal = selectedCell.textContent;
cells.forEach(c => {
const r = parseInt(c.dataset.row);
const col = parseInt(c.dataset.col);
const boxRow = Math.floor(r / 3);
const boxCol = Math.floor(col / 3);
if (r === selRow || col === selCol || (boxRow === selBoxRow && boxCol === selBoxCol)) {
c.classList.add('related-cell');
}
if (selVal !== '' && c.textContent === selVal) {
c.classList.add('same-number');
}
});
selectedCell.classList.add('selected-cell');
}
// Fungsi saat tombol angka 1-9 atau Hapus pada Numpad Virtual ditekan
function inputNumber(num) {
if (!selectedCell) {
statusElement.textContent = 'Ketuk kotak pada papan terlebih dahulu.';
return;
}
if (selectedCell.dataset.locked === 'true') {
playSound('wrong');
return;
}
const r = parseInt(selectedCell.dataset.row);
const c = parseInt(selectedCell.dataset.col);
selectedCell.classList.remove('hint-cell', 'error-cell');
if (num === 0) {
selectedCell.textContent = '';
updateHighlights();
return;
}
selectedCell.textContent = num;
updateHighlights();
const isEntryValid = validateLiveInput(r, c, num, selectedCell);
if (!isEntryValid) {
playSound('wrong');
} else {
const won = checkWinCondition();
if (!won) {
playSound('correct');
}
}
}
// Tetap mendukung keyboard fisik jika dibuka di laptop/PC
document.addEventListener('keydown', (e) => {
if (!selectedCell) return;
if (e.key >= '1' && e.key <= '9') {
inputNumber(parseInt(e.key));
} else if (e.key === 'Backspace' || e.key === 'Delete' || e.key === '0') {
inputNumber(0);
} else if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key)) {
e.preventDefault();
let r = parseInt(selectedCell.dataset.row);
let c = parseInt(selectedCell.dataset.col);
if (e.key === 'ArrowUp' && r > 0) r--;
if (e.key === 'ArrowDown' && r < 8) r++;
if (e.key === 'ArrowLeft' && c > 0) c--;
if (e.key === 'ArrowRight' && c < 8) c++;
const cells = document.querySelectorAll('#sudoku-grid .cell');
selectCell(cells[r * 9 + c]);
}
});
function isValid(board, row, col, num) {
for (let i = 0; i < 9; i++) {
if (board[row][i] === num || board[i][col] === num) return false;
const boxRow = 3 * Math.floor(row / 3) + Math.floor(i / 3);
const boxCol = 3 * Math.floor(col / 3) + (i % 3);
if (board[boxRow][boxCol] === num) return false;
}
return true;
}
function solveSudoku(board, randomize = false) {
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
if (board[r][c] === 0) {
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
if (randomize) nums.sort(() => Math.random() - 0.5);
for (let num of nums) {
if (isValid(board, r, c, num)) {
board[r][c] = num;
if (solveSudoku(board, randomize)) return true;
board[r][c] = 0;
}
}
return false;
}
}
}
return true;
}
function startNewGame() {
statusElement.textContent = '';
selectedCell = null;
let board = Array.from({ length: 9 }, () => Array(9).fill(0));
solveSudoku(board, true);
solutionBoard = board.map(row => [...row]);
let holes = parseInt(document.getElementById('difficulty').value);
while (holes > 0) {
let r = Math.floor(Math.random() * 9);
let c = Math.floor(Math.random() * 9);
if (board[r][c] !== 0) {
board[r][c] = 0;
holes--;
}
}
renderBoard(board, true);
startTimer();
}
function renderBoard(board, lockPrefilled) {
const cells = document.querySelectorAll('#sudoku-grid .cell');
let firstEmpty = null;
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
const cell = cells[r * 9 + c];
const val = board[r][c];
cell.textContent = val === 0 ? '' : val;
cell.classList.remove('fixed-cell', 'hint-cell', 'error-cell', 'selected-cell', 'related-cell', 'same-number');
if (val !== 0 && lockPrefilled) {
cell.dataset.locked = 'true';
cell.classList.add('fixed-cell');
} else {
cell.dataset.locked = 'false';
if (!firstEmpty) firstEmpty = cell;
}
}
}
if (firstEmpty) {
selectCell(firstEmpty);
}
}
function giveHint() {
const cells = document.querySelectorAll('#sudoku-grid .cell');
const currentBoard = getBoardFromDOM();
if (solutionBoard.length === 0) {
let tempBoard = currentBoard.map(row => [...row]);
if (!isBoardValid(tempBoard) || !solveSudoku(tempBoard)) {
statusElement.textContent = '⚠️ Papan tidak valid untuk diberikan hint!';
playSound('wrong');
return;
}
solutionBoard = tempBoard;
}
let candidates = [];
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
if (currentBoard[r][c] !== solutionBoard[r][c]) {
candidates.push({ r, c });
}
}
}
if (candidates.length === 0) {
statusElement.textContent = '✅ Papan sudah terisi benar semua!';
return;
}
const chosen = candidates[Math.floor(Math.random() * candidates.length)];
const targetCell = cells[chosen.r * 9 + chosen.c];
targetCell.textContent = solutionBoard[chosen.r][chosen.c];
targetCell.classList.remove('error-cell');
targetCell.classList.add('hint-cell');
targetCell.dataset.locked = 'true';
selectCell(targetCell);
const won = checkWinCondition();
if (!won) {
playSound('correct');
}
}
function solveAll() {
const currentBoard = getBoardFromDOM();
if (solutionBoard.length === 0) {
if (!isBoardValid(currentBoard)) {
statusElement.textContent = '⚠️ Ada angka kembar yang melanggar aturan!';
playSound('wrong');
return;
}
if (!solveSudoku(currentBoard)) {
statusElement.textContent = '❌ Sudoku ini tidak memiliki solusi.';
playSound('wrong');
return;
}
solutionBoard = currentBoard;
}
const cells = document.querySelectorAll('#sudoku-grid .cell');
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
const cell = cells[r * 9 + c];
if (cell.dataset.locked !== 'true') {
cell.textContent = solutionBoard[r][c];
cell.classList.remove('error-cell');
cell.classList.add('hint-cell');
}
}
}
updateHighlights();
stopTimer();
playSound('win');
statusElement.textContent = `✅ Sudoku selesai! (Waktu: ${formatTime(secondsElapsed)})`;
}
function clearBoard() {
solutionBoard = [];
resetTimer();
statusElement.textContent = 'Mode Solver: Ketuk kotak & masukkan angka soal.';
const cells = document.querySelectorAll('#sudoku-grid .cell');
cells.forEach(cell => {
cell.textContent = '';
cell.dataset.locked = 'false';
cell.classList.remove('fixed-cell', 'hint-cell', 'error-cell', 'selected-cell', 'related-cell', 'same-number');
});
if (cells.length > 0) {
selectCell(cells[0]);
}
}
function getBoardFromDOM() {
const cells = document.querySelectorAll('#sudoku-grid .cell');
const board = [];
for (let r = 0; r < 9; r++) {
const row = [];
for (let c = 0; c < 9; c++) {
const val = cells[r * 9 + c].textContent;
row.push(val === '' ? 0 : parseInt(val));
}
board.push(row);
}
return board;
}
function validateLiveInput(r, c, num, cellElement) {
const board = getBoardFromDOM();
board[r][c] = 0;
if (!isValid(board, r, c, num)) {
cellElement.classList.add('error-cell');
return false;
}
if (solutionBoard.length > 0 && solutionBoard[r][c] !== num) {
cellElement.classList.add('error-cell');
return false;
}
return true;
}
function isBoardValid(board) {
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
const num = board[r][c];
if (num !== 0) {
board[r][c] = 0;
const valid = isValid(board, r, c, num);
board[r][c] = num;
if (!valid) return false;
}
}
}
return true;
}
function checkWinCondition() {
const board = getBoardFromDOM();
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
if (board[r][c] === 0) return false;
}
}
if (isBoardValid(board)) {
stopTimer();
playSound('win');
statusElement.textContent = `🎉 Selamat! Selesai dalam waktu ${formatTime(secondsElapsed)}!`;
return true;
}
return false;
}
startNewGame();
</script>
</body>
</html>