Tic Tac Toe Javascript is a simple but fun game that can be played on any web browser. Create your own Tic Tac Toe game using JavaScript.

Learn how to build your own version with this step-by-step tutorial!”
Play, learn, and have fun with the Tic Tac Toe JavaScript game!

Introduction to Tic Tac Toe Game

A tic tac toe game built using JavaScript

Final view of Tic tac toe built using JavaScript.

Tic Tac Toe is a classic game that has been enjoyed for generations. It is a simple yet engaging game that can be played by people of all ages.

In this tutorial, you will learn how to create your own Tic Tac Toe game using JavaScript. With step-by-step instructions, you will be able to create a fully-functional game that you can play and share with others.

So, let’s get started and bring this timeless game to life! #tictactoe #javascript #webdevelopment #tutorial

Step 1: Set up the HTML structure

Create an HTML file and add the following structure to it:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tic Tac Toe JavaScript Game</title>
	<link rel="stylesheet" href="style.css">
</head>
<body>
	<h1>Tic Tac Toe Game using</h1>
    <div id="game">
		<div id="board">
			<div class="square"></div>
			<div class="square"></div>
			<div class="square"></div>
			<div class="square"></div>
			<div class="square"></div>
			<div class="square"></div>
			<div class="square"></div>
			<div class="square"></div>
			<div class="square"></div>
		</div>
        <div id="winner-message"></div>
	</div>
    <button id="restart-button">Restart Game</button>
	<script src="script.js"></script>
</body>
</html>

In this HTML structure, we have a div with an id of “game” that contains another div with an id of “board”.

The “board” div contains nine squares, each with a class of “square”. We’ll use these squares to represent the Tic Tac Toe board.

Finally, we need to add an HTML element to display the winner message. See line number 22 in the above code.


<div id="winner-message"></div>

Step 2: Add CSS Styles to give the Game look & feel

Create a CSS file ( style.css ) and add the following styles to it:


h1 {
    text-align: center;
}

#board {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(3, 1fr);
    gap: 5px;
    width: 300px;
    height: 300px;
    margin: 0 auto;
}

.square {
    width: 100%;
    height: 100%;
    border: 1px solid #999;
    font-size: 72px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.square:hover {
    cursor: pointer;
}

#restart-button {
    display: block;
    margin: 100px auto;
    font-size: 16px;
    padding: 10px 20px;
    background-color: #ccc;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.2s ease;
}

#restart-button:hover {
    background-color: #aaa;
}

#restart-button:active {
    background-color: #999;
}

#winner-message {
    margin-top: 75px;
    font-size: 24px;
    text-align: center;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

Step 3: Create the  Tic Tac Toe game logic in JavaScript

Create a JavaScript file and add the following code to it:


const squares = document.querySelectorAll('.square');
let currentPlayer = 'X';

squares.forEach(square => {
    square.addEventListener('click', handleClick);
});

function handleClick(event) {
    const square = event.target;
    square.textContent = currentPlayer;
    currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
}

In this code, we first select all the “square” elements using document.querySelectorAll().

We then set a variable currentPlayer to “X” to represent the current player.

We use a forEach loop to add a click event listener to each square. The event listener calls the handleClick function when a square is clicked.

The handleClick function receives the clicked square as an event parameter.

We set the text content of the square to the current player (“X” or “O”) using the textContent property.

We then toggle the currentPlayer variable between “X” and “O” using a ternary operator.

Step 4: Add Win/Lose Logic

We need to check if a player has won the game after every move. Add the following code to the handleClick function:


const winningCombos = [
    [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 winner = null;

function checkForWin() {
    winningCombos.forEach(combo => {
        const [a, b, c] = combo;
        if (squares[a].textContent && 
            squares[a].textContent === squares[b].textContent &&
            squares[b].textContent === squares[c].textContent) {
            winner = currentPlayer;
        }
    });
    return winner;
}

function handleGameOver() {
    const winnerMessage = document.querySelector('#winner-message');
    winnerMessage.textContent = `Congratulations! ${winner} is the winner!`;
}

function handleClick(event) {
    const square = event.target;
    if (square.textContent !== '') return;
    square.textContent = currentPlayer;
    winner = checkForWin();
    if (winner) return handleGameOver();
    currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
}

In this code, we first create an array winningCombos that contains arrays of the indexes of the squares that make up a winning combination.

We then define a function checkForWin() that loops through each winning combination and checks if the text content of the squares at those indexes match. If a match is found, we set the winner variable to the currentPlayer.

We also define a function handleGameOver() that displays a message when a winner is found.

We update the handleClick() function to first check if the clicked square is empty.

If not, the function returns and the player cannot make a move. We then call the checkForWin() function after each move and set the winner variable if a winning combination is found.

If a winner is found, we call the handleGameOver() function and return to prevent further moves.

Step 5: Add Restart Game Logic

Finally, we’ll add a button to restart the game. Note- It’s already added to HTML in Step 1 at line 24.


<button id="restart-button">Restart Game</button>

And add the following JavaScript code to your javascript tic tac toe file:


const restartButton = document.querySelector('#restart-button');
restartButton.addEventListener('click', restartGame);

function restartGame() {
    squares.forEach(square => square.textContent = '');
    winner = null;
    currentPlayer = 'X';
    document.querySelector('#winner-message').textContent = '';
}

In this code, we select the restart button using document.querySelector() .

Then add a click event listener to it, and define a restartGame() function that resets all the game variables to their initial values. Also, it clears the board by setting the text content of all squares to an empty string.

And that’s it! You now have a working Tic Tac Toe

Conclusion

In conclusion, Tic Tac Toe is a simple yet entertaining game that can be easily built using JavaScript, HTML, and CSS. It’s a great way to enhance your programming skills and a fun project to work on.

With the step-by-step tutorial provided, you can create your own version of the game and even add your own personal touch to it.

So why not give it a try? Who knows, maybe you’ll be the next developer to create a revolutionary version of the classic game.

You might want to check out our HTML help and JavaScript help or other programming help services.