Untitled

 avatar
unknown
plain_text
2 years ago
2.4 kB
1
Indexable
<!DOCTYPE html>
<html>
  <head>
    <title>Tic Tac Toe</title>
    <style>
      table {
        border-collapse: collapse;
      }

      td {
        border: 1px solid black;
        width: 100px;
        height: 100px;
        text-align: center;
        vertical-align: middle;
        font-size: 3em;
      }

      td:hover {
        background-color: #e6e6e6;
      }

      .winner {
        background-color: #00ff00;
      }

      .tie {
        background-color: #ffff00;
      }
    </style>
  </head>
  <body>
    <h1>Tic Tac Toe</h1>
    <table id="board">
      <tr>
        <td id="0"></td>
        <td id="1"></td>
        <td id="2"></td>
      </tr>
      <tr>
        <td id="3"></td>
        <td id="4"></td>
        <td id="5"></td>
      </tr>
      <tr>
        <td id="6"></td>
        <td id="7"></td>
        <td id="8"></td>
      </tr>
    </table>
    <script>
      // Initialize the game board with null values
      let board = [null, null, null, null, null, null, null, null, null];

      // Initialize the current player
      let currentPlayer = "X";

      // Get references to the game board and all cells
      const gameBoard = document.getElementById("board");
      const cells = document.getElementsByTagName("td");

      // Render the game board
      function render() {
        for (let i = 0; i < 9; i++) {
          cells[i].textContent = board[i] || "";
        }
      }

      // Handle player turns
      function handleTurn(cell, index) {
        if (board[index] === null) {
          board[index] = currentPlayer;
          cell.textContent = currentPlayer;
          cell.style.backgroundColor = "#ddd";
          currentPlayer = currentPlayer === "X" ? "O" : "X";
        }
        checkForWinner();
      }

      // Check for a winner
      function checkForWinner() {
        const winningCombinations = [
          // Rows
          [0, 1, 2],
          [3, 4, 5],
          [6, 7, 8],
          // Columns
          [0, 3, 6],
          [1, 4, 7],
          [2, 5, 8],
          // Diagonals
          [0, 4, 8],
          [2, 4, 6],
        ];

        for (let i = 0; i < winningCombinations.length; i++) {
          const [a, b, c] = winningCombinations[i];
          if (board[a] &&