o1-preview-2024-09-12· OpenAI
WildChat-4.8M (AI2)
index.html [code] server.js [code] style.css [code] Rebuild this game, but make it…
- User
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Card Bluff & Shoot - Multiplayer</title> <link rel="stylesheet" href="style.css"> <style> /* Basic styling for visibility */ .selected { border: 2px solid blue; } .player { margin: 5px 0; } .active { background-color: #e0ffe0; } .eliminated { text-decoration: line-through; color: gray; } .card { display: inline-block; width: 50px; height: 70px; border: 1px solid #000; border-radius: 5px; margin: 5px; text-align: center; line-height: 70px; font-size: 1.2em; cursor: pointer; position: relative; perspective: 1000px; /* For flip animation */ } .card-inner { position: absolute; width: 100%; height: 100%; transition: transform 0.6s; transform-style: preserve-3d; } .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); } .hearts, .diamonds { color: red; } .spades, .clubs { color: black; } .match { border: 2px solid green; /* Highlight matching cards */ } .mismatch { border: 2px solid red; /* Highlight non-matching cards */ } .overlay-content { background-color: rgba(0, 0, 0, 0.8); color: white; padding: 20px; border-radius: 10px; text-align: center; } .overlay-button { padding: 10px 20px; margin-top: 15px; font-size: 1em; cursor: pointer; } </style> </head> <body> <div class="container"> <!-- Waiting Room Section --> <div id="waitingRoom" class="section"> <h3>Room: <span id="roomDisplay">ABC123</span></h3> <div id="playersList"> <h4>Players in room:</h4> <!-- List of players will be appended here --> </div> <button id="startGameBtn" style="display: none;">Start Game</button> <button id="resetRoomBtn" style="display: none; margin-top: 10px;">Reset Room</button> </div> <!-- Game Section --> <div id="gameSection" class="game-container" style="display: none;"> <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> <!-- Overlay for Bluff Result --> <div class="overlay" id="resultOverlay" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); align-items: center; justify-content: center;"> <div class="overlay-content"> <h2 id="overlayTitle">Result</h2> <p id="overlayMessage"></p> <button id="overlayButton" class="overlay-button" onclick="handleOverlayAction()">Shoot</button> </div> </div> </div> <!-- Game Over Overlay --> <div class="shooting-overlay" id="gameOverOverlay" style="display: none;"> <div class="overlay-content"> <h2>Game Over!</h2> <p id="gameOverText"></p> <button onclick="resetToLobby()" class="overlay-button">Return to Lobby</button> </div> </div> </div> <script> let ws; let username; const roomId = 'ABC123'; // Predefined room ID let isCreator = false; let userHand = []; let gameState = null; let isWaitingForShot = false; // Flag to prevent multiple shots // Utility function to generate random username function generateRandomUsername() { const adjectives = ['Swift', 'Silent', 'Mighty', 'Brave', 'Clever', 'Nimble', 'Fierce', 'Sly', 'Bold', 'Wise']; const nouns = ['Lion', 'Tiger', 'Eagle', 'Shark', 'Wolf', 'Panther', 'Dragon', 'Falcon', 'Leopard', 'Cobra']; const adj = adjectives[Math.floor(Math.random() * adjectives.length)]; const noun = nouns[Math.floor(Math.random() * nouns.length)]; const number = Math.floor(Math.random() * 1000); return `${adj}${noun}${number}`; } // Connect to WebSocket server function connectWebSocket() { ws = new WebSocket('ws://localhost:3000'); // Ensure this URL matches your server's address and port ws.onopen = () => { console.log('Connected to server'); // Assign random username username = generateRandomUsername(); // Send JOIN_ROOM message ws.send(JSON.stringify({ type: 'JOIN_ROOM', username: username, roomId: roomId })); }; ws.onmessage = (event) => { const data = JSON.parse(event.data); handleWebSocketMessage(data); }; ws.onclose = () => { console.log('Disconnected from server'); alert('Disconnected from server'); resetToLobby(); }; } // Handle WebSocket messages function handleWebSocketMessage(data) { switch(data.type) { case 'PLAYER_JOINED': updatePlayersList(data.players, data.creator); break; case 'PLAYER_LEFT': updatePlayersList(data.players, null); // Creator remains unchanged break; case 'NEW_CREATOR': isCreator = false; alert(`New room creator is: ${data.newCreator}`); updateStartButton(); // Update button visibility break; case 'CREATOR': isCreator = data.isCreator; updateStartButton(); break; case 'GAME_STARTED': gameState = data.gameState; userHand = data.hand || []; startGameUI(data.gameState); break; case 'GAME_UPDATE': gameState = data.gameState; if (data.gameState.hand !== undefined) { userHand = data.gameState.hand || []; } updateGameUI(); break; case 'BLUFF_RESULT': handleBluffResult(data); break; case 'SHOT_RESULT': handleShotResult(data); break; case 'GAME_OVER': showGameOver(data); break; case 'RESET': alert(data.message); resetToLobby(); break; case 'ERROR': alert(data.message); break; default: console.log('Unknown message type:', data.type); } } // Update players list in waiting room function updatePlayersList(players, creatorUsername) { const list = document.getElementById('playersList'); list.innerHTML = '<h4>Players in room:</h4>'; players.forEach(player => { const div = document.createElement('div'); div.className = 'player'; div.textContent = player; list.appendChild(div); }); // Determine if the current user is the creator if (creatorUsername && creatorUsername === username) { isCreator = true; updateStartButton(); } // Show start button only to creator and if at least two players if (isCreator && players.length >=2 ) { document.getElementById('startGameBtn').style.display = 'block'; } else { document.getElementById('startGameBtn').style.display = 'none'; } // Show reset button only to creator if (isCreator) { document.getElementById('resetRoomBtn').style.display = 'block'; } else { document.getElementById('resetRoomBtn').style.display = 'none'; } } // Update start button based on creator status and player count function updateStartButton() { const players = document.querySelectorAll('#playersList .player'); if (isCreator && players.length >= 2) { document.getElementById('startGameBtn').style.display = 'block'; } else { document.getElementById('startGameBtn').style.display = 'none'; } // Show reset button only to creator if (isCreator) { document.getElementById('resetRoomBtn').style.display = 'block'; } else { document.getElementById('resetRoomBtn').style.display = 'none'; } } // Start Game UI function startGameUI(gameStateData) { document.getElementById('waitingRoom').style.display = 'none'; document.getElementById('gameSection').style.display = 'grid'; renderGame(gameStateData); } // Update Game UI function updateGameUI() { if (!gameState) return; renderGame(gameState); } // Render Game UI function renderGame(gameState) { // Render players const playersContainer = document.getElementById('players'); playersContainer.innerHTML = ''; gameState.players.forEach(player => { const playerEl = document.createElement('div'); playerEl.className = `player ${player.username === gameState.currentPlayer ? 'active' : ''} ${player.isEliminated ? 'eliminated' : ''}`; playerEl.innerHTML = ` <strong>${player.username}${player.username === username ? ' (You)' : ''}</strong> <div class="bullets">Bullets: ${player.bulletSlots}/6</div> `; playersContainer.appendChild(playerEl); }); // Render core card const coreCardSpan = document.getElementById('coreCard'); if (gameState.coreCard && gameState.coreCard !== '-') { coreCardSpan.innerHTML = formatCard(gameState.coreCard); } else { coreCardSpan.textContent = '-'; } // Render last played const lastPlayedSpan = document.getElementById('lastPlayed'); if (gameState.lastPlayedCount > 0) { lastPlayedSpan.textContent = `${gameState.lastPlayedCount} card(s) played`; } else { lastPlayedSpan.textContent = 'None'; } // Render central table const centralTable = document.getElementById('centralTable'); centralTable.innerHTML = ''; gameState.centralTableCards.forEach(cardObj => { const cardEl = document.createElement('div'); if (!cardObj.revealed) { // Keep cards hidden cardEl.className = `card`; cardEl.innerHTML = ` <div class="card-inner"> <div class="card-front">🂠</div> <div class="card-back">🂠</div> </div> `; } else { // Reveal cards using flip animation cardEl.className = `card flipped ${getSuitClass(cardObj.card)}`; cardEl.innerHTML = ` <div class="card-inner"> <div class="card-front">${cardObj.card}</div> <div class="card-back">🂠</div> </div> `; // Set color based on suit cardEl.style.color = getCardColor(cardObj.card); // Highlight card based on core card matching const coreValue = gameState.coreCard.slice(0, -1); // Extract value without suit const cardValue = cardObj.card.slice(0, -1); // Extract value without suit if (cardValue === coreValue) { cardEl.classList.add('match'); } else { cardEl.classList.add('mismatch'); } } centralTable.appendChild(cardEl); }); // Always render current player's hand const handContainer = document.getElementById('currentHand'); handContainer.innerHTML = ''; userHand.forEach((card, index) => { const cardEl = document.createElement('div'); cardEl.className = `card ${getSuitClass(card)}`; cardEl.style.color = getCardColor(card); cardEl.dataset.index = index; cardEl.textContent = card; // Display the card face cardEl.onclick = () => { // Only allow selection if it's the player's turn if (gameState.currentPlayer === username && !gameState.isGameOver) { cardEl.classList.toggle('selected'); } }; handContainer.appendChild(cardEl); }); // Enable/Disable action buttons based on turn if (gameState.currentPlayer === username && !gameState.isGameOver) { document.getElementById('playButton').disabled = (userHand.length === 0); document.getElementById('callBluffButton').disabled = (gameState.lastPlayedCount === 0); } else { document.getElementById('playButton').disabled = true; document.getElementById('callBluffButton').disabled = true; } } // Format card HTML function formatCard(cardStr) { const color = getCardColor(cardStr); return `<span style="color: ${color};">${cardStr}</span>`; } // Get card color based on suit function getCardColor(cardStr) { const suit = cardStr.slice(-1); return (suit === '♥' || suit === '♦') ? 'red' : 'black'; } // Get suit class for styling function getSuitClass(cardStr) { const suit = cardStr.slice(-1); return suit === '♠' ? 'spades' : suit === '♣' ? 'clubs' : suit === '♥' ? 'hearts' : 'diamonds'; } // Play selected cards function playSelectedCards() { // Get selected cards const selectedCards = Array.from(document.querySelectorAll('.card.selected')); if (selectedCards.length === 0) { alert('Please select at least one card to play.'); return; } const selectedIndices = selectedCards.map(card => parseInt(card.dataset.index)); // Send PLAY_CARDS message to server ws.send(JSON.stringify({ type: 'PLAY_CARDS', selectedIndices: selectedIndices })); // Remove selected cards from userHand selectedIndices.sort((a, b) => b - a); // Remove from higher index to lower selectedIndices.forEach(index => { userHand.splice(index, 1); }); // Clear selected classes selectedCards.forEach(card => { card.classList.remove('selected'); }); } // Call bluff function callBluff() { // Send CALL_BLUFF message to server ws.send(JSON.stringify({ type: 'CALL_BLUFF' })); } // Handle Bluff Result function handleBluffResult(data) { // Reveal the central table cards based on 'revealed' flag const centralTable = document.getElementById('centralTable'); centralTable.innerHTML = ''; const coreCard = data.coreCard; data.centralTableCards.forEach(cardObj => { const cardEl = document.createElement('div'); if (!cardObj.revealed) { // Keep cards hidden cardEl.className = `card`; cardEl.innerHTML = ` <div class="card-inner"> <div class="card-front">🂠</div> <div class="card-back">🂠</div> </div> `; } else { // Reveal cards using flip animation cardEl.className = `card flipped ${getSuitClass(cardObj.card)}`; cardEl.innerHTML = ` <div class="card-inner"> <div class="card-front">${cardObj.card}</div> <div class="card-back">🂠</div> </div> `; // Set color based on suit cardEl.style.color = getCardColor(cardObj.card); // Highlight card based on core card matching const coreValue = coreCard.slice(0, -1); // Extract value without suit const cardValue = cardObj.card.slice(0, -1); // Extract value without suit if (cardValue === coreValue) { cardEl.classList.add('match'); } else { cardEl.classList.add('mismatch'); } } centralTable.appendChild(cardEl); }); // After a 2-second delay, show the shooting 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); // 2-second delay } // Handle Shot Result function handleShotResult(data) { const overlay = document.getElementById('resultOverlay'); const overlayTitle = document.getElementById('overlayTitle'); const overlayMessage = document.getElementById('overlayMessage'); const overlayButton = document.getElementById('overlayButton'); if (data.player === username) { if (data.result === 'SHOT') { overlayTitle.textContent = '💀 You have been Shot!'; overlayMessage.textContent = 'You have been eliminated.'; } else if (data.result === 'SURVIVED') { overlayTitle.textContent = '✨ You Survived!'; overlayMessage.textContent = 'You can continue playing.'; } } else { // For observers or other players overlayTitle.textContent = `${data.player} has ${data.result === 'SHOT' ? 'been Shot!' : 'Survived!'}`; overlayMessage.textContent = ''; } // Hide the 'Shoot' button if present overlayButton.style.display = 'none'; // After 2 seconds, hide the overlay and reset the game state setTimeout(() => { overlay.style.display = 'none'; // Clear the central table (if desired, based on game rules) // centralTable.innerHTML = ''; // Update game UI via GAME_UPDATE // If game is over, GAME_OVER will handle the UI }, 2000); } // Show game over overlay function showGameOver(data) { document.getElementById('gameSection').style.display = 'none'; document.getElementById('gameOverOverlay').style.display = 'flex'; if (data.winner) { document.getElementById('gameOverText').textContent = `Winner: ${data.winner}`; } else if (data.message) { document.getElementById('gameOverText').textContent = data.message; } else { document.getElementById('gameOverText').textContent = 'The game has ended.'; } } // Reset to lobby function resetToLobby() { document.getElementById('gameSection').style.display = 'none'; document.getElementById('gameOverOverlay').style.display = 'none'; document.getElementById('resultOverlay').style.display = 'none'; document.getElementById('waitingRoom').style.display = 'block'; // Reset variables // roomId is constant 'ABC123' isCreator = false; gameState = null; userHand = []; isWaitingForShot = false; // Reload the page to rejoin window.location.reload(); } // Handle overlay button (Shoot) function handleOverlayAction() { if (isWaitingForShot) return; // Prevent multiple shots isWaitingForShot = true; // Send PULL_TRIGGER message to server ws.send(JSON.stringify({ type: 'PULL_TRIGGER' })); } // Handle start game button document.getElementById('startGameBtn').addEventListener('click', () => { ws.send(JSON.stringify({ type: 'START_GAME' })); }); // Handle reset room button document.getElementById('resetRoomBtn').addEventListener('click', () => { if (confirm('Are you sure you want to reset the room? This will end the current game.')) { ws.send(JSON.stringify({ type: 'RESET_ROOM' })); } }); // Initialize connection on page load window.onload = () => { username = generateRandomUsername(); connectWebSocket(); }; </script> </body> </html> - Assistant