Mejoras y optimizaciones en general.
This commit is contained in:
@@ -3,12 +3,27 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Tres en Raya vs Máquina</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
</head>
|
||||
<body>
|
||||
<h1>Tres en Raya vs Máquina</h1>
|
||||
<div id="board"></div>
|
||||
<div id="status"></div>
|
||||
<h1 id="title">Tres en Raya vs Máquina</h1>
|
||||
|
||||
<div id="controls">
|
||||
<label for="player-side">Tu ficha:</label>
|
||||
<select id="player-side">
|
||||
<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 — Tú: <span id="score-player">0</span> · Máquina: <span id="score-ai">0</span> · Empates: <span id="score-d">0</span>
|
||||
</div>
|
||||
|
||||
<button id="restart-btn">Reiniciar</button>
|
||||
<script src="script.js"></script>
|
||||
</body>
|
||||
|
@@ -1,122 +1,307 @@
|
||||
'use strict';
|
||||
|
||||
// Referencias DOM
|
||||
const boardDiv = document.getElementById('board');
|
||||
const statusDiv = document.getElementById('status');
|
||||
const restartBtn = document.getElementById('restart-btn');
|
||||
let board, gameOver;
|
||||
const playerSideSelect = document.getElementById('player-side');
|
||||
const scorePlayerSpan = document.getElementById('score-player');
|
||||
const scoreAiSpan = document.getElementById('score-ai');
|
||||
const scoreDrawSpan = document.getElementById('score-d');
|
||||
|
||||
function initGame() {
|
||||
board = Array(9).fill('');
|
||||
gameOver = false;
|
||||
statusDiv.textContent = "Tu turno (X)";
|
||||
renderBoard();
|
||||
// Constantes
|
||||
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
|
||||
];
|
||||
|
||||
let board = Array(9).fill('');
|
||||
let gameOver = false;
|
||||
let playerSide = 'X';
|
||||
let aiSide = 'O';
|
||||
let scores = { player: 0, ai: 0, D: 0 };
|
||||
|
||||
function loadScores() {
|
||||
try {
|
||||
const raw = localStorage.getItem('ttt_ai_scores');
|
||||
if (raw) {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (parsed && typeof parsed === 'object') {
|
||||
scores.player = Number(parsed.player) || 0;
|
||||
scores.ai = Number(parsed.ai) || 0;
|
||||
scores.D = Number(parsed.D) || 0;
|
||||
}
|
||||
}
|
||||
} catch (_) {
|
||||
// Ignorar errores
|
||||
}
|
||||
}
|
||||
|
||||
function renderBoard() {
|
||||
boardDiv.innerHTML = '';
|
||||
board.forEach((cell, idx) => {
|
||||
const cellDiv = document.createElement('div');
|
||||
cellDiv.className = 'cell';
|
||||
cellDiv.textContent = cell;
|
||||
cellDiv.onclick = () => handlePlayerMove(idx);
|
||||
boardDiv.appendChild(cellDiv);
|
||||
function saveScores() {
|
||||
try {
|
||||
localStorage.setItem('ttt_ai_scores', JSON.stringify(scores));
|
||||
} catch (_) {
|
||||
// Ignorar errores
|
||||
}
|
||||
}
|
||||
|
||||
function updateScoreUI() {
|
||||
if (scorePlayerSpan) scorePlayerSpan.textContent = String(scores.player);
|
||||
if (scoreAiSpan) scoreAiSpan.textContent = String(scores.ai);
|
||||
if (scoreDrawSpan) scoreDrawSpan.textContent = String(scores.D);
|
||||
}
|
||||
|
||||
function initBoardDom() {
|
||||
// Si ya existen 9 hijos, reutilizarlos (mejor rendimiento)
|
||||
if (boardDiv.children.length === 9) {
|
||||
Array.from(boardDiv.children).forEach(c => {
|
||||
c.classList.remove('win');
|
||||
c.textContent = '';
|
||||
c.setAttribute('aria-label', 'Casilla');
|
||||
c.removeEventListener('click', onCellClick);
|
||||
c.addEventListener('click', onCellClick);
|
||||
c.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') onCellClick(e);
|
||||
});
|
||||
});
|
||||
boardDiv.setAttribute('aria-disabled', 'false');
|
||||
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('role', 'gridcell');
|
||||
cell.setAttribute('aria-label', `Casilla ${idx + 1}`);
|
||||
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 el = boardDiv.children[i];
|
||||
if (!el) continue;
|
||||
el.textContent = board[i];
|
||||
}
|
||||
}
|
||||
|
||||
function setStatus(msg) {
|
||||
statusDiv.textContent = msg;
|
||||
}
|
||||
|
||||
function getWinCombo(b, player) {
|
||||
for (const combo of WIN_COMBOS) {
|
||||
const [a, m, c] = combo;
|
||||
if (b[a] === player && b[m] === player && b[c] === player) {
|
||||
return combo;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function isDraw(b) {
|
||||
return b.every(cell => cell !== '') &&
|
||||
!getWinCombo(b, 'X') && !getWinCombo(b, 'O');
|
||||
}
|
||||
|
||||
function highlightCombo(combo) {
|
||||
if (!combo) return;
|
||||
combo.forEach(i => {
|
||||
const el = boardDiv.children[i];
|
||||
if (el) el.classList.add('win');
|
||||
});
|
||||
}
|
||||
|
||||
function handlePlayerMove(idx) {
|
||||
if (gameOver || board[idx] !== '') return;
|
||||
board[idx] = 'X';
|
||||
renderBoard();
|
||||
if (checkWinner('X')) {
|
||||
statusDiv.textContent = `¡Tú ganas! 🎉`;
|
||||
gameOver = true;
|
||||
function endGame(result, combo) {
|
||||
gameOver = true;
|
||||
boardDiv.setAttribute('aria-disabled', 'true');
|
||||
|
||||
if (result === playerSide) {
|
||||
setStatus('¡Tú ganas! 🎉');
|
||||
scores.player += 1;
|
||||
highlightCombo(combo);
|
||||
} else if (result === aiSide) {
|
||||
setStatus('¡La máquina gana! 🤖');
|
||||
scores.ai += 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;
|
||||
// Solo permitir movimiento del jugador cuando sea su turno
|
||||
const turn = nextTurn(board);
|
||||
if (turn !== playerSide) return;
|
||||
if (board[idx] !== '') return;
|
||||
|
||||
// Movimiento jugador
|
||||
board[idx] = playerSide;
|
||||
render();
|
||||
|
||||
// Comprobar fin
|
||||
const combo = getWinCombo(board, playerSide);
|
||||
if (combo) {
|
||||
endGame(playerSide, combo);
|
||||
return;
|
||||
}
|
||||
if (isDraw()) {
|
||||
statusDiv.textContent = "¡Empate!";
|
||||
gameOver = true;
|
||||
if (isDraw(board)) {
|
||||
endGame('D', null);
|
||||
return;
|
||||
}
|
||||
statusDiv.textContent = "Turno de la máquina (O)";
|
||||
setTimeout(machineMove, 400);
|
||||
|
||||
// Turno de la máquina
|
||||
setStatus(`Turno de la máquina (${aiSide})`);
|
||||
setTimeout(machineMove, 350);
|
||||
}
|
||||
|
||||
function nextTurn(b) {
|
||||
const xCount = b.filter(v => v === 'X').length;
|
||||
const oCount = b.filter(v => v === 'O').length;
|
||||
// En Tic-Tac-Toe empieza 'X'; si hay igual cantidad, le toca a 'X', si X > O, le toca 'O'
|
||||
return xCount === oCount ? 'X' : 'O';
|
||||
}
|
||||
|
||||
// Minimax con poda alfa-beta
|
||||
function minimax(b, depth, isMaximizing, alpha, beta) {
|
||||
const aiWin = getWinCombo(b, aiSide);
|
||||
const playerWin = getWinCombo(b, playerSide);
|
||||
|
||||
if (aiWin) return 10 - depth;
|
||||
if (playerWin) return depth - 10;
|
||||
if (isDraw(b)) return 0;
|
||||
|
||||
if (isMaximizing) {
|
||||
let best = -Infinity;
|
||||
for (let i = 0; i < 9; i++) {
|
||||
if (b[i] === '') {
|
||||
b[i] = aiSide;
|
||||
const score = minimax(b, depth + 1, false, alpha, beta);
|
||||
b[i] = '';
|
||||
best = Math.max(best, score);
|
||||
alpha = Math.max(alpha, best);
|
||||
if (beta <= alpha) break;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
} else {
|
||||
let best = Infinity;
|
||||
for (let i = 0; i < 9; i++) {
|
||||
if (b[i] === '') {
|
||||
b[i] = playerSide;
|
||||
const score = minimax(b, depth + 1, true, alpha, beta);
|
||||
b[i] = '';
|
||||
best = Math.min(best, score);
|
||||
beta = Math.min(beta, best);
|
||||
if (beta <= alpha) break;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
}
|
||||
|
||||
function machineMove() {
|
||||
if (gameOver) return;
|
||||
|
||||
// Si no es turno de la máquina, salir
|
||||
const turn = nextTurn(board);
|
||||
if (turn !== aiSide) return;
|
||||
|
||||
// Elegir mejor jugada con Minimax
|
||||
let bestScore = -Infinity;
|
||||
let move = null;
|
||||
for (let i = 0; i < 9; i++) {
|
||||
if (board[i] === '') {
|
||||
board[i] = 'O';
|
||||
let score = minimax(board, 0, false);
|
||||
board[i] = '';
|
||||
if (score > bestScore) {
|
||||
bestScore = score;
|
||||
move = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (move !== null) board[move] = 'O';
|
||||
renderBoard();
|
||||
if (checkWinner('O')) {
|
||||
statusDiv.textContent = `¡La máquina gana! 🤖`;
|
||||
gameOver = true;
|
||||
return;
|
||||
}
|
||||
if (isDraw()) {
|
||||
statusDiv.textContent = "¡Empate!";
|
||||
gameOver = true;
|
||||
return;
|
||||
}
|
||||
statusDiv.textContent = "Tu turno (X)";
|
||||
}
|
||||
|
||||
// Algoritmo Minimax
|
||||
function minimax(newBoard, depth, isMaximizing) {
|
||||
if (checkWinnerOnBoard(newBoard, 'O')) return 10 - depth;
|
||||
if (checkWinnerOnBoard(newBoard, 'X')) return depth - 10;
|
||||
if (newBoard.every(cell => cell !== '')) return 0;
|
||||
|
||||
if (isMaximizing) {
|
||||
let bestScore = -Infinity;
|
||||
for (let i = 0; i < 9; i++) {
|
||||
if (newBoard[i] === '') {
|
||||
newBoard[i] = 'O';
|
||||
let score = minimax(newBoard, depth + 1, false);
|
||||
newBoard[i] = '';
|
||||
bestScore = Math.max(score, bestScore);
|
||||
}
|
||||
}
|
||||
return bestScore;
|
||||
// Pequeña heurística: si está libre, prioriza centro (4) en primera jugada
|
||||
if (board.every(c => c === '')) {
|
||||
move = 4; // centro
|
||||
} else {
|
||||
let bestScore = Infinity;
|
||||
for (let i = 0; i < 9; i++) {
|
||||
if (newBoard[i] === '') {
|
||||
newBoard[i] = 'X';
|
||||
let score = minimax(newBoard, depth + 1, true);
|
||||
newBoard[i] = '';
|
||||
bestScore = Math.min(score, bestScore);
|
||||
if (board[i] === '') {
|
||||
board[i] = aiSide;
|
||||
const score = minimax(board, 0, false, -Infinity, Infinity);
|
||||
board[i] = '';
|
||||
if (score > bestScore) {
|
||||
bestScore = score;
|
||||
move = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
return bestScore;
|
||||
// Si no encontró nada (no debería), elige primera libre
|
||||
if (move === null) move = board.findIndex(c => c === '');
|
||||
}
|
||||
|
||||
if (move !== null) {
|
||||
board[move] = aiSide;
|
||||
}
|
||||
render();
|
||||
|
||||
// Comprobar fin
|
||||
const combo = getWinCombo(board, aiSide);
|
||||
if (combo) {
|
||||
endGame(aiSide, combo);
|
||||
return;
|
||||
}
|
||||
if (isDraw(board)) {
|
||||
endGame('D', null);
|
||||
return;
|
||||
}
|
||||
|
||||
setStatus(`Tu turno (${playerSide})`);
|
||||
}
|
||||
|
||||
function startGame() {
|
||||
// Lado del jugador según selector
|
||||
if (playerSideSelect && (playerSideSelect.value === 'X' || playerSideSelect.value === 'O')) {
|
||||
playerSide = playerSideSelect.value;
|
||||
} else {
|
||||
playerSide = 'X';
|
||||
}
|
||||
aiSide = playerSide === 'X' ? 'O' : 'X';
|
||||
|
||||
// Reset
|
||||
board = Array(9).fill('');
|
||||
gameOver = false;
|
||||
initBoardDom();
|
||||
Array.from(boardDiv.children).forEach(c => c.classList.remove('win'));
|
||||
render();
|
||||
|
||||
// Si empieza la IA (jugador eligió 'O'), IA mueve primero
|
||||
const turn = nextTurn(board);
|
||||
if (turn === aiSide) {
|
||||
setStatus(`Turno de la máquina (${aiSide})`);
|
||||
setTimeout(machineMove, 300);
|
||||
} else {
|
||||
setStatus(`Tu turno (${playerSide})`);
|
||||
}
|
||||
}
|
||||
|
||||
function checkWinner(player) {
|
||||
return checkWinnerOnBoard(board, player);
|
||||
// Listeners
|
||||
restartBtn.addEventListener('click', startGame);
|
||||
if (playerSideSelect) {
|
||||
playerSideSelect.addEventListener('change', () => {
|
||||
// Reiniciar al cambiar de lado
|
||||
startGame();
|
||||
});
|
||||
}
|
||||
|
||||
function checkWinnerOnBoard(b, player) {
|
||||
const wins = [
|
||||
[0,1,2],[3,4,5],[6,7,8],
|
||||
[0,3,6],[1,4,7],[2,5,8],
|
||||
[0,4,8],[2,4,6]
|
||||
];
|
||||
return wins.some(combo => combo.every(i => b[i] === player));
|
||||
}
|
||||
|
||||
function isDraw() {
|
||||
return board.every(cell => cell !== '') && !checkWinner('X') && !checkWinner('O');
|
||||
}
|
||||
|
||||
restartBtn.onclick = initGame;
|
||||
|
||||
initGame();
|
||||
// Init
|
||||
loadScores();
|
||||
updateScoreUI();
|
||||
startGame();
|
@@ -119,4 +119,56 @@ h1 {
|
||||
.cell {
|
||||
font-size: 3em;
|
||||
}
|
||||
}
|
||||
/* Controles y marcador */
|
||||
#controls {
|
||||
margin: 1rem auto 0.5rem auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
}
|
||||
#controls select#player-side {
|
||||
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;
|
||||
}
|
||||
|
||||
/* Botones-celda accesibles */
|
||||
.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#player-side {
|
||||
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