Transforming your single-player game into a real-time multiplayer experience involves several key steps. Below, I'll guide you through removing the robot players, setting up an Express.js server with WebSocket (using Socket.io) for real-time communication, managing game state with a JSON file, and updating your index.html to interact with the server.
Overview
- Remove Robot Players from Client-Side Logic
- Set Up an Express.js Server with Socket.io
- Manage Game State Using a JSON File
- Update
index.html to Support Room Creation and Joining
- Handle Real-Time Game Interactions
1. Remove Robot Players from Client-Side Logic
First, you'll need to modify your existing index.html to remove all robot player logic. This includes removing any code that initializes robot players and their actions.
Changes in index.html
-
Remove Robot Initialization:
// Remove robot initialization from the Game class
initializePlayers() {
this.players = [];
this.players.push(new Player(0, 'You', true));
// Removed robot players
}
-
Remove Robot Decision Logic:
// Remove or comment out the robotDecide and robotPlay methods
// These methods are no longer needed as all players will be human
-
Update the Render Method:
Ensure that only human players' hands are rendered and interactable.
2. Set Up an Express.js Server with Socket.io
The server will handle room management, player connections, game states, and real-time communication between clients.
Server Setup
-
Initialize the Project:
mkdir card-bluff-shoot
cd card-bluff-shoot
npm init -y
npm install express socket.io uuid fs
-
Create Server File (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');
const path = require('path');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
const PORT = process.env.PORT || 3000;
const DATA_FILE = path.join(__dirname, 'rooms.json');
// Initialize rooms data
let rooms = {};
// Load existing rooms from JSON file if exists
if (fs.existsSync(DATA_FILE)) {
const data = fs.readFileSync(DATA_FILE);
rooms = JSON.parse(data);
}
// Save rooms to JSON file
const saveRooms = () => {
fs.writeFileSync(DATA_FILE, JSON.stringify(rooms, null, 2));
};
// Serve static files
app.use(express.static(path.join(__dirname, 'public')));
io.on('connection', (socket) => {
console.log('A user connected:', socket.id);
// Handle room creation
socket.on('createRoom', (username, callback) => {
const roomId = uuidv4();
rooms[roomId] = {
id: roomId,
players: [{
id: socket.id,
name: username,
hand: [],
bulletSlots: 6,
isEliminated: false,
isHost: true
}],
gameStarted: false,
coreCard: null,
lastPlayedCards: [],
centralTableCards: [],
};
socket.join(roomId);
saveRooms();
callback({ status: 'ok', roomId });
io.to(roomId).emit('roomUpdate', rooms[roomId]);
});
// Handle joining a room
socket.on('joinRoom', ({ roomId, username }, callback) => {
const room = rooms[roomId];
if (!room) {
return callback({ status: 'error', message: 'Room not found.' });
}
if (room.gameStarted) {
return callback({ status: 'error', message: 'Game already started.' });
}
if (room.players.length >= 5) { // Maximum 5 players
return callback({ status: 'error', message: 'Room is full.' });
}
room.players.push({
id: socket.id,
name: username,
hand: [],
bulletSlots: 6,
isEliminated: false,
isHost: false
});
socket.join(roomId);
saveRooms();
callback({ status: 'ok', roomId });
io.to(roomId).emit('roomUpdate', room);
});
// Handle starting the game
socket.on('startGame', (roomId, callback) => {
const room = rooms[roomId];
if (!room) {
return callback({ status: 'error', message: 'Room not found.' });
}
const host = room.players.find(p => p.isHost);
if (host.id !== socket.id) {
return callback({ status: 'error', message: 'Only the host can start the game.' });
}
room.gameStarted = true;
initializeGame(room);
saveRooms();
io.to(roomId).emit('gameStarted', room);
callback({ status: 'ok' });
});
// Handle player actions (e.g., play cards, call bluff)
socket.on('playerAction', ({ roomId, action, data }, callback) => {
const room = rooms[roomId];
if (!room || !room.gameStarted) {
return callback({ status: 'error', message: 'Invalid game state.' });
}
// Handle different actions
// TODO: Implement game logic on the server
// For example:
// if (action === 'playCards') { ... }
// After handling, emit updated room state
saveRooms();
io.to(roomId).emit('gameUpdate', room);
callback({ status: 'ok' });
});
// Handle disconnection
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id);
// Remove player from any room they are in
for (const 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);
// If the host left, assign a new host
if (room.players.length > 0 && room.players[0].isHost === false) {
room.players[0].isHost = true;
}
// If room is empty, delete it
if (room.players.length === 0) {
delete rooms[roomId];
}
saveRooms();
io.to(roomId).emit('roomUpdate', room);
break;
}
}
});
});
// Function to initialize game (shuffle deck, deal cards, set core card)
const initializeGame = (room) => {
const deck = createDeck();
shuffle(deck);
room.deck = deck;
// Assign core card
room.coreCard = deck.shift();
// Deal 5 cards to each player
room.players.forEach(player => {
player.hand = deck.splice(0, 5);
});
// Initialize other game state
room.currentPlayerIndex = 0;
room.lastPlayedCards = [];
room.centralTableCards = [];
};
// Create a standard deck of cards
const createDeck = () => {
const values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'];
const suits = ['♠', '♥', '♦', '♣'];
const deck = [];
for (let value of values) {
for (let suit of suits) {
deck.push({ value, suit });
}
}
return deck;
};
// Shuffle array using Fisher-Yates
const shuffle = (array) => {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
};
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
-
Create a rooms.json File:
This file will store all room data. Ensure it's in the same directory as server.js.
touch rooms.json
Initialize it with an empty object:
{}
-
Organize Directory Structure:
card-bluff-shoot/
│
├── server.js
├── rooms.json
├── package.json
└── public/
└── index.html
The public folder will contain your updated index.html and any client-side JavaScript.
3. Manage Game State Using a JSON File
The server uses a rooms.json file to persist room data. Each room will have the following structure:
{
"roomId": {
"id": "roomId",
"players": [
{
"id": "socketId",
"name": "Player Name",
"hand": [],
"bulletSlots": 6,
"isEliminated": false,
"isHost": true
}
// More players...
],
"gameStarted": false,
"coreCard": null,
"lastPlayedCards": [],
"centralTableCards": [],
"deck": [],
"currentPlayerIndex": 0
}
// More rooms...
}
Note: Managing game state on the server ensures synchronization between all connected clients.
4. Update index.html to Support Room Creation and Joining
Update your client-side index.html to interact with the server via Socket.io. This includes:
- Creating or joining a room
- Displaying the waiting room with real-time updates
- Starting the game
- Handling game actions
Updated index.html
Place the following index.html inside the public folder.
<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Card Bluff & Shoot - Multiplayer</title>
<style>
/* Include your existing styles here */
body {
margin: 0;
padding: 20px;
background: #1a1a1a;
color: white;
font-family: Arial, sans-serif;
}
.hidden {
display: none;
}
.room-section, .game-container {
display: none;
}
.active-section {
display: block;
}
/* Add additional styles as needed */
</style>
</head>
<body>
<!-- Room Selection Section -->
<div class="room-selection active-section" id="roomSelection">
<h2>Card Bluff & Shoot</h2>
<input type="text" id="usernameInput" placeholder="Enter your name" required>
<div>
<button onclick="createRoom()">Create Room</button>
</div>
<h3>OR</h3>
<input type="text" id="roomIdInput" placeholder="Enter Room ID">
<input type="text" id="joinUsernameInput" placeholder="Enter your name">
<div>
<button onclick="joinRoom()">Join Room</button>
</div>
<div id="roomError" style="color: red;"></div>
</div>
<!-- Waiting Room Section -->
<div class="room-section" id="roomSection">
<h2>Room ID: <span id="currentRoomId"></span></h2>
<h3>Players:</h3>
<ul id="playerList"></ul>
<button id="startGameButton" onclick="startGame()">Start Game</button>
</div>
<!-- Game Container -->
<div class="game-container" 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>
</div>
</div>
</div>
<div class="overlay" id="shootingOverlay">
<h2>🎲 Russian Roulette Time! 🔫</h2>
<button onclick="pullTrigger()" style="padding: 15px 30px; font-size: 1em;">Pull Trigger</button>
</div>
<div id="debugControls" style="display:none;">
<button onclick="startNewGame()">New Game</button>
</div>
<!-- Include Socket.io -->
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
let currentRoomId = null;
let username = null;
let playerId = null;
let gameState = null;
// Room Selection Handlers
const createRoom = () => {
const name = document.getElementById('usernameInput').value.trim();
if (!name) {
alert('Please enter your name.');
return;
}
socket.emit('createRoom', name, (response) => {
if (response.status === 'ok') {
currentRoomId = response.roomId;
username = name;
showRoomSection();
} else {
alert('Error creating room.');
}
});
};
const joinRoom = () => {
const roomId = document.getElementById('roomIdInput').value.trim();
const name = document.getElementById('joinUsernameInput').value.trim();
if (!roomId || !name) {
alert('Please enter both Room ID and your name.');
return;
}
socket.emit('joinRoom', { roomId, username: name }, (response) => {
if (response.status === 'ok') {
currentRoomId = response.roomId;
username = name;
showRoomSection();
} else {
document.getElementById('roomError').innerText = response.message;
}
});
};
const showRoomSection = () => {
document.getElementById('roomSelection').classList.remove('active-section');
document.getElementById('roomSection').classList.add('active-section');
document.getElementById('currentRoomId').innerText = currentRoomId;
};
// Update Player List in Room
socket.on('roomUpdate', (room) => {
gameState = room;
const playerList = document.getElementById('playerList');
playerList.innerHTML = '';
room.players.forEach(player => {
const li = document.createElement('li');
li.innerText = `${player.name}${player.isHost ? ' (Host)' : ''}`;
playerList.appendChild(li);
});
// Show start button if host
const startButton = document.getElementById('startGameButton');
if (room.players.find(p => p.id === socket.id && p.isHost)) {
startButton.style.display = 'block';
} else {
startButton.style.display = 'none';
}
});
// Start Game Handler
const startGame = () => {
socket.emit('startGame', currentRoomId, (response) => {
if (response.status === 'ok') {
// Game will start via 'gameStarted' event
} else {
alert(response.message);
}
});
};
// Handle Game Started
socket.on('gameStarted', (room) => {
gameState = room;
switchToGameContainer();
renderGame();
});
// Switch to Game Container
const switchToGameContainer = () => {
document.getElementById('roomSection').classList.remove('active-section');
document.getElementById('gameContainer').classList.add('active-section');
};
// Game Rendering
const renderGame = () => {
// Render players
const playersContainer = document.getElementById('players');
playersContainer.innerHTML = '';
gameState.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.id === socket.id ? ' (You)' : ''}</strong>
<div class="bullets">Bullets: ${player.bulletSlots}/6</div>
`;
playersContainer.appendChild(playerEl);
});
// Render core card
const coreCardSpan = document.getElementById('coreCard');
if (gameState.coreCard) {
coreCardSpan.innerHTML = createCardHTML(gameState.coreCard);
} else {
coreCardSpan.textContent = '-';
}
// Render last played
const lastPlayedSpan = document.getElementById('lastPlayed');
if (gameState.lastPlayedCards.length > 0) {
lastPlayedSpan.textContent = `${gameState.lastPlayedCards.length} card(s) played as ${gameState.coreCard.value}${gameState.coreCard.suit}`;
} else {
lastPlayedSpan.textContent = 'None';
}
// Render central table
const centralTable = document.getElementById('centralTable');
centralTable.innerHTML = '';
gameState.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);
});
// Render current player's hand
const handContainer = document.getElementById('currentHand');
handContainer.innerHTML = '';
const currentPlayer = gameState.players.find(p => p.id === socket.id);
if (currentPlayer && !currentPlayer.isEliminated) {
currentPlayer.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');
};
handContainer.appendChild(cardEl);
});
}
// Enable/Disable buttons based on game state
const isYourTurn = gameState.currentPlayerId === socket.id;
const currentPlayerObj = gameState.players.find(p => p.id === socket.id);
document.getElementById('playButton').disabled = !isYourTurn || currentPlayerObj.hand.length === 0;
document.getElementById('callBluffButton').disabled = gameState.lastPlayedCards.length === 0 || !isYourTurn;
};
// Helper Functions
const getSuitClass = (suit) => {
return suit === '♠' ? 'spades' :
suit === '♣' ? 'clubs' :
suit === '♥' ? 'hearts' :
'diamonds';
};
const getColor = (suit) => {
return (suit === '♥' || suit === '♦') ? 'red' : 'black';
};
const createCardHTML = (card) => {
const color = getColor(card.suit);
return `<span style="color: ${color}; font-size: 1em;">${card.value}${card.suit}</span>`;
};
// Play Selected Cards
const playSelectedCards = () => {
const selectedCards = Array.from(document.querySelectorAll('.card.selected')).map(el => parseInt(el.dataset.index));
if (selectedCards.length === 0) {
alert('Please select at least one card to play.');
return;
}
// Prepare the selected cards
const playCards = selectedCards.map(index => gameState.players.find(p => p.id === socket.id).hand[index]);
// Emit playCards action
socket.emit('playerAction', { roomId: currentRoomId, action: 'playCards', data: { cards: playCards } }, (response) => {
if (response.status !== 'ok') {
alert(response.message);
}
});
};
// Call Bluff
const callBluff = () => {
socket.emit('playerAction', { roomId: currentRoomId, action: 'callBluff', data: {} }, (response) => {
if (response.status !== 'ok') {
alert(response.message);
}
});
};
// Pull Trigger (Shooting)
const pullTrigger = () => {
socket.emit('playerAction', { roomId: currentRoomId, action: 'pullTrigger', data: {} }, (response) => {
if (response.status !== 'ok') {
alert(response.message);
}
});
document.getElementById('shootingOverlay').classList.remove('active');
};
// Update Game State in Real-Time
socket.on('gameUpdate', (room) => {
gameState = room;
renderGame();
});
// Handle Game Over or Other Notifications
// You can implement additional socket events as needed
</script>
</body>
</html>
Explanation of Changes
-
Room Selection Section:
- Allows users to create or join a room by entering their name and room ID.
-
Waiting Room Section:
- Displays the list of players in the room.
- The host can start the game when ready.
-
Game Container:
- Displays the game state, including players, core card, last played cards, and the central table.
- Players can play selected cards or call bluff.
-
Socket.io Integration:
- Establishes a connection with the server.
- Handles events like
createRoom, joinRoom, startGame, and playerAction.
- Updates the UI in real-time based on server events.
5. Handle Real-Time Game Interactions
To ensure smooth gameplay, the server needs to handle various game actions and update all clients accordingly. Below are additional implementations to handle game logic.
Extending server.js for Game Logic
Update your server.js to handle game actions like playCards, callBluff, and pullTrigger.
// Inside server.js (continued from previous code)
// Handle player actions
socket.on('playerAction', ({ roomId, action, data }, callback) => {
const room = rooms[roomId];
if (!room || !room.gameStarted) {
return callback({ status: 'error', message: 'Invalid game state.' });
}
const player = room.players.find(p => p.id === socket.id);
if (!player || player.isEliminated) {
return callback({ status: 'error', message: 'Invalid player.' });
}
if (room.players[room.currentPlayerIndex].id !== socket.id) {
return callback({ status: 'error', message: 'Not your turn.' });
}
switch (action) {
case 'playCards':
if (!data.cards || data.cards.length === 0) {
return callback({ status: 'error', message: 'No cards selected.' });
}
// Validate that played cards match core card
const allMatch = data.cards.every(card => card.value === room.coreCard.value);
if (!allMatch) {
// Player is bluffing
room.lastPlayedCards = data.cards;
room.centralTableCards.push(...data.cards.map(card => ({ card, revealed: false })));
// Trigger shooting overlay
io.to(roomId).emit('shooting', { playerId: socket.id });
} else {
// Player played honestly
room.lastPlayedCards = data.cards;
room.centralTableCards.push(...data.cards.map(card => ({ card, revealed: true })));
nextTurn(room);
}
break;
case 'callBluff':
if (room.lastPlayedCards.length === 0) {
return callback({ status: 'error', message: 'No cards to call bluff on.' });
}
// Determine if the last play was a bluff
const lastPlayer = room.players[(room.currentPlayerIndex - 1 + room.players.length) % room.players.length];
const wasBluff = !room.lastPlayedCards.every(card => card.value === room.coreCard.value);
if (wasBluff) {
// Last player was bluffing
lastPlayer.isEliminated = true;
io.to(roomId).emit('playerEliminated', { playerId: lastPlayer.id, name: lastPlayer.name });
} else {
// Last player was honest, caller is penalized
player.isEliminated = true;
io.to(roomId).emit('playerEliminated', { playerId: player.id, name: player.name });
}
// Start a new round
room.lastPlayedCards = [];
room.centralTableCards = [];
room.coreCard = null;
initializeGame(room);
io.to(roomId).emit('gameUpdate', room);
break;
case 'pullTrigger':
// Implement Russian Roulette logic
const chance = 1 / player.bulletSlots;
const hit = Math.random() < chance;
if (hit) {
player.isEliminated = true;
io.to(roomId).emit('playerEliminated', { playerId: player.id, name: player.name });
// Check for game over
const remainingPlayers = room.players.filter(p => !p.isEliminated);
if (remainingPlayers.length === 1) {
io.to(roomId).emit('gameOver', { winner: remainingPlayers[0].name });
room.gameStarted = false;
}
} else {
player.bulletSlots--;
}
// Next turn
nextTurn(room);
io.to(roomId).emit('gameUpdate', room);
break;
default:
return callback({ status: 'error', message: 'Unknown action.' });
}
saveRooms();
io.to(roomId).emit('gameUpdate', room);
callback({ status: 'ok' });
});
// Helper function to advance to the next player's turn
const nextTurn = (room) => {
room.currentPlayerIndex = (room.currentPlayerIndex + 1) % room.players.length;
// Skip eliminated players
while (room.players[room.currentPlayerIndex].isEliminated) {
room.currentPlayerIndex = (room.currentPlayerIndex + 1) % room.players.length;
}
};
// Handle shooting overlay (notify players)
socket.on('shooting', ({ roomId }) => {
io.to(socket.id).emit('shooting', {});
});
Explanation of Changes
-
playCards Action:
- Validates if the played cards match the core card value.
- If not, it's considered a bluff, and the shooting overlay is triggered.
-
callBluff Action:
- Determines if the last play was a bluff.
- Eliminates the appropriate player based on the bluff.
- Checks for game over conditions.
-
pullTrigger Action:
- Simulates the Russian Roulette mechanism.
- Eliminates players based on random chance.
- Advances the turn to the next player.
-
nextTurn Function:
- Moves the turn to the next active player.
Final Notes
-
Security Considerations:
- This implementation is basic and lacks security measures. For a production environment, consider implementing authentication, validating all client inputs, and handling edge cases diligently.
-
Scalability:
- Using a JSON file for storing game state is not scalable for a large number of rooms or players. Consider using a database like MongoDB or Redis for better performance and scalability.
-
Enhanced Features:
- Add more game features such as chat, player avatars, game timers, etc., to enhance user experience.
-
Error Handling:
- Implement comprehensive error handling on both client and server sides to ensure smooth gameplay.
-
Testing:
- Thoroughly test the game with multiple players to identify and fix any bugs or synchronization issues.
By following these steps, you'll have transformed your single-player game into a real-time multiplayer experience with room management, player interactions, and synchronized game states. Happy coding!