Creating a Basic Tic-Tac-Toe Game
Table of Contents
- Introduction
- Setting Up the Environment
- HTML Structure
- Styling the Game with CSS
- Implementing Game Logic with JavaScript
- Enhancing the Game with Additional Features
- Optimizing the Code
- Conclusion
1. Introduction
Tic-Tac-Toe is a classic two-player game where players take turns marking a 3×3 grid with ‘X’ or ‘O’. The player who places three marks in a row, column, or diagonal wins the game. This guide walks you through creating a basic Tic-Tac-Toe game using HTML, CSS, and JavaScript.
2. Setting Up the Environment
To create the game, you need:
- A code editor (VS Code, Sublime, etc.)
- A web browser
- Basic knowledge of HTML, CSS, and JavaScript
3. HTML Structure
The following HTML code defines the structure of our Tic-Tac-Toe board:
<!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</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Tic-Tac-Toe</h1>
<div class="board" id="board">
<div class="cell" data-index="0"></div>
<div class="cell" data-index="1"></div>
<div class="cell" data-index="2"></div>
<div class="cell" data-index="3"></div>
<div class="cell" data-index="4"></div>
<div class="cell" data-index="5"></div>
<div class="cell" data-index="6"></div>
<div class="cell" data-index="7"></div>
<div class="cell" data-index="8"></div>
</div>
<p id="status"></p>
<button id="restart">Restart Game</button>
<script src="script.js"></script>
</body>
</html>
4. Styling the Game with CSS
The following CSS styles the game board and cells:
body {
text-align: center;
font-family: Arial, sans-serif;
}
.board {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-template-rows: repeat(3, 100px);
gap: 5px;
margin: 20px auto;
width: 310px;
}
.cell {
width: 100px;
height: 100px;
border: 2px solid black;
display: flex;
align-items: center;
justify-content: center;
font-size: 2em;
cursor: pointer;
}
.cell:hover {
background-color: #f0f0f0;
}
button {
padding: 10px;
font-size: 16px;
margin-top: 10px;
cursor: pointer;
}
5. Implementing Game Logic with JavaScript
The following JavaScript implements the game logic:
const board = document.getElementById("board");
const cells = document.querySelectorAll(".cell");
const status = document.getElementById("status");
const restartBtn = document.getElementById("restart");
let currentPlayer = "X";
let gameState = ["", "", "", "", "", "", "", "", ""];
let gameActive = true;
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 handleCellClick(event) {
const clickedCell = event.target;
const cellIndex = clickedCell.getAttribute("data-index");
if (gameState[cellIndex] !== "" || !gameActive) return;
gameState[cellIndex] = currentPlayer;
clickedCell.textContent = currentPlayer;
checkWinner();
currentPlayer = currentPlayer === "X" ? "O" : "X";
}
function checkWinner() {
for (let condition of winningConditions) {
const [a, b, c] = condition;
if (gameState[a] && gameState[a] === gameState[b] && gameState[a] === gameState[c]) {
status.textContent = `Player ${currentPlayer} Wins!`;
gameActive = false;
return;
}
}
if (!gameState.includes("")) {
status.textContent = "It's a Draw!";
gameActive = false;
}
}
function restartGame() {
gameState = ["", "", "", "", "", "", "", "", ""];
gameActive = true;
currentPlayer = "X";
status.textContent = "";
cells.forEach(cell => cell.textContent = "");
}
cells.forEach(cell => cell.addEventListener("click", handleCellClick));
restartBtn.addEventListener("click", restartGame);
6. Enhancing the Game with Additional Features
6.1 Adding an AI Opponent
Modify the game logic to include a simple AI that randomly picks an available cell for ‘O’.
6.2 Adding Sound Effects
Use the Audio
object in JavaScript to play sounds when a player makes a move or wins.
6.3 Keeping Score
Store and display the number of wins for each player.
7. Optimizing the Code
- Use efficient event listeners to avoid performance issues.
- Optimize the AI logic for a better challenge.
- Store game state in localStorage to persist across page reloads.
In this guide, we built a simple Tic-Tac-Toe game using HTML, CSS, and JavaScript. We covered game logic, event handling, and optimization techniques. Further enhancements like AI, sound effects, and a scoreboard can improve the user experience. Happy coding!