Añadidos juegos
This commit is contained in:
52
3-en-raya/script.js
Normal file
52
3-en-raya/script.js
Normal file
@@ -0,0 +1,52 @@
|
||||
const boardDiv = document.getElementById('board');
|
||||
const statusDiv = document.getElementById('status');
|
||||
const restartBtn = document.getElementById('restart-btn');
|
||||
let board, currentPlayer, gameOver;
|
||||
|
||||
function initGame() {
|
||||
board = Array(9).fill('');
|
||||
currentPlayer = 'X';
|
||||
gameOver = false;
|
||||
statusDiv.textContent = "Turno de " + currentPlayer;
|
||||
renderBoard();
|
||||
}
|
||||
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
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 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));
|
||||
}
|
||||
|
||||
restartBtn.onclick = initGame;
|
||||
|
||||
initGame();
|
Reference in New Issue
Block a user