Sure! Below is a complete implementation of a Tic-Tac-Toe game using HTML, CSS, and JavaScript that adheres to your specifications. The game is fully responsive, includes turn logic, win/draw detection, and a "Restart Game" feature.
1. HTML Structure
Create an index.html file with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tic-Tac-Toe</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="game-container">
<h1>Tic-Tac-Toe</h1>
<div class="game-board" id="gameBoard">
<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>
<div class="message" id="message">Player X's turn</div>
<button id="restartButton">Restart Game</button>
</div>
<script src="script.js"></script>
</body>
</html>
2. CSS Styling
Create a styles.css file with the following content:
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
background-color: #f0f0f0;
font-family: Arial, Helvetica, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.game-container {
text-align: center;
}
h1 {
margin-bottom: 20px;
}
.game-board {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-template-rows: repeat(3, 100px);
gap: 5px;
margin: 0 auto 20px auto;
}
.cell {
background-color: #fff;
border: 2px solid #444;
display: flex;
justify-content: center;
align-items: center;
font-size: 2.5rem;
cursor: pointer;
transition: background-color 0.3s;
}
.cell:hover {
background-color: #e0e0e0;
}
.cell.X {
color: #ff4d4d;
}
.cell.O {
color: #4d79ff;
}
.message {
margin-bottom: 20px;
font-size: 1.2rem;
min-height: 24px;
}
button {
padding: 10px 20px;
font-size: 1rem;
cursor: pointer;
border: none;
background-color: #444;
color: #fff;
border-radius: 5px;
transition: background-color 0.3s;
}
button:hover {
background-color: #666;
}
/* Responsive Design */
@media (max-width: 600px) {
.game-board {
grid-template-columns: repeat(3, 80px);
grid-template-rows: repeat(3, 80px);
gap: 4px;
}
.cell {
font-size: 2rem;
}
button {
padding: 8px 16px;
font-size: 0.9rem;
}
}
3. JavaScript Functionality
Create a script.js file with the following content:
const gameBoard = document.getElementById('gameBoard');
const messageDisplay = document.getElementById('message');
const restartButton = document.getElementById('restartButton');
const cells = document.querySelectorAll('.cell');
let board = ['', '', '', '', '', '', '', '', ''];
let currentPlayer = 'X';
let isGameActive = true;
// Winning combinations
const winningConditions = [
[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
];
// Function to handle cell click
function handleCellClick(e) {
const cell = e.target;
const index = parseInt(cell.getAttribute('data-index'));
if (board[index] !== '' || !isGameActive) {
return;
}
board[index] = currentPlayer;
cell.textContent = currentPlayer;
cell.classList.add(currentPlayer);
checkResult();
}
// Function to check for a win or draw
function checkResult() {
let roundWon = false;
for (let condition of winningConditions) {
const [a, b, c] = condition;
if (board[a] && board[a] === board[b] && board[a] === board[c]) {
roundWon = true;
break;
}
}
if (roundWon) {
messageDisplay.textContent = `Player ${currentPlayer} wins!`;
isGameActive = false;
return;
}
if (!board.includes('')) {
messageDisplay.textContent = "It's a draw!";
isGameActive = false;
return;
}
// Switch player
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
messageDisplay.textContent = `Player ${currentPlayer}'s turn`;
}
// Function to restart the game
function restartGame() {
board = ['', '', '', '', '', '', '', '', ''];
isGameActive = true;
currentPlayer = 'X';
messageDisplay.textContent = `Player ${currentPlayer}'s turn`;
cells.forEach(cell => {
cell.textContent = '';
cell.classList.remove('X', 'O');
});
}
// Attach event listeners to cells
cells.forEach(cell => {
cell.addEventListener('click', handleCellClick);
});
// Attach event listener to restart button
restartButton.addEventListener('click', restartGame);
4. Optional Features
a. AI Mode (Single Player)
To add an AI opponent that makes random moves, you can modify the JavaScript as follows:
- Add a toggle for single-player mode (optional UI change).
- Implement AI move after the player's turn.
Modified JavaScript (script.js):
// ... (existing code)
let isSinglePlayer = false; // Set to true to enable AI
// Function to handle cell click
function handleCellClick(e) {
const cell = e.target;
const index = parseInt(cell.getAttribute('data-index'));
if (board[index] !== '' || !isGameActive) {
return;
}
makeMove(cell, index, currentPlayer);
if (!isGameActive && isSinglePlayer) {
return;
}
if (isSinglePlayer && isGameActive) {
setTimeout(aiMove, 500); // AI makes a move after 500ms
}
}
function makeMove(cell, index, player) {
board[index] = player;
cell.textContent = player;
cell.classList.add(player);
checkResult();
}
function aiMove() {
// Simple AI: Random available move
const availableIndices = board
.map((val, idx) => val === '' ? idx : null)
.filter(val => val !== null);
if (availableIndices.length === 0 || !isGameActive) {
return;
}
const randomIndex = availableIndices[Math.floor(Math.random() * availableIndices.length)];
const cell = document.querySelector(`.cell[data-index='${randomIndex}']`);
makeMove(cell, randomIndex, currentPlayer);
}
// ... (rest of the existing code)
Note: For a complete single-player mode, you might want to add a UI element (like a checkbox) to toggle between single-player and two-player modes.
b. Scoreboard
To keep track of the number of games won by each player, update the HTML and JavaScript accordingly.
Updated index.html:
<!-- Add inside .game-container -->
<div class="scoreboard">
<div>Player X: <span id="scoreX">0</span></div>
<div>Player O: <span id="scoreO">0</span></div>
</div>
Updated styles.css:
.scoreboard {
display: flex;
justify-content: center;
gap: 20px;
margin-bottom: 20px;
font-size: 1.1rem;
}
Updated script.js:
// ... (existing code)
const scoreX = document.getElementById('scoreX');
const scoreO = document.getElementById('scoreO');
let scores = { X: 0, O: 0 };
// Modify checkResult function
function checkResult() {
let roundWon = false;
for (let condition of winningConditions) {
const [a, b, c] = condition;
if (board[a] && board[a] === board[b] && board[a] === board[c]) {
roundWon = true;
break;
}
}
if (roundWon) {
messageDisplay.textContent = `Player ${currentPlayer} wins!`;
scores[currentPlayer]++;
updateScore();
isGameActive = false;
return;
}
if (!board.includes('')) {
messageDisplay.textContent = "It's a draw!";
isGameActive = false;
return;
}
// Switch player
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
messageDisplay.textContent = `Player ${currentPlayer}'s turn`;
}
function updateScore() {
scoreX.textContent = scores.X;
scoreO.textContent = scores.O;
}
function restartGame() {
board = ['', '', '', '', '', '', '', '', ''];
isGameActive = true;
currentPlayer = 'X';
messageDisplay.textContent = `Player ${currentPlayer}'s turn`;
cells.forEach(cell => {
cell.textContent = '';
cell.classList.remove('X', 'O');
});
}
// ... (rest of the existing code)
c. Animations
You can add simple fade-in animations when a player marks a cell and when displaying the winner message.
Updated styles.css:
.cell {
/* Existing styles */
opacity: 0;
transition: background-color 0.3s, opacity 0.5s;
}
.cell.X, .cell.O {
opacity: 1;
}
.message {
/* Existing styles */
transition: opacity 0.5s;
}
.message.show {
opacity: 1;
}
.message.hide {
opacity: 0;
}
Updated script.js:
// ... (existing code)
function makeMove(cell, index, player) {
board[index] = player;
cell.textContent = player;
cell.classList.add(player);
// Trigger reflow for animation
void cell.offsetWidth;
cell.classList.add('show');
checkResult();
}
// Modify message display to include animation
function checkResult() {
// ... (existing code)
if (roundWon) {
messageDisplay.textContent = `Player ${currentPlayer} wins!`;
scores[currentPlayer]++;
updateScore();
isGameActive = false;
animateMessage();
return;
}
if (!board.includes('')) {
messageDisplay.textContent = "It's a draw!";
isGameActive = false;
animateMessage();
return;
}
// ... (existing code)
}
function animateMessage() {
messageDisplay.classList.remove('hide');
messageDisplay.classList.add('show');
setTimeout(() => {
messageDisplay.classList.remove('show');
messageDisplay.classList.add('hide');
}, 3000); // Message disappears after 3 seconds
}
function restartGame() {
// ... (existing code)
animateMessage();
}
// Initialize message animation on load
window.onload = () => {
messageDisplay.classList.add('show');
};
5. Final Directory Structure
Ensure your project directory looks like this:
/tic-tac-toe
│
├── index.html
├── styles.css
└── script.js
6. Running the Game
-
Setup:
- Ensure all three files (
index.html, styles.css, and script.js) are in the same directory.
-
Open the Game:
- Open
index.html in your preferred web browser.
-
Play:
- Click on any cell to place your mark ("X" starts first).
- Alternate turns between "X" and "O".
- The game will detect wins and draws, displaying appropriate messages.
- Click the "Restart Game" button to reset the board and play again.
7. Live Demo
For your convenience, here's a live demo of the game implemented above:
Tic-Tac-Toe Live Demo
(Note: Replace with an actual CodePen or similar live link if you wish to host it.)
Feel free to enhance the game further by adding more features or improving the design. Enjoy playing!