Tic Tac Toe Game In Html Css Javascript Code

Tic Tac Toe Game In Html Css Javascript Code

6 min read Jun 20, 2024
Tic Tac Toe Game In Html Css Javascript Code

Tic Tac Toe Game in HTML, CSS, and JavaScript

This article will guide you through creating a simple yet functional Tic Tac Toe game using HTML, CSS, and JavaScript.

HTML Structure

First, let's set up the basic HTML structure for our game board:




  Tic Tac Toe
  


  

Tic Tac Toe

Explanation:

  • We create a div with class game-container to hold the game board.
  • Inside, we have nine div elements with class cell, each representing a square on the board.
  • Each cell has a data-index attribute ranging from 0 to 8 to identify its position.
  • We also have a div with class message to display game status (like "X's turn" or "Game Over").

CSS Styling

Next, let's style our game using CSS:

body {
  font-family: sans-serif;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background-color: #f0f0f0;
}

h1 {
  margin-bottom: 20px;
}

.game-container {
  display: grid;
  grid-template-columns: repeat(3, 100px);
  grid-template-rows: repeat(3, 100px);
  gap: 10px;
  border: 2px solid #333;
  padding: 10px;
}

.cell {
  background-color: #fff;
  border: 2px solid #333;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 40px;
  cursor: pointer;
}

.message {
  margin-top: 20px;
  font-size: 18px;
}

Explanation:

  • We style the body for basic layout and font.
  • The game-container is styled as a 3x3 grid with spacing.
  • Each cell has a white background, a border, and centered text.
  • The message div is styled for clarity.

JavaScript Logic

Finally, we implement the game logic with JavaScript:

const cells = document.querySelectorAll('.cell');
const message = document.querySelector('.message');
let currentPlayer = 'X';
let board = ['', '', '', '', '', '', '', '', ''];
let gameActive = true;

// Function to handle cell clicks
const handleClick = (index) => {
  if (board[index] === '' && gameActive) {
    board[index] = currentPlayer;
    cells[index].textContent = currentPlayer;
    // Check for win or draw
    if (checkWin() || checkDraw()) {
      gameActive = false;
      message.textContent = gameActive ? `${currentPlayer}'s turn` : (checkWin() ? `${currentPlayer} wins!` : "It's a draw!");
    } else {
      // Switch player turn
      currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
      message.textContent = `${currentPlayer}'s turn`;
    }
  }
};

// Add click event listener to each cell
cells.forEach((cell, index) => {
  cell.addEventListener('click', () => handleClick(index));
});

// Function to check for a winning combination
const checkWin = () => {
  const winCombinations = [
    [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 < winCombinations.length; i++) {
    const [a, b, c] = winCombinations[i];
    if (board[a] && board[a] === board[b] && board[a] === board[c]) {
      return true;
    }
  }
  return false;
};

// Function to check for a draw
const checkDraw = () => {
  return board.every(cell => cell !== '');
};

// Initialize game
message.textContent = `${currentPlayer}'s turn`;

Explanation:

  • We select all cells and the message element.
  • We initialize the currentPlayer, board, and gameActive variables.
  • The handleClick function updates the board array, displays the move on the board, checks for win or draw, and switches the player.
  • The checkWin function checks for any winning combination.
  • The checkDraw function checks if the board is full.
  • Finally, we add event listeners to cells and initialize the game.

Now you have a basic but playable Tic Tac Toe game using HTML, CSS, and JavaScript. You can expand upon this by adding features like reset button, player names, or different game modes.