How to Create a Tick Tac Toe Game in JS?

Tick Tac Toe Game in JS

Tick Tac Toe, also known as Noughts and Crosses, is a classic game that has been played for generations. It’s a simple game that can be played on a piece of paper or a chalkboard, but why not take it to the next level and create your own version of the game in JS?

Introduction

Creating a tick tac toe game in JS is a great way to practice your coding skills and learn more about the language. In this article, we will guide you through the process of creating a tick tac toe game in JS from scratch, step by step.

Set up the HTML and CSS

The first step in creating a tick tac toe game in JS is to set up the HTML and CSS. Here’s how:

Create an HTML file and name it “index.html”.

Add the following code to the file:

<!DOCTYPE html>
<html>
  <head>
    <title>Tick Tac Toe Game</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <h1>Tick Tac Toe Game</h1>
    <div class="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="app.js"></script>
  </body>
</html>

Create a CSS file and name it “style.css”.

Add the following code to the file:

.board {
  display: flex;
  flex-wrap: wrap;
  width: 300px;
  height: 300px;
  margin: auto;
  border: 2px solid black;
}

.cell {
  width: 100px;
  height: 100px;
  border: 1px solid black;
}

In this code, we have created an HTML file with a title, a header, a game board with nine cells, and a script tag linking to the JavaScript file. We have also created a CSS file to style the game board and the cells.

Set up the JavaScript

Now that we have set up the HTML and CSS, it’s time to move on to the JavaScript. Here’s how to create a tick tac toe game in JS:

Create a JavaScript file and name it “app.js”.

Add the following code to the file:

let cells = document.querySelectorAll('.cell');
let currentPlayer = 'X';

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

function cellClicked(e) {
  e.target.textContent = currentPlayer;
  currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
}

In this code, we have selected all the cells on the game board and added an event listener to each cell that triggers the cellClicked function when clicked. This function adds the current player’s symbol to the cell and then switches to the other player’s turn.

Add Win Conditions

The tick tac toe game would not be complete without win conditions. Here’s how to add win conditions to your tick tac toe game in JS:

Add the following code to the app.js file after the cellClicked function:

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

function checkWin() {
  for (let i = 0; i < winningCombinations.length; i++) {
    const [a, b, c] = winningCombinations[i];
    if (cells[a].textContent === cells[b].textContent && cells[b].textContent === cells[c].textContent && cells[a].textContent !== '') {
      return true;
    }
  }
  return false;
}

In this code, we have created a constant array of winning combinations, which are the three cells in a row that would constitute a win. We have also created a checkWin function that loops through all the winning combinations and checks if the cells in those combinations have the same text content (either ‘X’ or ‘O’). If a winning combination is found, the function returns true.

Modify the cellClicked function to call the checkWin function and display a message when a win is detected:

function cellClicked(e) {
  e.target.textContent = currentPlayer;
  if (checkWin()) {
    alert(`${currentPlayer} wins!`);
    resetBoard();
  } else {
    currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
  }
}

In this modified code, the cellClicked function first adds the current player’s symbol to the cell and then checks if there is a win by calling the checkWin function. If a win is detected, the function displays an alert message with the winner’s symbol and then calls the resetBoard function (which we will define in the next step). If no win is detected, the function switches to the other player’s turn.

Add a Reset Function

To make the game more user-friendly, let’s add a reset function that clears the game board and starts a new game. Here’s how:

Add the following code to the app.js file after the checkWin function:

function resetBoard() {
  cells.forEach(cell => {
    cell.textContent = '';
  });
  currentPlayer = 'X';
}

In this code, we have created a resetBoard function that loops through all the cells on the game board and sets their text content to an empty string. We have also reset the current player to ‘X’.

Modify the cellClicked function to call the resetBoard function when the game is tied:

function cellClicked(e) {
  e.target.textContent = currentPlayer;
  if (checkWin()) {
    alert(`${currentPlayer} wins!`);
    resetBoard();
  } else if (isBoardFull()) {
    alert(`Tie game!`);
    resetBoard();
  } else {
    currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
  }
}

In this modified code, we have added an isBoardFull function that checks if all the cells on the game board have been filled. If all the cells have been filled and no win has been detected, the function displays an alert message with “Tie game!” and calls the resetBoard function.

FAQs

Q: Can I change the size of the game board?
A: Yes, you can change the size of the game board by modifying the boardSize variable in the app.js file.

Q: Can I change the symbols used in the game?
A: Yes, you can change the symbols used in the game by modifying the playerSymbols array in the app.js file.

Q: Can I change the order of the player symbols?
A: Yes, you can change the order of the player symbols by modifying the playerSymbols array in the app.js file.

Q: Can I change the styling of the game board?
A: Yes, you can change the styling of the game board by modifying the CSS code in the style.css file.

Conclusion

creating a tick tac toe game in JS is a great way to practice your programming skills and learn more about the language. By following the steps outlined in this article, you can create a functional game that you can play and share with others. Remember to experiment and make changes to the code to customize the game to your liking. Have fun and happy coding!

Follow Us on
https://www.linkedin.com/company/scribblers-den/
https://www.facebook.com/scribblersden.blogs

Read More
https://scribblersden.com/how-to-install-and-setup-react-native-on-mac/

Thank You

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *