/**
* Multiplayer Game Server with State Synchronization
* Features: WebSocket communication, state interpolation, lag compensation
*/
const http = require('http');
const express = require('express');
const WebSocket = require('ws');
const { v4: uuidv4 } = require('uuid');
// ==================== CONFIGURATION ====================
const CONFIG = {
PORT: process.env.PORT || 3000,
TICK_RATE: 60, // Server updates per second
WORLD_WIDTH: 2000,
WORLD_HEIGHT: 2000,
PLAYER_SPEED: 200,
PLAYER_SIZE: 20,
BULLET_SPEED: 500,
BULLET_DAMAGE: 10,
MAX_HEALTH: 100,
RESPAWN_TIME: 3000,
MAX_CLIENTS: 50
};
// ==================== GAME STATE ====================
class GameState {
constructor() {
this.players = new Map();
this.bullets = new Map();
this.powerups = new Map();
this.lastUpdate = Date.now();
this.tick = 0;
}
serialize() {
return {
tick: this.tick,
timestamp: Date.now(),
players: Array.from(this.players.values()).map(p => p.serialize()),
bullets: Array.from(this.bullets.values()).map(b => b.serialize()),
powerups: Array.from(this.powerups.values()).map(p => p.serialize())
};
}
}
// ==================== PLAYER CLASS ====================
class Player {
constructor(id, name, color) {
this.id = id;
this.name = name || `Player_${id.substr(0, 4)}`;
this.color = color || this.randomColor();
this.x = Math.random() * CONFIG.WORLD_WIDTH;
this.y = Math.random() * CONFIG.WORLD_HEIGHT;
this.vx = 0;
this.vy = 0;
this.angle = 0;
this.health = CONFIG.MAX_HEALTH;
this.score = 0;
this.alive = true;
this.lastInputSeq = 0;
this.inputBuffer = [];
this.lastShot = 0;
this.shootCooldown = 200;
}
randomColor() {
const colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#ffeaa7', '#dfe6e9', '#fd79a8', '#a29bfe'];
return colors[Math.floor(Math.random() * colors.length)];
}
update(dt, worldWidth, worldHeight) {
if (!this.alive) return;
// Apply velocity
this.x += this.vx * dt;
this.y += this.vy * dt;
// World bounds
this.x = Math.max(CONFIG.PLAYER_SIZE, Math.min(worldWidth - CONFIG.PLAYER_SIZE, this.x));
this.y = Math.max(CONFIG.PLAYER_SIZE, Math.min(worldHeight - CONFIG.PLAYER_SIZE, this.y));
}
canShoot() {
return Date.now() - this.lastShot >= this.shootCooldown;
}
shoot() {
if (!this.canShoot()) return null;
this.lastShot = Date.now();
return new Bullet(
uuidv4(),
this.id,
this.x + Math.cos(this.angle) * 30,
this.y + Math.sin(this.angle) * 30,
this.angle
);
}
takeDamage(amount) {
this.health -= amount;
if (this.health <= 0) {
this.health = 0;
this.alive = false;
return true; // Player died
}
return false;
}
respawn() {
this.x = Math.random() * CONFIG.WORLD_WIDTH;
this.y = Math.random() * CONFIG.WORLD_HEIGHT;
this.health = CONFIG.MAX_HEALTH;
this.alive = true;
}
serialize() {
return {
id: this.id,
name: this.name,
color: this.color,
x: parseFloat(this.x.toFixed(2)),
y: parseFloat(this.y.toFixed(2)),
angle: parseFloat(this.angle.toFixed(3)),
health: this.health,
score: this.score,
alive: this.alive
};
}
}
// ==================== BULLET CLASS ====================
class Bullet {
constructor(id, ownerId, x, y, angle) {
this.id = id;
this.ownerId = ownerId;
this.x = x;
this.y = y;
this.angle = angle;
this.speed = CONFIG.BULLET_SPEED;
this.damage = CONFIG.BULLET_DAMAGE;
this.createdAt = Date.now();
this.lifetime = 2000;
}
update(dt) {
this.x += Math.cos(this.angle) * this.speed * dt;
this.y += Math.sin(this.angle) * this.speed * dt;
}
isExpired() {
return Date.now() - this.createdAt > this.lifetime ||
this.x < 0 || this.x > CONFIG.WORLD_WIDTH ||
this.y < 0 || this.y > CONFIG.WORLD_HEIGHT;
}
serialize() {
return {
id: this.id,
ownerId: this.ownerId,
x: parseFloat(this.x.toFixed(2)),
y: parseFloat(this.y.toFixed(2)),
angle: parseFloat(this.angle.toFixed(3))
};
}
}
// ==================== POWERUP CLASS ====================
class Powerup {
constructor(id, type, x, y) {
this.id = id;
this.type = type; // 'health', 'speed', 'damage'
this.x = x;
this.y = y;
this.size = 15;
this.active = true;
this.respawnTime = 10000;
this.collectedAt = null;
}
collect() {
this.active = false;
this.collectedAt = Date.now();
}
update() {
if (!this.active && Date.now() - this.collectedAt >= this.respawnTime) {
this.active = true;
this.collectedAt = null;
}
}
serialize() {
return {
id: this.id,
type: this.type,
x: this.x,
y: this.y,
active: this.active
};
}
}
// ==================== GAME SERVER ====================
class GameServer {
constructor() {
this.app = express();
this.server = http.createServer(this.app);
this.wss = new WebSocket.Server({ server: this.server });
this.state = new GameState();
this.clients = new Map();
this.inputQueue = [];
this.setupRoutes();
this.setupWebSocket();
this.initializePowerups();
this.startGameLoop();
}
setupRoutes() {
this.app.use(express.static('public'));
this.app.get('/state', (req, res) => {
res.json(this.state.serialize());
});
}
setupWebSocket() {
this.wss.on('connection', (ws) => {
if (this.clients.size >= CONFIG.MAX_CLIENTS) {
ws.send(JSON.stringify({ type: 'error', message: 'Server full' }));
ws.close();
return;
}
const id = uuidv4();
const player = new Player(id);
this.state.players.set(id, player);
this.clients.set(id, { ws, player });
// Send initial state
ws.send(JSON.stringify({
type: 'init',
playerId: id,
config: CONFIG,
state: this.state.serialize()
}));
// Broadcast new player
this.broadcast({
type: 'playerJoined',
player: player.serialize()
}, id);
ws.on('message', (data) => {
try {
const message = JSON.parse(data);
this.handleMessage(id, message);
} catch (e) {
console.error('Invalid message:', e);
}
});
ws.on('close', () => {
this.handleDisconnect(id);
});
console.log(`Player ${id} connected. Total: ${this.clients.size}`);
});
}
handleMessage(playerId, message) {
const client = this.clients.get(playerId);
if (!client) return;
switch (message.type) {
case 'input':
this.processInput(playerId, message);
break;
case 'chat':
this.broadcast({
type: 'chat',
playerId: playerId,
playerName: client.player.name,
message: message.message
});
break;
case 'nameChange':
client.player.name = message.name.substr(0, 16);
this.broadcast({
type: 'playerUpdate',
player: client.player.serialize()
});
break;
}
}
processInput(playerId, message) {
const player = this.state.players.get(playerId);
if (!player || !player.alive) return;
// Store input with sequence number for reconciliation
player.inputBuffer.push({
seq: message.seq,
inputs: message.inputs,
timestamp: message.timestamp
});
// Keep buffer limited
if (player.inputBuffer.length > 100) {
player.inputBuffer.shift();
}
// Apply inputs
const inputs = message.inputs;
// Movement
player.vx = 0;
player.vy = 0;
if (inputs.up) player.vy = -CONFIG.PLAYER_SPEED;
if (inputs.down) player.vy = CONFIG.PLAYER_SPEED;
if (inputs.left) player.vx = -CONFIG.PLAYER_SPEED;
if (inputs.right) player.vx = CONFIG.PLAYER_SPEED;
// Normalize diagonal movement
if (player.vx !== 0 && player.vy !== 0) {
player.vx *= 0.707;
player.vy *= 0.707;
}
// Aiming
if (inputs.mouseX !== undefined) {
player.angle = Math.atan2(
inputs.mouseY - player.y,
inputs.mouseX - player.x
);
}
// Shooting
if (inputs.shooting) {
const bullet = player.shoot();
if (bullet) {
this.state.bullets.set(bullet.id, bullet);
}
}
player.lastInputSeq = message.seq;
}
handleDisconnect(playerId) {
this.state.players.delete(playerId);
this.clients.delete(playerId);
this.broadcast({
type: 'playerLeft',
playerId: playerId
});
console.log(`Player ${playerId} disconnected. Total: ${this.clients.size}`);
}
initializePowerups() {
const types = ['health', 'speed', 'damage'];
for (let i = 0; i < 10; i++) {
const powerup = new Powerup(
uuidv4(),
types[Math.floor(Math.random() * types.length)],
Math.random() * CONFIG.WORLD_WIDTH,
Math.random() * CONFIG.WORLD_HEIGHT
);
this.state.powerups.set(powerup.id, powerup);
}
}
startGameLoop() {
let lastTime = Date.now();
setInterval(() => {
const now = Date.now();
const dt = (now - lastTime) / 1000;
lastTime = now;
this.update(dt);
this.broadcastState();
}, 1000 / CONFIG.TICK_RATE);
}
update(dt) {
this.state.tick++;
// Update players
for (const player of this.state.players.values()) {
player.update(dt, CONFIG.WORLD_WIDTH, CONFIG.WORLD_HEIGHT);
}
// Update bullets and check collisions
const bulletsToRemove = [];
for (const bullet of this.state.bullets.values()) {
bullet.update(dt);
if (bullet.isExpired()) {
bulletsToRemove.push(bullet.id);
continue;
}
// Check collision with players
for (const player of this.state.players.values()) {
if (player.id === bullet.ownerId || !player.alive) continue;
const dx = player.x - bullet.x;
const dy = player.y - bullet.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < CONFIG.PLAYER_SIZE + 5) {
const died = player.takeDamage(bullet.damage);
bulletsToRemove.push(bullet.id);
// Update attacker score
const attacker = this.state.players.get(bullet.ownerId);
if (attacker) {
attacker.score += died ? 100 : 10;
}
if (died) {
this.broadcast({
type: 'kill',
killerId: bullet.ownerId,
victimId: player.id
});
// Respawn after delay
setTimeout(() => {
player.respawn();
this.broadcast({
type: 'playerRespawn',
player: player.serialize()
});
}, CONFIG.RESPAWN_TIME);
}
break;
}
}
}
// Remove expired bullets
for (const id of bulletsToRemove) {
this.state.bullets.delete(id);
}
// Update powerups
for (const powerup of this.state.powerups.values()) {
powerup.update();
if (powerup.active) {
for (const player of this.state.players.values()) {
if (!player.alive) continue;
const dx = player.x - powerup.x;
const dy = player.y - powerup.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < CONFIG.PLAYER_SIZE + powerup.size) {
this.applyPowerup(player, powerup);
powerup.collect();
}
}
}
}
}
applyPowerup(player, powerup) {
switch (powerup.type) {
case 'health':
player.health = Math.min(CONFIG.MAX_HEALTH, player.health + 25);
break;
case 'speed':
// Temporary speed boost could be implemented
player.score += 25;
break;
case 'damage':
player.score += 25;
break;
}
this.broadcast({
type: 'powerupCollected',
playerId: player.id,
powerupId: powerup.id
});
}
broadcastState() {
const stateUpdate = {
type: 'stateUpdate',
state: this.state.serialize()
};
this.broadcast(stateUpdate);
}
broadcast(message, excludeId = null) {
const data = JSON.stringify(message);
for (const [id, client] of this.clients) {
if (id === excludeId) continue;
if (client.ws.readyState === WebSocket.OPEN) {
client.ws.send(data);
}
}
}
start() {
this.server.listen(CONFIG.PORT, () => {
console.log(`
╔═══════════════════════════════════════════════════════╗
║ MULTIPLAYER GAME SERVER - STATE SYNCHRONIZATION ║
╠═══════════════════════════════════════════════════════╣
║ Server running on http://localhost:${CONFIG.PORT.toString().padEnd(18)}║
║ Tick Rate: ${CONFIG.TICK_RATE} Hz ║
║ World Size: ${CONFIG.WORLD_WIDTH}x${CONFIG.WORLD_HEIGHT} ║
║ Max Clients: ${CONFIG.MAX_CLIENTS} ║
╚═══════════════════════════════════════════════════════╝
`);
});
}
}
// Start server
const server = new GameServer();
server.start();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cyberpunk Arena - Multiplayer</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background: #0a0a0f;
font-family: 'Segoe UI', system-ui, sans-serif;
overflow: hidden;
color: #fff;
}
#gameContainer {
position: relative;
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
#gameCanvas {
border: 2px solid #00ffff;
box-shadow: 0 0 30px rgba(0, 255, 255, 0.3),
inset 0 0 50px rgba(0, 255, 255, 0.1);
cursor: crosshair;
}
#ui {
position: absolute;
top: 20px;
left: 20px;
z-index: 100;
}
.panel {
background: rgba(10, 10, 20, 0.9);
border: 1px solid #00ffff;
border-radius: 8px;
padding: 15px;
margin-bottom: 10px;
backdrop-filter: blur(10px);
}
.panel h3 {
color: #00ffff;
margin-bottom: 10px;
font-size: 14px;
text-transform: uppercase;
letter-spacing: 2px;
}
#healthBar {
width: 200px;
height: 20px;
background: rgba(255, 255, 255, 0.1);
border-radius: 10px;
overflow: hidden;
margin-bottom: 5px;
}
#healthFill {
height: 100%;
background: linear-gradient(90deg, #ff6b6b, #ff8e8e);
transition: width 0.3s;
box-shadow: 0 0 10px #ff6b6b;
}
#score {
font-size: 24px;
color: #ffeaa7;
text-shadow: 0 0 10px #ffeaa7;
}
#leaderboard {
position: absolute;
top: 20px;
right: 20px;
width: 200px;
}
.leaderboard-entry {
display: flex;
justify-content: space-between;
padding: 5px 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.leaderboard-entry.self {
color: #00ffff;
font-weight: bold;
}
#minimap {
position: absolute;
bottom: 20px;
right: 20px;
width: 180px;
height: 180px;
background: rgba(10, 10, 20, 0.9);
border: 1px solid #00ffff;
border-radius: 8px;
overflow: hidden;
}
#minimapCanvas {
width: 100%;
height: 100%;
}
#chat {
position: absolute;
bottom: 20px;
left: 20px;
width: 300px;
}
#chatMessages {
height: 150px;
overflow-y: auto;
margin-bottom: 10px;
}
.chat-message {
padding: 3px 0;
font-size: 12px;
}
.chat-message span {
color: #00ffff;
}
#chatInput {
width: 100%;
padding: 8px;
background: rgba(0, 0, 0, 0.5);
border: 1px solid #00ffff;
border-radius: 4px;
color: #fff;
font-family: inherit;
}
#chatInput:focus {
outline: none;
box-shadow: 0 0 10px rgba(0, 255, 255, 0.3);
}
#connectionStatus {
position: absolute;
top: 20px;
left: 50%;
transform: translateX(-50%);
padding: 5px 15px;
border-radius: 20px;
font-size: 12px;
text-transform: uppercase;
letter-spacing: 1px;
}
#connectionStatus.connected {
background: rgba(0, 255, 100, 0.2);
border: 1px solid #00ff64;
color: #00ff64;
}
#connectionStatus.disconnected {
background: rgba(255, 0, 0, 0.2);
border: 1px solid #ff0000;
color: #ff0000;
}
#killFeed {
position: absolute;
top: 60px;
left: 50%;
transform: translateX(-50%);
text-align: center;
}
.kill-message {
background: rgba(255, 0, 0, 0.3);
padding: 5px 15px;
border-radius: 4px;
margin-bottom: 5px;
animation: fadeOut 3s forwards;
}
@keyframes fadeOut {
0% { opacity: 1; }
70% { opacity: 1; }
100% { opacity: 0; }
}
#respawnOverlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.8);
display: none;
align-items: center;
justify-content: center;
flex-direction: column;
z-index: 200;
}
#respawnOverlay h2 {
color: #ff6b6b;
font-size: 48px;
margin-bottom: 20px;
}
#respawnTimer {
color: #00ffff;
font-size: 72px;
}
#instructions {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
text-align: center;
font-size: 12px;
color: rgba(255, 255, 255, 0.5);
}
#nameModal {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.9);
display: flex;
align-items: center;
justify-content: center;
z-index: 300;
}
.modal-content {
background: rgba(20, 20, 30, 0.95);
border: 2px solid #00ffff;
border-radius: 15px;
padding: 40px;
text-align: center;
}
.modal-content h2 {
color: #00ffff;
margin-bottom: 20px;
}
.modal-content input {
width: 250px;
padding: 12px;
background: rgba(0, 0, 0, 0.5);
border: 1px solid #00ffff;
border-radius: 8px;
color: #fff;
font-size: 16px;
margin-bottom: 20px;
}
.modal-content button {
padding: 12px 40px;
background: linear-gradient(135deg, #00ffff, #0088ff);
border: none;
border-radius: 8px;
color: #000;
font-size: 16px;
font-weight: bold;
cursor: pointer;
transition: all 0.3s;
}
.modal-content button:hover {
transform: scale(1.05);
box-shadow: 0 0 20px rgba(0, 255, 255, 0.5);
}
#ping {
position: absolute;
top: 20px;
right: 230px;
font-size: 12px;
color: #00ffff;
}
</style>
</head>
<body>
<div id="gameContainer">
<canvas id="gameCanvas"></canvas>
<div id="connectionStatus" class="disconnected">Connecting...</div>
<div id="ping">Ping: -- ms</div>
<div id="ui">
<div class="panel">
<h3>Health</h3>
<div id="healthBar">
<div id="healthFill" style="width: 100%"></div>
</div>
<div id="score">Score: 0</div>
</div>
</div>
<div id="leaderboard" class="panel">
<h3>Leaderboard</h3>
<div id="leaderboardList"></div>
</div>
<div id="minimap">
<canvas id="minimapCanvas"></canvas>
</div>
<div id="chat" class="panel">
<div id="chatMessages"></div>
<input type="text" id="chatInput" placeholder="Press Enter to chat..." maxlength="100">
</div>
<div id="killFeed"></div>
<div id="respawnOverlay">
<h2>YOU DIED</h2>
<div id="respawnTimer">3</div>
</div>
<div id="instructions">
WASD to move | Mouse to aim | Click to shoot | Enter to chat
</div>
<div id="nameModal">
<div class="modal-content">
<h2>ENTER THE ARENA</h2>
<input type="text" id="playerName" placeholder="Your name..." maxlength="16">
<br>
<button onclick="joinGame()">JOIN BATTLE</button>
</div>
</div>
</div>
<script>
// ==================== GAME CLIENT ====================
class GameClient {
constructor() {
this.canvas = document.getElementById('gameCanvas');
this.ctx = this.canvas.getContext('2d');
this.minimapCanvas = document.getElementById('minimapCanvas');
this.minimapCtx = this.minimapCanvas.getContext('2d');
this.resize();
window.addEventListener('resize', () => this.resize());
// Game state
this.playerId = null;
this.config = null;
this.state = {
players: [],
bullets: [],
powerups: []
};
// Input state
this.keys = {};
this.mouse = { x: 0, y: 0, down: false };
this.inputSeq = 0;
// Network
this.ws = null;
this.connected = false;
this.lastPing = 0;
this.ping = 0;
// Camera
this.camera = { x: 0, y: 0 };
// Prediction
this.serverState = null;
this.pendingInputs = [];
this.reconciliationThreshold = 10;
// Visual effects
this.particles = [];
this.screenShake = { x: 0, y: 0, intensity: 0 };
this.setupInput();
this.setupChat();
}
resize() {
this.canvas.width = Math.min(window.innerWidth - 40, 1200);
this.canvas.height = Math.min(window.innerHeight - 40, 800);
this.minimapCanvas.width = 180;
this.minimapCanvas.height = 180;
}
connect(name) {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
this.ws = new WebSocket(`${protocol}//${window.location.host}`);
this.playerName = name;
this.ws.onopen = () => {
document.getElementById('connectionStatus').className = 'connected';
document.getElementById('connectionStatus').textContent = 'Connected';
this.connected = true;
};
this.ws.onclose = () => {
document.getElementById('connectionStatus').className = 'disconnected';
document.getElementById('connectionStatus').textContent = 'Disconnected';
this.connected = false;
};
this.ws.onmessage = (e) => {
const data = JSON.parse(e.data);
this.handleMessage(data);
};
// Ping measurement
setInterval(() => {
if (this.connected) {
this.lastPing = Date.now();
this.ws.send(JSON.stringify({ type: 'ping' }));
}
}, 1000);
}
handleMessage(data) {
switch (data.type) {
case 'init':
this.playerId = data.playerId;
this.config = data.config;
this.processState(data.state);
// Send name
this.ws.send(JSON.stringify({
type: 'nameChange',
name: this.playerName
}));
break;
case 'stateUpdate':
this.serverState = data.state;
this.processState(data.state);
this.reconcile();
break;
case 'playerJoined':
this.addChatMessage('System', `${data.player.name} joined the arena!`, '#00ffff');
break;
case 'playerLeft':
const player = this.state.players.find(p => p.id === data.playerId);
if (player) {
this.addChatMessage('System', `${player.name} left the game`, '#888');
}
break;
case 'kill':
const killer = this.state.players.find(p => p.id === data.killerId);
const victim = this.state.players.find(p => p.id === data.victimId);
if (killer && victim) {
this.showKillFeed(killer.name, victim.name);
if (data.victimId === this.playerId) {
this.screenShake.intensity = 20;
this.showRespawnOverlay();
}
}
break;
case 'playerRespawn':
if (data.player.id === this.playerId) {
this.hideRespawnOverlay();
}
break;
case 'chat':
this.addChatMessage(data.playerName, data.message);
break;
case 'pong':
this.ping = Date.now() - this.lastPing;
document.getElementById('ping').textContent = `Ping: ${this.ping} ms`;
break;
case 'powerupCollected':
this.spawnParticles(data.x || 0, data.y || 0, '#ffff00', 10);
break;
}
}
processState(state) {
this.state.players = state.players;
this.state.bullets = state.bullets;
this.state.powerups = state.powerups;
// Update UI
const myPlayer = this.state.players.find(p => p.id === this.playerId);
if (myPlayer) {
document.getElementById('healthFill').style.width = `${myPlayer.health}%`;
document.getElementById('score').textContent = `Score: ${myPlayer.score}`;
}
this.updateLeaderboard();
}
reconcile() {
// Server reconciliation for client-side prediction
const serverPlayer = this.serverState?.players.find(p => p.id === this.playerId);
if (!serverPlayer) return;
// Remove processed inputs
while (this.pendingInputs.length > 0 &&
this.pendingInputs[0].seq <= serverPlayer.lastInputSeq) {
this.pendingInputs.shift();
}
}
setupInput() {
window.addEventListener('keydown', (e) => {
this.keys[e.key.toLowerCase()] = true;
});
window.addEventListener('keyup', (e) => {
this.keys[e.key.toLowerCase()] = false;
});
this.canvas.addEventListener('mousemove', (e) => {
const rect = this.canvas.getBoundingClientRect();
this.mouse.x = e.clientX - rect.left;
this.mouse.y = e.clientY - rect.top;
});
this.canvas.addEventListener('mousedown', () => {
this.mouse.down = true;
});
this.canvas.addEventListener('mouseup', () => {
this.mouse.down = false;
});
// Prevent right-click menu
this.canvas.addEventListener('contextmenu', (e) => e.preventDefault());
}
setupChat() {
const input = document.getElementById('chatInput');
input.addEventListener('keypress', (e) => {
if (e.key === 'Enter' && input.value.trim()) {
this.ws.send(JSON.stringify({
type: 'chat',
message: input.value.trim()
}));
input.value = '';
}
});
}
addChatMessage(name, message, color = '#fff') {
const div = document.getElementById('chatMessages');
const msg = document.createElement('div');
msg.className = 'chat-message';
msg.innerHTML = `<span style="color: ${color}">${name}:</span> ${message}`;
div.appendChild(msg);
div.scrollTop = div.scrollHeight;
// Remove old messages
while (div.children.length > 50) {
div.removeChild(div.firstChild);
}
}
showKillFeed(killer, victim) {
const feed = document.getElementById('killFeed');
const msg = document.createElement('div');
msg.className = 'kill-message';
msg.textContent = `${killer} eliminated ${victim}`;
feed.appendChild(msg);
setTimeout(() => {
if (msg.parentNode) {
msg.parentNode.removeChild(msg);
}
}, 3000);
}
showRespawnOverlay() {
document.getElementById('respawnOverlay').style.display = 'flex';
let time = 3;
const timer = document.getElementById('respawnTimer');
const interval = setInterval(() => {
time--;
timer.textContent = time;
if (time <= 0) {
clearInterval(interval);
}
}, 1000);
}
hideRespawnOverlay() {
document.getElementById('respawnOverlay').style.display = 'none';
}
updateLeaderboard() {
const sorted = [...this.state.players].sort((a, b) => b.score - a.score).slice(0, 5);
const list = document.getElementById('leaderboardList');
list.innerHTML = sorted.map((p, i) => `
<div class="leaderboard-entry ${p.id === this.playerId ? 'self' : ''}">
<span>${i + 1}. ${p.name}</span>
<span>${p.score}</span>
</div>
`).join('');
}
sendInput() {
if (!this.connected || !this.playerId) return;
const myPlayer = this.state.players.find(p => p.id === this.playerId);
if (!myPlayer || !myPlayer.alive) return;
this.inputSeq++;
const input = {
type: 'input',
seq: this.inputSeq,
timestamp: Date.now(),
inputs: {
up: this.keys['w'] || false,
down: this.keys['s'] || false,
left: this.keys['a'] || false,
right: this.keys['d'] || false,
mouseX: this.mouse.x + this.camera.x,
mouseY: this.mouse.y + this.camera.y,
shooting: this.mouse.down
}
};
this.pendingInputs.push(input);
this.ws.send(JSON.stringify(input));
// Limit pending inputs
while (this.pendingInputs.length > 100) {
this.pendingInputs.shift();
}
}
update() {
this.sendInput();
this.updateParticles();
this.updateScreenShake();
}
updateParticles() {
for (let i = this.particles.length - 1; i >= 0; i--) {
const p = this.particles[i];
p.x += p.vx;
p.y += p.vy;
p.life -= 0.02;
if (p.life <= 0) {
this.particles.splice(i, 1);
}
}
}
updateScreenShake() {
if (this.screenShake.intensity > 0) {
this.screenShake.x = (Math.random() - 0.5) * this.screenShake.intensity;
this.screenShake.y = (Math.random() - 0.5) * this.screenShake.intensity;
this.screenShake.intensity *= 0.9;
if (this.screenShake.intensity < 0.5) {
this.screenShake.intensity = 0;
this.screenShake.x = 0;
this.screenShake.y = 0;
}
}
}
spawnParticles(x, y, color, count) {
for (let i = 0; i < count; i++) {
this.particles.push({
x, y,
vx: (Math.random() - 0.5) * 5,
vy: (Math.random() - 0.5) * 5,
color,
life: 1
});
}
}
render() {
const ctx = this.ctx;
const myPlayer = this.state.players.find(p => p.id === this.playerId);
// Update camera
if (myPlayer) {
this.camera.x = myPlayer.x - this.canvas.width / 2;
this.camera.y = myPlayer.y - this.canvas.height / 2;
}
ctx.save();
ctx.translate(this.screenShake.x, this.screenShake.y);
// Clear with gradient background
const gradient = ctx.createLinearGradient(0, 0, 0, this.canvas.height);
gradient.addColorStop(0, '#0a0a1a');
gradient.addColorStop(1, '#1a0a2a');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
ctx.save();
ctx.translate(-this.camera.x, -this.camera.y);
// Draw grid
this.drawGrid();
// Draw world bounds
ctx.strokeStyle = '#ff006688';
ctx.lineWidth = 3;
ctx.strokeRect(0, 0, this.config?.WORLD_WIDTH || 2000, this.config?.WORLD_HEIGHT || 2000);
// Draw powerups
this.drawPowerups();
// Draw bullets
this.drawBullets();
// Draw players
this.drawPlayers();
// Draw particles
this.drawParticles();
ctx.restore();
ctx.restore();
// Draw minimap
this.drawMinimap();
// Draw crosshair
this.drawCrosshair();
}
drawGrid() {
const ctx = this.ctx;
const gridSize = 50;
const startX = Math.floor(this.camera.x / gridSize) * gridSize;
const startY = Math.floor(this.camera.y / gridSize) * gridSize;
const endX = startX + this.canvas.width + gridSize;
const endY = startY + this.canvas.height + gridSize;
ctx.strokeStyle = '#1a1a2e';
ctx.lineWidth = 1;
for (let x = startX; x <= endX; x += gridSize) {
ctx.beginPath();
ctx.moveTo(x, startY);
ctx.lineTo(x, endY);
ctx.stroke();
}
for (let y = startY; y <= endY; y += gridSize) {
ctx.beginPath();
ctx.moveTo(startX, y);
ctx.lineTo(endX, y);
ctx.stroke();
}
}
drawPlayers() {
const ctx = this.ctx;
for (const player of this.state.players) {
ctx.save();
ctx.translate(player.x, player.y);
// Player glow
const glowGradient = ctx.createRadialGradient(0, 0, 0, 0, 0, 40);
glowGradient.addColorStop(0, player.color + '44');
glowGradient.addColorStop(1, 'transparent');
ctx.fillStyle = glowGradient;
ctx.beginPath();
ctx.arc(0, 0, 40, 0, Math.PI * 2);
ctx.fill();
// Player body
ctx.rotate(player.angle);
// Body
ctx.fillStyle = player.color;
ctx.beginPath();
ctx.arc(0, 0, 20, 0, Math.PI * 2);
ctx.fill();
// Inner detail
ctx.fillStyle = '#000';
ctx.beginPath();
ctx.arc(0, 0, 12, 0, Math.PI * 2);
ctx.fill();
// Direction indicator / gun
ctx.fillStyle = player.color;
ctx.fillRect(15, -4, 20, 8);
// Gun tip
ctx.fillStyle = '#fff';
ctx.fillRect(32, -2, 5, 4);
ctx.restore();
// Health bar
if (player.alive) {
const barWidth = 40;
const barHeight = 5;
const healthPercent = player.health / (this.config?.MAX_HEALTH || 100);
ctx.fillStyle = '#333';
ctx.fillRect(player.x - barWidth/2, player.y - 35, barWidth, barHeight);
ctx.fillStyle = healthPercent > 0.3 ? '#00ff88' : '#ff4444';
ctx.fillRect(player.x - barWidth/2, player.y - 35, barWidth * healthPercent, barHeight);
}
// Name
ctx.fillStyle = player.id === this.playerId ? '#00ffff' : '#fff';
ctx.font = '12px Arial';
ctx.textAlign = 'center';
ctx.fillText(player.name, player.x, player.y - 42);
// Dead indicator
if (!player.alive) {
ctx.fillStyle = 'rgba(255, 0, 0, 0.5)';
ctx.beginPath();
ctx.arc(player.x, player.y, 25, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = '#fff';
ctx.font = 'bold 16px Arial';
ctx.fillText('☠', player.x, player.y + 5);
}
}
}
drawBullets() {
const ctx = this.ctx;
for (const bullet of this.state.bullets) {
ctx.save();
ctx.translate(bullet.x, bullet.y);
ctx.rotate(bullet.angle);
// Bullet trail
const trailGradient = ctx.createLinearGradient(-30, 0, 0, 0);
trailGradient.addColorStop(0, 'transparent');
trailGradient.addColorStop(1, '#ffff00');
ctx.strokeStyle = trailGradient;
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(-30, 0);
ctx.lineTo(0, 0);
ctx.stroke();
// Bullet core
ctx.fillStyle = '#fff';
ctx.beginPath();
ctx.arc(0, 0, 4, 0, Math.PI * 2);
ctx.fill();
// Bullet glow
ctx.shadowColor = '#ffff00';
ctx.shadowBlur = 10;
ctx.fill();
ctx.restore();
}
}
drawPowerups() {
const ctx = this.ctx;
const colors = {
health: '#00ff88',
speed: '#00ffff',
damage: '#ff6b6b'
};
for (const powerup of this.state.powerups) {
if (!powerup.active) continue;
ctx.save();
ctx.translate(powerup.x, powerup.y);
// Pulsing effect
const pulse = Math.sin(Date.now() / 200) * 3;
// Glow
const glowGradient = ctx.createRadialGradient(0, 0, 0, 0, 0, 25 + pulse);
glowGradient.addColorStop(0, colors[powerup.type] + '88');
glowGradient.addColorStop(1, 'transparent');
ctx.fillStyle = glowGradient;
ctx.beginPath();
ctx.arc(0, 0, 25 + pulse, 0, Math.PI * 2);
ctx.fill();
// Core
ctx.fillStyle = colors[powerup.type];
ctx.beginPath();
ctx.arc(0, 0, 12 + pulse/2, 0, Math.PI * 2);
ctx.fill();
// Icon
ctx.fillStyle = '#000';
ctx.font = 'bold 14px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
const icons = { health: '+', speed: '»', damage: '!' };
ctx.fillText(icons[powerup.type], 0, 0);
ctx.restore();
}
}
drawParticles() {
const ctx = this.ctx;
for (const p of this.particles) {
ctx.globalAlpha = p.life;
ctx.fillStyle = p.color;
ctx.beginPath();
ctx.arc(p.x, p.y, 3, 0, Math.PI * 2);
ctx.fill();
}
ctx.globalAlpha = 1;
}
drawMinimap() {
const ctx = this.minimapCtx;
const scale = 180 / (this.config?.WORLD_WIDTH || 2000);
// Background
ctx.fillStyle = '#0a0a1a';
ctx.fillRect(0, 0, 180, 180);
// Grid
ctx.strokeStyle = '#1a1a2e';
ctx.lineWidth = 0.5;
for (let i = 0; i < 180; i += 20) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, 180);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(180, i);
ctx.stroke();
}
// Powerups
for (const powerup of this.state.powerups) {
if (!powerup.active) continue;
ctx.fillStyle = '#ffff00';
ctx.beginPath();
ctx.arc(powerup.x * scale, powerup.y * scale, 2, 0, Math.PI * 2);
ctx.fill();
}
// Players
for (const player of this.state.players) {
ctx.fillStyle = player.id === this.playerId ? '#00ffff' : player.color;
ctx.beginPath();
ctx.arc(player.x * scale, player.y * scale, player.id === this.playerId ? 4 : 3, 0, Math.PI * 2);
ctx.fill();
}
// Viewport rectangle
const myPlayer = this.state.players.find(p => p.id === this.playerId);
if (myPlayer) {
ctx.strokeStyle = '#00ffff88';
ctx.lineWidth = 1;
ctx.strokeRect(
this.camera.x * scale,
this.camera.y * scale,
this.canvas.width * scale,
this.canvas.height * scale
);
}
}
drawCrosshair() {
const ctx = this.ctx;
ctx.strokeStyle = '#ff006688';
ctx.lineWidth = 2;
// Outer circle
ctx.beginPath();
ctx.arc(this.mouse.x, this.mouse.y, 15, 0, Math.PI * 2);
ctx.stroke();
// Cross
ctx.beginPath();
ctx.moveTo(this.mouse.x - 20, this.mouse.y);
ctx.lineTo(this.mouse.x - 8, this.mouse.y);
ctx.moveTo(this.mouse.x + 8, this.mouse.y);
ctx.lineTo(this.mouse.x + 20, this.mouse.y);
ctx.moveTo(this.mouse.x, this.mouse.y - 20);
ctx.lineTo(this.mouse.x, this.mouse.y - 8);
ctx.moveTo(this.mouse.x, this.mouse.y + 8);
ctx.lineTo(this.mouse.x, this.mouse.y + 20);
ctx.stroke();
// Center dot
ctx.fillStyle = '#ff0066';
ctx.beginPath();
ctx.arc(this.mouse.x, this.mouse.y, 2, 0, Math.PI * 2);
ctx.fill();
}
start() {
const gameLoop = () => {
this.update();
this.render();
requestAnimationFrame(gameLoop);
};
gameLoop();
}
}
// ==================== INITIALIZE ====================
const client = new GameClient();
client.start();
function joinGame() {
const name = document.getElementById('playerName').value.trim() || 'Anonymous';
document.getElementById('nameModal').style.display = 'none';
client.connect(name);
}
// Allow Enter key to join
document.getElementById('playerName').addEventListener('keypress', (e) => {
if (e.key === 'Enter') joinGame();
});
</script>
</body>
</html>