'use strict'; /* ---------- 1. DOM refs ---------- */ const boardEl = document.getElementById('board'); const statusEl = document.getElementById('status'); const statusTextEl = document.getElementById('status-text'); const overlayEl = document.getElementById('overlay'); const overlayTitleEl = document.getElementById('overlay-title'); const winLineEl = document.getElementById('win-line-el'); const confettiLayer = document.getElementById('confetti-layer'); const toastEl = document.getElementById('toast'); const scoreEls = { you: document.getElementById('score-you'), cpu: document.getElementById('score-cpu'), draws: document.getElementById('score-draws'), }; const cells = []; /* ---------- state ---------- */ const state = { board: Array(9).fill(null), turn: 'X', gameOver: false, scores: { you: 0, cpu: 0, draws: 0 }, }; let cpuTimer = 0; let toastTimer = 0; const WIN_LINES = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ]; const SCORES_KEY = 'ttt-scores'; const CPU_DELAY = 600; const X_SVG = ''; const O_SVG = ''; /* ---------- 2. Win detection ---------- */ function checkWinner(board) { for (const line of WIN_LINES) { const [a, b, c] = line; if (board[a] && board[a] === board[b] && board[a] === board[c]) { return { winner: board[a], line }; } } if (board.every((v) => v !== null)) return { winner: 'draw' }; return null; } /* ---------- 3. Player move ---------- */ function onCellTap(i) { if (state.gameOver || state.turn !== 'X' || state.board[i]) return; placeMark(i, 'X'); const result = checkWinner(state.board); if (result) { endRound(result); return; } state.turn = 'O'; renderStatus('CPU is thinking…', 'thinking'); cpuTimer = setTimeout(cpuMove, CPU_DELAY); } /* ---------- 4. CPU move ---------- */ function cpuMove() { if (state.gameOver) return; const empty = []; state.board.forEach((v, i) => { if (v === null) empty.push(i); }); if (!empty.length) return; const i = empty[Math.floor(Math.random() * empty.length)]; placeMark(i, 'O'); const result = checkWinner(state.board); if (result) { endRound(result); return; } state.turn = 'X'; renderStatus('Your turn', 'normal'); } function placeMark(i, mark) { state.board[i] = mark; renderMark(i, mark); } /* ---------- 5. Render ---------- */ function renderMark(i, mark) { const cell = cells[i]; cell.classList.remove('empty'); cell.classList.add(mark === 'X' ? 'has-x' : 'has-o'); cell.setAttribute('aria-label', mark === 'X' ? 'X' : 'O'); cell.innerHTML = mark === 'X' ? X_SVG : O_SVG; } function renderStatus(text, mode) { mode = mode || 'normal'; statusEl.classList.toggle('thinking', mode === 'thinking'); if (statusTextEl.textContent === text) return; statusEl.classList.add('fading'); setTimeout(() => { statusTextEl.textContent = text; statusEl.classList.remove('fading'); }, 150); } function renderScores(changed) { for (const k of ['you', 'cpu', 'draws']) { scoreEls[k].textContent = state.scores[k]; if (k === changed) { scoreEls[k].classList.remove('pop'); void scoreEls[k].offsetWidth; scoreEls[k].classList.add('pop'); } } } function cellCenter(i, boardRect) { const r = cells[i].getBoundingClientRect(); return { x: r.left + r.width / 2 - boardRect.left, y: r.top + r.height / 2 - boardRect.top, }; } function drawWinLine(line) { const boardRect = boardEl.getBoundingClientRect(); const p1 = cellCenter(line[0], boardRect); const p2 = cellCenter(line[2], boardRect); const dx = p2.x - p1.x; const dy = p2.y - p1.y; const len = Math.hypot(dx, dy) || 1; const ext = 16; const ux = dx / len; const uy = dy / len; const x1 = p1.x - ux * ext; const y1 = p1.y - uy * ext; const x2 = p2.x + ux * ext; const y2 = p2.y + uy * ext; winLineEl.setAttribute('x1', x1); winLineEl.setAttribute('y1', y1); winLineEl.setAttribute('x2', x2); winLineEl.setAttribute('y2', y2); const total = Math.hypot(x2 - x1, y2 - y1); winLineEl.style.transition = 'none'; winLineEl.style.strokeDasharray = total; winLineEl.style.strokeDashoffset = total; winLineEl.style.opacity = '1'; void winLineEl.getBoundingClientRect(); winLineEl.style.transition = 'stroke-dashoffset 400ms ease'; winLineEl.style.strokeDashoffset = '0'; } function clearWinLine() { winLineEl.style.transition = 'none'; winLineEl.style.opacity = '0'; winLineEl.style.strokeDashoffset = winLineEl.style.strokeDasharray; } /* ---------- 6. Round end ---------- */ function endRound(result) { state.gameOver = true; let title; let key; if (result.winner === 'X') { key = 'you'; title = 'You Win! 🎉'; renderStatus('You win! 🎉', 'normal'); } else if (result.winner === 'O') { key = 'cpu'; title = 'CPU Wins'; renderStatus('CPU wins', 'normal'); boardEl.classList.add('shake'); } else { key = 'draws'; title = "It's a Draw"; renderStatus("It's a draw", 'normal'); boardEl.classList.add('pulse'); } state.scores[key]++; persistScores(); renderScores(key); if (result.line) drawWinLine(result.line); setTimeout(() => { overlayTitleEl.textContent = title; overlayEl.classList.add('show'); if (result.winner === 'X') burstConfetti(); }, result.winner === 'draw' ? 400 : 600); } /* ---------- 7. Confetti ---------- */ const CONFETTI_COLORS = ['#22d3ee', '#f472b6', '#a78bfa', '#fbbf24', '#34d399', '#ffffff']; function burstConfetti() { const pieces = []; for (let i = 0; i < 40; i++) { const el = document.createElement('div'); el.className = 'confetti'; const size = 6 + Math.random() * 8; el.style.width = size + 'px'; el.style.height = size * 1.4 + 'px'; el.style.left = Math.random() * 100 + 'vw'; el.style.background = CONFETTI_COLORS[Math.floor(Math.random() * CONFETTI_COLORS.length)]; el.style.setProperty('--drift', (Math.random() * 160 - 80) + 'px'); el.style.setProperty('--spin', (360 + Math.random() * 720) + 'deg'); el.style.animationDuration = 1.3 + Math.random() * 0.5 + 's'; el.style.animationDelay = Math.random() * 0.25 + 's'; confettiLayer.appendChild(el); pieces.push(el); } setTimeout(() => pieces.forEach((p) => p.remove()), 2200); } /* ---------- 8. Reset ---------- */ function newRound() { clearTimeout(cpuTimer); state.board = Array(9).fill(null); state.turn = 'X'; state.gameOver = false; cells.forEach((cell) => { cell.innerHTML = ''; cell.classList.add('empty'); cell.classList.remove('has-x', 'has-o'); cell.setAttribute('aria-label', 'Empty cell'); }); clearWinLine(); boardEl.classList.remove('shake', 'pulse'); overlayEl.classList.remove('show'); confettiLayer.innerHTML = ''; renderStatus('Your turn', 'normal'); } function resetScores() { state.scores = { you: 0, cpu: 0, draws: 0 }; persistScores(); renderScores(); showToast('Scores reset'); } function persistScores() { try { localStorage.setItem(SCORES_KEY, JSON.stringify(state.scores)); } catch (e) { /* storage unavailable */ } } function loadScores() { try { const raw = localStorage.getItem(SCORES_KEY); if (raw) { const s = JSON.parse(raw); state.scores = { you: Number(s.you) || 0, cpu: Number(s.cpu) || 0, draws: Number(s.draws) || 0, }; } } catch (e) { /* corrupted storage — keep defaults */ } } function showToast(msg) { toastEl.textContent = msg; toastEl.classList.add('show'); clearTimeout(toastTimer); toastTimer = setTimeout(() => toastEl.classList.remove('show'), 1600); } /* ---------- 9. Init ---------- */ function buildBoard() { for (let i = 0; i < 9; i++) { const cell = document.createElement('button'); cell.type = 'button'; cell.className = 'cell empty'; cell.dataset.index = String(i); cell.setAttribute('aria-label', 'Empty cell'); cell.addEventListener('click', () => onCellTap(i)); boardEl.appendChild(cell); cells.push(cell); } } function init() { buildBoard(); loadScores(); renderScores(); document.getElementById('btn-new').addEventListener('click', newRound); document.getElementById('btn-reset').addEventListener('click', resetScores); document.getElementById('btn-again').addEventListener('click', newRound); renderStatus('Your turn', 'normal'); } init();