Tic Tac Toe Game in JavaScript


Tic-Tac-Toe JavaScript game is a simple example of games you can program in JavaScript. Game making is the most popular branch of programming. It is also an amazing way to learn the basics of a programming language while creating a simple and interesting project. In this article we will guide you, step by step, to make a simple Tic-Tac-Toe game using JavaScript, HTML and CSS.

Tic Tac Toe is a popular two-player game that can be implemented using JavaScript. The game is played on a 3x3 grid, and the goal is to place three of your symbols (either "X" or "O") in a row, either horizontally, vertically, or diagonally.

The JavaScript code for a Tic Tac Toe game usually includes the following elements:

  • A game board represented as a two-dimensional array
  • Variables to keep track of the current player (X or O)
  • Event listeners to detect when a player clicks on a square on the game board
  • Functions to check for a win or a draw
  • A game loop to handle the flow of the game

The game board can be represented using a two-dimensional array, with each element representing a square on the board. The elements of the array can be updated when a player clicks on a square, either with an "X" or an "O".

Event listeners can be used to detect when a player clicks on a square. These listeners can call a function that updates the game board and checks for a win or a draw.

A game loop can be used to handle the flow of the game. This loop can be implemented using a function that is called after each player's turn. The function can check the game board for a win or a draw and handle the game's end state.

Additionally, the game can be designed to have a UI that is interactive and visually appealing, with the use of HTML, CSS and JavaScript. And also have some functionalities like resetting the game, displaying the winner and also keeping the score of the players.

Source Code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="css/style.css">
</head>
<body>
  <div class="container">
    <div data-index="0" class="box"></div>
    <div data-index="1" class="box"></div>
    <div data-index="2" class="box"></div>
    <div data-index="3" class="box"></div>
    <div data-index="4" class="box"></div>
    <div data-index="5" class="box"></div>
    <div data-index="6" class="box"></div>
    <div data-index="7" class="box"></div>
    <div data-index="8" class="box"></div>
  </div>
  <div id="status">Play Now</div>
  <button id="restart">Restart</button>

  <script src="js/script.js"></script>
</body>
</html>

css/style.css

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

*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}

body{
  width: 100vw;
  height: 100vh;
  background-color: #2f3542;
  color:white;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.container{
  display: grid;
  grid-template-columns: repeat(3,auto);
}

.box{
  width: 100px;
  height: 100px;
  border: 2px solid #eccc68;
  box-shadow: 0 0 0 2px #eccc68;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  
  font-size: 25px;
}

#status{
  padding: 20px;
  font-size: 25px;
  font-weight: 500;
}

button{
  width: 150px;
  height: 40px;
  font-size: 18px;
  color:white;
  background-color: #ff4757;
  border: none;
  border-radius: 3px;
}

.win{
    animation: winAnimation ease-in-out 1s infinite;
}

@keyframes winAnimation {
  0%{background-color: #2c3a47;}
  100%{background-color: #130f40;}
  
}

This code is a JavaScript implementation of the Tic Tac Toe game. The game board is represented by a collection of HTML elements with the class "box", which are used to display the X and O moves. The game status is displayed in an HTML element with the id "status", and a "Restart" button with the id "restart" is used to restart the game.

The game logic is defined in several functions, including "init()" which initializes the game by adding event listeners to the boxes and the restart button, and sets the initial game state. When a box is clicked, the "boxClick()" function is called, which updates the box with the current player's move and checks if there is a winner. The "changePlayer()" function switches the current player between X and O, and updates the status text to indicate whose turn it is.

The "checkWinner()" function checks the current game state against a predefined array of winning combinations, and determines if there is a winner or if the game is a draw. If a winner is found, the function adds the "win" class to the boxes that make up the winning combination and updates the status text. The "restartGame()" function resets the game board, options and game status to the initial state.

js/script.js

const boxs=document.querySelectorAll('.box');
const statusTxt=document.querySelector('#status');
const btnRestart=document.querySelector('#restart');
let x="<img src='images/x.png'>";
let o="<img src='images/o.png'>";

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

let options=["","","","","","","","",""];
let currentPlayer=x;
let player="X";
let running=false;
init();

function init(){
  boxs.forEach(box=>box.addEventListener('click',boxClick));
  btnRestart.addEventListener('click',restartGame);
  statusTxt.textContent=`${player} Your Turn`;
  running=true;
}

function boxClick(){
  const index=this.dataset.index;
  if(options[index]!="" || !running){
    return;
  }
  updateBox(this,index);
  checkWinner();
}

function updateBox(box,index){
  options[index]=player;
  box.innerHTML=currentPlayer;
}

function changePlayer(){
    player=(player=='X') ? "O" :"X";
    currentPlayer=(currentPlayer==x) ? o :x;
    statusTxt.textContent=`${player} Your Turn`;
}

function checkWinner(){
  let isWon=false;
  for(let i=0;i<win.length;i++){
    const condition=win[i]; //[0,1,2]
    const box1=options[condition[0]]; //x
    const box2=options[condition[1]]; //''
    const box3=options[condition[2]]; //''
    if(box1=="" || box2=="" || box3==""){
      continue;
    }
    if(box1==box2 && box2==box3){
      isWon=true;
      boxs[condition[0]].classList.add('win');
      boxs[condition[1]].classList.add('win');
      boxs[condition[2]].classList.add('win');
    }
  }

  if(isWon){
    statusTxt.textContent=`${player} Won..`;
    running=false;
  }else if(!options.includes("")){
    statusTxt.textContent=`Game Draw..!`;
    running=false;
  }else{
    changePlayer();
  }

}

function restartGame(){
  options=["","","","","","","","",""];
  currentPlayer=x;
  player="X";
  running=true;
  statusTxt.textContent=`${player} Your Turn`;

  boxs.forEach(box=>{
      box.innerHTML="";
      box.classList.remove('win');
  });
}

Output

Tic Toc Toe

Live Preview


List of Programs


JS Practical Questions & Answers


JS Practical Project