Tic Tac Toe Game using HTML, CSS and JavaScript

tic tac toe

Introduction :

The Tic Tac Toe project is a web-based implementation of the classic two-player game, designed to be played in a browser environment. Comprising HTML, CSS, and JavaScript, this project encapsulates the essence of simplicity and interactivity. The fundamental goal is to create an engaging user interface, allowing players to take turns marking spaces on a 3×3 grid, with the objective of achieving a horizontal, vertical, or diagonal alignment of their chosen symbol (‘X’ or ‘O’). The HTML structure sets the stage, organizing the game content into meaningful sections. The inclusion of metadata and the viewport tag enhances compatibility across various devices and browsers. The game container, composed of individual cells, is implemented using div elements, each uniquely identified with a ‘data-cell-index’ attribute. This facilitates tracking the position of each cell within the overall grid.

The interaction between JavaScript functions and HTML elements seamlessly handles user actions. Clicking on a cell triggers the ‘handleCellClick’ function, updating the game state and validating the result. Player turns are managed through ‘handlePlayerChange,’ ensuring a smooth transition between ‘X’ and ‘O.’ The game’s conclusion, whether through a win or a draw, is judiciously assessed by the ‘handleResultValidation’ function, displaying relevant messages on the game status.

In essence, this Tic Tac Toe project encapsulates the synergy between HTML for structure, CSS for styling, and JavaScript for dynamic functionality. The collaborative orchestration of these technologies converges into a user-friendly and intuitive game interface, providing a digital rendition of a timeless classic. The detailed breakdown of the project components aims to foster a comprehensive understanding of the intricacies behind its design and implementation.

Explanation :

HTML Structure:

The HTML file sets the foundation for the project structure. It includes metadata for character set and viewport settings, ensuring compatibility across different devices and browsers. The primary content is organized within a <section> element, which encompasses the game’s title, a grid of cells, the game status, and a restart button. The cells are individual <div> elements, uniquely identified by a ‘data-cell-index’ attribute, enabling precise tracking of their positions within the 3×3 grid.

JavaScript Logic:

The JavaScript component is the engine that powers the game. It manages the game state, tracks the current player (‘X’ or ‘O’), and determines whether the game is still active. The script defines winning conditions in an array, specifying the combinations that lead to victory. Functions are implemented to handle player turns, validate game results, and respond to user interactions.

 

Game Flow:
  1. Initialization:

    • The game begins with ‘X’ as the starting player.
    • The initial game state is an array representing an empty grid.
    • Functions to display messages, such as the current player’s turn or the game outcome, are set up.
  2. Cell Click Handling:

    • When a player clicks on a cell, the script triggers the handleCellClick function.
    • This function updates the game state and displays the player’s symbol in the clicked cell.
  3. Player Switching:

    • After each move, the handlePlayerChange function is called, switching the current player between ‘X’ and ‘O.’
    • The game status is updated to reflect the current player’s turn.
  4. Result Validation:

    • The handleResultValidation function is invoked after every move to check for a win or draw.
    • It iterates through the winning conditions array, comparing the symbols in the corresponding cells to determine if a player has won.
    • If a win is detected, the game status is updated to declare the winner, and the game becomes inactive.
    • If no win is found, the script checks for a draw by examining whether the grid is completely filled.
    • The appropriate message is displayed, and the game becomes inactive.
  5. Restarting the Game:

    • The ‘Restart Game’ button triggers the handleRestartGame function.
    • This function resets the game state, sets ‘X’ as the starting player, and clears the cells for a new game.
    • The game status is updated to indicate the beginning of a new match

 

In summary, this project seamlessly combines HTML for structuring the content, CSS for styling, and JavaScript for dynamic behavior. The result is an interactive and visually appealing digital version of Tic Tac Toe that captures the essence of the classic game while leveraging the capabilities of modern web technologies.

SOURCE CODE :

HTML (index.html)

				
					



    
    
    
    <title>Tic-Tac-Toe</title>
    



    <section>
        <h1 class="game--title">Tic-Tac-Toe Game</h1>
        <div class="game--container">
            <div data-cell-index="0" class="cell"></div>
            <div data-cell-index="1" class="cell"></div>
            <div data-cell-index="2" class="cell"></div>
            <div data-cell-index="3" class="cell"></div>
            <div data-cell-index="4" class="cell"></div>
            <div data-cell-index="5" class="cell"></div>
            <div data-cell-index="6" class="cell"></div>
            <div data-cell-index="7" class="cell"></div>
            <div data-cell-index="8" class="cell"></div>
        </div>
        <h2 class="game--status"></h2>
        <button class="game--restart">Restart Game</button>
    </section>
    



				
			

CSS (style.css)

				
					body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background-color: #e4e4e4;
}

section {
    text-align: center;
}

.cell {
    font-family: "Permanent Marker", cursive;
    width: 100px;
    height: 100px;
    border: 2px solid #ecd7ba;
    cursor: pointer;
    line-height: 100px;
    font-size: 60px;
}

.game--title {
    font-size: 50px;
    color: #1f1f1f;
    margin: 50px auto;
    opacity: .8;
}

.game--container {
    display: grid;
    grid-template-columns: repeat(3, auto);
    width: 306px;
    margin: 10px auto;
    background-color: #3a3c3e;
    color: #04c0b2;

}

.game--status {
    font-size: 50px;
    color: #1ed86c;
    margin: 20px auto;
}

.game--restart {
    width: 200px;
    border-radius: 5px;
    height: 50px;
    font-size: 25px;
    color: #000000;
   
}

.game--restart:hover {
    background-color: #1ed86c;
}
				
			

JavaScript (script.js)

				
					const statusDisplay = document.querySelector('.game--status');

let gameActive = true;
let currentPlayer = "X";
let gameState = ["", "", "", "", "", "", "", "", ""];

const winningMessage = () =&gt; `Player ${currentPlayer} has won!`;
const drawMessage = () =&gt; `Game ended in a draw!`;
const currentPlayerTurn = () =&gt; `It's ${currentPlayer}'s turn`;

statusDisplay.innerHTML = currentPlayerTurn();

const winningConditions = [
    [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 handleCellPlayed(clickedCell, clickedCellIndex) {
    gameState[clickedCellIndex] = currentPlayer;
    clickedCell.innerHTML = currentPlayer;
}

function handlePlayerChange() {
    currentPlayer = currentPlayer === "X" ? "O" : "X";
    statusDisplay.innerHTML = currentPlayerTurn();
}

function handleResultValidation() {
    let roundWon = false;
    for (let i = 0; i  cell.innerHTML = "");
}


document.querySelectorAll('.cell').forEach(cell =&gt; cell.addEventListener('click', handleCellClick));
document.querySelector('.game--restart').addEventListener('click', handleRestartGame);

				
			

OUTPUT :

output
More HTML CSS JS Projects
Get Huge Discounts

Find More Projects

Jungle Dash Game Using Python with source code with pygame module Introduction: Dive into the excitement of jungle adventures with our new …

Building a Tetris Game with Python with source code Introduction: Welcome to the world of Tetris, where falling blocks meet strategic maneuvers …

Super Mario Game Using Python with source code Introduction: Remember playing Super Mario as a kid? It’s that classic game where you …

library management system using python with source code using Python GUI Tkinter (Graphical User Interface) How to Run the code: Introduction:  Imagine …

Space Shooter Game Using Python with source code Overview: A space shooter game typically involves controlling a spaceship to navigate through space …

Hotel Management System Using Python with source code Introduction: Welcome to our blog post introducing a helpful tool for hotels: the Tkinter-based …

All Coding Handwritten Notes

Browse Handwritten Notes