Create a Tic Tac Toe Game Using HTML CSS and JavaScript

0

Hey guys today we are discussing how to create a Tic Tac Toe Game using HTML CSS and JavaScript. Tic Tac Toe is a classic and fun game that you can easily create using HTML, CSS, and JavaScript.

creating projects using HTML CSS and JavaScript, you can improve your logic and you can create a different type of project easily. So, you need to create projects. Once you have the ideas, you can use the same tactics to create another game or project.

In this tutorial, we will guide you through the process step by step, and you won’t need to write any code yourself. We’ll keep it simple and easy to understand. Let’s get started!

Create a Tic Tac Toe Game Using HTML CSS and JavaScript

Before moving the codes, I’m going to share with you the complete video tutorial that I made. Inside that, you can learn how to create a Tic Tac Toe Game using HTML CSS, and JavaScript from scratch. You should watch it, If you face any problems with the video, you can check the source codes that I mentioned below.

I hope you’ve watched the complete tutorial, hope you’ve learned something new from the tutorial, let’s look at that the source codes that used inside the project.

You May Also Like:

Prerequisites:

  1. A basic understanding of HTML, CSS, and JavaScript.
  2. A code editor, like Visual Studio Code or Sublime Text.
  3. A web browser (e.g., Chrome, Firefox) to run your game.

Step 1: Set Up Your Project
Open your code editor and create a new folder for your project. Inside the folder, create three files:

  • index.html: This file will contain the structure of your game.
  • style.css: This file will handle the styling.
  • script.js: This file will handle the game logic.

Step 2: Building the HTML Structure
Open the index.html file and add the following structure:

  • Create a container div with an ID to hold the game board.
  • Inside the container, add a 3×3 grid using div elements to represent the cells.
  • Add a message area to display game status (e.g., “Player X’s turn” or “Player O wins!”).
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="css/style.css" />
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"
    />
    <script defer src="js/script.js"></script>
    <title>Tic Tac Toe Game using HTML CSS & JS</title>
  </head>
  <body>
    <div class="container">
      <h1>Tic Tac Toe</h1>
      <div id="gameboard">
        <div class="box" id="0"></div>
        <div class="box" id="1"></div>
        <div class="box" id="2"></div>
        <div class="box" id="3"></div>
        <div class="box" id="4"></div>
        <div class="box" id="5"></div>
        <div class="box" id="6"></div>
        <div class="box" id="7"></div>
        <div class="box" id="8"></div>

        <div class="modal">
          <div class="content">
            <h2 class="message">Congtratulation Player X</h2>
            <p>You've Won the Game :)</p>
            <button id="restartbtn">Restart</button>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

Step 3: Styling with CSS
Open the style.css file and style your game board and cells. You can make it colorful and attractive. Add styles for the X and O symbols, as well as the message area to make it clear and engaging.

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&family=Ruda:wght@400;600;700&display=swap");

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

:root {
  --orangeColor: #f2c14e;
  --darkColor: #2d414b;
}

body {
  background: rgb(61, 99, 218);
  background: radial-gradient(
    circle,
    rgba(61, 99, 218, 1) 0%,
    rgba(214, 84, 207, 1) 55%,
    rgba(151, 156, 203, 1) 100%
  );
  font-family: "poppins", sans-serif;
  overflow-x: hidden;
}

.container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  flex-direction: column;
}

.container h1 {
  font-size: 3.5rem;
  color: #fff;
}

#gameboard {
  width: 650px;
  padding: 2rem 5rem;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  background-color: rgba(255, 255, 255, 0.5);
  border-radius: 5px;
  position: relative;
}

.box {
  height: 130px;
  width: 130px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--darkColor);
  background-color: var(--orangeColor);
  font-weight: 600;
  font-size: 5.5rem;
  margin: 0.5rem;
  box-shadow: 2px 5px 5px #000;
  border-radius: 5px;
}

.container.success .box {
  cursor: not-allowed;
}

.modal {
  position: absolute;
  width: 650px;
  height: 400px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 5px 10px 10px #000;
  opacity: 0;
  transform: translateX(500%);
  transition: all 0.8s ease-in;
}

.container.success .modal {
  opacity: 1;
  transform: translateX(0);
}

.content {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  height: 100%;
}

.content h2 {
  font-size: 2.5rem;
}

button {
  outline: none;
  border: none;
  padding: 0.8rem 4rem;
  margin-top: 2rem;
  border-radius: 5px;
  font-family: inherit;
  font-size: 1.2rem;
  width: 320px;
  cursor: pointer;
  background-color: var(--orangeColor);
  color: var(--darkColor);
  font-weight: 600;
}

button:active {
  transform: scale(0.98);
}

Step 4: JavaScript for Game Logic
Open the script.js file and include the JavaScript code for your Tic Tac Toe game:

  • Create variables to track the current player (X or O) and the game board.
  • Add event listeners to handle cell clicks and update the board.
  • Implement game logic to check for a win, a draw, or a game in progress.
  • Update the message area to display the game status.
  • Reset the game when it’s over.
"use strict";

const ContainerEl = document.querySelector(".container");
let playerTxt = document.querySelector(".message");
let restartBtn = document.getElementById("restartbtn");
let boxes = document.querySelectorAll(".box");

const O_TXT = "O";
const X_TXT = "X";

let currentPlayer = O_TXT;
let spaces = Array(9).fill(null);

let winnnerIdicator = getComputedStyle(document.body).getPropertyValue(
  "--darkColor",
);

// start Game
const startGame = () => {
  boxes.forEach((boxs) => boxs.addEventListener("click", boxClicked));
};

// box cliekd
function boxClicked(e) {
  const id = e.target.id;

  // check id
  if (!spaces[id]) {
    spaces[id] = currentPlayer;
    e.target.innerText = currentPlayer;

    // winner logic
    if (playerHasWon() != false) {
      playerTxt.innerHTML = ` <h2 class="message">Congtratulation Player ${currentPlayer}</h2>`;
      winnnerIdicator = playerHasWon();

      winnnerIdicator.map(
        (box) => (boxes[box].style.backgroundColor = "#f4d03f"),
      );

      ContainerEl.classList.add("success");
    }
    currentPlayer = currentPlayer == X_TXT ? O_TXT : X_TXT;
  }
}

// wining combination
const winingCombination = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],
  [0, 4, 8],
  [2, 4, 6],
];

//player win
function playerHasWon() {
  for (const condition of winingCombination) {
    let [a, b, c] = condition;

    if (spaces[a] && spaces[a] == spaces[b] && spaces[a] == spaces[c]) {
      return [a, b, c];
    }
  }
  return false;
}

// reset the game
restartBtn.addEventListener("click", restartGame);

function restartGame() {
  spaces.fill(null);

  boxes.forEach((box) => {
    box.innerHTML = "";
    box.style.backgroundColor = "";
  });

  playerTxt.innerHTML = "Tic Tac Toe";
  currentPlayer = O_TXT;
  ContainerEl.classList.remove("success");
}

startGame();


Save your files, open index.html in your web browser, and you’ll have a functional Tic Tac Toe game! Click on the cells to play, and the game will respond accordingly.

Conclusion:
Creating a Tic Tac Toe game using HTML, CSS, and JavaScript
is a fun and educational project. With the provided steps, you can build your own simple game from scratch without needing to write any code yourself. Feel free to explore and customize the game further, adding features like a restart button or a more complex AI opponent. Happy gaming!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.