Sure! Let's develop a web application for Tic-Tac-Toe with the features you've described. Below is a step-by-step guide along with code snippets to help you build this application using HTML, CSS, and JavaScript. We'll use Node.js with Express for the server-side to handle user management, real-time gameplay, and data storage using JSON files.
Table of Contents
- Project Setup
- Installing Dependencies
- Directory Structure
- Creating the Server
- User Management
- Dashboard
- Waiting Queue and Matchmaking
- Real-time Gameplay
- Game Mechanics
- Leaderboard
- Styling with CSS
- Final Thoughts
1. Project Setup
First, ensure you have Node.js and npm installed. You can download them from Node.js official website.
Create a new directory for your project:
mkdir tic-tac-toe-app
cd tic-tac-toe-app
2. Installing Dependencies
Initialize a new Node.js project and install the required packages:
npm init -y
npm install express socket.io body-parser express-session
- express: Web framework for Node.js.
- socket.io: Enables real-time, bidirectional communication between web clients and servers.
- body-parser: Parses incoming request bodies.
- express-session: Manages user sessions.
3. Directory Structure
Organize your project files:
tic-tac-toe-app/
├── server.js
├── package.json
├── users.json
├── games.json
├── public/
├── index.html
├── dashboard.html
├── game.html
├── css/
├── styles.css
├── js/
├── main.js
├── dashboard.js
├── game.js
- server.js: The main server script.
- users.json: Stores user data.
- games.json: Stores game records.
- public/: Contains static files (HTML, CSS, JS).
4. Creating the Server
In server.js, set up the Express server and Socket.io:
// server.js
const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const http = require('http');
const fs = require('fs');
const path = require('path');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.use(session({
secret: 'tic-tac-toe-secret',
resave: false,
saveUninitialized: true,
}));
// Start server
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
5. User Management
Registration
Create a registration route in server.js:
// server.js
// Registration Route
app.post('/register', (req, res) => {
const { username, password } = req.body;
// Load existing users
let users = [];
if (fs.existsSync('users.json')) {
users = JSON.parse(fs.readFileSync('users.json'));
}
// Check if username is taken
if (users.find(user => user.username === username)) {
return res.send('Username already taken.');
}
// Add new user
users.push({
username,
password,
played: 0,
won: 0,
lost: 0,
});
fs.writeFileSync('users.json', JSON.stringify(users));
res.redirect('/');
});
Update public/index.html to include a registration form:
<!-- public/index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Tic-Tac-Toe - Register/Login</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<h1>Welcome to Tic-Tac-Toe</h1>
<div class="form-container">
<form action="/login" method="POST">
<h2>Login</h2>
<input type="text" name="username" placeholder="Username" required><br>
<input type="password" name="password" placeholder="Password" required><br>
<button type="submit">Login</button>
</form>
<form action="/register" method="POST">
<h2>Register</h2>
<input type="text" name="username" placeholder="Username" required><br>
<input type="password" name="password" placeholder="Password" required><br>
<button type="submit">Register</button>
</form>
</div>
</body>
</html>
Login
Add a login route in server.js:
// server.js
// Login Route
app.post('/login', (req, res) => {
const { username, password } = req.body;
// Load existing users
let users = [];
if (fs.existsSync('users.json')) {
users = JSON.parse(fs.readFileSync('users.json'));
}
const user = users.find(user => user.username === username && user.password === password);
if (user) {
// Set session
req.session.username = username;
res.redirect('/dashboard');
} else {
res.send('Invalid username or password.');
}
});
6. Dashboard
Create a dashboard route and page where users see their stats and the leaderboard.
// server.js
// Dashboard Route
app.get('/dashboard', (req, res) => {
if (!req.session.username) {
return res.redirect('/');
}
res.sendFile(path.join(__dirname, 'public', 'dashboard.html'));
});
In public/dashboard.html:
<!-- public/dashboard.html -->
<!DOCTYPE html>
<html>
<head>
<title>Dashboard - Tic-Tac-Toe</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<h1>Welcome, <span id="username"></span></h1>
<div class="stats">
<h2>Your Stats</h2>
<p>Played: <span id="played"></span></p>
<p>Won: <span id="won"></span></p>
<p>Lost: <span id="lost"></span></p>
</div>
<div class="leaderboard">
<h2>Leaderboard</h2>
<ul id="leaderboard-list"></ul>
</div>
<button id="join-queue">Join Game Queue</button>
<script src="/socket.io/socket.io.js"></script>
<script src="js/dashboard.js"></script>
</body>
</html>
In public/js/dashboard.js, fetch user stats and leaderboard data:
// public/js/dashboard.js
document.addEventListener('DOMContentLoaded', () => {
fetch('/user-data')
.then(response => response.json())
.then(data => {
document.getElementById('username').textContent = data.username;
document.getElementById('played').textContent = data.played;
document.getElementById('won').textContent = data.won;
document.getElementById('lost').textContent = data.lost;
});
fetch('/leaderboard')
.then(response => response.json())
.then(data => {
const leaderboardList = document.getElementById('leaderboard-list');
data.forEach(user => {
const li = document.createElement('li');
li.textContent = `${user.username} - Wins: ${user.won}`;
leaderboardList.appendChild(li);
});
});
document.getElementById('join-queue').addEventListener('click', () => {
fetch('/join-queue')
.then(response => response.json())
.then(data => {
if (data.gameId) {
window.location.href = `/game/${data.gameId}`;
}
});
});
});
In server.js, add routes to provide user data and leaderboard:
// server.js
// Get User Data
app.get('/user-data', (req, res) => {
if (!req.session.username) {
return res.status(401).json({ error: 'Not authenticated' });
}
let users = JSON.parse(fs.readFileSync('users.json'));
const user = users.find(user => user.username === req.session.username);
res.json(user);
});
// Get Leaderboard Data
app.get('/leaderboard', (req, res) => {
let users = JSON.parse(fs.readFileSync('users.json'));
// Sort users by number of wins
users.sort((a, b) => b.won - a.won);
res.json(users.slice(0, 10)); // Top 10 players
});
7. Waiting Queue and Matchmaking
Implement a waiting queue in server.js:
// server.js
let waitingUsers = [];
app.get('/join-queue', (req, res) => {
if (!req.session.username) {
return res.status(401).json({ error: 'Not authenticated' });
}
const username = req.session.username;
if (!waitingUsers.includes(username)) {
waitingUsers.push(username);
}
// Check if there are at least two users to start a game
if (waitingUsers.length >= 2) {
// Start a new game with the first two users
const player1 = waitingUsers.shift();
const player2 = waitingUsers.shift();
const gameId = Date.now();
// Save the game data
let games = [];
if (fs.existsSync('games.json')) {
games = JSON.parse(fs.readFileSync('games.json'));
}
games.push({
gameId,
player1,
player2,
board: ['', '', '', '', '', '', '', '', ''],
turn: player1,
winner: null,
});
fs.writeFileSync('games.json', JSON.stringify(games));
// Notify both players
io.to(player1).emit('startGame', { gameId, opponent: player2 });
io.to(player2).emit('startGame', { gameId, opponent: player1 });
res.json({ gameId });
} else {
res.json({ message: 'Waiting for an opponent...' });
}
});
// Serve the game page
app.get('/game/:gameId', (req, res) => {
if (!req.session.username) {
return res.redirect('/');
}
res.sendFile(path.join(__dirname, 'public', 'game.html'));
});
Setup Socket.io for real-time communication:
// server.js
io.on('connection', (socket) => {
// When a user connects, add them to a room with their username
socket.on('join', (username) => {
socket.join(username);
});
});
In public/js/dashboard.js, add the Socket.io connection:
// public/js/dashboard.js
const socket = io();
socket.emit('join', data.username);
8. Real-time Gameplay
In public/game.html:
<!-- public/game.html -->
<!DOCTYPE html>
<html>
<head>
<title>Tic-Tac-Toe Game</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<h1>Tic-Tac-Toe</h1>
<div id="game-status"></div>
<div class="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>
<script src="/socket.io/socket.io.js"></script>
<script src="js/game.js"></script>
</body>
</html>
In public/js/game.js:
// public/js/game.js
const socket = io();
let gameId;
let playerSymbol;
let currentTurn;
let opponent;
socket.on('connect', () => {
fetch('/user-data')
.then(response => response.json())
.then(userData => {
socket.emit('join', userData.username);
// Get game data
fetch(window.location.pathname + '/data')
.then(response => response.json())
.then(gameData => {
gameId = gameData.gameId;
opponent = gameData.opponent;
playerSymbol = gameData.playerSymbol;
currentTurn = gameData.turn;
document.getElementById('game-status').textContent = `Your symbol: ${playerSymbol}. It's ${currentTurn}'s turn.`;
// Initialize board state
updateBoard(gameData.board);
});
});
});
// Handle board clicks
document.querySelectorAll('.cell').forEach(cell => {
cell.addEventListener('click', () => {
const index = cell.getAttribute('data-index');
fetch(`/make-move/${gameId}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ index })
}).then(response => response.json())
.then(data => {
if (data.error) {
alert(data.error);
} else {
updateBoard(data.board);
currentTurn = data.turn;
document.getElementById('game-status').textContent = `It's ${currentTurn}'s turn.`;
if (data.winner) {
alert(`${data.winner} wins!`);
}
}
});
});
});
// Update board function
function updateBoard(board) {
board.forEach((symbol, index) => {
document.querySelector(`.cell[data-index='${index}']`).textContent = symbol;
});
}
In server.js, handle game data and moves:
// server.js
// Get game data
app.get('/game/:gameId/data', (req, res) => {
const gameId = parseInt(req.params.gameId);
const username = req.session.username;
let games = JSON.parse(fs.readFileSync('games.json'));
const game = games.find(g => g.gameId === gameId);
if (!game) {
return res.status(404).json({ error: 'Game not found' });
}
let playerSymbol = game.player1 === username ? 'X' : 'O';
let opponent = game.player1 === username ? game.player2 : game.player1;
res.json({
gameId,
opponent,
playerSymbol,
turn: game.turn,
board: game.board,
});
});
// Handle move
app.post('/make-move/:gameId', (req, res) => {
const gameId = parseInt(req.params.gameId);
const index = req.body.index;
const username = req.session.username;
let games = JSON.parse(fs.readFileSync('games.json'));
const game = games.find(g => g.gameId === gameId);
if (!game) {
return res.status(404).json({ error: 'Game not found' });
}
if (game.turn !== username) {
return res.json({ error: 'Not your turn.' });
}
if (game.board[index] !== '') {
return res.json({ error: 'Cell already occupied.' });
}
const symbol = game.player1 === username ? 'X' : 'O';
game.board[index] = symbol;
// Check for winner
const winner = checkWinner(game.board);
if (winner) {
game.winner = username;
updateUserStats(username, 'won');
const loser = game.player1 === username ? game.player2 : game.player1;
updateUserStats(loser, 'lost');
} else if (!game.board.includes('')) {
// Draw
updateUserStats(game.player1, 'played');
updateUserStats(game.player2, 'played');
} else {
// Switch turn
game.turn = game.turn === game.player1 ? game.player2 : game.player1;
}
fs.writeFileSync('games.json', JSON.stringify(games));
// Notify both players
io.to(game.player1).emit('updateBoard', game);
io.to(game.player2).emit('updateBoard', game);
res.json({
board: game.board,
turn: game.turn,
winner: game.winner,
});
});
// Helper functions
function checkWinner(board) {
const winningCombos = [
[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 combo of winningCombos) {
const [a, b, c] = combo;
if (board[a] && board[a] === board[b] && board[a] === board[c]) {
return true;
}
}
return false;
}
function updateUserStats(username, result) {
let users = JSON.parse(fs.readFileSync('users.json'));
const user = users.find(u => u.username === username);
user.played += 1;
if (result === 'won') {
user.won += 1;
} else if (result === 'lost') {
user.lost += 1;
}
fs.writeFileSync('users.json', JSON.stringify(users));
}
9. Game Mechanics
The checkWinner function checks all possible winning combinations. The updateUserStats function updates the user's statistics in users.json.
Ensure the server broadcasts updates to both players using Socket.io.
10. Leaderboard
The leaderboard is updated by fetching the top players sorted by the number of games won. This was implemented earlier in the /leaderboard route.
11. Styling with CSS
Create public/css/styles.css to add visual appeal:
/* public/css/styles.css */
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #fafafa;
}
h1 {
margin-top: 20px;
}
.form-container {
display: flex;
justify-content: center;
margin-top: 50px;
}
form {
margin: 0 20px;
}
input {
display: block;
margin: 10px auto;
padding: 10px;
width: 200px;
}
button {
padding: 10px 20px;
}
.board {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-gap: 10px;
justify-content: center;
margin: 20px auto;
}
.cell {
width: 100px;
height: 100px;
background-color: #fff;
font-size: 48px;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
border: 2px solid #ccc;
}
.stats, .leaderboard {
display: inline-block;
margin: 20px;
}
button#join-queue {
padding: 15px 30px;
font-size: 16px;
}
12. Final Thoughts
This guide provides a basic implementation of a Tic-Tac-Toe web application with user management, real-time gameplay, and a leaderboard, using JSON files for data storage.
Security Considerations:
- Passwords: In a production environment, always hash passwords before storing them.
- Data Validation: Implement proper input validation to prevent injection attacks.
- Concurrency: Using JSON files is not ideal for handling concurrent requests; consider using a database like MongoDB or MySQL.
Enhancements:
- User Experience: Improve the UI/UX with better graphics and animations.
- Chat Feature: Add a chat so players can communicate during the game.
- Multiple Game Modes: Implement single-player mode against an AI.
Feel free to modify and expand upon this code to suit your needs. If you have any questions or need further assistance, please let me know!