-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
618 lines (563 loc) · 22.9 KB
/
server.js
File metadata and controls
618 lines (563 loc) · 22.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
// Serve multiplayer.html as default page
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'multiplayer.html'));
});
// Serve static files (after routes)
app.use(express.static(path.join(__dirname)));
// Game world dimensions
const WORLD_WIDTH = 3000;
const WORLD_HEIGHT = 2250;
// Game state
const players = new Map();
const fireballs = [];
const coins = [];
const bots = [];
const teleportEffects = [];
// Generate initial coins
function generateCoins() {
for (let i = 0; i < 50; i++) {
coins.push({
id: uuidv4(),
x: Math.random() * (WORLD_WIDTH - 40) + 20,
y: Math.random() * (WORLD_HEIGHT - 40) + 20,
size: 12,
collected: false,
bobOffset: Math.random() * Math.PI * 2,
sparkles: []
});
}
}
// Generate initial bots
function generateBots() {
for (let i = 0; i < 3; i++) {
bots.push({
id: uuidv4(),
x: Math.random() * (WORLD_WIDTH - 100) + 50,
y: Math.random() * (WORLD_HEIGHT - 100) + 50,
width: 32,
height: 32,
speed: 5,
health: 2,
maxHealth: 2,
direction: Math.random() * Math.PI * 2,
coins: 0,
lastShot: 0,
shootCooldown: 60,
state: 'wander',
alive: true,
color: ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57'][i % 5]
});
}
}
// Initialize game objects
generateCoins();
generateBots();
// WebSocket connection handling
wss.on('connection', (ws) => {
const playerId = uuidv4();
// Create new player with placeholder nickname/color
const player = {
id: playerId,
x: Math.random() * (WORLD_WIDTH - 100) + 50,
y: Math.random() * (WORLD_HEIGHT - 100) + 50,
width: 32,
height: 32,
baseWidth: 32,
baseHeight: 32,
speed: 8,
minSpeed: 4,
health: 100,
maxHealth: 100,
direction: 0,
coins: 0,
level: 1,
coinsToNextLevel: 10,
fireballSize: 12,
teleportCooldown: 0,
teleportMaxCooldown: 180,
teleportDistance: 120,
shootCooldown: 0,
shootMaxCooldown: 12, // 200ms at 60 FPS
alive: true,
mouseX: 0,
mouseY: 0,
keys: {},
nickname: 'Player',
color: '#ff6b6b'
};
players.set(playerId, player);
console.log(`Player ${playerId} connected. Total players: ${players.size}`);
console.log(`Current game state: ${coins.filter(c => !c.collected).length} coins, ${bots.filter(b => b.alive).length} bots, ${fireballs.length} fireballs`);
// Wait for join message to set nickname/color
ws.on('message', (message) => {
try {
const data = JSON.parse(message);
switch (data.type) {
case 'join':
if (players.has(playerId)) {
const p = players.get(playerId);
p.nickname = data.nickname || 'Player';
p.color = data.color || '#ff6b6b';
}
// Send initial game state to new player
ws.send(JSON.stringify({
type: 'init',
playerId: playerId,
players: Array.from(players.values()),
coins: coins,
bots: bots,
worldWidth: WORLD_WIDTH,
worldHeight: WORLD_HEIGHT
}));
// Broadcast updated game state to all
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
type: 'gameUpdate',
players: Array.from(players.values()),
fireballs: fireballs,
coins: coins.filter(coin => !coin.collected),
bots: bots.filter(bot => bot.alive)
}));
}
});
break;
case 'updateInput':
if (players.has(playerId)) {
const player = players.get(playerId);
player.keys = data.keys || {};
player.mouseX = data.mouseX || 0;
player.mouseY = data.mouseY || 0;
if (typeof data.direction === 'number') {
player.direction = data.direction;
}
}
break;
case 'shootFireball':
if (players.has(playerId)) {
const player = players.get(playerId);
if (player.shootCooldown <= 0) {
const fireball = {
id: uuidv4(),
x: data.x,
y: data.y,
direction: data.direction,
speed: 8,
size: data.size || 12,
lifetime: 120,
isPlayerFireball: true,
playerId: playerId,
damage: Math.floor(Math.log(player.level)*5 + 1)
};
fireballs.push(fireball);
// Set shooting cooldown
player.shootCooldown = player.shootMaxCooldown;
// Broadcast fireball to all players
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
type: 'fireballShot',
fireball: fireball
}));
}
});
}
}
break;
case 'teleport':
if (players.has(playerId)) {
const player = players.get(playerId);
if (player.teleportCooldown <= 0) {
player.x = data.x;
player.y = data.y;
player.teleportCooldown = player.teleportMaxCooldown;
// Broadcast teleport to all players
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
type: 'playerTeleported',
playerId: playerId,
x: player.x,
y: player.y
}));
}
});
}
}
break;
}
} catch (error) {
console.error('Error parsing message:', error);
}
});
// Handle player disconnect
ws.on('close', () => {
players.delete(playerId);
console.log(`Player ${playerId} disconnected. Total players: ${players.size}`);
// Broadcast player disconnect to all other players
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
type: 'playerLeft',
playerId: playerId
}));
}
});
});
});
// Game loop for server-side updates
setInterval(() => {
// Update all players
players.forEach((player, playerId) => {
if (!player.alive) return;
// Update player movement based on keys
let dx = 0;
let dy = 0;
if (player.keys['w'] || player.keys['arrowup']) dy -= player.speed;
if (player.keys['s'] || player.keys['arrowdown']) dy += player.speed;
if (player.keys['a'] || player.keys['arrowleft']) dx -= player.speed;
if (player.keys['d'] || player.keys['arrowright']) dx += player.speed;
// Diagonal movement normalization
if (dx !== 0 && dy !== 0) {
dx *= 0.707;
dy *= 0.707;
}
// Update player position
player.x = Math.max(0, Math.min(player.x + dx, WORLD_WIDTH - player.width));
player.y = Math.max(0, Math.min(player.y + dy, WORLD_HEIGHT - player.height));
// Check coin collection
coins.forEach(coin => {
if (!coin.collected) {
// Check if coin intersects with player's body rectangle
const playerLeft = player.x;
const playerRight = player.x + player.width;
const playerTop = player.y;
const playerBottom = player.y + player.height;
const coinLeft = coin.x - coin.size;
const coinRight = coin.x + coin.size;
const coinTop = coin.y - coin.size;
const coinBottom = coin.y + coin.size;
// Check for rectangle intersection
if (playerLeft < coinRight && playerRight > coinLeft &&
playerTop < coinBottom && playerBottom > coinTop) {
coin.collected = true;
player.coins++;
// Level up every 10 coins
if (player.coins >= player.coinsToNextLevel) {
player.level++;
player.coinsToNextLevel += 10;
player.maxHealth = Math.min(100, player.maxHealth + 3);
player.health = Math.min(100, player.health + 3);
const scaleFactor = 1 + Math.log(player.level) * 1.5;
player.width = player.baseWidth * scaleFactor;
player.height = player.baseHeight * scaleFactor;
player.fireballSize = 12 * scaleFactor;
player.speed = Math.max(player.minSpeed, player.speed - 0.3);
}
// Reduce teleport cooldown
player.teleportCooldown = Math.max(0, player.teleportCooldown - 30);
// Broadcast coin collected
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
type: 'coinCollected',
coinId: coin.id,
playerId: playerId,
newCoins: player.coins,
newLevel: player.level
}));
}
});
}
}
});
// Update teleport cooldown
if (player.teleportCooldown > 0) {
player.teleportCooldown--;
}
// Update shooting cooldown
if (player.shootCooldown > 0) {
player.shootCooldown--;
}
});
// Update fireballs
const fireballsToRemove = [];
for (let i = fireballs.length - 1; i >= 0; i--) {
const fireball = fireballs[i];
// Move fireball
fireball.x += Math.cos(fireball.direction) * fireball.speed;
fireball.y += Math.sin(fireball.direction) * fireball.speed;
// Check bounds
if (fireball.x < 0 || fireball.x > WORLD_WIDTH ||
fireball.y < 0 || fireball.y > WORLD_HEIGHT) {
fireballsToRemove.push(i);
continue;
}
// Check collisions
let shouldRemove = false;
if (fireball.isPlayerFireball) {
// Player fireball hits bots
for (let j = 0; j < bots.length; j++) {
const bot = bots[j];
if (bot.alive) {
const distance = Math.sqrt(
Math.pow(fireball.x - (bot.x + bot.width/2), 2) +
Math.pow(fireball.y - (bot.y + bot.height/2), 2)
);
if (distance < fireball.size) {
bot.health -= fireball.damage;
if (bot.health <= 0) {
bot.alive = false;
// Drop coins
const coinsToDrop = Math.max(5, bot.coins);
for (let k = 0; k < coinsToDrop; k++) {
const angle = (k / coinsToDrop) * Math.PI * 2;
const dropDistance = 30 + Math.random() * 20;
const dropX = bot.x + bot.width/2 + Math.cos(angle) * dropDistance;
const dropY = bot.y + bot.height/2 + Math.sin(angle) * dropDistance;
coins.push({
id: uuidv4(),
x: dropX,
y: dropY,
size: 12,
collected: false,
bobOffset: Math.random() * Math.PI * 2,
sparkles: []
});
}
}
shouldRemove = true;
break;
}
}
}
// Player fireball hits other players
for (const [otherId, otherPlayer] of players.entries()) {
if (otherPlayer.alive && otherId !== fireball.playerId) {
const distance = Math.sqrt(
Math.pow(fireball.x - (otherPlayer.x + otherPlayer.width/2), 2) +
Math.pow(fireball.y - (otherPlayer.y + otherPlayer.height/2), 2)
);
if (distance < fireball.size) {
otherPlayer.health -= fireball.damage;
if (otherPlayer.health <= 0) {
otherPlayer.alive = false;
}
shouldRemove = true;
break;
}
}
}
} else {
// Bot fireball hits players
for (let j = 0; j < players.size; j++) {
const player = Array.from(players.values())[j];
if (player.alive) {
const distance = Math.sqrt(
Math.pow(fireball.x - (player.x + player.width/2), 2) +
Math.pow(fireball.y - (player.y + player.height/2), 2)
);
if (distance < fireball.size) {
player.health -= fireball.damage;
if (player.health <= 0) {
player.alive = false;
}
shouldRemove = true;
break;
}
}
}
}
// Update lifetime
fireball.lifetime--;
if (fireball.lifetime <= 0) {
shouldRemove = true;
}
if (shouldRemove) {
fireballsToRemove.push(i);
}
}
// Remove fireballs that should be removed
fireballsToRemove.forEach(index => {
fireballs.splice(index, 1);
});
// Update bots
bots.forEach(bot => {
if (!bot.alive) return;
// Simple AI: move towards nearest coin or player, or wander randomly
let targetX = bot.x;
let targetY = bot.y;
let hasTarget = false;
// Find nearest coin
let nearestCoin = null;
let nearestDistance = Infinity;
coins.forEach(coin => {
if (!coin.collected) {
const distance = Math.sqrt(
Math.pow(bot.x - coin.x, 2) + Math.pow(bot.y - coin.y, 2)
);
if (distance < nearestDistance) {
nearestDistance = distance;
nearestCoin = coin;
}
}
});
if (nearestCoin && nearestDistance < 150) {
targetX = nearestCoin.x;
targetY = nearestCoin.y;
hasTarget = true;
} else {
// Move towards nearest player
let nearestPlayer = null;
let nearestPlayerDistance = Infinity;
players.forEach(player => {
if (player.alive) {
const distance = Math.sqrt(
Math.pow(bot.x - (player.x + player.width/2), 2) +
Math.pow(bot.y - (player.y + player.height/2), 2)
);
if (distance < nearestPlayerDistance) {
nearestPlayerDistance = distance;
nearestPlayer = player;
}
}
});
if (nearestPlayer && nearestPlayerDistance < 200) {
targetX = nearestPlayer.x + nearestPlayer.width/2;
targetY = nearestPlayer.y + nearestPlayer.height/2;
hasTarget = true;
}
}
// If no specific target, wander randomly
if (!hasTarget) {
// Change wandering direction occasionally
if (!bot.wanderTarget || Math.random() < 0.02) {
bot.wanderTarget = {
x: Math.random() * (WORLD_WIDTH - 100) + 50,
y: Math.random() * (WORLD_HEIGHT - 100) + 50
};
}
targetX = bot.wanderTarget.x;
targetY = bot.wanderTarget.y;
}
// Move towards target
const dx = targetX - bot.x;
const dy = targetY - bot.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance > 0) {
bot.direction = Math.atan2(dy, dx);
bot.x += Math.cos(bot.direction) * bot.speed;
bot.y += Math.sin(bot.direction) * bot.speed;
}
// Keep within bounds
bot.x = Math.max(0, Math.min(bot.x, WORLD_WIDTH - bot.width));
bot.y = Math.max(0, Math.min(bot.y, WORLD_HEIGHT - bot.height));
// Shoot at players
bot.lastShot++;
if (bot.lastShot >= bot.shootCooldown && Math.random() < 1.0) {
players.forEach(player => {
if (player.alive) {
const distance = Math.sqrt(
Math.pow(bot.x - (player.x + player.width/2), 2) +
Math.pow(bot.y - (player.y + player.height/2), 2)
);
if (distance < 300) {
const direction = Math.atan2(
(player.y + player.height/2) - bot.y,
(player.x + player.width/2) - bot.x
);
fireballs.push({
id: uuidv4(),
x: bot.x + bot.width/2,
y: bot.y + bot.height/2,
direction: direction,
speed: 6,
size: 10,
lifetime: 90,
isPlayerFireball: false,
damage: 1
});
bot.lastShot = 0;
}
}
});
}
// Collect coins
coins.forEach(coin => {
if (!coin.collected) {
const distance = Math.sqrt(
Math.pow(bot.x - coin.x, 2) + Math.pow(bot.y - coin.y, 2)
);
if (distance < 25) {
coin.collected = true;
bot.coins++;
}
}
});
});
// Regenerate coins if needed
const activeCoins = coins.filter(coin => !coin.collected).length;
if (activeCoins < 20) {
for (let i = 0; i < 15; i++) {
coins.push({
id: uuidv4(),
x: Math.random() * (WORLD_WIDTH - 40) + 20,
y: Math.random() * (WORLD_HEIGHT - 40) + 20,
size: 12,
collected: false,
bobOffset: Math.random() * Math.PI * 2,
sparkles: []
});
}
}
// Regenerate bots if needed
const aliveBots = bots.filter(bot => bot.alive).length;
if (aliveBots < 3) {
bots.push({
id: uuidv4(),
x: Math.random() * (WORLD_WIDTH - 100) + 50,
y: Math.random() * (WORLD_HEIGHT - 100) + 50,
width: 32,
height: 32,
speed: 5,
health: 2,
maxHealth: 2,
direction: Math.random() * Math.PI * 2,
coins: 0,
lastShot: 0,
shootCooldown: 60,
state: 'wander',
alive: true,
color: ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57'][Math.floor(Math.random() * 5)]
});
}
// Broadcast updated game state to all players
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
type: 'gameUpdate',
players: Array.from(players.values()),
fireballs: fireballs,
coins: coins.filter(coin => !coin.collected),
bots: bots.filter(bot => bot.alive)
}));
}
});
}, 1000 / 60); // 60 FPS
const PORT = process.env.PORT || 3000;
const HOST = '0.0.0.0';
server.listen(PORT, HOST, () => {
console.log(`Fireballz server running on http://0.0.0.0:${PORT}`);
console.log(`Local access: http://localhost:${PORT}`);
console.log(`Network access: http://[YOUR_IP]:${PORT}`);
console.log(`WebSocket server ready for multiplayer connections`);
console.log(`Other devices on your network can connect using your computer's IP address`);
});