306 lines
9.3 KiB
JavaScript
306 lines
9.3 KiB
JavaScript
'use strict';
|
|
|
|
const BASE = location.pathname === '/' ? '' : location.pathname.replace(/\/$/, '');
|
|
|
|
const App = (() => {
|
|
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'),
|
|
opponent: document.getElementById('score-opponent'),
|
|
draws: document.getElementById('score-draws'),
|
|
};
|
|
|
|
const labelYou = document.getElementById('label-you');
|
|
const labelOpponent = document.getElementById('label-opponent');
|
|
|
|
const cells = [];
|
|
let toastTimer = 0;
|
|
let activeMode = null;
|
|
|
|
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 X_SVG =
|
|
'<svg viewBox="0 0 100 100" class="mark mark-x" aria-hidden="true">' +
|
|
'<line x1="24" y1="24" x2="76" y2="76"></line>' +
|
|
'<line x1="76" y1="24" x2="24" y2="76"></line>' +
|
|
'</svg>';
|
|
|
|
const O_SVG =
|
|
'<svg viewBox="0 0 100 100" class="mark mark-o" aria-hidden="true">' +
|
|
'<circle cx="50" cy="50" r="30"></circle>' +
|
|
'</svg>';
|
|
|
|
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;
|
|
}
|
|
|
|
function showScreen(name) {
|
|
document.getElementById('screen-menu').style.display = name === 'menu' ? '' : 'none';
|
|
document.getElementById('screen-waiting').style.display = name === 'waiting' ? '' : 'none';
|
|
document.getElementById('screen-game').style.display = name === 'game' ? '' : 'none';
|
|
}
|
|
|
|
function buildBoard() {
|
|
boardEl.innerHTML = '';
|
|
cells.length = 0;
|
|
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 onCellTap(i) {
|
|
if (activeMode === 'cpu') CpuGame.handleMove(i);
|
|
if (activeMode === 'online') Multiplayer.handleMove(i);
|
|
}
|
|
|
|
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(scores) {
|
|
scoreEls.you.textContent = scores.you || 0;
|
|
scoreEls.opponent.textContent = scores.opponent || 0;
|
|
scoreEls.draws.textContent = scores.draws || 0;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
function showOverlay(title) {
|
|
overlayTitleEl.textContent = title;
|
|
overlayEl.classList.add('show');
|
|
}
|
|
|
|
function hideOverlay() {
|
|
overlayEl.classList.remove('show');
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
function clearBoard() {
|
|
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');
|
|
hideOverlay();
|
|
confettiLayer.innerHTML = '';
|
|
}
|
|
|
|
function showToast(msg) {
|
|
toastEl.textContent = msg;
|
|
toastEl.classList.add('show');
|
|
clearTimeout(toastTimer);
|
|
toastTimer = setTimeout(() => toastEl.classList.remove('show'), 1600);
|
|
}
|
|
|
|
function setScoreboardLabels(youLabel, oppLabel) {
|
|
labelYou.textContent = youLabel;
|
|
labelOpponent.textContent = oppLabel;
|
|
}
|
|
|
|
function startCpuMode() {
|
|
activeMode = 'cpu';
|
|
showScreen('game');
|
|
setScoreboardLabels('You (X)', 'CPU (O)');
|
|
CpuGame.init();
|
|
}
|
|
|
|
function startOnlineHost({ id, token, link }) {
|
|
activeMode = 'online';
|
|
showScreen('waiting');
|
|
document.getElementById('link-text').textContent = link;
|
|
Multiplayer.init({ asHost: true, id, token, link });
|
|
}
|
|
|
|
function startOnlineJoiner(token) {
|
|
activeMode = 'online';
|
|
showScreen('game');
|
|
setScoreboardLabels('Opponent (X)', 'You (O)');
|
|
renderStatus('Connecting…', 'thinking');
|
|
Multiplayer.init({ asJoiner: true, token });
|
|
}
|
|
|
|
function backToMenu() {
|
|
if (activeMode === 'cpu') CpuGame.destroy();
|
|
if (activeMode === 'online') Multiplayer.destroy();
|
|
activeMode = null;
|
|
clearBoard();
|
|
hideOverlay();
|
|
showScreen('menu');
|
|
}
|
|
|
|
function init() {
|
|
buildBoard();
|
|
|
|
document.getElementById('btn-cpu').addEventListener('click', startCpuMode);
|
|
document.getElementById('btn-online').addEventListener('click', async () => {
|
|
try {
|
|
const res = await fetch(BASE + '/api/games', { method: 'POST' });
|
|
if (!res.ok) throw new Error('Server returned ' + res.status);
|
|
const data = await res.json();
|
|
startOnlineHost(data);
|
|
} catch (e) {
|
|
showToast('Error: ' + e.message);
|
|
console.error('Create game failed:', e);
|
|
}
|
|
});
|
|
|
|
document.getElementById('btn-copy').addEventListener('click', async () => {
|
|
const link = document.getElementById('link-text').textContent;
|
|
try {
|
|
await navigator.clipboard.writeText(link);
|
|
showToast('Link copied!');
|
|
} catch (e) {
|
|
prompt('Copy this link:', link);
|
|
}
|
|
});
|
|
|
|
document.getElementById('btn-back-menu-waiting').addEventListener('click', backToMenu);
|
|
document.getElementById('btn-new-game').addEventListener('click', () => {
|
|
if (activeMode === 'cpu') CpuGame.newRound();
|
|
if (activeMode === 'online') Multiplayer.newRound();
|
|
});
|
|
document.getElementById('btn-again-overlay').addEventListener('click', () => {
|
|
if (activeMode === 'cpu') CpuGame.newRound();
|
|
if (activeMode === 'online') Multiplayer.newRound();
|
|
});
|
|
document.getElementById('btn-reset').addEventListener('click', () => {
|
|
if (activeMode === 'cpu') CpuGame.resetScores();
|
|
});
|
|
|
|
const token = new URLSearchParams(location.search).get('token');
|
|
if (token) {
|
|
startOnlineJoiner(token);
|
|
} else {
|
|
showScreen('menu');
|
|
}
|
|
}
|
|
|
|
return {
|
|
init,
|
|
showScreen,
|
|
renderMark,
|
|
renderStatus,
|
|
renderScores,
|
|
drawWinLine,
|
|
clearWinLine,
|
|
showOverlay,
|
|
hideOverlay,
|
|
burstConfetti,
|
|
clearBoard,
|
|
showToast,
|
|
setScoreboardLabels,
|
|
checkWinner,
|
|
WIN_LINES,
|
|
get activeMode() { return activeMode; },
|
|
};
|
|
})();
|
|
|
|
App.init();
|