Building a Tic-Tac-Toe Game with JavaScript Building a Tic-Tac-Toe Game with JavaScript

Tic-tac-toe, also known as noughts and crosses, is a popular game that can be played on a grid of 3x3 squares. In this article, we'll walk you through the process of building a tic-tac-toe game using JavaScript. The game will allow players to compete against each other or play against the computer.


Prerequisites:

To follow along with this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript.

Setting up the HTML structure:

Let's start by setting up the HTML structure for our tic-tac-toe game. Create a new HTML file and add the following code:


<!DOCTYPE html>
<html>
<head>
<title>Tic-Tac-Toe Game</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1>Tic-Tac-Toe</h1>
<div id="board">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
<script src="script.js"></script>
</body>
</html>

Styling the game:

Next, let's style the game using CSS. Create a new CSS file called "styles.css" and add the following code:


#board {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 10px;
width: 300px;
margin: 0 auto;
}
.cell {
width: 100%;
height: 100px;
background-color: #ddd;
display: flex;
align-items: center;
justify-content: center;
font-size: 40px;
cursor: pointer;
}

Implementing the game logic:

Now let's move on to the JavaScript part and implement the game logic. Create a new JavaScript file called "script.js" and add the following code:


const cells = document.querySelectorAll('.cell');
let currentPlayer = 'X';
cells.forEach(cell => {
cell.addEventListener('click', handleCellClick);
});
function handleCellClick() {
if (this.textContent !== '') return;
this.textContent = currentPlayer;
this.classList.add(currentPlayer);
if (checkWin()) {
alert(`${currentPlayer} wins!`);
resetGame();
return;
}
if (checkDraw()) {
alert('It\'s a draw!');
resetGame();
return;
}
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
}
function checkWin() {
const winningCombinations = [
[0, 1, 2], [3, 4, 5], [6, 7, 8], // Rows
[0, 3, 6], [1, 4, 7], [2, 5, 8], // Columns
[0, 4, 8], [2, 4, 6] // Diagonals
];
for (let combination of winningCombinations) {
if (
cells[combination[0]].textContent === currentPlayer &&
cells[combination[1]].textContent === currentPlayer &&
cells[combination[2]].textContent === currentPlayer
) {
return true;
}
}
return false;
}
function check
Draw() {
return Array.from(cells).every(cell => cell.textContent !== '');
}
function resetGame() {
cells.forEach(cell => {
cell.textContent = '';
cell.classList.remove('X', 'O');
});
currentPlayer = 'X';
}

Explanation of the code:

  • We start by selecting all the cells using `document.querySelectorAll('.cell')` and attaching a click event listener to each cell.
  • In the `handleCellClick` function, we check if the clicked cell is already filled. If so, we return early and do nothing.
  • If the cell is empty, we mark it with the current player's symbol ('X' or 'O') and add the corresponding CSS class.
  • After each move, we check if the current player has won by calling the `checkWin` function. If so, we display an alert with the winner and reset the game.
  • If there is no winner and the board is full (i.e., all cells are filled), we call the `checkDraw` function to determine if it's a draw. If it is, we display an alert and reset the game.
  • The `resetGame` function is responsible for clearing the board and resetting the current player to 'X'.

Congratulations! You have successfully built a tic-tac-toe game using JavaScript. Players can now enjoy competing against each other or playing against the computer. You can further enhance the game by adding features such as player names, score tracking, or implementing an AI opponent.

Remember to customize the styling and add your personal touch to make the game visually appealing. Have fun playing and exploring the world of JavaScript game development!

Published on May 21, 2023

Tags: game development | JavaScript

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.