HTML Tic Tac Toe Game

To create a Tic Tac Toe game in HTML, you'll need to use HTML, CSS, and JavaScript. Here's a simple example:

HTML

First, create the HTML structure for the game board:

<div class='board'>
  <div class='square'></div>
  <div class='square'></div>
  <div class='square'></div>
  <div class='square'></div>
  <div class='square'></div>
  <div class='square'></div>
  <div class='square'></div>
  <div class='square'></div>
  <div class='square'></div>
</div>

CSS

Next, create the CSS styles to position the squares and style the board:

.board {
  display: flex;
  flex-wrap: wrap;
  width: 300px;
  height: 300px;
  margin: 0 auto;
  border: 5px solid black;
}

.square {
  width: 90px;
  height: 90px;
  border: 2px solid black;
  font-size: 60px;
  text-align: center;
  line-height: 80px;
  cursor: pointer;
}

JavaScript

Finally, create the JavaScript logic to allow players to make moves and determine the winner:

let squares = document.querySelectorAll('.square');
let currentPlayer = 'X';

function handleClick(e) {
  let square = e.target;
  if (square.innerHTML !== '') {
    return;
  }
  square.innerHTML = currentPlayer;
  checkForWinner();
  currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
}

squares.forEach(square => {
  square.addEventListener('click', handleClick);
});

function checkForWinner() {
  let 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++) {
    let [a, b, c] = winningCombinations[i];
    if (squares[a].innerHTML !== '' &&
        squares[a].innerHTML === squares[b].innerHTML &&
        squares[b].innerHTML === squares[c].innerHTML) {
      alert('${currentPlayer} wins!');
      resetGame();
      return;
    }
  }

  if ([...squares].every(square => square.innerHTML !== '')) {
    alert('It's a tie!');
    resetGame();
    return;
  }
}

function resetGame() {
  squares.forEach(square => {
    square.innerHTML = '';
  });
  currentPlayer = 'X';
}

Conclusion

That's it! With these HTML, CSS, and JavaScript code snippets, you can create a simple Tic Tac Toe game. Of course, you can customize the styles and add more features to make it more interesting or challenging. Happy coding!

HTML Tic Tac Toe Game: Simple Tutorial with Code Examples

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

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