How to create a tic tac toe game in JavaScript

Tic-tac-toe is a classic game played on a 3x3 grid. Two players take turns marking spaces with their respective symbols, usually X and O. The objective is to be the first to form a horizontal, vertical, or diagonal line of three of our symbols. The game is typically played until one player achieves this goal or until all spaces on the grid are filled, resulting in a draw. It’s a simple yet engaging game that people of all ages have enjoyed for generations.

HTML for the tic tac toe JavaScript game

We’ll begin by working on the HTML structure, the initial and straightforward part of our code. Here, we’ll define classes and IDs for our HTML elements. As our game comprises a board with cells, we’ll use the <div> and <button> elements to create these cells. Essentially, we’ll create basic containers that we’ll style later on. Our focus at this stage is to keep the board as simple as possible.

<!DOCTYPE html>
<html lang="en">
<head>
<title> Tic Tac Toe </title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="msg-container hide">
<p id="msg">Winner</p>
<button id="new-btn"><b></b>New Game</button>
</div>
<main>
<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"><b>Reset Game</b></button>
</main>
<script src="script.js"></script>
</body>
</html>

HTML explanation

  • Lines 10–13: We define a <div> with the class msg-container and hide. This <div> contains a <button> and a message within a <p> tag.

  • Lines 16–25: We define a <div> with the class game containing nine <button> elements that represent the grid of 3x3 cells.

  • Line 28: We define <button> having ID reset-btn that reset the game to its initial state.

JavaScript for the tic tac toe game

Now, we’ll write the JavaScript code for the tic tac toe game. This part is crucial as it adds the functionality that makes the game interactive and playable.

// Selecting DOM elements
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");
// Initializing game variables
let turnO = true; // Tracks current player (true for O, false for X)
let count = 0; // Tracks number of moves made
// Winning patterns for tic tac toe
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],
];
// Function to reset the game
const resetGame = () => {
turnO = true;
count = 0;
enableBoxes();
msgContainer.classList.add("hide");
};
// Event listeners for each box
boxes.forEach((box) => {
box.addEventListener("click", () => {
if (turnO) {
// Player O's turn
box.innerText = "O";
turnO = false;
} else {
// Player X's turn
box.innerText = "X";
turnO = true;
}
box.disabled = true;
count++;
// Check for winner after each move
let isWinner = checkWinner();
// If no winner and all boxes are filled, it's a draw
if (count === 9 && !isWinner) {
gameDraw();
}
});
});
// Function to handle a draw
const gameDraw = () => {
msg.innerText = `Game Draw.`;
msgContainer.classList.remove("hide");
disableBoxes();
};
// Function to disable all boxes
const disableBoxes = () => {
for (let box of boxes) {
box.disabled = true;
}
};
// Function to enable all boxes
const enableBoxes = () => {
for (let box of boxes) {
box.disabled = false;
box.innerText = "";
}
};
// Function to display winner message
const showWinner = (winner) => {
msg.innerText = `Congratulations, Winner is ${winner}`;
msgContainer.classList.remove("hide");
disableBoxes();
};
// Function to check for a winner
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;
}
}
}
};
// Event listeners for reset and new game buttons
newGameBtn.addEventListener("click", resetGame);
resetBtn.addEventListener("click", resetGame);

JavaScript explanation

  • Lines 13–22: We define all the winning possibilities of the 3x3 grid.

  • Lines 25–30: We reset the game to its initial state.

  • Lines 33–55: We define event listeners for each box.

  • Lines 79–84: Display the winning player.

  • Lines 87–100: We define a function to check which player is winning.

CSS for the tic tac toe game

In the upcoming section of our code, we have the opportunity to unleash our imagination and creativity. In the style sheet, we'll utilize our id, tags, and classes to customize the visual aspects of our game. This includes everything from borders and line widths to colors and text sizes. Since this part of the code is highly customizable, we can either write it from scratch according to our preferences or use our example as a reference. Feel free to adjust colors, sizes, fonts, and other elements to suit our needs.

body {
background-color: lightgrey;
text-align: center;
display: felx;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.container {
height: 70vh;
display: flex;
flex-wrap: wrap;
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;
}
#new-btn {
padding: 1rem;
font-size: 1.5rem;
background-color: #4b2227;
color: #fff;
border-radius: 1rem;
border: none;
box-shadow: 0 0 1rem rgba(0, 0, 0, 0.5);
}
.box {
height: 18vmin;
width: 18vmin;
border-radius: 1rem;
border: none;
box-shadow: 0 0 1rem rgba(0, 0, 0, 0.5);
font-size: 8vmin;
color: #656060;
background-color: #26dbd2;
}
#reset-btn {
padding: 1rem;
font-size: 1.5rem;
background-color: #6f5659;
color: #fff;
border-radius: 1rem;
border: none;
box-shadow: 0 0 1rem rgba(0, 0, 0, 0.5);
}
#msg {
color: #ffffc7;
font-size: 5vmin;
}
.msg-container {
height: 100vmin;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
gap: 4rem;
}
.hide {
display: none;
}

CSS explanation

  • Lines 1–8: We make custom styles for our body tag. Here is the breakdown of the style.

    • background-color: Sets the background color of the entire page to light grey.

    • text-align: Centers the text horizontally within the body.

    • display: felx: This should be corrected to display: flex, which enables a flexbox layout.

    • justify-content: Centers the content horizontally.

    • align-items: Centers the content vertically.

    • min-height: Specifies the minimum height of the body to be 100% of the viewport height.

  • Lines 10–16: We make custom styles for our container class. Here is the breakdown of the style.

    • height: Sets the height of the container to 70% of the viewport height.

    • display: Enables flexbox layout for the container.

    • flex-wrap: Allows content to wrap to the next line if it exceeds the container width.

    • justify-content: Centers the content horizontally within the container.

    • align-items: Centers the content vertically within the container.

  • Lines 18–26: We make custom styles for our game class. Here is the breakdown of the style.

    • height and width: Sets the dimensions of the game grid to 60% of the viewport minimum width and height.

    • display: Enables flexbox layout for the game grid.

    • flex-wrap: Allows content to wrap to the next line if it exceeds the game grid dimensions.

    • justify-content and align-items: Centers the content horizontally and vertically within the game grid.

    • gap: Specifies the gap between each grid item.

  • Similarly, we can apply styles to our buttons and message class as well.

Complete tic tac toe game

Now, let's integrate the HTML structure with the JavaScript logic to create a fully functional tic tac toe game. This combination allows us to bring the game to life by enabling player interactions and determining game outcomes based on their moves.

Conclusion

In a world filled with complex digital games and high-tech entertainment, tic tac toe stands as a timeless reminder of the joy found in simplicity. Whether played on a scrap of paper or a digital device, the allure of tic tac toe continues to captivate players young and old, proving that sometimes, the simplest games are the most enduring.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved