Crear una Aplicación Web de Tres en Raya

CSSBeginner
Practicar Ahora

Introducción

En este proyecto, aprenderás a crear un juego de Tres en Raya (Tic-Tac-Toe) usando HTML, CSS y JavaScript. Tres en Raya es un juego para dos jugadores donde los jugadores se turnan para marcar X u O en una cuadrícula de 3x3. El objetivo es conseguir tres marcas seguidas, ya sea horizontal, vertical o diagonalmente. Crearás los archivos HTML, CSS y JavaScript necesarios e implementarás la lógica del juego paso a paso.

👀 Vista Previa

Vista previa del juego de Tres en Raya

🎯 Tareas

En este proyecto aprenderás:

  • Cómo configurar la estructura básica del juego de Tres en Raya usando HTML.
  • Cómo añadir estilos CSS para definir la apariencia de los elementos del juego.
  • Cómo implementar la lógica del juego usando JavaScript.
  • Cómo manejar las interacciones del usuario, comprobar si hay victorias o empates y actualizar las puntuaciones.
  • Cómo renderizar el tablero de juego y actualizar el indicador de turno.
  • Cómo permitir a los jugadores reiniciar el juego y comenzar una nueva ronda.

🏆 Logros

Después de completar este proyecto, serás capaz de:

  • Estructurar un archivo HTML para una aplicación web.
  • Estilizar elementos usando clases CSS.
  • Implementar la lógica del juego usando JavaScript.
  • Manejar las interacciones del usuario y actualizar la interfaz de usuario en consecuencia.
  • Renderizar el tablero de juego y actualizar el indicador de turno.
  • Crear oyentes de eventos y manejar eventos en JavaScript.
Este es un Laboratorio Guiado, que proporciona instrucciones paso a paso para ayudarte a aprender y practicar. Sigue las instrucciones cuidadosamente para completar cada paso y obtener experiencia práctica. Los datos históricos muestran que este es un laboratorio de nivel intermedio con una tasa de finalización del 52%. Ha recibido una tasa de revisión positiva del 100% por parte de los estudiantes.

Crear el Archivo HTML

Crea un nuevo archivo llamado index.html y añade el siguiente código.

cd ~/project
touch index.html

Este código configura la estructura básica del juego de Tres en Raya.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Tic-Tac-Toe</title>
    <link
      href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css"
      rel="stylesheet"
    />
    <style>
      /* Estilos CSS para el juego */
    </style>
  </head>

  <body>
    <div id="app">
      <h1 class="text-3xl font-bold mb-4 text-gray-900">Tic-Tac-Toe</h1>
      <div id="board" class="grid grid-cols-3 gap-4 mb-4">
        <!-- Celdas del tablero de juego -->
      </div>
      <div id="scoreboard" class="flex justify-between items-center mb-4">
        <!-- Puntuaciones de los jugadores -->
      </div>
      <div
        id="turn-indicator"
        class="text-2xl font-bold mb-4 text-gray-900"
      ></div>
      <button
        id="reset-button"
        class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
      >
        Reset Game
      </button>
    </div>

    <script>
      // Código JavaScript para la lógica del juego
    </script>
  </body>
</html>
✨ Revisar Solución y Practicar

Añadir Estilos CSS

Dentro de la etiqueta <style> en la sección <head> del archivo HTML, añade los estilos CSS necesarios para el juego. Estos estilos definen la apariencia de los elementos del juego, como el tablero, las celdas, las puntuaciones y los botones.

<style>
  .board-cell {
    width: 100px;
    height: 100px;
  }

  body {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
    background-color: #222;
    font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
  }

  #app {
    text-align: center;
    background-color: #f5f5f5;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  }

  h1 {
    font-size: 32px;
    color: #333;
  }

  .text-gray-900 {
    color: #333 !important;
  }

  .text-2xl {
    font-size: 24px;
  }

  .bg-blue-500 {
    background-color: #4267b2;
  }

  .bg-blue-500:hover {
    background-color: #3b5ca0;
  }

  .bg-blue-700 {
    background-color: #385898;
  }

  .text-white {
    color: #fff !important;
  }

  .rounded {
    border-radius: 4px;
  }

  .highlight {
    background-color: #ffed4a;
  }
</style>

También puedes añadir style.css al proyecto y enlazarlo al archivo HTML usando la etiqueta <link>.

<link rel="stylesheet" href="style.css" />

Elige el método que prefieras.

✨ Revisar Solución y Practicar

Añadir el Código JavaScript de la Lógica del Juego

Dentro de la etiqueta <script> al final del archivo HTML, añade el código JavaScript que maneja la lógica del juego. Este código realiza un seguimiento del estado del juego, maneja las interacciones del usuario, comprueba si hay una victoria o un empate, actualiza las puntuaciones y renderiza el tablero de juego.

<script>
  // Código de la lógica del juego
</script>
✨ Revisar Solución y Practicar

Inicializar Variables del Juego

Declara las variables necesarias al principio del código JavaScript. Estas variables almacenarán el estado del juego, las puntuaciones de los jugadores y otra información relevante.

// Lógica del juego
const board = ["", "", "", "", "", "", "", "", ""];
let currentPlayer = "X";
let gameEnded = false;
let playerXScore = 0;
let playerOScore = 0;
let winningCells = [];
✨ Revisar Solución y Practicar

Manejar el Clic en la Celda

Crea una función llamada handleCellClick que se llamará cuando se haga clic en una celda del tablero de juego. Esta función manejará la lógica principal del juego, como actualizar el tablero, comprobar si hay una victoria, actualizar las puntuaciones y cambiar el jugador actual.

function handleCellClick(index) {
  if (gameEnded || board[index] !== "") return;
  board[index] = currentPlayer;
  renderBoard();

  if (checkWin()) {
    updateScore();
    highlightWinningCells();
    alert(`Player ${currentPlayer} wins!`);
    gameEnded = true;
  } else if (board.every((cell) => cell !== "")) {
    alert("It's a tie!");
    gameEnded = true;
  } else {
    currentPlayer = currentPlayer === "X" ? "O" : "X";
    updateTurnIndicator();
  }
}
✨ Revisar Solución y Practicar

Comprobar si hay Victoria

Crea una función llamada checkWin que comprueba si existe una condición de victoria en el tablero de juego. Esta función compara los valores en el array board con las combinaciones ganadoras para determinar si un jugador ha ganado la partida.

function checkWin() {
  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 (let i = 0; i < winningCombinations.length; i++) {
    const [a, b, c] = winningCombinations[i];
    if (board[a] !== "" && board[a] === board[b] && board[a] === board[c]) {
      winningCells = [a, b, c];
      return true;
    }
  }
  return false;
}
✨ Revisar Solución y Practicar

Reiniciar el Juego

Crea una función llamada resetGame que reinicia el estado del juego a sus valores iniciales. Esta función se llama cuando se hace clic en el botón de reinicio y borra el tablero, restablece el jugador actual, borra las celdas ganadoras, actualiza el indicador de turno y renderiza el tablero.

function resetGame() {
  board.fill("");
  currentPlayer = "X";
  gameEnded = false;
  winningCells = [];
  updateTurnIndicator();
  renderBoard();
}
✨ Revisar Solución y Practicar

Actualizar Puntuaciones de los Jugadores

Crea una función llamada updateScore que actualiza las puntuaciones de los jugadores. Esta función se llama cuando un jugador gana una partida. Incrementa la puntuación del jugador correspondiente y actualiza la visualización de la puntuación en la página.

function updateScore() {
  if (currentPlayer === "X") {
    playerXScore++;
    document.getElementById("player-x-score").textContent = playerXScore;
  } else {
    playerOScore++;
    document.getElementById("player-o-score").textContent = playerOScore;
  }
}
✨ Revisar Solución y Practicar

Actualizar Indicador de Turno

Crea una función llamada updateTurnIndicator que actualiza el indicador de turno en la página para mostrar el turno del jugador actual.

function updateTurnIndicator() {
  const turnIndicator = document.getElementById("turn-indicator");
  turnIndicator.textContent = `Current Turn: Player ${currentPlayer}`;
}
✨ Revisar Solución y Practicar

Resumen

Summary content missing in import file.

✨ Revisar Solución y Practicar

Render the Game Board

Create a function named renderBoard that updates the game board on the page according to the current state of the board array. This function is called after each player's move to update the visuals.

function renderBoard() {
  const cells = document.querySelectorAll(".board-cell");
  cells.forEach((cell, index) => {
    cell.textContent = board[index];
    cell.classList.remove("highlight");
  });
}
✨ Revisar Solución y Practicar

Add Event Listeners

Add event listeners to the game board cells and the reset button. These event listeners call the corresponding functions when the events occur.

// Event listeners
const cells = document.querySelectorAll(".board-cell");
cells.forEach((cell, index) => {
  cell.addEventListener("click", () => handleCellClick(index));
});

const resetButton = document.getElementById("reset-button");
resetButton.addEventListener("click", resetGame);
✨ Revisar Solución y Practicar

Initial Render

At the end of the JavaScript code, add the code for the initial render. This code sets up the initial state of the game, updates the turn indicator, and renders the game board.

// Initial render
updateTurnIndicator();
renderBoard();
✨ Revisar Solución y Practicar

Run the Project

You can now run the project and play Tic-Tac-Toe!

Click on Go Live button in the bottom right corner of WebIDE, to run the project.

WebIDE Go Live button

This will open the project in Web 8080 Tab.

Web 8080 Tab interface

Click on the cells to make your moves and click the reset button to start a new game.

✨ Revisar Solución y Practicar

Summary

Congratulations! You have successfully created a Tic-Tac-Toe game using HTML, CSS, and JavaScript. The project covered creating the HTML file, adding CSS styles, implementing the game logic, and handling user interactions. The game allows two players to take turns, checks for a win or a tie, updates scores, and highlights winning cells. You can now run the project and enjoy playing Tic-Tac-Toe!