Tic Tac Toe Game

This is a simple tic tac toe game built with HTML, CSS, and JavaScript.

Game Board

The game board is a 3x3 grid made up of HTML 'div' elements. Each cell on the grid is identified by a unique 'id' attribute that enables the JavaScript code to interact with it.

<div class='cell' id='cell-1'></div>
<div class='cell' id='cell-2'></div>
<div class='cell' id='cell-3'></div>
<div class='cell' id='cell-4'></div>
<div class='cell' id='cell-5'></div>
<div class='cell' id='cell-6'></div>
<div class='cell' id='cell-7'></div>
<div class='cell' id='cell-8'></div>
<div class='cell' id='cell-9'></div>

Game Logic

The game logic is implemented in JavaScript. The game tracks the current player turn, and when a cell is clicked, it checks if it is empty. If the cell is empty, it places the player's symbol in the cell and switches the turn to the other player.

let currentPlayer = 'X';

function handleCellClick(event) {
  const cell = event.target;
  const cellIndex = parseInt(cell.getAttribute('id').split('-')[1]);

  if (board[cellIndex] !== '' || !gameActive) {
    return;
  }

  cell.innerText = currentPlayer;
  board[cellIndex] = currentPlayer;
  handleResultValidation();
}

Game Result Validation

After each turn, the game checks if a player has won or if the game is tied. If a player has won, the game displays a message announcing the winner. If the game is tied, the game displays a message announcing the tie.

function handleResultValidation() {
  let roundWon = false;
  for (let i = 0; i <= 7; i++) {
    const winCondition = winningConditions[i];
    let a = board[winCondition[0]];
    let b = board[winCondition[1]];
    let c = board[winCondition[2]];
    if (a === '' || b === '' || c === '') {
      continue;
    }
    if (a === b && b === c) {
      roundWon = true;
      break;
    }
  }

  if (roundWon) {
    statusDisplay.innerHTML = winningMessage();
    gameActive = false;
    return;
  }

  let roundTied = !board.includes('');
  if (roundTied) {
    statusDisplay.innerHTML = tieMessage();
    gameActive = false;
    return;
  }

  handlePlayerChange();
}

Conclusion

That's it! A simple tic tac toe game built with HTML, CSS, and JavaScript. This is just a starting point, and there are many ways to enhance this game. Happy coding!

Tic Tac Toe Game: Simple HTML Implementation

原文地址: https://www.cveoy.top/t/topic/lnk4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录