Certainly! Below is a comprehensive guide to transforming your single-player card game into a real-time multiplayer experience using Express.js and WebSockets (Socket.io). This involves removing the robot players from the client-side logic, setting up an Express.js server to manage game rooms and states, and modifying the index.html to interact with the server for real-time updates.
Table of Contents
- Overview
- Server Setup
- Client Setup (
index.html)
- Running the Application
- Important Considerations
- Complete Code Listings
Overview
To transition your game to a multiplayer setup:
- Remove Robot Players: Eliminate all robot-related logic from the client-side code.
- Express.js Server: Set up an Express.js server with Socket.io to handle real-time communication.
- Central Data Source: Manage game rooms, player data, and game states on the server, persisting them in a JSON file.
- WebSocket Communication: Modify the client to communicate with the server via WebSockets for actions like creating/joining rooms, playing cards, etc.
- User Interface: Update the UI to allow users to create or join rooms and interact with other players in real-time.
Server Setup
1. Initialize the Server
First, set up a new Node.js project and install the necessary dependencies.
# Create a new directory for the server
mkdir card-game-server
cd card-game-server
# Initialize a new Node.js project
npm init -y
# Install dependencies
npm install express socket.io uuid fs-extra
- express: Web framework for Node.js.
- socket.io: For real-time WebSocket communication.
- uuid: To generate unique room IDs.
- fs-extra: For easier JSON file handling.
2. Server Code (server.js)
Create a server.js file in the card-game-server directory with the following content:
// server.js
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const { v4: uuidv4 } = require('uuid');
const fs = require('fs-extra');
const path = require('path');
// Initialize Express app
const app = express();
const server = http.createServer(app);
const io = new Server(server);
// Serve static files (if any)
// app.use(express.static('public'));
// Path to the rooms data file
const ROOMS_FILE = path.join(__dirname, 'rooms.json');
// Ensure the rooms file exists
fs.ensureFileSync(ROOMS_FILE);
if (!fs.readJsonSync(ROOMS_FILE, { throws: false })) {
fs.writeJsonSync(ROOMS_FILE, { rooms: {} }, { spaces: 2 });
}
// Helper function to read rooms data
const readRooms = () => {
try {
const data = fs.readJsonSync(ROOMS_FILE);
return data.rooms;
} catch (err) {
console.error('Error reading rooms data:', err);
return {};
}
};
// Helper function to write rooms data
const writeRooms = (rooms) => {
try {
fs.writeJsonSync(ROOMS_FILE, { rooms }, { spaces: 2 });
} catch (err) {
console.error('Error writing rooms data:', err);
}
};
// Socket.io connection handler
io.on('connection', (socket) => {
console.log(`New client connected: ${socket.id}`);
// Handle creating a new room
socket.on('createRoom', (playerName, callback) => {
const rooms = readRooms();
const roomId = uuidv4().slice(0, 6); // Shorter ID for easy sharing
// Initialize room data
rooms[roomId] = {
id: roomId,
host: socket.id,
players: [
{
id: socket.id,
name: playerName || 'Host',
hand: [],
bulletSlots: 6,
isEliminated: false,
isHost: true,
isHuman: true,
},
],
status: 'waiting', // 'waiting' or 'started'
coreCard: null,
lastPlayedCards: [],
centralTableCards: [],
currentPlayerIndex: 0,
deck: [],
};
writeRooms(rooms);
socket.join(roomId);
socket.emit('roomCreated', roomId);
io.to(roomId).emit('roomUpdate', rooms[roomId]);
console.log(`Room ${roomId} created by ${socket.id}`);
if (callback) callback({ success: true, roomId });
});
// Handle joining an existing room
socket.on('joinRoom', (data, callback) => {
const { roomId, playerName } = data;
const rooms = readRooms();
if (!rooms[roomId]) {
if (callback) callback({ success: false, message: 'Room does not exist.' });
return;
}
const room = rooms[roomId];
if (room.status !== 'waiting') {
if (callback) callback({ success: false, message: 'Game already started.' });
return;
}
if (room.players.length >= 5) { // Maximum 5 players
if (callback) callback({ success: false, message: 'Room is full.' });
return;
}
// Add new player to the room
room.players.push({
id: socket.id,
name: playerName || `Player ${room.players.length + 1}`,
hand: [],
bulletSlots: 6,
isEliminated: false,
isHost: false,
isHuman: true,
});
writeRooms(rooms);
socket.join(roomId);
io.to(roomId).emit('roomUpdate', room);
if (callback) callback({ success: true, roomId });
console.log(`Player ${socket.id} joined room ${roomId}`);
});
// Handle starting the game
socket.on('startGame', (roomId, callback) => {
const rooms = readRooms();
const room = rooms[roomId];
if (!room) {
if (callback) callback({ success: false, message: 'Room does not exist.' });
return;
}
if (room.host !== socket.id) {
if (callback) callback({ success: false, message: 'Only the host can start the game.' });
return;
}
if (room.players.length < 2) {
if (callback) callback({ success: false, message: 'At least 2 players required to start.' });
return;
}
// Initialize the game
initializeGame(room);
room.status = 'started';
writeRooms(rooms);
io.to(roomId).emit('gameStarted', room);
if (callback) callback({ success: true });
console.log(`Game started in room ${roomId}`);
});
// Handle playing selected cards
socket.on('playCards', (data, callback) => {
const { roomId, selectedCardIndices } = data;
const rooms = readRooms();
const room = rooms[roomId];
if (!room || room.status !== 'started') {
if (callback) callback({ success: false, message: 'Game not started or room does not exist.' });
return;
}
const currentPlayer = room.players[room.currentPlayerIndex];
if (currentPlayer.id !== socket.id) {
if (callback) callback({ success: false, message: 'Not your turn.' });
return;
}
if (!Array.isArray(selectedCardIndices) || selectedCardIndices.length === 0) {
if (callback) callback({ success: false, message: 'No cards selected.' });
return;
}
// Validate selected cards
const selectedCards = [];
selectedCardIndices.sort((a, b) => b - a); // Descending to remove from hand correctly
for (let index of selectedCardIndices) {
if (index < 0 || index >= currentPlayer.hand.length) {
if (callback) callback({ success: false, message: 'Invalid card index.' });
return;
}
selectedCards.push(currentPlayer.hand.splice(index, 1)[0]);
}
// Add to central table (face-down)
selectedCards.forEach(card => {
room.centralTableCards.push({
card: card,
revealed: false,
playedBy: socket.id,
});
});
room.lastPlayedCards = selectedCards;
// Update last played description server-side logic (handled on client via 'gameUpdate')
// Move to next player
room.currentPlayerIndex = (room.currentPlayerIndex + 1) % room.players.length;
// Skip eliminated players
let attempts = 0;
while (room.players[room.currentPlayerIndex].isEliminated && attempts < room.players.length) {
room.currentPlayerIndex = (room.currentPlayerIndex + 1) % room.players.length;
attempts++;
}
writeRooms(rooms);
io.to(roomId).emit('gameUpdate', room);
if (callback) callback({ success: true });
console.log(`Player ${socket.id} played cards in room ${roomId}`);
});
// Handle calling bluff
socket.on('callBluff', (roomId, callback) => {
const rooms = readRooms();
const room = rooms[roomId];
if (!room || room.status !== 'started') {
if (callback) callback({ success: false, message: 'Game not started or room does not exist.' });
return;
}
const caller = room.players.find(p => p.id === socket.id);
if (!caller) {
if (callback) callback({ success: false, message: 'Player not found in room.' });
return;
}
// Determine who played last
const lastPlayerIndex = (room.currentPlayerIndex - 1 + room.players.length) % room.players.length;
const lastPlayer = room.players[lastPlayerIndex];
const lastPlayed = room.lastPlayedCards;
const isBluff = !lastPlayed.every(card => card.value === room.coreCard.value);
// Determine who gets shot
const shootingPlayer = isBluff ? lastPlayer : caller;
// Update shooting player's status
const player = room.players.find(p => p.id === shootingPlayer.id);
if (player.bulletSlots <= 0) {
player.isEliminated = true;
} else {
// Determine chance to get shot
const chance = 1 / player.bulletSlots;
const hitBullet = Math.random() < chance;
if (hitBullet) {
player.isEliminated = true;
player.bulletSlots--;
} else {
player.bulletSlots--;
}
}
// Reveal last played cards if bluff was called
if (isBluff) {
room.centralTableCards.forEach(cardObj => {
if (lastPlayed.includes(cardObj.card)) {
cardObj.revealed = true;
}
});
}
// Check for game over
const remainingPlayers = room.players.filter(p => !p.isEliminated);
if (remainingPlayers.length === 1) {
room.status = 'ended';
io.to(roomId).emit('gameEnded', { winner: remainingPlayers[0].name });
writeRooms(rooms);
console.log(`Game ended in room ${roomId}. Winner: ${remainingPlayers[0].name}`);
return;
}
// Reset for next round
room.coreCard = null;
room.lastPlayedCards = [];
room.centralTableCards = [];
// Reset current player index
room.currentPlayerIndex = room.players.findIndex(p => !p.isEliminated);
if (room.currentPlayerIndex === -1) room.currentPlayerIndex = 0;
// Draw new core card if not set
if (!room.coreCard) {
if (room.deck.length < room.players.length * 5) {
initializeDeck(room);
}
room.coreCard = room.deck.shift();
}
writeRooms(rooms);
io.to(roomId).emit('gameUpdate', room);
if (callback) callback({ success: true });
console.log(`Player ${socket.id} called bluff in room ${roomId}`);
});
// Handle pulling trigger (Russian Roulette)
socket.on('pullTrigger', (roomId, callback) => {
const rooms = readRooms();
const room = rooms[roomId];
if (!room || room.status !== 'started') {
if (callback) callback({ success: false, message: 'Game not started or room does not exist.' });
return;
}
const shooter = room.players[room.currentPlayerIndex];
if (!shooter) {
if (callback) callback({ success: false, message: 'No shooter found.' });
return;
}
if (shooter.bulletSlots <= 0) {
shooter.isEliminated = true;
} else {
const chance = 1 / shooter.bulletSlots;
const hitBullet = Math.random() < chance;
if (hitBullet) {
shooter.isEliminated = true;
shooter.bulletSlots--;
} else {
shooter.bulletSlots--;
}
}
// Check for game over
const remainingPlayers = room.players.filter(p => !p.isEliminated);
if (remainingPlayers.length === 1) {
room.status = 'ended';
io.to(roomId).emit('gameEnded', { winner: remainingPlayers[0].name });
writeRooms(rooms);
console.log(`Game ended in room ${roomId}. Winner: ${remainingPlayers[0].name}`);
return;
}
// Reset coreCard for the next round
room.coreCard = null;
room.lastPlayedCards = [];
room.centralTableCards = [];
// Move to next player
room.currentPlayerIndex = (room.currentPlayerIndex + 1) % room.players.length;
// Skip eliminated players
let attempts = 0;
while (room.players[room.currentPlayerIndex].isEliminated && attempts < room.players.length) {
room.currentPlayerIndex = (room.currentPlayerIndex + 1) % room.players.length;
attempts++;
}
// Initialize new round
initializeGame(room);
writeRooms(rooms);
io.to(roomId).emit('gameUpdate', room);
if (callback) callback({ success: true });
console.log(`Player ${shooter.id} pulled trigger in room ${roomId}`);
});
// Handle disconnect
socket.on('disconnect', () => {
console.log(`Client disconnected: ${socket.id}`);
const rooms = readRooms();
let updated = false;
for (let roomId in rooms) {
const room = rooms[roomId];
const playerIndex = room.players.findIndex(p => p.id === socket.id);
if (playerIndex !== -1) {
room.players.splice(playerIndex, 1);
updated = true;
// If host leaves, assign a new host
if (room.host === socket.id && room.players.length > 0) {
room.host = room.players[0].id;
room.players[0].isHost = true;
}
// If all players leave, delete the room
if (room.players.length === 0) {
delete rooms[roomId];
}
writeRooms(rooms);
io.to(roomId).emit('roomUpdate', room);
break;
}
}
if (updated) {
console.log(`Player ${socket.id} removed from their room.`);
}
});
});
// Helper function to initialize game settings
const initializeGame = (room) => {
initializeDeck(room);
shuffleDeck(room);
// Assign hands to players
room.players.forEach(player => {
player.hand = room.deck.splice(0, 5);
});
// Assign core card if not set
if (!room.coreCard) {
room.coreCard = room.deck.shift();
}
room.lastPlayedCards = [];
room.centralTableCards = [];
};
// Initialize deck for the room
const initializeDeck = (room) => {
const values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'];
const suits = ['♠', '♥', '♦', '♣'];
room.deck = [];
for (let value of values) {
for (let suit of suits) {
room.deck.push({ value, suit });
}
}
};
// Shuffle deck using Fisher-Yates algorithm
const shuffleDeck = (room) => {
for (let i = room.deck.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[room.deck[i], room.deck[j]] = [room.deck[j], room.deck[i]];
}
};
// Start the server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
Explanation:
-
Express & Socket.io Setup: The server uses Express to create an HTTP server and integrates Socket.io for real-time communication.
-
Room Management:
- Creating a Room: When a client emits
createRoom, the server generates a unique room ID, initializes the room data, assigns the creating player as the host, and emits the room ID back to the creator.
- Joining a Room: Clients can join existing rooms by emitting
joinRoom with the room ID and their name. The server validates the room's existence and capacity before adding the player.
-
Game Flow:
- Starting the Game: The host can start the game by emitting
startGame. The server initializes the deck, shuffles, deals hands, and changes the room status to started.
- Playing Cards: Players can play cards by emitting
playCards with selected card indices. The server validates the action, updates the game state, and notifies all players.
- Calling Bluff: When a bluff is called via
callBluff, the server determines if it was a bluff, updates player statuses, and checks for the game's end.
- Pulling Trigger: This action simulates the Russian Roulette mechanic. The server handles the logic and updates the game accordingly.
-
Data Persistence: Rooms and their states are stored in a rooms.json file using fs-extra for file operations.
-
Player Disconnects: If a player disconnects, they are removed from their room. If the host leaves, a new host is assigned. If all players leave, the room is deleted.
3. Room Data Structure
Each room in rooms.json has the following structure:
{
"rooms": {
"roomId": {
"id": "roomId",
"host": "socketId",
"players": [
{
"id": "socketId",
"name": "Player Name",
"hand": [
{ "value": "A", "suit": "♠" },
// ... more cards
],
"bulletSlots": 6,
"isEliminated": false,
"isHost": true,
"isHuman": true
}
// ... more players
],
"status": "waiting" | "started" | "ended",
"coreCard": { "value": "A", "suit": "♠" },
"lastPlayedCards": [
{ "value": "A", "suit": "♠" }
// ... more cards
],
"centralTableCards": [
{
"card": { "value": "A", "suit": "♠" },
"revealed": false,
"playedBy": "socketId"
}
// ... more cards
],
"currentPlayerIndex": 0,
"deck": [
{ "value": "2", "suit": "♥" },
// ... more cards
]
}
// ... more rooms
}
}
- Room Properties:
id: Unique room ID.
host: Socket ID of the room creator.
players: Array of player objects.
status: Current status of the room (waiting, started, or ended).
coreCard: The core card for the round.
lastPlayedCards: The last set of cards played.
centralTableCards: Cards placed on the table.
currentPlayerIndex: Index of the current player in the players array.
deck: Remaining deck of cards.
Client Setup (index.html)
1. HTML Structure
Update your index.html to include interfaces for creating/joining rooms and interacting with the game in real-time.
2. CSS Styles
Retain most of your existing styles, focusing on ensuring the new UI elements for room management fit seamlessly.
3. Client-Side JavaScript
Replace the existing game logic with Socket.io client interactions. Below is the modified index.html with necessary changes and comments.
Running the Application
-
Start the Server:
Ensure you have Node.js installed. Navigate to the card-game-server directory and run:
node server.js
The server will start on port 3000 (or another port if specified).
-
Client-Side Setup:
- Ensure your
index.html is served via a web server (e.g., using Live Server in VSCode) or placed in a directory where it can access the server at http://localhost:3000.
- Important: The client needs to connect to the Socket.io server. Ensure the Socket.io client library is included.
-
Play the Game:
- Open
index.html in your browser.
- Create a new room or join an existing one using the room ID.
- Once all players have joined, the host can start the game.
- Interact with other players in real-time as the game progresses.
Important Considerations
-
Security: This setup is basic and does not include authentication or authorization. For a production environment, implement proper security measures.
-
Concurrency: Managing concurrent read/write operations to the rooms.json file can lead to race conditions. For scalability, consider using a database like MongoDB or Redis.
-
Scalability: Storing game states in memory (or in a file) is suitable for small applications. For larger scales, utilize databases or in-memory data stores.
-
Error Handling: Ensure robust error handling in both server and client to handle unexpected scenarios gracefully.
Complete Code Listings
1. Server (server.js)
// server.js
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const { v4: uuidv4 } = require('uuid');
const fs = require('fs-extra');
const path = require('path');
// Initialize Express app
const app = express();
const server = http.createServer(app);
const io = new Server(server);
// Serve static files (optional, uncomment if needed)
// app.use(express.static('public'));
// Path to the rooms data file
const ROOMS_FILE = path.join(__dirname, 'rooms.json');
// Ensure the rooms file exists
fs.ensureFileSync(ROOMS_FILE);
if (!fs.readJsonSync(ROOMS_FILE, { throws: false })) {
fs.writeJsonSync(ROOMS_FILE, { rooms: {} }, { spaces: 2 });
}
// Helper function to read rooms data
const readRooms = () => {
try {
const data = fs.readJsonSync(ROOMS_FILE);
return data.rooms;
} catch (err) {
console.error('Error reading rooms data:', err);
return {};
}
};
// Helper function to write rooms data
const writeRooms = (rooms) => {
try {
fs.writeJsonSync(ROOMS_FILE, { rooms }, { spaces: 2 });
} catch (err) {
console.error('Error writing rooms data:', err);
}
};
// Socket.io connection handler
io.on('connection', (socket) => {
console.log(`New client connected: ${socket.id}`);
// Handle creating a new room
socket.on('createRoom', (playerName, callback) => {
const rooms = readRooms();
const roomId = uuidv4().slice(0, 6); // Shorter ID for easy sharing
// Initialize room data
rooms[roomId] = {
id: roomId,
host: socket.id,
players: [
{
id: socket.id,
name: playerName || 'Host',
hand: [],
bulletSlots: 6,
isEliminated: false,
isHost: true,
isHuman: true,
},
],
status: 'waiting', // 'waiting' or 'started'
coreCard: null,
lastPlayedCards: [],
centralTableCards: [],
currentPlayerIndex: 0,
deck: [],
};
writeRooms(rooms);
socket.join(roomId);
socket.emit('roomCreated', roomId);
io.to(roomId).emit('roomUpdate', rooms[roomId]);
console.log(`Room ${roomId} created by ${socket.id}`);
if (callback) callback({ success: true, roomId });
});
// Handle joining an existing room
socket.on('joinRoom', (data, callback) => {
const { roomId, playerName } = data;
const rooms = readRooms();
if (!rooms[roomId]) {
if (callback) callback({ success: false, message: 'Room does not exist.' });
return;
}
const room = rooms[roomId];
if (room.status !== 'waiting') {
if (callback) callback({ success: false, message: 'Game already started.' });
return;
}
if (room.players.length >= 5) { // Maximum 5 players
if (callback) callback({ success: false, message: 'Room is full.' });
return;
}
// Add new player to the room
room.players.push({
id: socket.id,
name: playerName || `Player ${room.players.length + 1}`,
hand: [],
bulletSlots: 6,
isEliminated: false,
isHost: false,
isHuman: true,
});
writeRooms(rooms);
socket.join(roomId);
io.to(roomId).emit('roomUpdate', room);
if (callback) callback({ success: true, roomId });
console.log(`Player ${socket.id} joined room ${roomId}`);
});
// Handle starting the game
socket.on('startGame', (roomId, callback) => {
const rooms = readRooms();
const room = rooms[roomId];
if (!room) {
if (callback) callback({ success: false, message: 'Room does not exist.' });
return;
}
if (room.host !== socket.id) {
if (callback) callback({ success: false, message: 'Only the host can start the game.' });
return;
}
if (room.players.length < 2) {
if (callback) callback({ success: false, message: 'At least 2 players required to start.' });
return;
}
// Initialize the game
initializeGame(room);
room.status = 'started';
writeRooms(rooms);
io.to(roomId).emit('gameStarted', room);
if (callback) callback({ success: true });
console.log(`Game started in room ${roomId}`);
});
// Handle playing selected cards
socket.on('playCards', (data, callback) => {
const { roomId, selectedCardIndices } = data;
const rooms = readRooms();
const room = rooms[roomId];
if (!room || room.status !== 'started') {
if (callback) callback({ success: false, message: 'Game not started or room does not exist.' });
return;
}
const currentPlayer = room.players[room.currentPlayerIndex];
if (currentPlayer.id !== socket.id) {
if (callback) callback({ success: false, message: 'Not your turn.' });
return;
}
if (!Array.isArray(selectedCardIndices) || selectedCardIndices.length === 0) {
if (callback) callback({ success: false, message: 'No cards selected.' });
return;
}
// Validate selected cards
const selectedCards = [];
selectedCardIndices.sort((a, b) => b - a); // Descending to remove from hand correctly
for (let index of selectedCardIndices) {
if (index < 0 || index >= currentPlayer.hand.length) {
if (callback) callback({ success: false, message: 'Invalid card index.' });
return;
}
selectedCards.push(currentPlayer.hand.splice(index, 1)[0]);
}
// Add to central table (face-down)
selectedCards.forEach(card => {
room.centralTableCards.push({
card: card,
revealed: false,
playedBy: socket.id,
});
});
room.lastPlayedCards = selectedCards;
// Update last played description server-side logic (handled on client via 'gameUpdate')
// Move to next player
room.currentPlayerIndex = (room.currentPlayerIndex + 1) % room.players.length;
// Skip eliminated players
let attempts = 0;
while (room.players[room.currentPlayerIndex].isEliminated && attempts < room.players.length) {
room.currentPlayerIndex = (room.currentPlayerIndex + 1) % room.players.length;
attempts++;
}
writeRooms(rooms);
io.to(roomId).emit('gameUpdate', room);
if (callback) callback({ success: true });
console.log(`Player ${socket.id} played cards in room ${roomId}`);
});
// Handle calling bluff
socket.on('callBluff', (roomId, callback) => {
const rooms = readRooms();
const room = rooms[roomId];
if (!room || room.status !== 'started') {
if (callback) callback({ success: false, message: 'Game not started or room does not exist.' });
return;
}
const caller = room.players.find(p => p.id === socket.id);
if (!caller) {
if (callback) callback({ success: false, message: 'Player not found in room.' });
return;
}
// Determine who played last
const lastPlayerIndex = (room.currentPlayerIndex - 1 + room.players.length) % room.players.length;
const lastPlayer = room.players[lastPlayerIndex];
const lastPlayed = room.lastPlayedCards;
const isBluff = !lastPlayed.every(card => card.value === room.coreCard.value);
// Determine who gets shot
const shootingPlayer = isBluff ? lastPlayer : caller;
// Update shooting player's status
const player = room.players.find(p => p.id === shootingPlayer.id);
if (player.bulletSlots <= 0) {
player.isEliminated = true;
} else {
// Determine chance to get shot
const chance = 1 / player.bulletSlots;
const hitBullet = Math.random() < chance;
if (hitBullet) {
player.isEliminated = true;
player.bulletSlots--;
} else {
player.bulletSlots--;
}
}
// Reveal last played cards if bluff was called
if (isBluff) {
room.centralTableCards.forEach(cardObj => {
if (lastPlayed.includes(cardObj.card)) {
cardObj.revealed = true;
}
});
}
// Check for game over
const remainingPlayers = room.players.filter(p => !p.isEliminated);
if (remainingPlayers.length === 1) {
room.status = 'ended';
io.to(roomId).emit('gameEnded', { winner: remainingPlayers[0].name });
writeRooms(rooms);
console.log(`Game ended in room ${roomId}. Winner: ${remainingPlayers[0].name}`);
return;
}
// Reset for next round
room.coreCard = null;
room.lastPlayedCards = [];
room.centralTableCards = [];
// Reset current player index
room.currentPlayerIndex = room.players.findIndex(p => !p.isEliminated);
if (room.currentPlayerIndex === -1) room.currentPlayerIndex = 0;
// Draw new core card if not set
if (!room.coreCard) {
if (room.deck.length < room.players.length * 5) {
initializeDeck(room);
}
room.coreCard = room.deck.shift();
}
writeRooms(rooms);
io.to(roomId).emit('gameUpdate', room);
if (callback) callback({ success: true });
console.log(`Player ${socket.id} called bluff in room ${roomId}`);
});
// Handle pulling trigger (Russian Roulette)
socket.on('pullTrigger', (roomId, callback) => {
const rooms = readRooms();
const room = rooms[roomId];
if (!room || room.status !== 'started') {
if (callback) callback({ success: false, message: 'Game not started or room does not exist.' });
return;
}
const shooter = room.players[room.currentPlayerIndex];
if (!shooter) {
if (callback) callback({ success: false, message: 'No shooter found.' });
return;
}
if (shooter.bulletSlots <= 0) {
shooter.isEliminated = true;
} else {
const chance = 1 / shooter.bulletSlots;
const hitBullet = Math.random() < chance;
if (hitBullet) {
shooter.isEliminated = true;
shooter.bulletSlots--;
} else {
shooter.bulletSlots--;
}
}
// Check for game over
const remainingPlayers = room.players.filter(p => !p.isEliminated);
if (remainingPlayers.length === 1) {
room.status = 'ended';
io.to(roomId).emit('gameEnded', { winner: remainingPlayers[0].name });
writeRooms(rooms);
console.log(`Game ended in room ${roomId}. Winner: ${remainingPlayers[0].name}`);
return;
}
// Reset coreCard for the next round
room.coreCard = null;
room.lastPlayedCards = [];
room.centralTableCards = [];
// Move to next player
room.currentPlayerIndex = (room.currentPlayerIndex + 1) % room.players.length;
// Skip eliminated players
let attempts = 0;
while (room.players[room.currentPlayerIndex].isEliminated && attempts < room.players.length) {
room.currentPlayerIndex = (room.currentPlayerIndex + 1) % room.players.length;
attempts++;
}
// Initialize new round
initializeGame(room);
writeRooms(rooms);
io.to(roomId).emit('gameUpdate', room);
if (callback) callback({ success: true });
console.log(`Player ${shooter.id} pulled trigger in room ${roomId}`);
});
// Handle disconnect
socket.on('disconnect', () => {
console.log(`Client disconnected: ${socket.id}`);
const rooms = readRooms();
let updated = false;
for (let roomId in rooms) {
const room = rooms[roomId];
const playerIndex = room.players.findIndex(p => p.id === socket.id);
if (playerIndex !== -1) {
room.players.splice(playerIndex, 1);
updated = true;
// If host leaves, assign a new host
if (room.host === socket.id && room.players.length > 0) {
room.host = room.players[0].id;
room.players[0].isHost = true;
}
// If all players leave, delete the room
if (room.players.length === 0) {
delete rooms[roomId];
}
writeRooms(rooms);
io.to(roomId).emit('roomUpdate', room);
break;
}
}
if (updated) {
console.log(`Player ${socket.id} removed from their room.`);
}
});
});
// Helper function to initialize game settings
const initializeGame = (room) => {
initializeDeck(room);
shuffleDeck(room);
// Assign hands to players
room.players.forEach(player => {
player.hand = room.deck.splice(0, 5);
});
// Assign core card if not set
if (!room.coreCard) {
room.coreCard = room.deck.shift();
}
room.lastPlayedCards = [];
room.centralTableCards = [];
};
// Initialize deck for the room
const initializeDeck = (room) => {
const values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'];
const suits = ['♠', '♥', '♦', '♣'];
room.deck = [];
for (let value of values) {
for (let suit of suits) {
room.deck.push({ value, suit });
}
}
};
// Shuffle deck using Fisher-Yates algorithm
const shuffleDeck = (room) => {
for (let i = room.deck.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[room.deck[i], room.deck[j]] = [room.deck[j], room.deck[i]];
}
};
// Start the server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
2. Client (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Card Bluff & Shoot - Multiplayer</title>
<style>
/* (Retain your existing styles here) */
body {
margin: 0;
padding: 20px;
background: #1a1a1a;
color: white;
font-family: Arial, sans-serif;
}
.hidden {
display: none;
}
.room-management {
display: flex;
flex-direction: column;
align-items: center;
gap: 15px;
margin-top: 50px;
}
.room-management input {
padding: 10px;
width: 250px;
border: none;
border-radius: 5px;
}
.room-management button {
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
background: #4CAF50;
color: white;
transition: background 0.3s;
}
.room-management button:hover {
background: #45a049;
}
/* (Rest of your existing styles) */
</style>
</head>
<body>
<!-- Room Management Section -->
<div class="room-management" id="roomManagement">
<h2>Card Bluff & Shoot</h2>
<input type="text" id="playerNameInput" placeholder="Enter Your Name" required>
<button id="createRoomBtn">Create Room</button>
<h3>OR</h3>
<input type="text" id="roomIdInput" placeholder="Enter Room ID">
<button id="joinRoomBtn">Join Room</button>
<p id="roomStatus"></p>
</div>
<!-- Game Interface (Initially Hidden) -->
<div class="game-container hidden" id="gameContainer">
<div class="top-section" id="players"></div>
<div class="middle-section">
<div class="game-info">
<strong>Core Card:</strong> <span id="coreCard">-</span>
</div>
<div class="game-info">
<strong>Last Played:</strong> <span id="lastPlayed">None</span>
</div>
<!-- Central Card Table -->
<div class="central-table" id="centralTable"></div>
</div>
<div class="bottom-section">
<div class="player-hand" id="currentHand"></div>
<div class="actions">
<button id="playButton" onclick="playSelectedCards()">Play Selected Cards</button>
<button id="callBluffButton" onclick="callBluff()" style="background: #f44336">Call Bluff</button>
<button id="pullTriggerButton" onclick="pullTrigger()" style="background: #555; display: none;">Pull Trigger</button>
</div>
</div>
</div>
<!-- Modal for Room Creation/Joining (Optional) -->
<!-- Overlay for Shooting (Optional) -->
<div class="overlay" id="shootingOverlay">
<h2>🎲 Russian Roulette Time! 🔫</h2>
<button onclick="pullTrigger()" style="padding: 15px 30px; font-size: 1em;">Pull Trigger</button>
</div>
<!-- Debug Controls (Optional) -->
<div id="debugControls" class="hidden">
<button onclick="startNewGame()">New Game</button>
</div>
<!-- Include Socket.io Client Library -->
<script src="https://cdn.socket.io/4.5.4/socket.io.min.js"
integrity="sha384-fpVhm4ea/qNrVrLj7hPlbqE/JVSgYWSwponOPkz6eDVXSJvoPEynqbpDzESrQB88"
crossorigin="anonymous"></script>
<script>
const socket = io('http://localhost:3000'); // Adjust the URL if different
// Elements
const roomManagement = document.getElementById('roomManagement');
const createRoomBtn = document.getElementById('createRoomBtn');
const joinRoomBtn = document.getElementById('joinRoomBtn');
const playerNameInput = document.getElementById('playerNameInput');
const roomIdInput = document.getElementById('roomIdInput');
const roomStatus = document.getElementById('roomStatus');
const gameContainer = document.getElementById('gameContainer');
const playersDiv = document.getElementById('players');
const coreCardSpan = document.getElementById('coreCard');
const lastPlayedSpan = document.getElementById('lastPlayed');
const centralTable = document.getElementById('centralTable');
const currentHand = document.getElementById('currentHand');
const playButton = document.getElementById('playButton');
const callBluffButton = document.getElementById('callBluffButton');
const pullTriggerButton = document.getElementById('pullTriggerButton');
let currentRoomId = null;
let isHost = false;
let mySocketId = null;
// Store selected cards
let selectedCardIndices = [];
// Event Listeners
createRoomBtn.addEventListener('click', () => {
const playerName = playerNameInput.value.trim();
if (playerName === '') {
alert('Please enter your name.');
return;
}
socket.emit('createRoom', playerName, (response) => {
if (response.success) {
currentRoomId = response.roomId;
isHost = true;
roomStatus.textContent = `Room Created. Share Room ID: ${currentRoomId}`;
} else {
alert(response.message);
}
});
});
joinRoomBtn.addEventListener('click', () => {
const playerName = playerNameInput.value.trim();
const roomId = roomIdInput.value.trim();
if (playerName === '' || roomId === '') {
alert('Please enter your name and room ID.');
return;
}
socket.emit('joinRoom', { roomId, playerName }, (response) => {
if (response.success) {
currentRoomId = response.roomId;
isHost = false;
roomStatus.textContent = `Joined Room: ${currentRoomId}`;
} else {
alert(response.message);
}
});
});
// Socket.io Event Handlers
// When room is created
socket.on('roomCreated', (roomId) => {
currentRoomId = roomId;
isHost = true;
roomStatus.textContent = `Room Created. Share Room ID: ${roomId}`;
});
// When room is updated (players joined or left)
socket.on('roomUpdate', (room) => {
if (currentRoomId !== room.id) return;
updateRoomUI(room);
});
// When game starts
socket.on('gameStarted', (room) => {
roomManagement.classList.add('hidden');
gameContainer.classList.remove('hidden');
updateGameUI(room);
});
// When game updates
socket.on('gameUpdate', (room) => {
updateGameUI(room);
});
// When game ends
socket.on('gameEnded', (data) => {
alert(`Game Over! Winner: ${data.winner} 👑`);
location.reload();
});
// Update Room UI
const updateRoomUI = (room) => {
playersDiv.innerHTML = '';
room.players.forEach(player => {
const playerEl = document.createElement('div');
playerEl.className = `player ${player.id === socket.id ? 'active' : ''} ${player.isEliminated ? 'eliminated' : ''}`;
playerEl.innerHTML = `
<strong>${player.name}${player.isHost ? ' (Host)' : ''}${player.id === socket.id ? ' (You)' : ''}</strong>
<div class="bullets">Bullets: ${player.bulletSlots}/6</div>
`;
playersDiv.appendChild(playerEl);
});
// If host, show start game button
if (isHost && room.status === 'waiting') {
if (!document.getElementById('startGameBtn')) {
const startGameBtn = document.createElement('button');
startGameBtn.id = 'startGameBtn';
startGameBtn.textContent = 'Start Game';
startGameBtn.style.padding = '10px 20px';
startGameBtn.style.border = 'none';
startGameBtn.style.borderRadius = '5px';
startGameBtn.style.cursor = 'pointer';
startGameBtn.style.background = '#2196F3';
startGameBtn.style.color = 'white';
startGameBtn.style.marginTop = '10px';
startGameBtn.onclick = () => {
socket.emit('startGame', currentRoomId, (response) => {
if (!response.success) {
alert(response.message);
}
});
};
roomManagement.appendChild(startGameBtn);
}
}
};
// Update Game UI
const updateGameUI = (room) => {
playersDiv.innerHTML = '';
room.players.forEach(player => {
const playerEl = document.createElement('div');
playerEl.className = `player ${player.id === socket.id ? 'active' : ''} ${player.isEliminated ? 'eliminated' : ''}`;
playerEl.innerHTML = `
<strong>${player.name}${player.isHost ? ' (Host)' : ''}${player.id === socket.id ? ' (You)' : ''}</strong>
<div class="bullets">Bullets: ${player.bulletSlots}/6</div>
`;
playersDiv.appendChild(playerEl);
});
// Update Core Card
if (room.coreCard) {
coreCardSpan.innerHTML = createCardHTML(room.coreCard);
} else {
coreCardSpan.textContent = '-';
}
// Update Last Played
if (room.lastPlayedCards.length > 0) {
lastPlayedSpan.textContent = `${room.lastPlayedCards.length} card(s) played as ${room.coreCard.value}${room.coreCard.suit}`;
} else {
lastPlayedSpan.textContent = 'None';
}
// Update Central Table
centralTable.innerHTML = '';
room.centralTableCards.forEach((cardObj, index) => {
const cardEl = document.createElement('div');
cardEl.className = `card ${cardObj.revealed ? getSuitClass(cardObj.card.suit) : 'back'}`;
if (cardObj.revealed) {
cardEl.innerHTML = `${cardObj.card.value}${cardObj.card.suit}`;
cardEl.style.color = getColor(cardObj.card.suit);
} else {
cardEl.innerHTML = '🂠';
}
centralTable.appendChild(cardEl);
});
// Update Current Player's Hand
if (room.players.find(p => p.id === socket.id)) {
const me = room.players.find(p => p.id === socket.id);
currentHand.innerHTML = '';
me.hand.forEach((card, index) => {
const cardEl = document.createElement('div');
cardEl.className = `card ${getSuitClass(card.suit)}`;
cardEl.style.color = getColor(card.suit);
cardEl.dataset.index = index;
cardEl.innerHTML = `${card.value}${card.suit}`;
cardEl.onclick = () => {
cardEl.classList.toggle('selected');
if (selectedCardIndices.includes(index)) {
selectedCardIndices = selectedCardIndices.filter(i => i !== index);
} else {
selectedCardIndices.push(index);
}
};
currentHand.appendChild(cardEl);
});
}
// Determine if it's the player's turn
const currentPlayer = room.players[room.currentPlayerIndex];
const isMyTurn = currentPlayer.id === socket.id && !room.players.find(p => p.id === socket.id).isEliminated;
// Show or hide action buttons based on turn
playButton.style.display = isMyTurn ? 'inline-block' : 'none';
callBluffButton.style.display = room.lastPlayedCards.length > 0 && !isMyTurn ? 'inline-block' : 'none';
pullTriggerButton.style.display = isMyTurn ? 'inline-block' : 'none';
};
// Play Selected Cards
const playSelectedCards = () => {
if (selectedCardIndices.length === 0) {
alert('Please select at least one card to play.');
return;
}
socket.emit('playCards', { roomId: currentRoomId, selectedCardIndices }, (response) => {
if (!response.success) {
alert(response.message);
} else {
// Clear selected cards
selectedCardIndices = [];
}
});
};
// Call Bluff
const callBluff = () => {
socket.emit('callBluff', currentRoomId, (response) => {
if (!response.success) {
alert(response.message);
}
});
};
// Pull Trigger
const pullTrigger = () => {
socket.emit('pullTrigger', currentRoomId, (response) => {
if (!response.success) {
alert(response.message);
}
});
};
// Helper Functions
const createCardHTML = (card) => {
const color = getColor(card.suit);
return `<span style="color: ${color}; font-size: 1em;">${card.value}${card.suit}</span>`;
};
const getSuitClass = (suit) => {
return suit === '♠' ? 'spades' :
suit === '♣' ? 'clubs' :
suit === '♥' ? 'hearts' :
'diamonds';
};
const getColor = (suit) => {
return (suit === '♥' || suit === '♦') ? 'red' : 'black';
};
</script>
</body>
</html>
Explanation:
-
Room Management UI: Users can enter their name, create a room, or join an existing room using a room ID.
-
Socket.io Client Connection: The client connects to the server at http://localhost:3000. Adjust this URL if your server is hosted elsewhere.
-
Socket.io Events:
createRoom: Emitted when a user creates a room. The server responds with the room ID.
joinRoom: Emitted when a user joins a room using a room ID.
roomUpdate: Receives updates about the room (e.g., players joining).
gameStarted: Indicates the game has started.
gameUpdate: Receives updates about the game state.
gameEnded: Notifies clients when the game has ended and announces the winner.
-
Game UI Updates: The client updates the UI based on the received game state, including player statuses, hands, and central table cards.
-
Player Actions:
- Play Cards: Select cards from the hand and emit
playCards to the server.
- Call Bluff: Emit
callBluff to challenge the last played cards.
- Pull Trigger: For the Russian Roulette mechanic, emit
pullTrigger.
-
Card Selection: Players can click on their cards to select/deselect them for play.
-
Visibility of Actions: The Play, Call Bluff, and Pull Trigger buttons are shown or hidden based on the player's turn and game state.
Final Notes
This setup provides a foundational structure for a real-time multiplayer card game. Depending on your specific game mechanics and additional features, you might need to extend or modify the server and client code. Always ensure that your server validates all actions to prevent cheating or invalid game states.
For scalability and better performance, consider migrating from file-based storage (rooms.json) to a database system like MongoDB, especially if you expect a large number of concurrent games and players.
Happy coding, and enjoy your multiplayer card game development!