Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.8 kB
2
Indexable
<!DOCTYPE html>
<html>
<head>
  <title>Tic Tac Toe</title>
  <style>
    .board {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      grid-gap: 5px;
      margin-bottom: 10px;
    }

    .cell {
      background-color: #f2f2f2;
      border: 1px solid #ccc;
      width: 100px;
      height: 100px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 48px;
      cursor: pointer;
    }

    .cell:hover {
      background-color: #e0e0e0;
    }

    #message {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    #reset-button {
      padding: 10px;
      font-size: 16px;
      cursor: pointer;
    }
  </style>
</head>
<body>
  <h1>Tic Tac Toe</h1>
  <div id="message"></div>
  <div class="board">
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
  </div>
  <button id="reset-button">Reset</button>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="script.js"></script>
  <script>
$(document).ready(function() {
  var currentPlayer = 'X';
  var gameEnded = false;

  $('.cell').click(function() {
    if ($(this).text() === '' && !gameEnded) {
      $(this).text(currentPlayer);
      $(this).addClass('selected');
      checkForWinner();
      currentPlayer = (currentPlayer === 'X') ? 'O' : 'X';
    }
  });

  $('#reset-button').click(function() {
    resetBoard();
  });

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

    for (var i = 0; i < winningCombinations.length; i++) {
      var combination = winningCombinations[i];
      var a = combination[0];
      var b = combination[1];
      var c = combination[2];

      if ($('.cell').eq(a).text() === currentPlayer && $('.cell').eq(b).text() === currentPlayer && $('.cell').eq(c).text() === currentPlayer) {
        $('#message').text('Player ' + currentPlayer + ' wins!');
        gameEnded = true;
        $('.cell').eq(a).addClass('winning-cell');
        $('.cell').eq(b).addClass('winning-cell');
        $('.cell').eq(c).addClass('winning-cell');
        break;
      }
    }

    if ($('.cell:not(.selected)').length === 0 && !gameEnded) {
      $('#message').text("It's a draw!");
      gameEnded = true;
    }
  }

  function resetBoard() {
    $('.cell').text('');
    $('.cell').removeClass('selected');
    $('.cell').removeClass('winning-cell');
    $('#message').text('');
    currentPlayer = 'X';
    gameEnded = false;
  }
});

</script>
</body>
</html>