Bienvenido, les saluda Luis y aquà les traigo otro artÃculo.
Índice
Aprenda a construir un juego simple de tic tac toe
usando JavaScript
puro
Hoy, en esta historia, crearemos un juego de Tic Tac Toe simple usando JavaScript puro. Por lo tanto, debe conocer algunos conceptos básicos de html
y css y las funciones de selección de consultas para crear este juego.
Entremos en el tema. Primero crearemos una estructura básica para nuestro juego. Primero asegúrese de crear una interfaz de usuario. Vamos a romper en pedazos pequeños. Para que sea fácil de mantener para nosotros.
- TÃtulo.
- CuadrÃcula
3 × 3
. - Muestra la información del turno del jugador actual.
- Muestra quién ganó el juego.
- Mostrar si el juego termina en empate.
- Botón de reinicio para reiniciar todo el juego.
Ahora entremos en el flujo del juego para hacer clic en una celda.
- Rastree cualquier clic que haga clic en nuestra celda.
- Verifique el movimiento válido y asegúrese de que se haya hecho clic en una celda ya jugada.
- Actualiza el estado del juego.
- Validar el estado del juego.
- Actualice los cambios realizados en la interfaz de usuario.
- Repite y finaliza el juego por última vez.
Ahora profundicemos en el proyecto para construirlo.
Comencemos a construir la interfaz de usuario del juego. Como mencioné antes, es un juego simple, asà que hagamos que la interfaz de usuario también sea simple.
La estructura contiene tres archivos principales.
-
index.html
(contiene la estructura de la interfaz de usuario). -
style.css
(hace que nuestro juego parezca más inteligente). -
script.js
(contiene la lógica del juego).
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Tic Tac Toe</title> <link rel="stylesheet" href="style.css"> </head> <body> <section> <h1 class="game--title">Tic Tac Toe</h1> <div class="game--container"> <div data-cell-index="0" class="cell"></div> <div data-cell-index="1" class="cell"></div> <div data-cell-index="2" class="cell"></div> <div data-cell-index="3" class="cell"></div> <div data-cell-index="4" class="cell"></div> <div data-cell-index="5" class="cell"></div> <div data-cell-index="6" class="cell"></div> <div data-cell-index="7" class="cell"></div> <div data-cell-index="8" class="cell"></div> </div> <h2 class="game--status"></h2> <button class="game--restart">Restart Game</button> </section> <script src="script.js"></script> </body> </html>
Incluimos nuestra hoja de estilo en el elemento <head>
 para hacer que la hoja de estilo se cargue antes del html.
También incluimos el archivo script.js
 justo encima de </body>
 para cargar el archivo JavaScript después del html.
También incluimos el elemento <h2>
 para mostrar la información del juego y el botón de reinicio.
Además, cada uno contiene atributos de Ãndice de celda de datos utilizados para realizar un seguimiento del clic.
body { font-family: "Arial", sans-serif; } section { text-align: center; } .game--container { display: grid; grid-template-columns: repeat(3, auto); width: 306px; margin: 50px auto; } .cell { font-family: "Permanent Marker", cursive; width: 100px; height: 100px; box-shadow: 0 0 0 1px #333333; border: 1px solid #333333; cursor: pointer; line-height: 100px; font-size: 60px; }
Solo querÃa implementar los estilos para el  contenedor .game
 para nuestra cuadrÃcula css.
Queremos construir una cuadrÃcula de 3 × 3
, asà que asegúrese de la plantilla de columna de la cuadrÃcula con la propiedad 3
y repÃtala.
Divide las celdas contenidas en 3
columnas y la celda establece automáticamente su ancho.
Ahora entre en la lógica del juego y divida el código JavaScript en pequeños pedazos para nuestra plantilla.
/* We store our game status element here to allow us to more easily use it later on */ const statusDisplay = document.querySelector('.game--status'); let gameActive = true; let currentPlayer = "X"; let gameState = ["", "", "", "", "", "", "", "", ""]; const winningMessage = () => `Player $ {currentPlayer} has won!`; const drawMessage = () => `Game ended in a draw!`; const currentPlayerTurn = () => `It's $ {currentPlayer}'s turn`; /* We set the inital message to let the players know whose turn it is */ statusDisplay.innerHTML = currentPlayerTurn(); function handleCellPlayed() { } function handlePlayerChange() { } function handleResultValidation() { } function handleCellClick() { } function handleRestartGame() { } document.querySelectorAll('.cell').forEach(cell => cell.addEventListener('click', handleCellClick)); document.querySelector('.game--restart').addEventListener('click', handleRestartGame);
Acabamos de delinear nuestra lógica de juego. Tendremos que manejar nuestra lógica de juego. Asà que creemos nuestra lógica.
En handleCellClick
, tenemos que manejar dos cosas. Primero tenemos que comprobar si ya se ha hecho clic en la celda. Si no continúa con nuestro juego.
Veamos cómo se ve.
function handleCellClick(clickedCellEvent) { /* We will save the clicked html element in a variable for easier further use */ const clickedCell = clickedCellEvent.target; /* Here we will grab the 'data-cell-index' attribute from the clicked cell to identify where that cell is in our grid. Please note that the getAttribute will return a string value. Since we need an actual number we will parse it to an integer(number) */ const clickedCellIndex = parseInt( clickedCell.getAttribute('data-cell-index') ); /* Next up we need to check whether the call has already been played, or if the game is paused. If either of those is true we will simply ignore the click. */ if (gameState[clickedCellIndex] !== "" || !gameActive) { return; } /* If everything if in order we will proceed with the game flow */ handleCellPlayed(clickedCell, clickedCellIndex); handleResultValidation(); }
En este controlador, tenemos que actualizar dos cosas. Primero actualice nuestro estado y luego la interfaz de usuario.
function handleCellPlayed(clickedCell, clickedCellIndex) { /* We update our internal game state to reflect the played move, as well as update the user interface to reflect the played move */ gameState[clickedCellIndex] = currentPlayer; clickedCell.innerHTML = currentPlayer; }
Aceptamos solo la celda en la que se hace clic actualmente y el Ãndice de la celda en la que se hace clic.
La validación de resultados es el núcleo de nuestro juego de tic tac toe
. Aquà solo comprobaremos si el juego termina con victoria o empate.
Comencemos a verificar si el jugador actual ganó el juego.
const winningConditions = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6] ]; function handleResultValidation() { let roundWon = false; for (let i = 0; i <= 7; i++) { const winCondition = winningConditions[i]; let a = gameState[winCondition[0]]; let b = gameState[winCondition[1]]; let c = gameState[winCondition[2]]; if (a === '' || b === '' || c === '') { continue; } if (a === b && b === c) { roundWon = true; break } } if (roundWon) { statusDisplay.innerHTML = winningMessage(); gameActive = false; return; } }
Revisemos la otra condición si el juego terminó con empate. La forma en que el juego termina en empate bajo ciertas condiciones.
const winningConditions = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6] ]; function handleResultValidation() { let roundWon = false; for (let i = 0; i <= 7; i++) { const winCondition = winningConditions[i]; let a = gameState[winCondition[0]]; let b = gameState[winCondition[1]]; let c = gameState[winCondition[2]]; if (a === '' || b === '' || c === '') { continue; } if (a === b && b === c) { roundWon = true; break } } if (roundWon) { statusDisplay.innerHTML = winningMessage(); gameActive = false; return; } /* We will check weather there are any values in our game state array that are still not populated with a player sign */ let roundDraw = !gameState.includes(""); if (roundDraw) { statusDisplay.innerHTML = drawMessage(); gameActive = false; return; } /* If we get to here we know that the no one won the game yet, and that there are still moves to be played, so we continue by changing the current player. */ handlePlayerChange(); }
Esto cambiará el jugador actual y actualizará el estado del juego. Aquà estamos usando un operador ternario para asignar el valor al nuevo jugador.
function handlePlayerChange() { currentPlayer = currentPlayer === "X" ? "O" : "X"; statusDisplay.innerHTML = currentPlayerTurn(); }
Esto restablecerá todo el seguimiento de nuestro juego a los valores predeterminados. Borra todas las canciones del tablero de juego y actualiza el estado del juego en el mensaje del jugador actual.
function handleRestartGame() { gameActive = true; currentPlayer = "X"; gameState = ["", "", "", "", "", "", "", "", ""]; statusDisplay.innerHTML = currentPlayerTurn(); document.querySelectorAll('.cell') .forEach(cell => cell.innerHTML = ""); }
Tic Tac Toe
.
Por supuesto, este es el básico que puedes convertir en un juego multijugador. También puedes desarrollar este proyecto como uno más largo.
Si te fue de utilidad deja un comentario. Gracias por leer.
Añadir comentario