Tic Tac Toe Game using HTML, CSS and JavaScript With Source Code
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:
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.
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.
- When a player clicks on a cell, the script triggers the
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.
- After each move, the
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.
- The
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
- The ‘Restart Game’ button triggers the
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)
Tic-Tac-Toe
Tic-Tac-Toe Game
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 = () => `Player ${currentPlayer} has won!`;
const drawMessage = () => `Game ended in a draw!`;
const currentPlayerTurn = () => `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 => cell.addEventListener('click', handleCellClick));
document.querySelector('.game--restart').addEventListener('click', handleRestartGame);
Output :
Find More Projects
Build a Quiz Game Using HTML CSS and JavaScript Introduction Hello coders, you might have played various games, but were you aware …
Emoji Catcher Game Using HTML CSS and JavaScript Introduction Hello Coders, Welcome to another new blog. In this article we’ve made a …
Typing Challenge Using HTML CSS and JavaScript Introduction Hello friends, all you developer friends are welcome to our new project. If you …
Breakout Game Using HTML CSS and JavaScript With Source Code Introduction Hello friends, welcome to today’s new blog post. All of you …
Digital and Analog Clock using HTML CSS and JavaScript Introduction : This project is a digital clock and stopwatch system, which allows …
Coffee Shop Website using HTML, CSS & JavaScript Introduction : This project is a website for coffee house business. It uses HTML …