class Game {
constructor(roomId, players) {
this.roomId = roomId;
this.players = players; // Array of Player objects
this.currentPlayerIndex = 0;
this.coreCard = null;
this.lastPlayedCards = [];
this.deck = [];
this.isGameOver = false;
this.centralTableCards = [];
this.shootingPlayer = null; // Player object
this.initializeDeck();
this.shuffleDeck();
this.dealCards();
}
initializeDeck() {
const values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'];
const suits = ['♠', '♥', '♦', '♣'];
this.deck = [];
for (let value of values) {
for (let suit of suits) {
this.deck.push(new Card(value, suit));
}
}
}
shuffleDeck() {
for (let i = this.deck.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[this.deck[i], this.deck[j]] = [this.deck[j], this.deck[i]];
}
}
dealCards() {
// Assign a core card
if (this.deck.length === 0) {
throw new Error('Deck is empty. Cannot deal cards.');
}
this.coreCard = this.deck.shift();
// Deal 5 cards to each player
this.players.forEach(player => {
for (let i = 0; i < 5; i++) {
if (this.deck.length > 0) {
player.hand.push(this.deck.shift());
}
}
});
}
getCurrentPlayer() {
return this.players[this.currentPlayerIndex];
}
nextPlayer() {
if (this.isGameOver) return;
let attempts = 0;
do {
this.currentPlayerIndex = (this.currentPlayerIndex + 1) % this.players.length;
attempts++;
if (attempts > this.players.length) break; // Prevent infinite loop
} while (this.getCurrentPlayer().isEliminated);
}
getGameState(requestingPlayerId) {
return {
roomId: this.roomId,
players: this.players.map(player => ({
id: player.id,
username: player.username,
isEliminated: player.isEliminated,
bulletSlots: player.bulletSlots,
// Only send hand to the requesting player
hand: player.id === requestingPlayerId ? player.hand.map(card => card.toString()) : undefined
})),
currentPlayer: this.getCurrentPlayer().username,
coreCard: this.coreCard ? this.coreCard.toString() : '-',
lastPlayedCount: this.lastPlayedCards.length, // Only send count, not actual cards
centralTableCards: this.centralTableCards.map(cardObj => ({
card: cardObj.card.toString(),
revealed: cardObj.revealed
})),
isGameOver: this.isGameOver
};
}
// Assign a new core card for the next round
assignNewCoreCard() {
if (this.deck.length === 0) {
// Reshuffle central table cards back into the deck if needed
this.deck = this.centralTableCards.map(cardObj => cardObj.card);
this.shuffleDeck();
this.centralTableCards = [];
}
if (this.deck.length > 0) {
this.coreCard = this.deck.shift();
} else {
// If deck is still empty, set coreCard to null (shouldn't happen with proper deck management)
this.coreCard = null;
}
}
Assistant
I acknowledge the game you've provided, which includes both server-side and client-side code for a multiplayer card game implemented using Node.js, Express, WebSocket, and HTML/CSS. I have developed a detailed mental model of the overall engine and am ready to assist you with any instructions or questions you have.
}
// Initialize Express server
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
// Serve static files from 'public' directory
app.use(express.static('public'));
// Define the single room ID
const ROOM_ID = 'ABC123';
// Initialize the room
const room = {
id: ROOM_ID,
creator: null, // Will be set to the first player
players: [], // Array of Player objects
isStarted: false
};
// Initialize games
let currentGame = null;
// Handle WebSocket connections
wss.on('connection', (ws) => {
ws.id = uuidv4(); // Assign a unique ID to each connection
ws.on('message', (message) => {
let data;
try {
data = JSON.parse(message);
} catch (e) {
ws.send(JSON.stringify({ type: 'ERROR', message: 'Invalid JSON' }));
return;
}
switch (data.type) {
case 'JOIN_ROOM':
handleJoinRoom(ws, data);
break;
case 'START_GAME':
handleStartGame(ws, data);
break;
case 'PLAY_CARDS':
handlePlayCards(ws, data);
break;
case 'CALL_BLUFF':
handleCallBluff(ws, data);
break;
case 'PULL_TRIGGER':
handlePullTrigger(ws, data);
break;
case 'RESET_ROOM':
handleResetRoom(ws, data);
break;
default:
ws.send(JSON.stringify({ type: 'ERROR', message: 'Unknown command' }));
}
});
ws.on('close', () => {
handleDisconnect(ws);
});
});
// Handle joining the room
function handleJoinRoom(ws, data) {
const username = data.username;
const dataRoomId = data.roomId;
if (!username) {
ws.send(JSON.stringify({ type: 'ERROR', message: 'Username is required to join the room' }));
return;
}
// Validate room ID
if (dataRoomId !== ROOM_ID) {
ws.send(JSON.stringify({ type: 'ERROR', message: 'Room not found' }));
return;
}
if (room.isStarted) {
ws.send(JSON.stringify({ type: 'ERROR', message: 'Game already started in this room. Please wait for the next round.' }));
return;
}
if (room.players.length >= 5) { // Assuming max 5 players
ws.send(JSON.stringify({ type: 'ERROR', message: 'Room is full' }));
return;
}
const playerId = uuidv4();
const player = new Player(playerId, username, ws);
room.players.push(player);
ws.roomId = room.id;
ws.playerId = playerId;
// Assign creator if first player
let isCreator = false;
if (room.creator === null) {
room.creator = playerId;
isCreator = true;
}
// Notify all players in the room about the new player and current creator
broadcastToRoom(room.id, {
type: 'PLAYER_JOINED',
players: room.players.map(p => p.username),
creator: isCreator ? player.username : getPlayerById(room.creator).username
});
// If the new player is the creator, send a separate message
if (isCreator) {
ws.send(JSON.stringify({ type: 'CREATOR', isCreator: true }));
}
}
// Handle starting the game
function handleStartGame(ws, data) {
const roomId = ws.roomId;
const playerId = ws.playerId;
if (roomId !== ROOM_ID) {
ws.send(JSON.stringify({ type: 'ERROR', message: 'Invalid room' }));
return;
}
if (room.creator !== playerId) {
ws.send(JSON.stringify({ type: 'ERROR', message: 'Only the room creator can start the game' }));
return;
}
if (room.isStarted) {
ws.send(JSON.stringify({ type: 'ERROR', message: 'Game already started' }));
return;
}
if (room.players.length < 2) {
ws.send(JSON.stringify({ type: 'ERROR', message: 'At least two players are required to start the game' }));
return;
}
try {
// Initialize game
currentGame = new Game(roomId, room.players);
room.isStarted = true;
} catch (error) {
ws.send(JSON.stringify({ type: 'ERROR', message: error.message }));
return;
}
// Broadcast game start and initial game state to all players
room.players.forEach(player => {
player.ws.send(JSON.stringify({
type: 'GAME_STARTED',
gameState: currentGame.getGameState(player.id),
hand: player.hand.map(card => card.toString())
}));
});
}
// Handle playing cards
function handlePlayCards(ws, data) {
if (!currentGame || currentGame.isGameOver) {
ws.send(JSON.stringify({ type: 'ERROR', message: 'Game not found or already over' }));
return;
}
const playerId = ws.playerId;
const selectedIndices = data.selectedIndices; // Array of indices
const player = currentGame.players.find(p => p.id === playerId);
if (!player) {
ws.send(JSON.stringify({ type: 'ERROR', message: 'Player not found in the game' }));
return;
}
if (currentGame.getCurrentPlayer().id !== playerId) {
ws.send(JSON.stringify({ type: 'ERROR', message: 'Not your turn' }));
return;
}
if (!Array.isArray(selectedIndices) || selectedIndices.length === 0) {
ws.send(JSON.stringify({ type: 'ERROR', message: 'No cards selected' }));
return;
}
// Validate selected indices
if (selectedIndices.some(index => index < 0 || index >= player.hand.length)) {
ws.send(JSON.stringify({ type: 'ERROR', message: 'Invalid card indices' }));
return;
}
// Get selected cards
const selectedCards = selectedIndices.map(index => player.hand[index]);
// Remove selected cards from player's hand (reverse sort to remove from higher index to lower)
selectedIndices.sort((a, b) => b - a);
selectedIndices.forEach(index => {
player.hand.splice(index, 1);
});
// Update game state's last played cards
currentGame.lastPlayedCards = selectedCards;
// **Reset the central table to only hold the latest played cards**
currentGame.centralTableCards = []; // Clear previous cards
// Add to central table as face-down
selectedCards.forEach(card => {
currentGame.centralTableCards.push({
card: card,
revealed: false
});
});
// Broadcast game state to all players
broadcastGameState(room.id);
// Move to next player
currentGame.nextPlayer();
// Broadcast updated game state after moving the turn
broadcastGameState(room.id);
}
// Handle calling bluff
function handleCallBluff(ws, data) {
if (!currentGame || currentGame.isGameOver) {
ws.send(JSON.stringify({ type: 'ERROR', message: 'Game not found or already over' }));
return;
}
const playerId = ws.playerId;
const caller = currentGame.players.find(p => p.id === playerId);
if (!caller) {
ws.send(JSON.stringify({ type: 'ERROR', message: 'Player not found in the game' }));
return;
}
// Cannot call bluff if no one has played yet
if (currentGame.lastPlayedCards.length === 0) {
ws.send(JSON.stringify({ type: 'ERROR', message: 'No cards have been played yet' }));
return;
}
// Determine if the last played cards are a bluff
// Assuming in this game, players must play the coreCard value
const coreCard = currentGame.coreCard;
if (!coreCard) {
ws.send(JSON.stringify({ type: 'ERROR', message: 'Core card is not set' }));
return;
}
const actual = currentGame.lastPlayedCards.every(card => card.value === coreCard.value);
if (!actual) {
// Bluff was called, and player who played the last cards was bluffing
const lastPlayerIndex = (currentGame.currentPlayerIndex - 1 + currentGame.players.length) % currentGame.players.length;
const lastPlayer = currentGame.players[lastPlayerIndex];
lastPlayer.bulletSlots -= 1;
// Check if player is eliminated
const isEliminated = lastPlayer.bulletSlots <= 0;
if (isEliminated) {
lastPlayer.isEliminated = true;
}
// Notify all players about the result
broadcastToRoom(room.id, {
type: 'BLUFF_RESULT',
result: 'PLAYER_BLUFFED',
player: lastPlayer.username,
bulletSlots: lastPlayer.bulletSlots,
isEliminated: isEliminated,
centralTableCards: currentGame.centralTableCards.map(cardObj => ({
card: cardObj.card.toString(),
revealed: true // Reveal the cards
})),
coreCard: coreCard.toString()
});
// **Set shootingPlayer to the last player who bluffed**
currentGame.shootingPlayer = lastPlayer;
// Do not clear played cards and central table here
// currentGame.lastPlayedCards = [];
// currentGame.centralTableCards = [];
// Do not assign a new core card here; wait until after the shot is resolved
} else {
// Bluff was called, but it was not a bluff
caller.bulletSlots -= 1;
// Check if caller is eliminated
const isEliminated = caller.bulletSlots <= 0;
if (isEliminated) {
caller.isEliminated = true;
}
// Notify all players about the result
broadcastToRoom(room.id, {
type: 'BLUFF_RESULT',
result: 'PLAYER_NOT_BLUFFED',
player: caller.username,
bulletSlots: caller.bulletSlots,
isEliminated: isEliminated,
centralTableCards: currentGame.centralTableCards.map(cardObj => ({
card: cardObj.card.toString(),
revealed: true // Reveal the cards
})),
coreCard: coreCard.toString()
});
// **Set shootingPlayer to the caller who called a false bluff**
currentGame.shootingPlayer = caller;
// Do not clear played cards and central table here
// currentGame.lastPlayedCards = [];
// currentGame.centralTableCards = [];
// Do not assign a new core card here; wait until after the shot is resolved
}
// No longer assign a new core card or clear centralTableCards here
// The shot overlay will handle the next steps
}
// Handle pulling trigger
function handlePullTrigger(ws, data) {
if (!currentGame || currentGame.isGameOver) {
ws.send(JSON.stringify({ type: 'ERROR', message: 'Game not found or already over' }));
return;
}
const playerId = ws.playerId;
if (!currentGame.shootingPlayer) {
ws.send(JSON.stringify({ type: 'ERROR', message: 'No shooting action pending' }));
return;
}
const shootingPlayer = currentGame.shootingPlayer;
// **Ensure that only the shooting player can pull the trigger**
if (shootingPlayer.id !== playerId) {
ws.send(JSON.stringify({ type: 'ERROR', message: 'You are not authorized to pull the trigger' }));
return;
}
// Pull the trigger: determine if the player is shot
const bulletChance = 1 / shootingPlayer.bulletSlots;
const shot = Math.random() < bulletChance;
if (shot) {
shootingPlayer.bulletSlots -= 1;
shootingPlayer.isEliminated = true;
broadcastToRoom(room.id, {
type: 'SHOT_RESULT',
result: 'SHOT',
player: shootingPlayer.username,
bulletSlots: shootingPlayer.bulletSlots,
isEliminated: shootingPlayer.isEliminated
});
} else {
shootingPlayer.bulletSlots -= 1;
broadcastToRoom(room.id, {
type: 'SHOT_RESULT',
result: 'SURVIVED',
player: shootingPlayer.username,
bulletSlots: shootingPlayer.bulletSlots,
isEliminated: shootingPlayer.isEliminated
});
}
// Reset shooting player
currentGame.shootingPlayer = null;
// Check if the game is over
const remainingPlayers = currentGame.players.filter(p => !p.isEliminated);
if (remainingPlayers.length === 1) {
currentGame.isGameOver = true;
broadcastToRoom(room.id, {
type: 'GAME_OVER',
winner: remainingPlayers[0].username
});
currentGame = null;
room.isStarted = false;
return;
}
// Reset for next round
// Assign a new core card here after the shot is resolved
currentGame.assignNewCoreCard();
// Move to next player
currentGame.nextPlayer();
// Broadcast updated game state
broadcastGameState(room.id);
// Clear central table cards for the next round
currentGame.centralTableCards = [];
}
// Handle resetting the room
function handleResetRoom(ws, data) {
const playerId = ws.playerId;
if (room.creator !== playerId) {
ws.send(JSON.stringify({ type: 'ERROR', message: 'Only the room creator can reset the room' }));
return;
}
// Reset game state
if (currentGame && !currentGame.isGameOver) {
currentGame.isGameOver = true;
broadcastToRoom(room.id, {
type: 'GAME_OVER',
winner: null,
message: 'Game has been reset by the creator.'
});
currentGame = null;
}
// Reset room state
room.isStarted = false;
// Notify all players to reset
broadcastToRoom(room.id, {
type: 'RESET',
message: 'Room has been reset. You can join again.'
});
// Reset all players' states
room.players.forEach(player => {
player.hand = [];
player.bulletSlots = 6;
player.isEliminated = false;
});
// Broadcast a message to all players in a room
function broadcastToRoom(roomId, message) {
const targetRoom = roomId === ROOM_ID ? room : null;
if (!targetRoom) return;