Construa um Aplicativo Web de Jogo da Velha

CSSBeginner
Pratique Agora

Introdução

Neste projeto, você aprenderá a criar um jogo da velha (Tic-Tac-Toe) usando HTML, CSS e JavaScript. Jogo da Velha é um jogo para dois jogadores onde os participantes se revezam marcando X ou O em uma grade 3x3. O objetivo é conseguir três marcas seguidas, seja horizontalmente, verticalmente ou diagonalmente. Você criará os arquivos HTML, CSS e JavaScript necessários e implementará a lógica do jogo passo a passo.

👀 Prévia

Prévia do jogo da velha

🎯 Tarefas

Neste projeto, você aprenderá:

  • Como configurar a estrutura básica do jogo da velha usando HTML.
  • Como adicionar estilos CSS para definir a aparência dos elementos do jogo.
  • Como implementar a lógica do jogo usando JavaScript.
  • Como lidar com interações do usuário, verificar vitórias ou empates e atualizar as pontuações.
  • Como renderizar o tabuleiro do jogo e atualizar o indicador de turno.
  • Como permitir que os jogadores reiniciem o jogo e comecem uma nova rodada.

🏆 Conquistas

Após concluir este projeto, você será capaz de:

  • Estruturar um arquivo HTML para uma aplicação web.
  • Estilizar elementos usando classes CSS.
  • Implementar a lógica do jogo usando JavaScript.
  • Lidar com interações do usuário e atualizar a interface do usuário (UI) de acordo.
  • Renderizar o tabuleiro do jogo e atualizar o indicador de turno.
  • Criar event listeners e manipular eventos em JavaScript.
Este é um Laboratório Guiado, que fornece instruções passo a passo para ajudá-lo a aprender e praticar. Siga as instruções cuidadosamente para completar cada etapa e obter experiência prática. Dados históricos mostram que este é um laboratório de nível intermediário com uma taxa de conclusão de 52%. Recebeu uma taxa de avaliação positiva de 100% dos alunos.

Criar o Arquivo HTML

Crie um novo arquivo chamado index.html e adicione o seguinte código a ele.

cd ~/project
touch index.html

Este código configura a estrutura básica do jogo da velha.

<!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 o jogo */
    </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">
        <!-- Células do tabuleiro do jogo -->
      </div>
      <div id="scoreboard" class="flex justify-between items-center mb-4">
        <!-- Pontuações dos jogadores -->
      </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 a lógica do jogo
    </script>
  </body>
</html>
✨ Verificar Solução e Praticar

Adicionar Estilos CSS

Dentro da tag <style> na seção <head> do arquivo HTML, adicione os estilos CSS necessários para o jogo. Esses estilos definem a aparência dos elementos do jogo, como o tabuleiro, as células, as pontuações e os botões.

<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>

Você também pode adicionar style.css ao projeto e vinculá-lo ao arquivo HTML usando a tag <link>.

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

Escolha o método que preferir.

✨ Verificar Solução e Praticar

Adicionar Código JavaScript da Lógica do Jogo

Dentro da tag <script> no final do arquivo HTML, adicione o código JavaScript que lida com a lógica do jogo. Este código mantém o controle do estado do jogo, lida com as interações do usuário, verifica se há vitória ou empate, atualiza as pontuações e renderiza o tabuleiro do jogo.

<script>
  // Código da lógica do jogo
</script>
✨ Verificar Solução e Praticar

Inicializar Variáveis do Jogo

Declare as variáveis necessárias no início do código JavaScript. Essas variáveis armazenarão o estado do jogo, as pontuações dos jogadores e outras informações relevantes.

// Lógica do jogo
const board = ["", "", "", "", "", "", "", "", ""];
let currentPlayer = "X";
let gameEnded = false;
let playerXScore = 0;
let playerOScore = 0;
let winningCells = [];
✨ Verificar Solução e Praticar

Lidar com o Clique na Célula

Crie uma função chamada handleCellClick que será chamada quando uma célula do tabuleiro de jogo for clicada. Esta função lidará com a lógica principal do jogo, como atualizar o tabuleiro, verificar se há vitória, atualizar pontuações e mudar o jogador atual.

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();
  }
}
✨ Verificar Solução e Praticar

Verificar Vitória

Crie uma função chamada checkWin que verifica se há uma condição de vitória no tabuleiro do jogo. Esta função compara os valores no array board com as combinações vencedoras para determinar se um jogador venceu o jogo.

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;
}
✨ Verificar Solução e Praticar

Reiniciar o Jogo

Crie uma função chamada resetGame que reinicia o estado do jogo para os valores iniciais. Esta função é chamada quando o botão de reset é clicado e limpa o tabuleiro, redefine o jogador atual, limpa as células vencedoras, atualiza o indicador de turno e renderiza o tabuleiro.

function resetGame() {
  board.fill("");
  currentPlayer = "X";
  gameEnded = false;
  winningCells = [];
  updateTurnIndicator();
  renderBoard();
}
✨ Verificar Solução e Praticar

Atualizar Pontuações dos Jogadores

Crie uma função chamada updateScore que atualiza as pontuações dos jogadores. Esta função é chamada quando um jogador vence uma partida. Ela incrementa a pontuação do jogador correspondente e atualiza a exibição da pontuação na página.

function updateScore() {
  if (currentPlayer === "X") {
    playerXScore++;
    document.getElementById("player-x-score").textContent = playerXScore;
  } else {
    playerOScore++;
    document.getElementById("player-o-score").textContent = playerOScore;
  }
}
✨ Verificar Solução e Praticar

Atualizar Indicador de Turno

Crie uma função chamada updateTurnIndicator que atualiza o indicador de turno na página para mostrar o turno do jogador atual.

function updateTurnIndicator() {
  const turnIndicator = document.getElementById("turn-indicator");
  turnIndicator.textContent = `Current Turn: Player ${currentPlayer}`;
}
✨ Verificar Solução e Praticar

Resumo

Summary content missing in import file.

✨ Verificar Solução e Praticar

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");
  });
}
✨ Verificar Solução e Praticar

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);
✨ Verificar Solução e Praticar

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();
✨ Verificar Solução e Praticar

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.

✨ Verificar Solução e Praticar

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!