Tic Tac Toe is a very famous and challenging game. If you are learning JavaScript and want to build project to understand the basic concepts of JavaScript then this is the best project for you. In this blog post I have shared source code for the Tic Tac Toe Game using HTML, CSS and JavaScript and also tell about the steps to play this game.

Prerequisites

Before we start, make sure you have a basic understanding of

  • HTML
  • CSS
  • JavaScript

How To Play Tic Tac Toe Game

Game Setup: This game is a two player game usually denoted as Player 1 (X) and Player 2 (O). Tic Tac Toe is played on a 3×3 grid and players take turns placing their symbols on the empty cells of the grid.

Gameplay Rules: The game starts with an empty grid. Player 1 (X) goes first, placing their symbol in any empty cell. Player 2 (O) then takes their turn, placing their symbol in any remaining empty cell.

Players continue taking turns until one of the following conditions is met:

A player gets three of their symbols in a row horizontally, vertically, or diagonally.
The entire grid is filled with symbols, resulting in a tie/draw.

Winning Conditions:

  • Horizontal Line: If a player gets three of their symbols in a horizontal line (across any row), they win.
  • Vertical Line: If a player gets three of their symbols in a vertical line (down any column), they win.
  • Diagonal Line: If a player gets three of their symbols in a diagonal line (from one corner to the opposite corner), they win.
tic tac toe game winning conditiond
tic tac toe game winning conditiond

End of Game: The game ends when one player achieves a winning combination. The entire grid is filled with symbols, resulting in a tie/draw.

Restarting the Game: After the game ends (either due to a win or a tie), players have the option to restart the game and play again.

Step To Create Tic Tac Toe Game

Basic Structure of the Game- First of all Open your Code Editor such as Visual Code Studio and create a index.html file to create the basic structure.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Tic-Tac-Toe Game</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="msg-container hide">
      <p id="msg">Winner</p>
      <button id="new-btn">New Game</button>
    </div>
    <main>
      <h1 class="heading">Tic Tac Toe</h1>
      <div class="container">
        <div class="game">
          <button class="box"></button>
          <button class="box"></button>
          <button class="box"></button>
          <button class="box"></button>
          <button class="box"></button>
          <button class="box"></button>
          <button class="box"></button>
          <button class="box"></button>
          <button class="box"></button>
        </div>
      </div>
      <button id="reset-btn">Reset Game</button>
    </main>
    <script src="app.js"></script>
  </body>
</html>

Styling Your Game: Create a CSS File to add style to make our game look good.

* {
  margin: 0;
  padding: 0;
}

body {
  background-color: #4b4870;
  text-align: center;
}

.heading {
  padding-top: 30px;
  color: #ffffff;
}

.container {
  height: 70vh;
  display: flex;

  justify-content: center;
  align-items: center;
}

.game {
  height: 60vmin;
  width: 60vmin;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  gap: 1.5vmin;
}

.box {
  height: 18vmin;
  width: 18vmin;
  border-radius: 1rem;
  border: none;
  box-shadow: 0 0 1rem rgba(0, 0, 0, 0.3);
  font-size: 8vmin;
  color: #000;
  background-color: #f0f0f0;
}

#reset-btn {
  padding: 1rem;
  font-size: 1.25rem;
  background-color: #f7931e;
  color: #fff;
  border-radius: 1rem;
  border: none;
  margin-bottom: 30px;
}

#new-btn {
  padding: 1rem;
  font-size: 1.25rem;
  background-color: #f7931e;
  color: #fff;
  border-radius: 1rem;
  border: none;
}

#msg {
  color: #fff;
  font-size: 5vmin;
}

.msg-container {
  height: 100vmin;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  gap: 4rem;
}

.hide {
  display: none;
}

Implementing the Game Logic- Now Create a app.js file to provide functionality to our game using JavaScript.

let boxes = document.querySelectorAll(".box");
let resetBtn = document.querySelector("#reset-btn");
let newGameBtn = document.querySelector("#new-btn");
let msgContainer = document.querySelector(".msg-container");
let msg = document.querySelector("#msg");

let turnO = true; //playerX, playerO
let count = 0; //To Track Draw

const winPatterns = [
  [0, 1, 2],
  [0, 3, 6],
  [0, 4, 8],
  [1, 4, 7],
  [2, 5, 8],
  [2, 4, 6],
  [3, 4, 5],
  [6, 7, 8],
];

const resetGame = () => {
  turnO = true;
  count = 0;
  enableBoxes();
  msgContainer.classList.add("hide");
};

boxes.forEach((box) => {
  box.addEventListener("click", () => {
    if (turnO) {
      //playerO
      box.innerText = "O";
      turnO = false;
    } else {
      //playerX
      box.innerText = "X";
      turnO = true;
    }
    box.disabled = true;
    count++;

    let isWinner = checkWinner();

    if (count === 9 && !isWinner) {
      gameDraw();
    }
  });
});

const gameDraw = () => {
  msg.innerText = `Game was a Draw.`;
  msgContainer.classList.remove("hide");
  disableBoxes();
};

const disableBoxes = () => {
  for (let box of boxes) {
    box.disabled = true;
  }
};

const enableBoxes = () => {
  for (let box of boxes) {
    box.disabled = false;
    box.innerText = "";
  }
};

const showWinner = (winner) => {
  msg.innerText = `Congratulations, Winner is ${winner}`;
  msgContainer.classList.remove("hide");
  disableBoxes();
};

const checkWinner = () => {
  for (let pattern of winPatterns) {
    let pos1Val = boxes[pattern[0]].innerText;
    let pos2Val = boxes[pattern[1]].innerText;
    let pos3Val = boxes[pattern[2]].innerText;

    if (pos1Val != "" && pos2Val != "" && pos3Val != "") {
      if (pos1Val === pos2Val && pos2Val === pos3Val) {
        showWinner(pos1Val);
        return true;
      }
    }
  }
};

newGameBtn.addEventListener("click", resetGame);
resetBtn.addEventListener("click", resetGame);

This JavaScript code handles the game logic for Tic Tac Toe. It checks for a winner after each move, allows players to take turns, and resets the game when the reset button is clicked.

Conclusion:

In this article we’ve built a simple Tic Tac Toe game using HTML, CSS, and JavaScript. This project is a great way for beginners to practice their coding skills and understand basic concept of JavaScript.

Categorized in: