Mejoras y optimizaciones en general.
This commit is contained in:
@@ -3,12 +3,27 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Tres en Raya</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
</head>
|
||||
<body>
|
||||
<h1>Tres en Raya (Tic Tac Toe)</h1>
|
||||
<div id="board"></div>
|
||||
<div id="status"></div>
|
||||
<h1 id="title">Tres en Raya (Tic Tac Toe)</h1>
|
||||
|
||||
<div id="controls">
|
||||
<label for="first-player">Primer jugador:</label>
|
||||
<select id="first-player">
|
||||
<option value="X" selected>X</option>
|
||||
<option value="O">O</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div id="board" role="grid" aria-labelledby="title"></div>
|
||||
<div id="status" aria-live="polite"></div>
|
||||
|
||||
<div id="score">
|
||||
Marcador — X: <span id="score-x">0</span> · O: <span id="score-o">0</span> · Empates: <span id="score-d">0</span>
|
||||
</div>
|
||||
|
||||
<button id="restart-btn">Reiniciar</button>
|
||||
<script src="script.js"></script>
|
||||
</body>
|
||||
|
@@ -1,52 +1,184 @@
|
||||
'use strict';
|
||||
|
||||
const boardDiv = document.getElementById('board');
|
||||
const statusDiv = document.getElementById('status');
|
||||
const restartBtn = document.getElementById('restart-btn');
|
||||
let board, currentPlayer, gameOver;
|
||||
const firstPlayerSelect = document.getElementById('first-player');
|
||||
const scoreXSpan = document.getElementById('score-x');
|
||||
const scoreOSpan = document.getElementById('score-o');
|
||||
const scoreDrawSpan = document.getElementById('score-d');
|
||||
|
||||
function initGame() {
|
||||
board = Array(9).fill('');
|
||||
currentPlayer = 'X';
|
||||
gameOver = false;
|
||||
statusDiv.textContent = "Turno de " + currentPlayer;
|
||||
renderBoard();
|
||||
}
|
||||
const WIN_COMBOS = [
|
||||
[0, 1, 2], [3, 4, 5], [6, 7, 8], // Filas
|
||||
[0, 3, 6], [1, 4, 7], [2, 5, 8], // Columnas
|
||||
[0, 4, 8], [2, 4, 6] // Diagonales
|
||||
];
|
||||
|
||||
function renderBoard() {
|
||||
boardDiv.innerHTML = '';
|
||||
board.forEach((cell, idx) => {
|
||||
const cellDiv = document.createElement('div');
|
||||
cellDiv.className = 'cell';
|
||||
cellDiv.textContent = cell;
|
||||
cellDiv.onclick = () => handleCellClick(idx);
|
||||
boardDiv.appendChild(cellDiv);
|
||||
});
|
||||
}
|
||||
let board = Array(9).fill('');
|
||||
let currentPlayer = 'X';
|
||||
let gameOver = false;
|
||||
let scores = { X: 0, O: 0, D: 0 };
|
||||
|
||||
function handleCellClick(idx) {
|
||||
if (gameOver || board[idx] !== '') return;
|
||||
board[idx] = currentPlayer;
|
||||
renderBoard();
|
||||
if (checkWinner(currentPlayer)) {
|
||||
statusDiv.textContent = `¡${currentPlayer} gana! 🎉`;
|
||||
gameOver = true;
|
||||
} else if (board.every(cell => cell !== '')) {
|
||||
statusDiv.textContent = "¡Empate!";
|
||||
gameOver = true;
|
||||
} else {
|
||||
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
|
||||
statusDiv.textContent = "Turno de " + currentPlayer;
|
||||
function loadScores() {
|
||||
try {
|
||||
const raw = localStorage.getItem('ttt_scores');
|
||||
if (raw) {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (parsed && typeof parsed === 'object') {
|
||||
scores.X = Number(parsed.X) || 0;
|
||||
scores.O = Number(parsed.O) || 0;
|
||||
scores.D = Number(parsed.D) || 0;
|
||||
}
|
||||
}
|
||||
} catch (_) {
|
||||
// Ignorar errores de parsing o acceso
|
||||
}
|
||||
}
|
||||
|
||||
function checkWinner(player) {
|
||||
const winCases = [
|
||||
[0,1,2],[3,4,5],[6,7,8], // Filas
|
||||
[0,3,6],[1,4,7],[2,5,8], // Columnas
|
||||
[0,4,8],[2,4,6] // Diagonales
|
||||
];
|
||||
return winCases.some(combo => combo.every(i => board[i] === player));
|
||||
function saveScores() {
|
||||
try {
|
||||
localStorage.setItem('ttt_scores', JSON.stringify(scores));
|
||||
} catch (_) {
|
||||
// Ignorar errores de almacenamiento
|
||||
}
|
||||
}
|
||||
|
||||
restartBtn.onclick = initGame;
|
||||
function updateScoreUI() {
|
||||
if (scoreXSpan) scoreXSpan.textContent = String(scores.X);
|
||||
if (scoreOSpan) scoreOSpan.textContent = String(scores.O);
|
||||
if (scoreDrawSpan) scoreDrawSpan.textContent = String(scores.D);
|
||||
}
|
||||
|
||||
initGame();
|
||||
function initBoardDom() {
|
||||
// Crear la cuadrícula de 3x3 solo si no existe
|
||||
if (boardDiv.children.length === 9) {
|
||||
// limpiar estado de clases win previas
|
||||
Array.from(boardDiv.children).forEach(c => c.classList.remove('win'));
|
||||
return;
|
||||
}
|
||||
boardDiv.textContent = '';
|
||||
for (let idx = 0; idx < 9; idx++) {
|
||||
const cell = document.createElement('button');
|
||||
cell.type = 'button';
|
||||
cell.className = 'cell';
|
||||
cell.setAttribute('data-idx', String(idx));
|
||||
cell.setAttribute('aria-label', `Casilla ${idx + 1}`);
|
||||
cell.setAttribute('role', 'gridcell');
|
||||
cell.addEventListener('click', onCellClick);
|
||||
cell.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') onCellClick(e);
|
||||
});
|
||||
boardDiv.appendChild(cell);
|
||||
}
|
||||
boardDiv.setAttribute('aria-disabled', 'false');
|
||||
}
|
||||
|
||||
function render() {
|
||||
for (let i = 0; i < 9; i++) {
|
||||
const cellEl = boardDiv.children[i];
|
||||
if (!cellEl) continue;
|
||||
cellEl.textContent = board[i];
|
||||
}
|
||||
}
|
||||
|
||||
function setStatus(msg) {
|
||||
statusDiv.textContent = msg;
|
||||
}
|
||||
|
||||
function checkWinner(player) {
|
||||
for (const combo of WIN_COMBOS) {
|
||||
const [a, b, c] = combo;
|
||||
if (board[a] === player && board[b] === player && board[c] === player) {
|
||||
return { win: true, combo };
|
||||
}
|
||||
}
|
||||
return { win: false, combo: null };
|
||||
}
|
||||
|
||||
function highlightCombo(combo) {
|
||||
if (!combo) return;
|
||||
combo.forEach(i => {
|
||||
const el = boardDiv.children[i];
|
||||
if (el) el.classList.add('win');
|
||||
});
|
||||
}
|
||||
|
||||
function endGame(result, combo) {
|
||||
gameOver = true;
|
||||
boardDiv.setAttribute('aria-disabled', 'true');
|
||||
|
||||
if (result === 'X' || result === 'O') {
|
||||
setStatus(`¡${result} gana! 🎉`);
|
||||
scores[result] += 1;
|
||||
highlightCombo(combo);
|
||||
} else {
|
||||
setStatus('¡Empate!');
|
||||
scores.D += 1;
|
||||
}
|
||||
|
||||
updateScoreUI();
|
||||
saveScores();
|
||||
}
|
||||
|
||||
function onCellClick(e) {
|
||||
const target = e.currentTarget;
|
||||
const idx = Number(target.getAttribute('data-idx'));
|
||||
|
||||
if (gameOver || !Number.isInteger(idx)) return;
|
||||
if (board[idx] !== '') return;
|
||||
|
||||
board[idx] = currentPlayer;
|
||||
render();
|
||||
|
||||
const { win, combo } = checkWinner(currentPlayer);
|
||||
if (win) {
|
||||
endGame(currentPlayer, combo);
|
||||
return;
|
||||
}
|
||||
|
||||
// Comprueba empate
|
||||
if (board.every(cell => cell !== '')) {
|
||||
endGame('D', null);
|
||||
return;
|
||||
}
|
||||
|
||||
// Cambiar turno
|
||||
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
|
||||
setStatus(`Turno de ${currentPlayer}`);
|
||||
}
|
||||
|
||||
function startGame() {
|
||||
board = Array(9).fill('');
|
||||
gameOver = false;
|
||||
|
||||
// Determinar primer jugador desde el selector si existe
|
||||
if (firstPlayerSelect && (firstPlayerSelect.value === 'X' || firstPlayerSelect.value === 'O')) {
|
||||
currentPlayer = firstPlayerSelect.value;
|
||||
} else {
|
||||
currentPlayer = 'X';
|
||||
}
|
||||
|
||||
boardDiv.setAttribute('aria-disabled', 'false');
|
||||
initBoardDom();
|
||||
// Remover cualquier resaltado previo
|
||||
Array.from(boardDiv.children).forEach(c => c.classList.remove('win'));
|
||||
render();
|
||||
setStatus(`Turno de ${currentPlayer}`);
|
||||
}
|
||||
|
||||
// Listeners
|
||||
restartBtn.addEventListener('click', startGame);
|
||||
if (firstPlayerSelect) {
|
||||
firstPlayerSelect.addEventListener('change', () => {
|
||||
// Solo afecta si la partida no ha empezado o si no ha terminado aún
|
||||
if (!gameOver && board.every(v => v === '')) {
|
||||
currentPlayer = firstPlayerSelect.value;
|
||||
setStatus(`Turno de ${currentPlayer}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Init
|
||||
loadScores();
|
||||
updateScoreUI();
|
||||
startGame();
|
@@ -118,4 +118,56 @@ h1 {
|
||||
.cell {
|
||||
font-size: 3em;
|
||||
}
|
||||
}
|
||||
/* Controles de partida y marcador */
|
||||
#controls {
|
||||
margin: 1rem auto 0.5rem auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
}
|
||||
#controls select#first-player {
|
||||
font-size: 1em;
|
||||
padding: 6px 10px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #ddd;
|
||||
}
|
||||
#score {
|
||||
margin: 0.6rem auto 0.4rem auto;
|
||||
font-size: 1em;
|
||||
color: #444;
|
||||
}
|
||||
|
||||
/* Ajustes para botones-celda (accesibilidad) */
|
||||
.cell {
|
||||
border: none;
|
||||
outline: none;
|
||||
}
|
||||
.cell:focus-visible {
|
||||
box-shadow: 0 0 0 4px rgba(52, 152, 219, 0.35);
|
||||
}
|
||||
|
||||
/* Resaltado de combinación ganadora */
|
||||
.win {
|
||||
background: #eaf7ff;
|
||||
box-shadow: 0 0 0 2px rgba(61, 90, 254, 0.25), 0 2px 10px rgba(61, 90, 254, 0.16);
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
#controls select#first-player {
|
||||
background: #20233a;
|
||||
color: #eaeaf0;
|
||||
border-color: #2c3252;
|
||||
}
|
||||
#score {
|
||||
color: #a0a3b0;
|
||||
}
|
||||
.cell:focus-visible {
|
||||
box-shadow: 0 0 0 4px rgba(61, 90, 254, 0.35);
|
||||
}
|
||||
.win {
|
||||
background: #172441;
|
||||
box-shadow: 0 0 0 2px rgba(61, 90, 254, 0.35), 0 2px 12px rgba(61, 90, 254, 0.22);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user