Tic Tac Toe Game

This is a simple Tic Tac Toe game that you can play with a friend.

Instructions

  1. Choose who will be Player 1 and who will be Player 2.
  2. Player 1 starts by clicking on an empty square on the board.
  3. Player 2 then clicks on an empty square on the board.
  4. Players alternate turns until one player gets three in a row (horizontally, vertically, or diagonally) or all squares are filled.
  5. If a player gets three in a row, they win!
  6. If all squares are filled and no one has three in a row, the game ends in a tie.

The Board

Below is the game board. Click on an empty square to make your move.

<table>
  <tr>
    <td class='square'></td>
    <td class='square'></td>
    <td class='square'></td>
  </tr>
  <tr>
    <td class='square'></td>
    <td class='square'></td>
    <td class='square'></td>
  </tr>
  <tr>
    <td class='square'></td>
    <td class='square'></td>
    <td class='square'></td>
  </tr>
</table>

Styling

Here is the CSS code to style the game board and squares:

table {
  border-collapse: collapse;
  margin: 0 auto;
}

td.square {
  border: 1px solid black;
  width: 100px;
  height: 100px;
  text-align: center;
  vertical-align: middle;
  font-size: 50px;
  cursor: pointer;
}

td.square:hover {
  background-color: #eee;
}

td.square:active {
  background-color: #ddd;
}

JavaScript

And finally, here is the JavaScript code to handle the game logic:

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

function handleClick(event) {
  const square = event.target;
  if (square.innerHTML !== '') {
    return;
  }
  if (currentPlayer === 1) {
    square.innerHTML = 'X';
    currentPlayer = 2;
  } else {
    square.innerHTML = 'O';
    currentPlayer = 1;
  }
  checkForWin();
}

function checkForWin() {
  const winningCombos = [
    [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 < winningCombos.length; i++) {
    const combo = winningCombos[i];
    const a = squares[combo[0]].innerHTML;
    const b = squares[combo[1]].innerHTML;
    const c = squares[combo[2]].innerHTML;
    if (a === b && b === c && a !== '') {
      alert('Player ' + currentPlayer + ' wins!');
      resetBoard();
      return;
    }
  }
  if (isBoardFull()) {
    alert('Tie game!');
    resetBoard();
    return;
  }
}

function isBoardFull() {
  for (let i = 0; i < squares.length; i++) {
    if (squares[i].innerHTML === '') {
      return false;
    }
  }
  return true;
}

function resetBoard() {
  for (let i = 0; i < squares.length; i++) {
    squares[i].innerHTML = '';
  }
  currentPlayer = 1;
}

for (let i = 0; i < squares.length; i++) {
  squares[i].addEventListener('click', handleClick);
}

Have fun playing!

Tic Tac Toe Game - Play Online for Free

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

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