¡Claro! Aquí tienes un código simple para un juego de tres en raya (también conocido como "tic-tac-toe") en JavaScript que puedes ejecutar en un navegador. Este código incluye un tablero básico y la lógica para jugar:
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Juego 3 en Raya</title>
<style>
#board {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-template-rows: repeat(3, 100px);
gap: 5px;
}
.cell {
display: flex;
justify-content: center;
align-items: center;
border: 1px solid #000;
font-size: 24px;
cursor: pointer;
}
.cell:hover {
background-color: #f0f0f0;
}
</style>
</head>
<body>
<h1>Juego 3 en Raya</h1>
<div id="board"></div>
<button onclick="resetGame()">Reiniciar Juego</button>
<p id="status"></p>
<script>
const boardElement = document.getElementById('board');
const statusElement = document.getElementById('status');
let board = ['', '', '', '', '', '', '', '', ''];
let currentPlayer = 'X';
function createBoard() {
boardElement.innerHTML = '';
board.forEach((cell, index) => {
const cellElement = document.createElement('div');
cellElement.innerText = cell;
cellElement.classList.add('cell');
cellElement.addEventListener('click', () => handleCellClick(index));
boardElement.appendChild(cellElement);
});
updateStatus();
}
function handleCellClick(index) {
if (board[index] === '' && !checkWinner()) {
board[index] = currentPlayer;
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
createBoard();
}
}
function checkWinner() {
const winningCombinations = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
for (const combination of winningCombinations) {
const [a, b, c] = combination;
if (board[a] && board[a] === board[b] && board[a] === board[c]) {
statusElement.innerText = `¡Jugador ${board[a]} gana!`;
return true;
}
}
if (!board.includes('')) {
statusElement.innerText = '¡Es un empate!';
return true;
}
return false;
}
function resetGame() {
board = ['', '', '', '', '', '', '', '', ''];
currentPlayer = 'X';
statusElement.innerText = '';
createBoard();
}
createBoard();
</script>
</body>
</html>
Cómo usar el código:
- Copia el código anterior en un archivo con la extensión
.html (por ejemplo, tres_en_raya.html).
- Abre el archivo en un navegador web.
- Podrás hacer clic en las casillas del tablero para jugar.
Características del juego:
- Dos jugadores se turnan para colocar sus símbolos (X y O).
- El juego detecta automáticamente si hay un ganador o un empate.
- Incluye un botón para reiniciar la partida.
¡Espero que te diviertas jugando! Si necesitas más funcionalidades o modificaciones, no dudes en decírmelo.