Tic Tac Toe Game In Javascript W3schools

Tic Tac Toe Game In Javascript W3schools

6 min read Jun 18, 2024
Tic Tac Toe Game In Javascript W3schools

Tic Tac Toe Game in JavaScript: A Beginner's Guide

This article will guide you through creating a basic Tic Tac Toe game using JavaScript, following the principles of W3Schools. We will create a functional game that can be played in your web browser.

1. Setting up the HTML Structure

First, let's create the basic HTML structure for our game board. We'll use a 3x3 table for the game board.




  Tic Tac Toe
  


  

This HTML code creates a simple 3x3 table with cells. Each cell has a data-index attribute, which will be helpful for identifying and referencing each cell in our JavaScript code. We also include a basic style sheet to make the board visually appealing.

2. Implementing JavaScript Logic

Now, let's write the JavaScript code to handle the game logic:

const board = ["", "", "", "", "", "", "", "", ""]; // Initialize the board array
let currentPlayer = "X"; // Set the initial player
let gameActive = true; // Flag to indicate if the game is running

const cells = document.querySelectorAll("td"); // Select all table cells
const message = document.createElement("p"); // Create a paragraph element for messages

// Function to handle clicks on the cells
function handleClick(event) {
  const index = parseInt(event.target.dataset.index);
  if (board[index] === "" && gameActive) { // Check if cell is empty and game is active
    board[index] = currentPlayer;
    event.target.textContent = currentPlayer; // Update cell content
    checkWin(); // Check for a win condition
    switchPlayer(); // Switch to the next player
  }
}

// Function to check for win conditions
function checkWin() {
  const winConditions = [
    [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 i = 0; i < winConditions.length; i++) {
    const [a, b, c] = winConditions[i];
    if (board[a] && board[a] === board[b] && board[a] === board[c]) {
      gameActive = false;
      message.textContent = `${currentPlayer} wins!`;
      document.body.appendChild(message);
    }
  }
  // Check for draw
  if (gameActive && !board.includes("")) {
    gameActive = false;
    message.textContent = "It's a draw!";
    document.body.appendChild(message);
  }
}

// Function to switch players
function switchPlayer() {
  currentPlayer = currentPlayer === "X" ? "O" : "X";
  message.textContent = `Player ${currentPlayer}'s turn`; // Update message
}

// Add event listeners to each cell
cells.forEach(cell => {
  cell.addEventListener("click", handleClick);
});

// Initial message
message.textContent = `Player ${currentPlayer}'s turn`;
document.body.appendChild(message);

This JavaScript code handles all the game logic. It uses an array to represent the game board, a variable to track the current player, and flags to manage game state. The code also implements functions for handling cell clicks, checking for win conditions, switching players, and displaying messages.

3. Running the Game

Save the HTML and JavaScript code in separate files (e.g., index.html and script.js). Then, open the HTML file in your web browser. You should now have a fully functional Tic Tac Toe game.

4. Additional Features

You can add more features to enhance your Tic Tac Toe game, such as:

  • Reset button: Add a button to reset the game and start a new one.
  • Scorekeeping: Keep track of the number of wins for each player.
  • Difficulty levels: Implement different difficulty levels for the AI opponent.

By following this guide, you can create a simple but functional Tic Tac Toe game using JavaScript. You can build upon this foundation by adding more features and customization to your game. Remember, the key is to break down the problem into smaller, manageable tasks and use JavaScript to handle the logic and interactions.