Robert Johns | 03 Apr, 2024
Fact checked by Jim Markus

How To Build A Tic-Tac-Toe Game In JavaScript For Beginners

Want to know how to create a JavaScript Tic-Tac-Toe game? In this tutorial, I’ll walk you through this JavaScript project step-by-step. 

Whether you’re just starting your web development journey or are keen to learn JavaScript, this is a fantastic project for beginners to learn real-world JavaScript skills.

In this JavaScript tutorial, you’ll:

  • Design a User Interface for Your Tic-Tac-Toe Game.
  • Implement the Core Game Logic with JavaScript.
  • Dynamically Update the Game Board Based on Player Actions.
  • Handle Game States like Winning, Drawing, or Resetting the Game.

To make the most of this tutorial, it helps to have basic web development skills, including familiarity with HTML and CSS. 

Some previous experience with JavaScript, such as manipulating HTML DOM elements and handling events, can also be helpful. However, you don't need to be a JavaScript pro or have prior experience with Tic-Tac-Toe games.

I’ve also provided the full source code for this JavaScript project so you can follow along, experiment, and even build upon it for your own projects. 

Plus, you can follow along with me using our online JavaScript compiler, so you don't need an IDE to code this JavaScript project from scratch.

Let’s dive in and start building!

How To Build A Tic-Tac-Toe Game In JavaScript

Are you ready to step into the interactive world of JavaScript web development with a classic JavaScript project

Well, you’re in the right place because today, we're going to build a Tic-Tac-Toe game using HTML, CSS, and JavaScript. 

This project is an ideal starting point if you’re new to JavaScript or web development, as it offers a really fun and clear example of how these three core technologies blend together to create fun, interactive web applications.

At the heart of our project, we'll be using JavaScript to animate and interact with a static webpage. I always like to think of JavaScript as the brains of the operation, bringing logic and interactivity to the static structure and style of HTML and CSS. 

In this simple Tic-Tac-Toe game, JavaScript will handle the game logic, player interactions, and dynamic content changes, making our Tic-Tac-Toe board come alive with every move.

But we won't stop at functionality! We'll also ensure our game is visually appealing. That's where our CSS skills come into play, adding a touch of style and sleek design to our game board.

Take a look at the image I’ve included below to see what you’re going to be building!

Create your own interactive JavaScript Tic-Tac-Toe Game

Now, you might be wondering, "Is this going to be hard to build?" Absolutely not! 

I’ve designed this JavaScript project to be beginner-friendly, and I'll even break it down into manageable, easy-to-follow steps. 

So whether you're just starting your journey in web development or have some experience with HTML and CSS but are new to JavaScript, this project is a great way to enhance your skills.

So, let's gear up, switch on our favorite web development IDE, and get ready to create our very own Tic-Tac-Toe game. 

By the end of this tutorial, you'll not only have an entertaining game to add to your portfolio, but you’ll also have a deeper understanding of how JavaScript, HTML, and CSS work together to create dynamic web experiences. 

Let’s get started and build something fun!

Project Prerequisites

Before we jump into the nitty gritty of creating our Tic-Tac-Toe game with JavaScript, let's recap the skills you’ll need to follow along with me. 

And don't worry, you don't need to be a JavaScript wizard to get started, but having a few basics under your belt will make this journey smoother and more enjoyable.

Plus, if you're rusty in any of these areas, you can always brush up with a JavaScript course

Remember, we’re also here to help, so don’t hesitate to search hackr.io for help as you go along.

A Touch of HTML

HTML is the structural foundation of any website, akin to the framework of a house. For this project, you should be comfortable with basic HTML tags such as <div>, <button>, and the overall structure of an HTML document. 

If you've ever created a simple webpage or played around with HTML at school or on a web development course, you're good to go!

Basic CSS Skills

CSS is the tool we use to style and beautify our web pages. It's like the decor and interior design of our HTML structure. 

For this Tic-Tac-Toe game, you should know the basics of CSS, including how to style elements – think colors, fonts, and layout properties like margins and padding. 

If you've ever found yourself playing with colors or aligning content on a page, you've got enough CSS knowledge for this project.

JavaScript Fundamentals

JavaScript is the magic that makes our page interactive. It's like adding smart home features to our HTML house. 

You don't need to be a JavaScript wizard, but you should understand basics like variables, functions, arrays, and event handling. 

If terms like function, event listener, or conditional statements don't sound too alien to you, you're all set! You can always refer to a JavaScript cheat sheet if you need a quick refresher.

A Curious and Experimental Mind 

This might be the most important prerequisite. The best way to learn is by doing, making mistakes, and trying again. 

Be ready to experiment, tweak the code, and maybe even break things (and then fix them). That's how we learn and grow!

You could also consider using an AI coding assistant like GitHub Copilot to help out, but I’d recommend waiting until you’re 100% stuck, as this is where you really learn.

Step 1: Setting Up The Project

Alright! Let's get started by setting up our project. This step is all about laying the groundwork for our Tic-Tac-Toe game. 

If you want to dive straight in, I'd recommend following along with me using our online JavaScript compiler. This is pre-populated with the HTML, CSS, and JavaScript files you need to build this JavaScript project without switching on an IDE.

Alternatively, I've outlined the steps for you to create the necessary files and organize your workspace on your own computer. Just follow these, and you'll have a solid foundation for your project.

i. Create a Project Folder

First things first, let's keep things tidy. Create a new folder on your computer where you'll store all the files for this project. You can name it something like Tic-Tac-Toe-game.

ii. Initialize Your Files

Inside your project folder, you're going to create three essential files:

  • index.html: This will be the main HTML file for your project.
  • style.css: This CSS file will hold all your styling rules to make your game look snazzy.
  • script.js: Here's where the magic happens – your JavaScript code goes in this file.

You can create these files using a code editor like VSCode and Sublime Text, or even a text editor like Notepad. Just make sure to save them with the correct extensions.

iii. Link Your CSS and JavaScript Files

Once you've created these files, you need to link them together. Open your index.html file and add the following lines of code inside the <head> tag for the CSS:

<link rel="stylesheet" href="style.css">

Try It Yourself »

And right before the closing </body> tag, add this line for the JavaScript:

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

Try It Yourself »

These lines tell your HTML file where to find the CSS and JavaScript files and incorporate them into your webpage.

iv. Open Your Project in a Browser

Now, let's see what we've got. Open your index.html file in a web browser. 

You won't see much yet – a blank page – but that's about to change. If the page opens without any errors, you're all set!

v. Ready Your Tools

As you work through the next steps, keep your code editor and web browser open side by side. This will allow you to make changes to your code and immediately see the results in the browser.

And there you have it! You've successfully set up your project, and you're ready to dive into the exciting part. 

Let's move on to Step 2, where we'll start crafting the HTML structure.

Step 2: Crafting The Game Board With HTML

Now that our project is set up, it's time to create the heart of our Tic-Tac-Toe game - the game board. 

In this step, we'll focus on writing the HTML necessary to display a 3x3 grid where the game will take place. Let's jump right into the details.

i. Start with Basic HTML Structure

Open your index.html file. We'll begin by ensuring the basic structure of an HTML document is in place. If you're new to this or need a refresher, here's how it should look:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Tic-Tac-Toe Game</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <!-- Game board will be added here -->
  <script src="script.js"></script>
</body>
</html>

Try It Yourself »

This is the basic structure every HTML project and page starts with, including the DOCTYPE declaration, HTML tag, head section (with meta tags, title, and CSS link), and the body for our content.

ii. Adding the Tic-Tac-Toe Grid

Within the <body> tag, we'll create the grid for our Tic-Tac-Toe game. The grid will be a simple 3x3 structure, and we'll use div elements for this. Here’s how you can do it:

<div id="tic-tac-toe-board">
  <div class="row">
      <div class="cell" id="cell-1"></div>
      <div class="cell" id="cell-2"></div>
      <div class="cell" id="cell-3"></div>
  </div>
  <div class="row">
      <div class="cell" id="cell-4"></div>
      <div class="cell" id="cell-5"></div>
      <div class="cell" id="cell-6"></div>
  </div>
  <div class="row">
      <div class="cell" id="cell-7"></div>
      <div class="cell" id="cell-8"></div>
      <div class="cell" id="cell-9"></div>
  </div>
</div>

Try It Yourself »

In this structure:

  • We have a main container div with the ID Tic-Tac-Toe-board.
  • Inside it, we created three div elements with the class row, each representing a row of the grid.
  • Each row contains three div elements with the class cell, representing individual cells of the Tic-Tac-Toe grid. 
  • We also assign unique IDs to each cell for later manipulation with JavaScript.

iii. Checking Your Work

After saving your changes, refresh your web page. You won’t see the grid yet as we haven’t applied any styles, but you're ensuring that there are no errors so far. 

A clean, error-free page load is a good sign!

iv. Understanding the HTML Structure

  • The <div> elements are versatile and are used here to create the structure of our game board.
  • Each cell in the grid is represented by a div with a class cell, allowing us to target these cells easily with CSS and JavaScript.

v. Tips on HTML Best Practices

While focusing on the game's functionality, remember that clean, well-structured HTML is crucial for maintainability and future enhancements. 

Commenting your HTML can also be very helpful, especially in larger projects or when working in teams.

And there you have it! You've successfully created the basic HTML structure for your Tic-Tac-Toe game board. 

This setup might seem simple now, but it's the foundation upon which we will build the interactive elements of our game. 

Great work getting this far – let’s keep the momentum going as we move on to Step 3, where we'll add style and life to our game board!

Step 3: Styling The Game Board With CSS

With our HTML game board in place, it’s time to add some pizzazz to it with CSS. 

This step will transform our basic 3x3 grid into a visually appealing Tic-Tac-Toe board. Let's roll up our sleeves and bring some style to the game!

i. Begin with Basic Styles

Open your style.css file. We'll start by setting some foundational styles to ensure our game board looks great on any device:

body {
  font-family: 'Arial', sans-serif;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
  background: linear-gradient(to right, #74ebd5, #ACB6E5);
  color: #333;
}

#tic-tac-toe-board {
  display: grid;
  grid-template-columns: repeat(3, 100px);
  grid-template-rows: repeat(3, 100px);
  gap: 10px;
}

Try It Yourself »

In this setup, we’re:

  • Setting a universal font for a consistent look.
  • Using Flexbox to center the game board vertically and horizontally.
  • Applying a full viewport height for the body for a full-screen appearance.
  • Adding a gradient background for a modern, appealing look.
  • Defining the layout of the game board using CSS Grid.

ii. Style the Tic-Tac-Toe Grid

Next, let's style the grid cells to make them distinct and interactive:

.cell {
  background-color: #fff;
  border: 2px solid #333;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 2rem;
  cursor: pointer;
  transition: background-color 0.3s ease;
  width: 100px;
  height: 100px;
}

.cell:hover {
  background-color: #e3e3e3;
}

Try It Yourself »

Here, we’re:

  • Giving each cell a solid border and background color.
  • Using Flexbox again to center content within each cell.
  • Increasing the font size for visibility.
  • Changing the cursor to a pointer to indicate interactivity.
  • Adding a hover effect for a responsive feel.

iii. Save and Refresh

After adding these styles, save your style.css file. Then, refresh the page in your browser where you have index.html open. You should now see a well-defined, interactive game board.

iv. Experiment with Styles

Feel free to tweak the styles to match your preferences or the theme of your website. Play around with colors, borders, hover effects, and more. 

CSS offers a wide array of properties to experiment with, enhancing both the look and user experience of your game.

v. Responsive Design Consideration

To ensure your game looks good on all devices, consider adding responsive design elements. This can be achieved with media queries in CSS, which allow you to apply different styles based on the device's screen size. Here’s an example:

@media (max-width: 600px) {
  .cell {
      width: 60px;
      height: 60px;
  }

  #tic-tac-toe-board {
      grid-template-columns: repeat(3, 60px);
      grid-template-rows: repeat(3, 60px);
  }
}

Try It Yourself »

This media query adjusts the size of the cells and the grid on screens smaller than 600 pixels wide, making the game more accessible and enjoyable on mobile devices.

And there you have it! You've successfully added style to your Tic-Tac-Toe game, making it not just functional but also aesthetically pleasing. 

Great work on completing this step. Next, we'll move on to the exciting part of our web development project – adding JavaScript to bring our game to life with interactive functionalities. Stay tuned!

Step 4: JavaScript - Laying Out The Game Logic

As we venture into the heart of our Tic-Tac-Toe game, it's time to focus on the JavaScript that will breathe life into our interactive board. 

In this step, we're going to establish the game's logic, handle player turns, define winning conditions, and set up a way to reset the game when it's over. 

Let's dive into coding our game's brain!

i. Initializing the Game State

Open your script.js file. First, we need to initialize some variables to keep track of the game state. 

This includes the current player, the game board state, and whether the game has been won or is still ongoing.

let currentPlayer = 'X'; // Player X always starts
let gameBoard = ['', '', '', '', '', '', '', '', '']; // 3x3 game board
let gameActive = true;

Try It Yourself »

These lines of code set up the basic variables. currentPlayer will alternate between 'X' and 'O', gameBoard is an array representing our 3x3 grid, and gameActive indicates if the game is ongoing.

ii. Handling Player Turns

Now, let's write a function to handle player turns. This function will update the game board and then switch to the other player.

function handlePlayerTurn(clickedCellIndex) {
  if (gameBoard[clickedCellIndex] !== '' || !gameActive) {
      return;
  }
  gameBoard[clickedCellIndex] = currentPlayer;
  currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
}

Try It Yourself »

This function checks if the clicked cell is empty and the game is active. If so, it sets the cell to the current player's symbol and switches players.

In the next step, we will integrate this logic with our HTML and CSS to make the game fully playable in a web browser.

Step 5: JavaScript - Managing Player Interactions

In this step, we will take our Tic-Tac-Toe game to the next level by implementing player interactions. 

We'll add event listeners to the game board, allowing players to click on cells to make their moves. 

Additionally, we'll update the game state and UI in response to these actions. Let's start making our game board responsive to player inputs!

i. Adding Event Listeners to the Cells

Inside your script.js file, let's add event listeners to each cell in the game board. First, we need to select all the cell elements.

const cells = document.querySelectorAll('.cell');

Try It Yourself »

Now, we'll add an event listener to each cell. This listener will call a function when a cell is clicked.

cells.forEach(cell => {
  cell.addEventListener('click', cellClicked, false);
});

Try It Yourself »

We’ll then create a cellClicked function to handle the logic when a cell is clicked. It will check the cell index, update the game state, and refresh the UI.

ii. Handling Cell Clicks

Let's define the cellClicked function. This function will be triggered whenever a player clicks on a cell.

function cellClicked(clickedCellEvent) {
  const clickedCell = clickedCellEvent.target;
  const clickedCellIndex = parseInt(clickedCell.id.replace('cell-', '')) - 1;
 
  if (gameBoard[clickedCellIndex] !== '' || !gameActive) {
      return;
  }


  handlePlayerTurn(clickedCellIndex);
  updateUI();
}

Try It Yourself »

In this function, we:

  • Get the clicked cell and its index.
  • Check if the cell is already taken or if the game is inactive.
  • If not, we call handlePlayerTurn to update the game state and updateUI to reflect these changes on the board.

iii. Updating the User Interface

After each turn, we need to update the game board to show the players' moves. Let's write the updateUI function.

function updateUI() {
  for (let i = 0; i < cells.length; i++) {
      cells[i].innerText = gameBoard[i];
  }
}

Try It Yourself »

This function updates each cell with the corresponding value in the gameBoard array, effectively displaying the Xs and Os on the board.

iv. Testing Player Interactions

Now, it's time to test your game. Open your game in a web browser and click on different cells. Check if the game state updates correctly and the UI reflects the players' moves. 

Also, verify that the game doesn't allow overwriting a cell that's already taken.

v. Troubleshooting

If the clicks don't seem to affect the game, here are a few things to check:

  • Ensure that your event listeners are correctly set up.
  • Verify that the handlePlayerTurn and updateUI functions are working as expected.
  • Check the console for any JavaScript errors.

Congratulations! You have now implemented interactive gameplay in your Tic-Tac-Toe game. Players can click on cells to make their moves, and the game state updates in real-time. 

In the upcoming steps, we'll add finishing touches, such as declaring a winner and allowing for game resets.

Step 6: Implementing The Win Logic In JavaScript

Now that our Tic-Tac-Toe game is interactive, it's time to add the logic that determines the winner or detects a draw. 

In this step, we'll write the necessary code to check for win conditions after each move and display appropriate messages when a player wins, or the game ends in a draw. 

i. Defining the Win Conditions

First, let's define the possible winning combinations on the Tic-Tac-Toe board. We can represent these as an array of arrays, where each inner array represents a winning line (row, column, or diagonal).

const winConditions = [
  [0, 1, 2], // Top row
  [3, 4, 5], // Middle row
  [6, 7, 8], // Bottom row
  [0, 3, 6], // Left column
  [1, 4, 7], // Middle column
  [2, 5, 8], // Right column
  [0, 4, 8], // Left-to-right diagonal
  [2, 4, 6]  // Right-to-left diagonal
];

Try It Yourself »

ii. Checking for a Win or Draw

Next, we need a function to check after each move whether the current player has won or if the game is a draw. We'll call this function after each turn in the handlePlayerTurn function.

function checkForWinOrDraw() {
  let roundWon = false;

  for (let i = 0; i < winConditions.length; i++) {
      const [a, b, c] = winConditions[i];
      if (gameBoard[a] && gameBoard[a] === gameBoard[b] && gameBoard[a] === gameBoard[c]) {
          roundWon = true;
          break;
      }
  }

  if (roundWon) {
      announceWinner(currentPlayer);
      gameActive = false;
      return;
  }

  let roundDraw = !gameBoard.includes('');
  if (roundDraw) {
      announceDraw();
      gameActive = false;
      return;
  }
}

Try It Yourself »

In this function, we:

  • Check each winning condition to see if the current player has a winning combination.
  • Declare a winner if a winning combination is found.
  • Check for a draw if no spaces are left and no winner is declared.

iii. Announcing the Winner and Handling Draws

Now, let's write functions to display messages when a player wins, or the game ends in a draw.

Before we do that, let’s add a new div to our HTML, and this is where we’ll display game messages.

<div id="gameMessage" class="game-message"></div>

Try It Yourself »

Let’s also add some styling to our CSS file.

.game-message {
  text-align: center;
  margin-top: 20px;
  font-size: 20px;
  color: #333;
}

Try It Yourself »

Great, now, let’s tackle those JavaScript functions.

function announceWinner(player) {
  const messageElement = document.getElementById('gameMessage');
  messageElement.innerText = `Player ${player} Wins!`;
}

function announceDraw() {
  const messageElement = document.getElementById('gameMessage');
  messageElement.innerText = 'Game Draw!';
}

Try It Yourself »

These functions will update the UI to inform players of the game's outcome.

iv. Testing the Win and Draw Logic

After implementing this logic, test your game thoroughly:

  • Play the game and create scenarios where each player wins.
  • Fill the board without a winning combination to test the draw condition.
  • Ensure that the game correctly identifies and announces the winner or a draw.

v. Troubleshooting

If the win or draw logic doesn't work as expected, here are a few things to check:

  • Make sure that the winConditions array correctly represents all possible winning combinations.
  • Verify that the checkForWinOrDraw function is being called after each player's turn.
  • Check that the announceWinner and announceDraw functions properly display the results.
  • Look for any logical errors in the checkForWinOrDraw function, especially in the loops and conditionals.
  • Review your console for any JavaScript errors that might be affecting the execution of your logic.

vi. Wrapping Up

Congratulations! You've successfully implemented the win-and-draw logic in your Tic-Tac-Toe game. 

This step is crucial as it not only marks the completion of the gameplay mechanics but also ensures that the game can reach a conclusive end, whether it's a win for one of the players or a draw. 

In the next steps, we'll focus on refining the game's interface, adding a reset button, and finalizing our project. 

You're almost at the finish line of creating a fully functional Tic-Tac-Toe game in JavaScript!

Step 7: Adding Game Reset Functionality

A complete Tic-Tac-Toe game needs a way for players to start over once a game has concluded, whether by a win, a draw, or simply because the players want to play again. 

In this step, we'll create a function to reset the game, clearing the board and resetting all necessary variables. This function will enable players to start a fresh game without reloading the entire page.

i. Creating the Reset Function

Inside your script.js file, let's write a resetGame function. This function will reset the game board, the game state variables, and any game messages or indicators.

function resetGame() {
  gameBoard = ['', '', '', '', '', '', '', '', '']; // Clear the game board
  gameActive = true; // Set the game as active
  currentPlayer = 'X'; // Reset to player X
  // Clear all cells on the UI
  cells.forEach(cell => {
      cell.innerText = '';
  });
  document.getElementById('gameMessage').innerText = '';
}

Try It Yourself »

This function resets the gameBoard array to its initial state, sets gameActive to true, and sets the currentPlayer back to 'X'. 

It also clears the text content of each cell on the UI, effectively clearing the game board visually.

Finally, we also clear any game result messages to fully reset the game for a new round.

ii. Adding a Reset Button

To allow players to trigger the reset function, we need to add a reset button in our HTML and set up an event listener for it. 

In your HTML file, add a reset button:

<button id="resetButton">Reset Game</button>

Try It Yourself »

Then, in your script.js, add an event listener to this button:

const resetButton = document.getElementById('resetButton');
resetButton.addEventListener('click', resetGame, false);

Try It Yourself »

This code selects the reset button and attaches an event listener to it. When the button is clicked, the resetGame function is called.

We’ll also add some CSS styling to our CSS file for this new button:

#resetButton {
  padding: 10px 20px;
  font-size: 1rem;
  color: #fff;
  background-color: #333;
  border: none;
  cursor: pointer;
  border-radius: 5px;
  transition: background-color 0.3s ease;
}

#resetButton:hover {
  background-color: #555;
}

Try It Yourself »

iii. Testing the Reset Functionality

After implementing the reset functionality, it's important to test it:

  • Play a game to completion, and then use the reset button to start a new game.
  • Check if the game board clears and the game state resets correctly.
  • Ensure the reset function works at any point in the game, not just after it has concluded.

iv. Troubleshooting

If the reset button isn't working as expected, here are some things to check:

Ensure that the resetButton is correctly referenced in your JavaScript.

Confirm that the event listener is properly attached to the resetButton.

Verify that the resetGame function correctly resets all relevant game state variables and UI elements.

v. Final Touches

With the reset functionality in place, your Tic-Tac-Toe game is nearly complete. This step allows players to engage in multiple rounds without interruption, enhancing the user experience. 

In the next steps, we'll focus on finalizing your project with testing, and we’ll also discuss additional features you could add to further challenge yourself.

Step 8: Final Touches And Testing

We're now at the final stage of our Tic-Tac-Toe game development! This step is all about reviewing and refining our game, ensuring that everything works seamlessly, and adding any final aesthetic or functional touches. 

We'll also focus on thorough testing to ensure our game is ready for players to enjoy.

i. Reviewing the Code

Take some time to go through your JavaScript, HTML, and CSS files. Look for:

  • Consistency: Ensure that your coding style is consistent throughout. This includes variable naming, indentation, and commenting.
  • Optimization: Check if there are any parts of your code that can be optimized for better performance or readability.
  • Comments: Make sure your code is well-commented. This will not only help others understand your code but also help you if you return to your code after some time.

ii. Enhancing the User Interface

Consider the user experience and make any final adjustments to the interface. This could include:

  • Styling: Add or refine CSS styles to make your game visually appealing.
  • Responsiveness: Ensure that your game looks good on different screen sizes and devices.
  • Feedback: Provide visual or auditory feedback for player interactions, like clicks or winning moments.

iii. Adding Additional Features (Optional)

If you have extra time and want to challenge yourself, consider adding more features like:

  • Score Tracking: Keep track of how many games each player has won.
  • Player Names: Allow players to enter their names before starting the game.
  • AI opponent: Implement a simple AI for a single-player mode.

iv. Testing the Game

Thorough testing is crucial. Test the game in different browsers and devices, and ask friends or family to play it. Look for:

  • Functionality: Ensure that all parts of the game work as expected.
  • Usability: Check if the game is intuitive and easy to play.
  • Bugs: Look out for and fix any bugs or unexpected behavior.

v. Gathering Feedback and Making Adjustments

After testing, gather feedback from your testers. Pay attention to their experience and any suggestions they have. Use this feedback to make final adjustments to your game.

vi. Celebrating Your Achievement

Congratulations on reaching this milestone in your JavaScript journey! 

Take a moment to appreciate your hard work. You've successfully created a Tic-Tac-Toe game from scratch, which is a fantastic achievement!

Whether you're building this for fun, as a learning experience, or as a portfolio piece, you've developed valuable skills in programming, problem-solving, and user interface design. 

Be proud of your work, share it with others, and consider what project you'll take on next!

Next Steps & Further Learning

Congratulations on successfully building your own interactive Tic-Tac-Toe game using JavaScript! 

This is a significant achievement, but your learning journey doesn't stop here. There are many ways to further your skills in web development. Let's explore some ideas:

Learn More About JavaScript and Web Technologies

  • JavaScript Enhancements: Explore more advanced JavaScript concepts and apply them to your game. Could features like localStorage be used to remember game state?
  • Explore Frameworks: Experiment with JS frameworks like React or Vue.js to see how they can be used to build more dynamic and complex web applications.
  • Web Animations: Learn about CSS animations and JavaScript to add engaging animations to your game.

Join Online Communities and Collaborate

  • Engage in Forums: Participate in web development forums and communities. Share your Tic-Tac-Toe game, get feedback, and learn from others.
  • Contribute to Open Source: Consider making your game open source and collaborate with others to improve it.

Keep Up with Trends and Best Practices

Stay updated with the latest trends in web development and JavaScript. Subscribe to blogs like hackr.io, watch webinars, and join online courses.

Document and Share Your Learning Journey

  • Blog About Your Project: Write about your development process, challenges you faced, and how you overcame them. Share your blog with the developer community.
  • Share Your Code: Publish your code on platforms like GitHub. This not only showcases your work but also allows others to learn from your project.

Challenge Yourself Regularly

Take part in coding challenges or hackathons to sharpen your skills and learn new techniques.

And if you're hungry for more JavaScript projects, check out the rest of our step-by-step tutorials, including:

JavaScript Tic-Tac-Toe Game Full Source Code

HTML Source Code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Tic-Tac-Toe Game</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div id="tic-tac-toe-board">
      <div class="row">
          <div class="cell" id="cell-1"></div>
          <div class="cell" id="cell-2"></div>
          <div class="cell" id="cell-3"></div>
      </div>
      <div class="row">
          <div class="cell" id="cell-4"></div>
          <div class="cell" id="cell-5"></div>
          <div class="cell" id="cell-6"></div>
      </div>
      <div class="row">
          <div class="cell" id="cell-7"></div>
          <div class="cell" id="cell-8"></div>
          <div class="cell" id="cell-9"></div>
      </div>
  </div>
  <div id="gameMessage" class="game-message"></div>
  <button id="resetButton">Reset Game</button>  
  <script src="script.js"></script>
</body>
</html>

Try It Yourself »

CSS Source Code:

body {
  font-family: 'Arial', sans-serif;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
  background: linear-gradient(to right, #74ebd5, #ACB6E5);
  color: #333;
}

#tic-tac-toe-board {
  display: grid;
  grid-template-columns: repeat(3, 100px);
  grid-template-rows: repeat(3, 100px);
  gap: 10px;
}

.cell {
  background-color: #fff;
  border: 2px solid #333;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 2rem;
  cursor: pointer;
  transition: background-color 0.3s ease;
  width: 100px;
  height: 100px;
}

.cell:hover {
  background-color: #e3e3e3;
}

.game-message {
  text-align: center;
  margin-top: 20px;
  font-size: 20px;
  color: #333;
}

#resetButton {
  padding: 10px 20px;
  font-size: 1rem;
  color: #fff;
  background-color: #333;
  border: none;
  cursor: pointer;
  border-radius: 5px;
  transition: background-color 0.3s ease;
}

#resetButton:hover {
  background-color: #555;
}

Try It Yourself »

JavaScript Source Code:

let currentPlayer = 'X'; // Player X always starts
let gameBoard = ['', '', '', '', '', '', '', '', '']; // 3x3 game board
let gameActive = true;

function handlePlayerTurn(clickedCellIndex) {
  if (gameBoard[clickedCellIndex] !== '' || !gameActive) {
      return;
  }
  gameBoard[clickedCellIndex] = currentPlayer;
  checkForWinOrDraw();
  currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
}

function cellClicked(clickedCellEvent) {
  const clickedCell = clickedCellEvent.target;
  const clickedCellIndex = parseInt(clickedCell.id.replace('cell-', '')) - 1;
  if (gameBoard[clickedCellIndex] !== '' || !gameActive) {
      return;
  }
  handlePlayerTurn(clickedCellIndex);
  updateUI();
}

const cells = document.querySelectorAll('.cell');

cells.forEach(cell => {
  cell.addEventListener('click', cellClicked, false);
});

function updateUI() {
  for (let i = 0; i < cells.length; i++) {
      cells[i].innerText = gameBoard[i];
  }
}

function announceWinner(player) {
  const messageElement = document.getElementById('gameMessage');
  messageElement.innerText = `Player ${player} Wins!`;
}

function announceDraw() {
  const messageElement = document.getElementById('gameMessage');
  messageElement.innerText = 'Game Draw!';
}

const winConditions = [
  [0, 1, 2], // Top row
  [3, 4, 5], // Middle row
  [6, 7, 8], // Bottom row
  [0, 3, 6], // Left column
  [1, 4, 7], // Middle column
  [2, 5, 8], // Right column
  [0, 4, 8], // Left-to-right diagonal
  [2, 4, 6]  // Right-to-left diagonal
];

function checkForWinOrDraw() {
  let roundWon = false;

  for (let i = 0; i < winConditions.length; i++) {
      const [a, b, c] = winConditions[i];
      if (gameBoard[a] && gameBoard[a] === gameBoard[b] && gameBoard[a] === gameBoard[c]) {
          roundWon = true;
          break;
      }
  }

  if (roundWon) {
      announceWinner(currentPlayer);
      gameActive = false;
      return;
  }

  let roundDraw = !gameBoard.includes('');
  if (roundDraw) {
      announceDraw();
      gameActive = false;
      return;
  }
}

function resetGame() {
  gameBoard = ['', '', '', '', '', '', '', '', ''];
  gameActive = true;
  currentPlayer = 'X';
  cells.forEach(cell => {
      cell.innerText = '';
  });
  document.getElementById('gameMessage').innerText = '';
}

const resetButton = document.getElementById('resetButton');
resetButton.addEventListener('click', resetGame, false);

Try It Yourself »

Wrapping Up

Building a Tic-Tac-Toe game using HTML, CSS, and JavaScript is a fantastic way to enhance your web development skills and delve into creating interactive web applications. 

By developing this classic game, you've navigated various challenges, including designing a user-friendly interface, implementing game logic, and dynamically updating the webpage based on player actions and game state.

In this tutorial, you’ve learned how to:

  • Use HTML and CSS to design and style the Tic-Tac-Toe game board.
  • Write JavaScript to implement game logic, handle player turns, and determine outcomes
  • Dynamically update HTML content using JavaScript to reflects each player's move
  • Respond to user interactions by adding event listeners to game cells and a reset button.
  • Create functions to manage game state, like resetting or announcing the game outcome

You now have the foundational tools and knowledge you need to further develop and enhance this Tic-Tac-Toe game. You can add more features, such as AI opponents, score tracking, and personalization options, or even integrate it into a larger web application. 

Your journey into the world of JavaScript doesn't end here. With these new skills, you're well-equipped to experiment with more complex JavaScript projects, explore other aspects of JavaScript, and continue building fun and interactive web experiences.

And remember, you can do all this using our online JavaScript compiler, so get creative, have fun, and happy coding!

Want to sharpen up your JavaScript and web development skills? Check out:

Dr. Angela Yu's Complete Web Development Bootcamp

 

 

By Robert Johns

Technical Editor for Hackr.io | 15+ Years in Python, Java, SQL, C++, C#, JavaScript, Ruby, PHP, .NET, MATLAB, HTML & CSS, and more... 10+ Years in Networking, Cloud, APIs, Linux | 5+ Years in Data Science | 2x PhDs in Structural & Blast Engineering

View all post by the author

Subscribe to our Newsletter for Articles, News, & Jobs.

I accept the Terms and Conditions.
Thanks for subscribing! Look out for our welcome email to verify your email and get our free newsletters.

Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.

In this article

Learn More

Please login to leave comments