Implement a real-time multiplayer game backend using Node.js and WebSockets.
- User
Implement a real-time multiplayer game backend using Node.js and WebSockets.
Assistant
The user wants a real-time multiplayer game backend using Node.js and WebSockets. This is a substantial project that requires:
- A Node.js server using the
wslibrary for WebSockets - Game state management
- Player connection/disconnection handling
- Real-time updates to all clients
- Simple game logic (I'll create a simple multiplayer arena game where players can move around)
Since this is a backend-focused request, I should:
- Create a WebSocket server
- Handle player connections
- Manage game state (players, positions, etc.)
- Implement game loop for physics/updates
- Broadcast updates to all clients
- Handle player input
But the user asked for a complete implementation. I should provide both server and client code so they can test it. The client will be a simple HTML page.
Let me create:
- A Node.js WebSocket server
- A simple browser-based client with Three.js visualization
Game concept: A simple multiplayer arena where players are represented as spheres. They can move around using WASD keys. Other players are visible in real-time.
Server features:
- WebSocket connections
- Player spawning at random positions
- Movement synchronization
- Player disconnection handling
- Game state broadcasting at regular intervals
Client features:
- Three.js 3D visualization
- WASD movement
- See other players
- Simple arena visualization
Let me write this as a complete, runnable solution. I'll include:
- server.js - Node.js WebSocket server
- client.html - Browser client with Three.js
Actually, let me think about what makes this a good real-time multiplayer backend:
-
Connection Management
- Handle new connections
- Assign unique IDs
- Track all connected players
-
State Synchronization
- Authoritative server model
- Broadcast state at fixed intervals (tick rate)
- Handle client input
-
Game Logic
- Validate player movements
- Handle collisions
- Manage game entities
-
Performance
- Use binary protocols or efficient JSON
- Interpolation on client side
- Server-side game loop
Let me create a professional-grade implementation with:
- Server-authoritative game state
- Fixed tick rate
- Client-side prediction ready
- Simple but engaging gameplay
I'll write the server code that can be run with Node.js, and a client that connects to it.
Real-Time Multiplayer Game Backend
I'll create a complete multiplayer game backend with Node.js and WebSockets, along with a Three.js client for testing. The game will be a simple arena where players can move around and see each other in real-time.
Architecture Overview
┌─────────────────────────────────────────────────────────────┐ │ NODE.JS GAME SERVER │ ├─────────────────────────────────────────────────────────────┤ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │ │ │ WebSocket │ │ Game State │ │ Physics Engine │ │ │ │ Server │ │ Manager │ │ (Movement/Collision)│ │ │ └─────────────┘ └─────────────┘ └─────────────────────┘ │ │ │ │ │ │ │ └────────────────┼────────────────────┘ │ │ │ │ │ ┌───────▼───────┐ │ │ │ Game Loop │ (60 FPS tick rate) │ │ │ Broadcaster │ │ │ └───────────────┘ │ └─────────────────────────────────────────────────────────────┘ │ ┌───────────────┼───────────────┐ │ │ │ ┌────▼────┐ ┌────▼────┐ ┌────▼────┐ │ Client │ │ Client │ │ Client │ │ Player 1│ │ Player 2│ │ Player N│ └─────────┘ └─────────┘ └─────────┘Files Structure
- server.js - Main game server
- client.html - Three.js browser client
1. Server Code (server.js)
// server.js - Real-time Multiplayer Game Backend // Run with: node server.js const WebSocket = require('ws'); const http = require('http'); // ==================== CONFIGURATION ==================== const CONFIG = { PORT: process.env.PORT || 8080, TICK_RATE: 60, // Server updates per second ARENA_SIZE: 100, // Arena dimensions PLAYER_SPEED: 15, // Units per second PLAYER_RADIUS: 1.5, MAX_PLAYERS: 50, PING_INTERVAL: 5000, // Ping clients every 5 seconds CONNECTION_TIMEOUT: 15000, // Disconnect after 15s of no response }; // ==================== GAME STATE ==================== class GameState { constructor() { this.players = new Map(); this.projectiles = new Map(); this.pickups = []; this.lastUpdate = Date.now(); } addPlayer(id, player) { this.players.set(id, player); } removePlayer(id) { this.players.delete(id); } getPlayer(id) { return this.players.get(id); } getAllPlayers() { return Array.from(this.players.values()); } } // ==================== PLAYER CLASS ==================== class Player { constructor(id, ws) { this.id = id; this.ws = ws; this.name = `Player_${id.substring(0, 4)}`; this.color = this.generateColor(); // Position this.x = (Math.random() - 0.5) * CONFIG.ARENA_SIZE * 0.8; this.y = 1.5; this.z = (Math.random() - 0.5) * CONFIG.ARENA_SIZE * 0.8; // Velocity this.vx = 0; this.vz = 0; // Input state this.input = { forward: false, backward: false, left: false, right: false, jump: false, action: false }; // Stats this.score = 0; this.health = 100; this.isAlive = true; // Connection tracking this.lastPing = Date.now(); this.latency = 0; } generateColor() { const hue = Math.random() * 360; return `hsl(${hue}, 70%, 50%)`; } getState() { return { id: this.id, name: this.name, color: this.color, x: this.x, y: this.y, z: this.z, vx: this.vx, vz: this.vz, score: this.score, health: this.health, isAlive: this.isAlive, latency: this.latency }; } } // ==================== PHYSICS ENGINE ==================== class PhysicsEngine { constructor(gameState) { this.gameState = gameState; this.arenaSize = CONFIG.ARENA_SIZE; } update(deltaTime) { const players = this.gameState.getAllPlayers(); for (const player of players) { if (!player.isAlive) continue; // Process input let moveX = 0; let moveZ = 0; if (player.input.forward) moveZ -= 1; if (player.input.backward) moveZ += 1; if (player.input.left) moveX -= 1; if (player.input.right) moveX += 1; // Normalize diagonal movement const length = Math.sqrt(moveX * moveX + moveZ * moveZ); if (length > 0) { moveX /= length; moveZ /= length; } // Apply velocity with smoothing const targetVx = moveX * CONFIG.PLAYER_SPEED; const targetVz = moveZ * CONFIG.PLAYER_SPEED; // Smooth acceleration const accel = 10 * deltaTime; player.vx += (targetVx - player.vx) * accel; player.vz += (targetVz - player.vz) * accel; // Update position player.x += player.vx * deltaTime; player.z += player.vz * deltaTime; // Arena boundaries with collision response const boundary = this.arenaSize / 2 - CONFIG.PLAYER_RADIUS; player.x = Math.max(-boundary, Math.min(boundary, player.x)); player.z = Math.max(-boundary, Math.min(boundary, player.z)); // Player vs Player collision this.handlePlayerCollisions(player, players); } } handlePlayerCollisions(player, players) { for (const other of players) { if (other.id === player.id || !other.isAlive) continue; const dx = other.x - player.x; const dz = other.z - player.z; const dist = Math.sqrt(dx * dx + dz * dz); const minDist = CONFIG.PLAYER_RADIUS * 2; if (dist < minDist && dist > 0) { // Push players apart const overlap = minDist - dist; const nx = dx / dist; const nz = dz / dist; player.x -= nx * overlap * 0.5; player.z -= nz * overlap * 0.5; other.x += nx * overlap * 0.5; other.z += nz * overlap * 0.5; } } } } // ==================== GAME SERVER ==================== class GameServer { constructor() { this.gameState = new GameState(); this.physics = new PhysicsEngine(this.gameState); this.clients = new Map(); this.lastTick = Date.now(); this.tickCount = 0; this.setupServer(); this.startGameLoop(); } setupServer() { // Create HTTP server this.server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('WebSocket Game Server Running'); }); // Create WebSocket server this.wss = new WebSocket.Server({ server: this.server }); this.wss.on('connection', (ws, req) => { this.handleConnection(ws, req); }); this.server.listen(CONFIG.PORT, () => { console.log(`🎮 Game Server started on port ${CONFIG.PORT}`); console.log(`📡 WebSocket ready at ws://localhost:${CONFIG.PORT}`); console.log(`⚙️ Tick Rate: ${CONFIG.TICK_RATE} Hz`); }); } handleConnection(ws, req) { // Generate unique player ID const playerId = this.generateId(); // Check max players if (this.clients.size >= CONFIG.MAX_PLAYERS) { ws.send(JSON.stringify({ type: 'error', message: 'Server is full' })); ws.close(); return; } // Create new player const player = new Player(playerId, ws); this.gameState.addPlayer(playerId, player); this.clients.set(playerId, ws); console.log(`✅ Player connected: ${player.name} (${this.clients.size} online)`); // Send initial state ws.send(JSON.stringify({ type: 'init', player: player.getState(), arenaSize: CONFIG.ARENA_SIZE, serverTime: Date.now() })); // Broadcast to others this.broadcast({ type: 'playerJoined', player: player.getState() }, playerId); // Handle incoming messages ws.on('message', (data) => { this.handleMessage(playerId, data); }); // Handle disconnect ws.on('close', () => { this.handleDisconnect(playerId); }); ws.on('error', (err) => { console.error(`WebSocket error for ${playerId}:`, err.message); }); } handleMessage(playerId, data) { try { const message = JSON.parse(data); const player = this.gameState.getPlayer(playerId); if (!player) return; switch (message.type) { case 'input': this.handleInput(player, message); break; case 'ping': player.lastPing = Date.now(); player.latency = Date.now() - message.timestamp; this.send(playerId, { type: 'pong', timestamp: message.timestamp, serverTime: Date.now() }); break; case 'chat': this.broadcast({ type: 'chat', playerId: playerId, playerName: player.name, message: this.sanitizeChat(message.message) }); break; case 'setName': player.name = this.sanitizeName(message.name); this.broadcast({ type: 'playerUpdate', player: player.getState() }); break; } } catch (err) { console.error('Message parsing error:', err.message); } } handleInput(player, message) { if (message.input) { player.input = { ...player.input, ...message.input }; player.lastPing = Date.now(); } // Optional: Client-side prediction acknowledgment if (message.sequence !== undefined) { player.lastSequence = message.sequence; } } handleDisconnect(playerId) { const player = this.gameState.getPlayer(playerId); if (player) { console.log(`❌ Player disconnected: ${player.name}`); } this.gameState.removePlayer(playerId); this.clients.delete(playerId); this.broadcast({ type: 'playerLeft', playerId: playerId }); } startGameLoop() { const tickInterval = 1000 / CONFIG.TICK_RATE; setInterval(() => { const now = Date.now(); const deltaTime = (now - this.lastTick) / 1000; this.lastTick = now; this.tickCount++; // Update physics this.physics.update(deltaTime); // Check for disconnected clients (timeout) this.checkTimeouts(); // Broadcast game state this.broadcastState(); }, tickInterval); // Ping interval setInterval(() => { this.broadcast({ type: 'pingCheck', timestamp: Date.now() }); }, CONFIG.PING_INTERVAL); console.log('🔄 Game loop started'); } broadcastState() { const players = this.gameState.getAllPlayers(); const state = { type: 'state', tick: this.tickCount, timestamp: Date.now(), players: players.map(p => p.getState()) }; this.broadcast(state); } checkTimeouts() { const now = Date.now(); for (const [id, player] of this.gameState.players) { if (now - player.lastPing > CONFIG.CONNECTION_TIMEOUT) { console.log(`⏰ Player timed out: ${player.name}`); const ws = this.clients.get(id); if (ws) ws.close(); this.handleDisconnect(id); } } } broadcast(message, excludeId = null) { const data = JSON.stringify(message); for (const [id, ws] of this.clients) { if (id !== excludeId && ws.readyState === WebSocket.OPEN) { ws.send(data); } } } send(playerId, message) { const ws = this.clients.get(playerId); if (ws && ws.readyState === WebSocket.OPEN) { ws.send(JSON.stringify(message)); } } generateId() { return Math.random().toString(36).substr(2, 9) + Date.now().toString(36); } sanitizeChat(message) { return message.toString().substring(0, 100); } sanitizeName(name) { return name.toString().replace(/[^a-zA-Z0-9_]/g, '').substring(0, 16) || 'Player'; } } // ==================== START SERVER ==================== console.log('╔══════════════════════════════════════╗'); console.log('║ Real-Time Multiplayer Game Server ║'); console.log('╚══════════════════════════════════════╝'); const gameServer = new GameServer(); // Graceful shutdown process.on('SIGINT', () => { console.log('\n🛑 Shutting down server...'); gameServer.broadcast({ type: 'serverShutdown', message: 'Server is shutting down' }); setTimeout(() => process.exit(0), 1000); });
2. Client Code (client.html)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Multiplayer Arena</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { overflow: hidden; background: #0a0a0f; font-family: 'Segoe UI', system-ui, sans-serif; } #gameContainer { position: fixed; top: 0; left: 0; width: 100%; height: 100%; } /* Connection Overlay */ #connectionOverlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: linear-gradient(135deg, #0a0a0f 0%, #1a1a2e 100%); display: flex; flex-direction: column; align-items: center; justify-content: center; z-index: 1000; transition: opacity 0.5s; } #connectionOverlay.hidden { opacity: 0; pointer-events: none; } .connection-box { background: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 16px; padding: 40px; text-align: center; max-width: 400px; backdrop-filter: blur(10px); } .connection-box h1 { color: #fff; font-size: 2rem; margin-bottom: 10px; } .connection-box p { color: rgba(255, 255, 255, 0.6); margin-bottom: 20px; } input { width: 100%; padding: 14px 18px; background: rgba(255, 255, 255, 0.08); border: 1px solid rgba(255, 255, 255, 0.15); border-radius: 8px; color: #fff; font-size: 1rem; margin-bottom: 15px; outline: none; transition: all 0.3s; } input:focus { border-color: #4ecdc4; background: rgba(255, 255, 255, 0.12); } button { width: 100%; padding: 14px; background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%); border: none; border-radius: 8px; color: #fff; font-size: 1rem; font-weight: 600; cursor: pointer; transition: transform 0.2s, box-shadow 0.2s; } button:hover { transform: translateY(-2px); box-shadow: 0 8px 25px rgba(78, 205, 196, 0.3); } .status { margin-top: 15px; padding: 10px; border-radius: 6px; font-size: 0.9rem; } .status.connecting { color: #ffd93d; background: rgba(255, 217, 61, 0.1); } .status.connected { color: #4ecdc4; background: rgba(78, 205, 196, 0.1); } .status.error { color: #ff6b6b; background: rgba(255, 107, 107, 0.1); } /* HUD */ #hud { position: fixed; top: 20px; left: 20px; z-index: 100; pointer-events: none; } .hud-panel { background: rgba(0, 0, 0, 0.7); border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 10px; padding: 15px 20px; margin-bottom: 10px; backdrop-filter: blur(5px); } .stat-row { display: flex; align-items: center; gap: 10px; color: #fff; font-size: 0.9rem; margin-bottom: 8px; } .stat-row:last-child { margin-bottom: 0; } .stat-icon { width: 20px; height: 20px; display: flex; align-items: center; justify-content: center; } .stat-value { font-weight: 600; color: #4ecdc4; } /* Leaderboard */ #leaderboard { position: fixed; top: 20px; right: 20px; z-index: 100; min-width: 200px; } .leaderboard-title { color: rgba(255, 255, 255, 0.5); font-size: 0.75rem; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 8px; } .leaderboard-item { display: flex; align-items: center; gap: 10px; padding: 8px 0; border-bottom: 1px solid rgba(255, 255, 255, 0.05); } .leaderboard-item:last-child { border-bottom: none; } .player-color { width: 12px; height: 12px; border-radius: 50%; } .player-name { flex: 1; color: #fff; font-size: 0.85rem; } .player-ping { color: rgba(255, 255, 255, 0.4); font-size: 0.75rem; } /* Chat */ #chat { position: fixed; bottom: 20px; left: 20px; width: 300px; z-index: 100; pointer-events: none; } #chatMessages { background: rgba(0, 0, 0, 0.5); border-radius: 10px; padding: 10px; max-height: 150px; overflow-y: auto; margin-bottom: 10px; } .chat-message { color: rgba(255, 255, 255, 0.8); font-size: 0.85rem; padding: 4px 0; } .chat-message .name { font-weight: 600; margin-right: 8px; } #chatInput { pointer-events: auto; opacity: 0.8; } /* Controls Info */ #controls { position: fixed; bottom: 20px; right: 20px; z-index: 100; pointer-events: none; } .control-key { display: inline-block; background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.2); border-radius: 4px; padding: 2px 8px; font-size: 0.75rem; color: rgba(255, 255, 255, 0.7); margin-right: 5px; } .control-desc { color: rgba(255, 255, 255, 0.5); font-size: 0.75rem; } </style> </head> <body> <!-- Connection Overlay --> <div id="connectionOverlay"> <div class="connection-box"> <h1>Multiplayer Arena</h1> <p>Connect to the game server to play</p> <input type="text" id="serverAddress" placeholder="Server Address" value="ws://localhost:8080"> <input type="text" id="playerName" placeholder="Your Name (optional)" maxlength="16"> <button id="connectBtn">Connect</button> <div id="connectionStatus" class="status"></div> </div> </div> <!-- Game Container --> <div id="gameContainer"></div> <!-- HUD --> <div id="hud"> <div class="hud-panel"> <div class="stat-row"> <div class="stat-icon">●</div> <span>Players:</span> <span class="stat-value" id="playerCount">0</span> </div> <div class="stat-row"> <div class="stat-icon">⌛</div> <span>Ping:</span> <span class="stat-value" id="pingValue">0ms</span> </div> <div class="stat-row"> <div class="stat-icon">⚡</div> <span>Tick:</span> <span class="stat-value" id="tickValue">0</span> </div> </div> </div> <!-- Leaderboard --> <div id="leaderboard" class="hud-panel"> <div class="leaderboard-title">Players Online</div> <div id="leaderboardList"></div> </div> <!-- Chat --> <div id="chat"> <div id="chatMessages"></div> <input type="text" id="chatInput" placeholder="Press Enter to chat..."> </div> <!-- Controls --> <div id="controls" class="hud-panel"> <div style="margin-bottom: 8px;"> <span class="control-key">W</span> <span class="control-key">A</span> <span class="control-key">S</span> <span class="control-key">D</span> <span class="control-desc">Move</span> </div> <div> <span class="control-key">Mouse</span> <span class="control-desc">Look around</span> </div> </div> <script type="importmap"> { "imports": { "three": "https://unpkg.com/three@0.160.0/build/three.module.js", "three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/" } } </script> <script type="module"> import * as THREE from 'three'; // ==================== GAME CLIENT ==================== class GameClient { constructor() { this.ws = null; this.connected = false; this.playerId = null; this.localPlayer = null; this.players = new Map(); this.playerMeshes = new Map(); // Input state this.keys = {}; this.mouseX = 0; this.mouseY = 0; // Camera this.cameraYaw = 0; this.cameraPitch = 0.3; this.cameraDistance = 12; // Timing this.lastTick = 0; this.serverTick = 0; this.latency = 0; this.initThree(); this.initInput(); this.initUI(); } initThree() { // Scene this.scene = new THREE.Scene(); this.scene.background = new THREE.Color(0x0a0a0f); this.scene.fog = new THREE.Fog(0x0a0a0f, 30, 80); // Camera this.camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 200 ); this.camera.position.set(0, 15, 20); // Renderer this.renderer = new THREE.WebGLRenderer({ antialias: true }); this.renderer.setSize(window.innerWidth, window.innerHeight); this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); this.renderer.shadowMap.enabled = true; this.renderer.shadowMap.type = THREE.PCFSoftShadowMap; document.getElementById('gameContainer').appendChild(this.renderer.domElement); // Lights const ambientLight = new THREE.AmbientLight(0x404060, 0.5); this.scene.add(ambientLight); const directionalLight = new THREE.DirectionalLight(0xffffff, 1); directionalLight.position.set(30, 50, 30); directionalLight.castShadow = true; directionalLight.shadow.mapSize.width = 2048; directionalLight.shadow.mapSize.height = 2048; directionalLight.shadow.camera.near = 10; directionalLight.shadow.camera.far = 150; directionalLight.shadow.camera.left = -60; directionalLight.shadow.camera.right = 60; directionalLight.shadow.camera.top = 60; directionalLight.shadow.camera.bottom = -60; this.scene.add(directionalLight); // Arena this.createArena(); } createArena() { const arenaSize = 100; // Must match server // Ground with grid const groundGeometry = new THREE.PlaneGeometry(arenaSize, arenaSize, 50, 50); const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x1a1a2e, roughness: 0.8, metalness: 0.2 }); const ground = new THREE.Mesh(groundGeometry, groundMaterial); ground.rotation.x = -Math.PI / 2; ground.receiveShadow = true; this.scene.add(ground); // Grid lines const gridHelper = new THREE.GridHelper(arenaSize, 50, 0x2a2a4a, 0x1a1a3a); gridHelper.position.y = 0.01; this.scene.add(gridHelper); // Arena walls const wallHeight = 4; const wallMaterial = new THREE.MeshStandardMaterial({ color: 0x4ecdc4, emissive: 0x4ecdc4, emissiveIntensity: 0.3, transparent: true, opacity: 0.3 }); const halfSize = arenaSize / 2; const wallPositions = [ { x: 0, z: -halfSize, rotY: 0 }, { x: 0, z: halfSize, rotY: 0 }, { x: -halfSize, z: 0, rotY: Math.PI / 2 }, { x: halfSize, z: 0, rotY: Math.PI / 2 } ]; wallPositions.forEach(pos => { const wallGeometry = new THREE.BoxGeometry(arenaSize, wallHeight, 0.3); const wall = new THREE.Mesh(wallGeometry, wallMaterial); wall.position.set(pos.x, wallHeight / 2, pos.z); wall.rotation.y = pos.rotY; this.scene.add(wall); }); // Corner pillars with lights const corners = [ [-halfSize, -halfSize], [halfSize, -halfSize], [-halfSize, halfSize], [halfSize, halfSize] ]; corners.forEach(([x, z]) => { const pillarGeometry = new THREE.CylinderGeometry(0.5, 0.7, 6, 8); const pillarMaterial = new THREE.MeshStandardMaterial({ color: 0x2a2a4a, roughness: 0.3, metalness: 0.7 }); const pillar = new THREE.Mesh(pillarGeometry, pillarMaterial); pillar.position.set(x, 3, z); pillar.castShadow = true; this.scene.add(pillar); // Light on top const light = new THREE.PointLight(0x4ecdc4, 2, 20); light.position.set(x, 6.5, z); this.scene.add(light); // Light sphere const sphereGeometry = new THREE.SphereGeometry(0.3, 16, 16); const sphereMaterial = new THREE.MeshBasicMaterial({ color: 0x4ecdc4 }); const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial); sphere.position.set(x, 6.5, z); this.scene.add(sphere); }); // Add some decorative elements this.addDecorations(); } addDecorations() { // Scattered energy orbs for (let i = 0; i < 15; i++) { const angle = (i / 15) * Math.PI * 2; const radius = 20 + Math.random() * 20; const x = Math.cos(angle) * radius; const z = Math.sin(angle) * radius; const orbGeometry = new THREE.OctahedronGeometry(0.5, 0); const orbMaterial = new THREE.MeshStandardMaterial({ color: 0xff6b6b, emissive: 0xff6b6b, emissiveIntensity: 0.5, metalness: 0.8, roughness: 0.2 }); const orb = new THREE.Mesh(orbGeometry, orbMaterial); orb.position.set(x, 1.5 + Math.random(), z); orb.userData.floatOffset = Math.random() * Math.PI * 2; orb.userData.isOrb = true; this.scene.add(orb); } } createPlayerMesh(playerData, isLocal = false) { const group = new THREE.Group(); // Body const bodyGeometry = new THREE.CapsuleGeometry(0.8, 1.5, 8, 16); const bodyMaterial = new THREE.MeshStandardMaterial({ color: new THREE.Color(playerData.color), roughness: 0.3, metalness: 0.7 }); const body = new THREE.Mesh(bodyGeometry, bodyMaterial); body.position.y = 1.5; body.castShadow = true; group.add(body); // Glow ring const ringGeometry = new THREE.TorusGeometry(1.2, 0.1, 8, 32); const ringMaterial = new THREE.MeshBasicMaterial({ color: new THREE.Color(playerData.color), transparent: true, opacity: 0.5 }); const ring = new THREE.Mesh(ringGeometry, ringMaterial); ring.rotation.x = Math.PI / 2; ring.position.y = 0.1; group.add(ring); // Name tag if (!isLocal) { const canvas = document.createElement('canvas'); const context = canvas.getContext('2d'); canvas.width = 256; canvas.height = 64; context.fillStyle = 'rgba(0, 0, 0, 0.5)'; context.roundRect(0, 0, 256, 64, 10); context.fill(); context.font = 'bold 28px Arial'; context.textAlign = 'center'; context.fillStyle = '#ffffff'; context.fillText(playerData.name, 128, 42); const texture = new THREE.CanvasTexture(canvas); const spriteMaterial = new THREE.SpriteMaterial({ map: texture, transparent: true }); const sprite = new THREE.Sprite(spriteMaterial); sprite.scale.set(4, 1, 1); sprite.position.y = 4; group.add(sprite); } group.position.set(playerData.x, playerData.y, playerData.z); this.scene.add(group); return group; } initInput() { document.addEventListener('keydown', (e) => { this.keys[e.code] = true; // Chat focus if (e.code === 'Enter') { const chatInput = document.getElementById('chatInput'); if (document.activeElement === chatInput) { if (chatInput.value.trim()) { this.send({ type: 'chat', message: chatInput.value.trim() }); chatInput.value = ''; } chatInput.blur(); } else { chatInput.focus(); } } }); document.addEventListener('keyup', (e) => { this.keys[e.code] = false; }); document.addEventListener('mousemove', (e) => { if (document.pointerLockElement === this.renderer.domElement) { this.cameraYaw -= e.movementX * 0.003; this.cameraPitch -= e.movementY * 0.003; this.cameraPitch = Math.max(0.1, Math.min(1.2, this.cameraPitch)); } }); this.renderer.domElement.addEventListener('click', () => { this.renderer.domElement.requestPointerLock(); }); window.addEventListener('resize', () => { this.camera.aspect = window.innerWidth / window.innerHeight; this.camera.updateProjectionMatrix(); this.renderer.setSize(window.innerWidth, window.innerHeight); }); } initUI() { document.getElementById('connectBtn').addEventListener('click', () => { this.connect(); }); document.getElementById('playerName').addEventListener('keypress', (e) => { if (e.key === 'Enter') this.connect(); }); } connect() { const address = document.getElementById('serverAddress').value; const status = document.getElementById('connectionStatus'); status.textContent = 'Connecting...'; status.className = 'status connecting'; try { this.ws = new WebSocket(address); this.ws.onopen = () => { status.textContent = 'Connected! Joining game...'; status.className = 'status connected'; this.connected = true; const name = document.getElementById('playerName').value; if (name) { this.send({ type: 'setName', name: name }); } }; this.ws.onmessage = (event) => { this.handleMessage(JSON.parse(event.data)); }; this.ws.onclose = () => { this.connected = false; document.getElementById('connectionOverlay').classList.remove('hidden'); status.textContent = 'Disconnected from server'; status.className = 'status error'; }; this.ws.onerror = (error) => { status.textContent = 'Connection failed'; status.className = 'status error'; console.error('WebSocket error:', error); }; } catch (err) { status.textContent = 'Invalid server address'; status.className = 'status error'; } } send(data) { if (this.ws && this.ws.readyState === WebSocket.OPEN) { this.ws.send(JSON.stringify(data)); } } handleMessage(message) { switch (message.type) { case 'init': this.playerId = message.player.id; this.localPlayer = message.player; this.players.set(this.playerId, message.player); // Hide overlay document.getElementById('connectionOverlay').classList.add('hidden'); // Create local player mesh const mesh = this.createPlayerMesh(message.player, true); this.playerMeshes.set(this.playerId, mesh); break; case 'state': this.serverTick = message.tick; document.getElementById('tickValue').textContent = message.tick; // Update all players message.players.forEach(player => { this.updatePlayer(player); }); // Remove disconnected players for (const [id] of this.players) { if (!message.players.find(p => p.id === id)) { this.removePlayer(id); } } // Update player count document.getElementById('playerCount').textContent = message.players.length; this.updateLeaderboard(message.players); break; case 'playerJoined': this.players.set(message.player.id, message.player); const newMesh = this.createPlayerMesh(message.player); this.playerMeshes.set(message.player.id, newMesh); this.addChatMessage('System', `${message.player.name} joined the game`, '#4ecdc4'); break; case 'playerLeft': this.removePlayer(message.playerId); break; case 'playerUpdate': if (this.players.has(message.player.id)) { this.players.set(message.player.id, message.player); } break; case 'chat': const player = this.players.get(message.playerId); this.addChatMessage(player?.name || 'Unknown', message.message); break; case 'pong': this.latency = Date.now() - message.timestamp; document.getElementById('pingValue').textContent = `${this.latency}ms`; break; } } updatePlayer(player) { this.players.set(player.id, player); let mesh = this.playerMeshes.get(player.id); if (!mesh) { mesh = this.createPlayerMesh(player, player.id === this.playerId); this.playerMeshes.set(player.id, mesh); } // Smooth interpolation mesh.position.x += (player.x - mesh.position.x) * 0.3; mesh.position.y = player.y; mesh.position.z += (player.z - mesh.position.z) * 0.3; // Update ring rotation const ring = mesh.children[1]; if (ring) { ring.rotation.z += 0.02; } } removePlayer(playerId) { const mesh = this.playerMeshes.get(playerId); if (mesh) { this.scene.remove(mesh); this.playerMeshes.delete(playerId); } this.players.delete(playerId); } updateLeaderboard(players) { const list = document.getElementById('leaderboardList'); list.innerHTML = players .sort((a, b) => a.name.localeCompare(b.name)) .map(p => ` <div class="leaderboard-item"> <div class="player-color" style="background: ${p.color}"></div> <span class="player-name">${p.name}${p.id === this.playerId ? ' (You)' : ''}</span> <span class="player-ping">${p.latency || 0}ms</span> </div> `).join(''); } addChatMessage(name, message, color = '#fff') { const container = document.getElementById('chatMessages'); const div = document.createElement('div'); div.className = 'chat-message'; div.innerHTML = `<span class="name" style="color: ${color}">${name}:</span>${message}`; container.appendChild(div); container.scrollTop = container.scrollHeight; // Remove old messages while (container.children.length > 20) { container.removeChild(container.firstChild); } } processInput() { const input = { forward: this.keys['KeyW'] || this.keys['ArrowUp'], backward: this.keys['KeyS'] || this.keys['ArrowDown'], left: this.keys['KeyA'] || this.keys['ArrowLeft'], right: this.keys['KeyD'] || this.keys['ArrowRight'] }; this.send({ type: 'input', input }); } startPing() { setInterval(() => { this.send({ type: 'ping', timestamp: Date.now() }); }, 2000); } animate() { requestAnimationFrame(() => this.animate()); // Process input if (this.connected) { this.processInput(); } // Update camera to follow local player if (this.localPlayer) { const mesh = this.playerMeshes.get(this.playerId); if (mesh) { const targetX = mesh.position.x + Math.sin(this.cameraYaw) * this.cameraDistance; const targetZ = mesh.position.z + Math.cos(this.cameraYaw) * this.cameraDistance; const targetY = mesh.position.y + this.cameraPitch * this.cameraDistance; this.camera.position.x += (targetX - this.camera.position.x) * 0.05; this.camera.position.y += (targetY - this.camera.position.y) * 0.05; this.camera.position.z += (targetZ - this.camera.position.z) * 0.05; this.camera.lookAt(mesh.position.x, mesh.position.y + 1, mesh.position.z); } } // Animate decorative orbs const time = Date.now() * 0.001; this.scene.traverse((obj) => { if (obj.userData.isOrb) { obj.rotation.y += 0.01; obj.position.y = 1.5 + Math.sin(time * 2 + obj.userData.floatOffset) * 0.3; } }); this.renderer.render(this.scene, this.camera); } run() { this.startPing(); this.animate(); } } // Start the game const client = new GameClient(); client.run(); </script> </body> </html>
How to Run
1. Server Setup
# Create a new directory mkdir multiplayer-game cd multiplayer-game # Initialize npm and install ws npm init -y npm install ws # Save the server code above as server.js # Run the server node server.js2. Client Setup
Save the client code as
client.htmland open it in a browser. If running locally, the defaultws://localhost:8080should work.
Key Features
Feature Description Authoritative Server Server validates all movement and state 60 FPS Tick Rate Consistent game loop updates Client Prediction Smooth movement interpolation Player Collision Server-side collision detection Latency Tracking Real-time ping measurement Connection Timeout Auto-disconnect for unresponsive clients Chat System Global chat messaging Player Management Join/leave notifications The server handles all game logic authoritatively while clients render with smooth interpolation for a polished multiplayer experience.
- A Node.js server using the
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.