// server.js
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const { v4: uuidv4 } = require('uuid');
// Define Game Classes
class Card {
constructor(value, suit) {
this.value = value;
this.suit = suit; // '♠', '♥', '♦', '♣'
}
toString() {
return `${this.value}${this.suit}`;
}
getSuitClass() {
switch (this.suit) {
case '♠':
return 'spades';
case '♥':
return 'hearts';
case '♦':
return 'diamonds';
case '♣':
return 'clubs';
default:
return '';
}
}
getColor() {
return (this.suit === '♥' || this.suit === '♦') ? 'red' : 'black';
}
}
class Player {
constructor(id, username, ws) {
this.id = id;
this.username = username;
this.ws = ws;
this.hand = [];
this.bulletSlots = 6;
this.isEliminated = false;
}
}
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;
}
}
}
// 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
// The previous player loses one bullet slot and might get eliminated
// Identify the player who played last
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, including the played cards and core card
broadcastToRoom(room.id, {
type: 'BLUFF_RESULT',
result: 'PLAYER_BLUFFED',
player: lastPlayer.username,
bulletSlots: lastPlayer.bulletSlots,
isEliminated: isEliminated,
centralTableCards: currentGame.centralTableCards.map(cardObj => cardObj.card.toString()),
coreCard: coreCard.toString()
});
// Clear last played cards and central table cards
currentGame.lastPlayedCards = [];
currentGame.centralTableCards = [];
// Assign a new core card for the next round
currentGame.assignNewCoreCard();
// Check if 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;
}
} else {
// Bluff called, but it was not a bluff
// The caller loses one bullet slot and might get eliminated
caller.bulletSlots -= 1;
// Check if caller is eliminated
const isEliminated = caller.bulletSlots <= 0;
if (isEliminated) {
caller.isEliminated = true;
}
// Notify all players about the result, including the played cards and core card
broadcastToRoom(room.id, {
type: 'BLUFF_RESULT',
result: 'PLAYER_NOT_BLUFFED',
player: caller.username,
bulletSlots: caller.bulletSlots,
isEliminated: isEliminated,
centralTableCards: currentGame.centralTableCards.map(cardObj => cardObj.card.toString()),
coreCard: coreCard.toString()
});
// Clear last played cards and central table cards
currentGame.lastPlayedCards = [];
currentGame.centralTableCards = [];
// Assign a new core card for the next round
currentGame.assignNewCoreCard();
// Check if 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;
}
}
// Broadcast updated game state
broadcastGameState(room.id);
}
// 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) {
// The shooting player should be the one who lost the bluff
// Find the shooting player based on who lost the bluff last
// Assuming the last BLUFF_RESULT specifies who lost
// Since the server sent BLUFF_RESULT with 'PLAYER_BLUFFED', we can identify who lost
// Alternatively, maintain a variable to track who lost the last bluff
// For simplicity, we'll assign shootingPlayer based on the last bluffed player
// Here, let's assume that after BLUFF_RESULT, the shootingPlayer is set appropriately
// So, we need to manage this in the server
// However, since the server processes the outcome and not the client,
// it's better to link BLUFF_RESULT to triggering shooting overlay on the client side
// Hence, no need to assign shootingPlayer here, simply process the shooting action
ws.send(JSON.stringify({ type: 'ERROR', message: 'No shooting action pending' }));
return;
}
const shootingPlayer = currentGame.shootingPlayer;
// 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 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
currentGame.lastPlayedCards = [];
currentGame.centralTableCards = [];
currentGame.assignNewCoreCard();
// Move to next player
currentGame.nextPlayer();
// Broadcast updated game state
broadcastGameState(room.id);
}
// 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;
});
}
// Handle disconnects
function handleDisconnect(ws) {
const roomId = ws.roomId;
const playerId = ws.playerId;
if (roomId !== ROOM_ID) return;
const playerIndex = room.players.findIndex(p => p.id === playerId);
if (playerIndex === -1) return;
const player = room.players.splice(playerIndex, 1)[0];
// Notify remaining players
broadcastToRoom(room.id, {
type: 'PLAYER_LEFT',
players: room.players.map(p => p.username)
});
// If game is ongoing, mark player as eliminated
if (currentGame) {
const gamePlayer = currentGame.players.find(p => p.id === playerId);
if (gamePlayer) {
gamePlayer.isEliminated = true;
// Check for game 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;
}
// Broadcast updated game state
broadcastGameState(room.id);
}
}
// If room is empty, reset creator and game state
if (room.players.length === 0) {
room.creator = null;
room.isStarted = false;
currentGame = null;
} else {
// If creator disconnected, assign a new creator
if (room.creator === playerId) {
room.creator = room.players[0].id;
room.players[0].ws.send(JSON.stringify({
type: 'NEW_CREATOR',
newCreator: room.players[0].username
}));
}
}
}
// Broadcast game state to all players in the room
function broadcastGameState(roomId) {
if (!currentGame) return;
room.players.forEach(player => {
player.ws.send(JSON.stringify({
type: 'GAME_UPDATE',
gameState: currentGame.getGameState(player.id)
}));
});
}
// Broadcast a message to all players in a room
function broadcastToRoom(roomId, message) {
const targetRoom = roomId === ROOM_ID ? room : null;
if (!targetRoom) return;
targetRoom.players.forEach(player => {
if (player.ws.readyState === WebSocket.OPEN) {
player.ws.send(JSON.stringify(message));
}
});
}
// Helper function to get a player by ID
function getPlayerById(playerId) {
return room.players.find(p => p.id === playerId);
}
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
The issues you're experiencing stem primarily from how the server manages the "shooting" mechanics and how the client handles the display of the central table cards after a bluff is called. Below, I'll outline the problems and provide detailed steps and code modifications to resolve them.
1. Shooting Mechanism Not Working
Issue:
When you click the "Shoot" button after calling a bluff, an alert appears saying "there's no pending shoot," and the game gets stuck. This happens because the server isn't properly tracking the player who needs to trigger the shoot action (shootingPlayer). As a result, when the client sends a PULL_TRIGGER message, the server responds with an error since it doesn't recognize any pending shoot action.
Solution:
To fix this, you need to ensure that the server correctly identifies and sets the shootingPlayer when a bluff is called. Specifically, after determining whether the bluff was genuine or not, the server should assign the responsible player as the shootingPlayer. Here's how to implement this:
Step-by-Step Fix:
-
Assign shootingPlayer After a Bluff is Called:
- For a Successful Bluff (
PLAYER_BLUFFED): The player who last played the cards (the one who bluffed) should be set as the shootingPlayer.
- For an Unsuccessful Bluff (
PLAYER_NOT_BLUFFED): The player who called the bluff should be set as the shootingPlayer.
-
Update the handleCallBluff Function in server.js:
Modify the handleCallBluff function to set the shootingPlayer appropriately based on the bluff result.
// server.js
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
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 => cardObj.card.toString()),
coreCard: coreCard.toString()
});
// **Set shootingPlayer to the last player who bluffed**
currentGame.shootingPlayer = lastPlayer;
// Clear played cards
currentGame.lastPlayedCards = [];
currentGame.centralTableCards = [];
// Assign a new core card
currentGame.assignNewCoreCard();
// 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;
}
} 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 => cardObj.card.toString()),
coreCard: coreCard.toString()
});
// **Set shootingPlayer to the caller who called a false bluff**
currentGame.shootingPlayer = caller;
// Clear played cards
currentGame.lastPlayedCards = [];
currentGame.centralTableCards = [];
// Assign a new core card
currentGame.assignNewCoreCard();
// 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;
}
}
// Broadcast updated game state
broadcastGameState(room.id);
}
- Modify the
handlePullTrigger Function to Validate Shooter:
Ensure that only the designated shootingPlayer can pull the 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
currentGame.lastPlayedCards = [];
currentGame.centralTableCards = [];
currentGame.assignNewCoreCard();
// Move to next player
currentGame.nextPlayer();
// Broadcast updated game state
broadcastGameState(room.id);
}
- Ensure
shootingPlayer is Reset Appropriately:
After the trigger is pulled and processed, ensure that shootingPlayer is set back to null to avoid unexpected behaviors.
2. Central Table Cards Disappearing Instead of Flipping
Issue:
When calling a bluff, the central table cards should flip to reveal their faces to indicate whether the bluff was genuine. Instead, the cards are disappearing from the table, making it unclear what was played.
Solution:
The client-side handling of the BLUFF_RESULT message needs to correctly render the central table cards by revealing them instead of removing or hiding them. Ensure that when a bluff is called, the client-side correctly receives and displays the card faces based on the server's data.
Step-by-Step Fix:
-
Ensure Server Sends Correct centralTableCards:
The server should send the actual card values in the centralTableCards array within the BLUFF_RESULT message. This seems to be correctly implemented in the server code you provided.
-
Update Client-Side handleBluffResult Function:
Modify the handleBluffResult function to ensure that the central table displays the cards' faces instead of hiding them. Here's an enhanced version that ensures cards are properly revealed:
// index.html (within the <script> tag)
function handleBluffResult(data) {
// Reveal the central table cards with appropriate coloring
const centralTable = document.getElementById('centralTable');
centralTable.innerHTML = '';
const coreCard = data.coreCard;
data.centralTableCards.forEach(cardStr => {
const cardEl = document.createElement('div');
const isMatch = isCardMatch(cardStr, coreCard);
cardEl.className = `card ${getSuitClass(cardStr)}`;
cardEl.style.color = isMatch ? 'green' : 'red';
cardEl.innerHTML = cardStr; // Show the card face
centralTable.appendChild(cardEl);
});
// After 2 seconds, show overlay
setTimeout(() => {
const overlay = document.getElementById('resultOverlay');
const overlayTitle = document.getElementById('overlayTitle');
const overlayMessage = document.getElementById('overlayMessage');
const overlayButton = document.getElementById('overlayButton');
// Determine if the current user is the one who lost the bluff
const lostPlayer = data.player;
const isUser = lostPlayer === username;
if (isUser) {
overlayTitle.textContent = '⛳ You must Trigger the Gun!';
overlayMessage.textContent = 'Click the button below to Pull the Trigger.';
overlayButton.style.display = 'inline-block';
overlayButton.textContent = 'Shoot';
} else {
overlayTitle.textContent = `${lostPlayer} must Trigger the Gun!`;
overlayMessage.textContent = 'Wait for the outcome.';
overlayButton.style.display = 'none';
}
overlay.style.display = 'flex';
}, 2000);
}
-
Ensure Central Table is Not Cleared Prematurely:
Verify that the central table isn't being cleared elsewhere in the client-side code after rendering the cards. Specifically, ensure the centralTable.innerHTML = ''; line is only used to prepare for rendering the new set of cards and isn't being called unintentionally elsewhere.
-
Optional Enhancement - Add Flip Animation:
To improve the user experience, you can add a flip animation when revealing the cards. Here's how you can implement a simple flip effect using CSS and JavaScript:
- Add CSS for Flip Animation:
/* Add this to your <style> section in index.html */
.card-container {
perspective: 1000px;
display: inline-block;
}
.card-inner {
position: relative;
width: 50px;
height: 70px;
text-align: center;
transition: transform 0.6s;
transform-style: preserve-3d;
cursor: pointer;
}
.card.flipped .card-inner {
transform: rotateY(180deg);
}
.card-front, .card-back {
position: absolute;
width: 100%;
height: 100%;
backface-visibility: hidden;
border: 1px solid #000;
border-radius: 5px;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.2em;
}
.card-front {
background-color: #fff;
color: inherit; /* Inherit color for suit */
}
.card-back {
background-color: #333;
color: #333;
transform: rotateY(180deg);
}
- Modify the
handleBluffResult Function to Use Flip Animation:
function handleBluffResult(data) {
// Reveal the central table cards with appropriate coloring
const centralTable = document.getElementById('centralTable');
centralTable.innerHTML = '';
const coreCard = data.coreCard;
data.centralTableCards.forEach(cardStr => {
const cardContainer = document.createElement('div');
cardContainer.className = `card-container`;
const cardInner = document.createElement('div');
cardInner.className = `card-inner`;
const cardFront = document.createElement('div');
cardFront.className = 'card-front';
cardFront.innerHTML = cardStr; // Show the card face
const cardBack = document.createElement('div');
cardBack.className = 'card-back';
cardBack.innerHTML = '🂠'; // Placeholder for card back
cardInner.appendChild(cardFront);
cardInner.appendChild(cardBack);
cardContainer.appendChild(cardInner);
centralTable.appendChild(cardContainer);
// Add a slight delay to trigger the flip animation
setTimeout(() => {
cardContainer.classList.add('flipped');
}, 100);
});
// After 2 seconds, show overlay
setTimeout(() => {
const overlay = document.getElementById('resultOverlay');
const overlayTitle = document.getElementById('overlayTitle');
const overlayMessage = document.getElementById('overlayMessage');
const overlayButton = document.getElementById('overlayButton');
// Determine if the current user is the one who lost the bluff
const lostPlayer = data.player;
const isUser = lostPlayer === username;
if (isUser) {
overlayTitle.textContent = '⛳ You must Trigger the Gun!';
overlayMessage.textContent = 'Click the button below to Pull the Trigger.';
overlayButton.style.display = 'inline-block';
overlayButton.textContent = 'Shoot';
} else {
overlayTitle.textContent = `${lostPlayer} must Trigger the Gun!`;
overlayMessage.textContent = 'Wait for the outcome.';
overlayButton.style.display = 'none';
}
overlay.style.display = 'flex';
}, 2000);
}
3. Additional Recommendations
a. Handle Edge Cases and Robustness:
Ensure that all possible edge cases are handled gracefully. For example, if multiple players disconnect simultaneously or if unexpected messages are received, the server should handle them without crashing.
b. Provide Clear Feedback to Users:
Add more descriptive messages and visual indicators to inform users about the game's state, especially during transitions like shooting or when players are eliminated.
c. Implement Consistent State Management:
Ensure that both the server and client maintain a consistent understanding of the game's state. This includes synchronizing player statuses, hands, and the central table accurately.
d. Testing:
After implementing the above fixes, thoroughly test the game with multiple players to ensure that the shooting mechanics and card displays work as expected. Pay special attention to scenarios where players are eliminated or when multiple bluffs are called in quick succession.
By implementing the above modifications, your game should correctly handle the shooting mechanics, allowing the designated player to trigger the shoot action without encountering errors. Additionally, the central table should now properly display the played cards, enhancing the overall user experience.
If you encounter further issues or need additional assistance, feel free to ask!