-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
456 lines (412 loc) · 16.2 KB
/
app.js
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
const express = require('express');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const path = require('path');
const fs = require('fs');
const vm = require('vm');
const { createCanvas } = require('canvas');
// Create a canvas context for server-side operations
const canvas = createCanvas(800, 600);
const p = canvas.getContext('2d');
// Debug logging
function debug(event, data) {
const timestamp = new Date().toISOString();
console.log(`[${timestamp}] ${event}:`, JSON.stringify(data, null, 2));
}
// Helper function for distance calculations
function distance(p1, p2) {
return Math.sqrt((p2.x-p1.x)**2 + (p2.y-p1.y)**2);
}
// Create base game context with shared dependencies and classes
const baseGameContext = {
console,
setTimeout,
clearTimeout,
setInterval,
clearInterval,
Buffer,
process,
Math,
Point: null, // Will be populated from class files
Item: null, // Will be populated from class files
ItemBox: null, // Will be populated from class files
Racer: null, // Will be populated from class files
Track: null, // Will be populated from class files
Triangle: null, // Will be populated from class files
GeneralPath: null, // Will be populated from class files
Arc: null, // Will be populated from class files
Shape: null, // Will be populated from class files
Items: {}, // Will be populated from Items.js
tracks: [], // Will be populated from Tracks.js
canvas, // Add canvas to game context
p, // Add canvas context to game context
global: null, // Will be set to self
trackNr: 1, // Default track number
items: [], // Room-specific items array
placements: [], // Room-specific placements array
racers: new Map(), // Room-specific racers map
distance: distance, // Add distance function
};
// Create the context and set up self-reference
baseGameContext.global = baseGameContext;
vm.createContext(baseGameContext);
// Load all class files in correct order
const clientPath = path.join(__dirname, 'Client');
const classFiles = [
'classes/ShapesClasses.js', // Contains Point and basic shapes
'classes/ItemClass.js', // Base Item class
'classes/itemBoxClass.js', // ItemBox class that extends Item
'classes/RacerClass.js', // Racer class
'classes/TrackClass.js' // Track class
];
// Load the class files in order
classFiles.forEach(file => {
const filepath = path.join(clientPath, file);
const content = fs.readFileSync(filepath, 'utf8');
try {
// Wrap class definitions to expose them to game context
const wrappedContent = `
(function(exports) {
${content}
if (typeof Point !== 'undefined') exports.Point = Point;
if (typeof Item !== 'undefined') exports.Item = Item;
if (typeof ItemBox !== 'undefined') exports.ItemBox = ItemBox;
if (typeof Racer !== 'undefined') exports.Racer = Racer;
if (typeof Track !== 'undefined') exports.Track = Track;
if (typeof Triangle !== 'undefined') exports.Triangle = Triangle;
if (typeof GeneralPath !== 'undefined') exports.GeneralPath = GeneralPath;
if (typeof Arc !== 'undefined') exports.Arc = Arc;
if (typeof Shape !== 'undefined') exports.Shape = Shape;
})(this);
`;
vm.runInContext(wrappedContent, baseGameContext);
} catch (error) {
console.error(`Error loading ${file}:`, error);
throw error;
}
});
// Load game data files
const dataFiles = [
'data/Items.js', // Must be loaded first as other files depend on Items
'data/CarStats.js',
'data/ItemDistributions.js',
'data/StateChanges.js',
'data/Tracks.js' // Load tracks last as they depend on Items
];
// Load the data files
dataFiles.forEach(file => {
const filepath = path.join(clientPath, file);
const content = fs.readFileSync(filepath, 'utf8');
try {
// Wrap data files to expose variables to game context
const wrappedContent = `
(function(exports) {
${content}
if (typeof tracks !== 'undefined') exports.tracks = tracks;
if (typeof Items !== 'undefined') exports.Items = Items;
if (typeof carStats !== 'undefined') exports.carStats = carStats;
if (typeof itemDistributions !== 'undefined') exports.itemDistributions = itemDistributions;
if (typeof stateChanges !== 'undefined') exports.stateChanges = stateChanges;
})(this);
`;
vm.runInContext(wrappedContent, baseGameContext);
} catch (error) {
console.error(`Error loading ${file}:`, error);
throw error;
}
});
// Create a new game context for a room
function createRoomGameContext() {
const context = {
...baseGameContext,
items: [], // Initialize new items array for this room
placements: [], // Initialize new placements array for this room
racers: new Map(), // Initialize new racers map for this room
// Override loadTrack to handle room-specific items
loadTrack: function(track) {
// Call base loadTrack to update trackNr
this.trackNr = this.tracks.indexOf(track) + 1;
this.items = []; // Clear existing items
this.placements = []; // Clear existing placements
// Load item boxes
track.itemBoxes.forEach(element => {
const itemBox = new this.Item(
"itemBox",
new this.Point(element.position.x * track.scale, element.position.y * track.scale),
null,
null,
0,
new this.Point(0, 0),
0
);
this.items.push(itemBox);
});
// Load other items (like nitro crystals)
track.items.forEach(element => {
const item = new this.Item(
element.type,
new this.Point(element.position.x * track.scale, element.position.y * track.scale),
null,
null,
0,
new this.Point(0, 0),
0
);
this.items.push(item);
});
let racerNr = 0;
this.racers.forEach((id, racer) => {
this.racers.set(id, track.racers[racerNr]);
racerNr++;
}
)
debug('Track loaded', {
itemCount: this.items.length,
itemBoxes: track.itemBoxes.length,
otherItems: track.items.length
});
}
};
return context;
}
// Create a new game room
function createGameRoom(roomId) {
const room = {
id: roomId,
gameStarted: false,
lastUpdate: Date.now(),
gameContext: createRoomGameContext(),
update: function(){
this.gameContext.items.forEach(function(item){
baseGameContext.Items[item.type].update(item);
});
this.gameContext.items = this.gameContext.items.filter(function(item){
return !item.delete;
});
}
};
// Initialize track (using first track from tracks array)
if (baseGameContext.tracks && baseGameContext.tracks.length > 0) {
debug('Loading initial track', {
trackCount: baseGameContext.tracks.length,
firstTrack: baseGameContext.tracks[0].name
});
room.gameContext.loadTrack(baseGameContext.tracks[0]);
} else {
debug('Warning: No tracks available for room', { roomId });
}
return room;
}
// Game rooms state
const gameRooms = new Map();
const MAX_PLAYERS_PER_ROOM = 6;
// Find or create a room for a player
function findOrCreateRoom(socket) {
// Find a room with space
for (const [roomId, room] of gameRooms) {
if (room.gameContext.racers.size < MAX_PLAYERS_PER_ROOM) {
debug('Found existing room', {
roomId,
players: room.gameContext.racers.size,
itemCount: room.gameContext.items.length
});
return roomId;
}
}
// Create new room if none found
const roomId = `room_${Date.now()}`;
const newRoom = createGameRoom(roomId);
gameRooms.set(roomId, newRoom);
debug('Created new room', {
roomId,
itemCount: newRoom.gameContext.items.length,
trackNumber: newRoom.gameContext.trackNr
});
return roomId;
}
// Serve static files from Client directory
app.use(express.static(path.join(__dirname, 'Client')));
// Import express-rate-limit
const rateLimit = require('express-rate-limit');
// Create a rate limit middleware
const limiter = rateLimit({
windowMs: 10 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per windowMs
message: 'Too many requests, please try again later.'
});
// Apply the rate limit middleware to the root route
app.get('/', limiter, (req, res) => {
res.sendFile(path.join(__dirname, 'Client', 'Racing.html'));
});
// Socket connection handling
io.on('connection', (socket) => {
debug('Player connected', { playerId: socket.id });
// Handle player joining
const roomId = findOrCreateRoom(socket);
socket.join(roomId);
const room = gameRooms.get(roomId);
// Create new racer
const newRacer = {
id: socket.id,
isPlayer: true,
position: room.gameContext.tracks[room.gameContext.trackNr-1].racers[room.gameContext.racers.size].position.copy(),
angle: room.gameContext.tracks[room.gameContext.trackNr-1].racers[room.gameContext.racers.size].angle,
speed: 0,
items: [],
effects: [],
currentLap: 1,
drifting: false,
driftAngle: 0,
finished: false
};
newRacer.position.scale(room.gameContext.tracks[room.gameContext.trackNr-1].scale);
room.gameContext.racers.set(socket.id, newRacer);
debug('Player joined room', {
roomId,
playerId: socket.id,
playerCount: room.gameContext.racers.size,
itemCount: room.gameContext.items.length
});
// Notify all players
io.to(roomId).emit('playerJoined', {
id: socket.id,
racers: Array.from(room.gameContext.racers.values()),
roomId: roomId
});
// Start game if enough players
if (room.gameContext.racers.size >= 2) {
room.gameStarted = true;
debug('Starting game', {
roomId,
playerCount: room.gameContext.racers.size
});
io.to(roomId).emit('gameStart', Array.from(room.gameContext.racers.values()));
}
// Handle player updates
socket.on('playerUpdate', (data) => {
const room = gameRooms.get(data.roomId);
if (!room || !room.gameContext.racers.has(socket.id)) return;
// Update racer state
const racer = room.gameContext.racers.get(socket.id);
Object.assign(racer, data);
room.lastUpdate = Date.now();
});
// Handle item events
socket.on('itemEvent', (data) => {
const room = gameRooms.get(data.roomId);
if (!room || !room.gameContext.racers.has(socket.id)) return;
debug('Item event', {
roomId: data.roomId,
playerId: socket.id,
itemType: data.item.type,
itemPosition: data.item.position,
itemState: data.state,
ownerId: data.item.ownerId,
itemId: data.item.id
});
const newItem = new room.gameContext.Item(data.item.type, new room.gameContext.Point(data.item.position.x, data.item.position.y), data.item.target, data.item.ownerId, data.item.duration, new room.gameContext.Point(data.item.velocity.x, data.item.velocity.y), data.item.direction, data.item.state);
newItem.id = data.item.id;
room.gameContext.items.push(newItem);
});
socket.on('itemUpdate', (data) => {
const room = gameRooms.get(data.roomId);
if (!room || !room.gameContext.racers.has(socket.id)) return;
debug('Item update', {
roomId: data.roomId,
playerId: socket.id,
itemId: data.itemId,
dataToUpdate: data.dataToUpdate
});
Object.assign(room.gameContext.items.find(item => item.id === data.itemId), data.dataToUpdate);
});
// Handle disconnection
socket.on('disconnect', () => {
for (const [roomId, room] of gameRooms) {
if (room.gameContext.racers.has(socket.id)) {
room.gameContext.racers.delete(socket.id);
debug('Player left', {
roomId,
playerId: socket.id,
remainingPlayers: room.gameContext.racers.size
});
// Notify other players
io.to(roomId).emit('playerLeft', socket.id);
// Clean up empty rooms
if (room.gameContext.racers.size === 0) {
gameRooms.delete(roomId);
debug('Room deleted', { roomId });
}
break;
}
}
});
});
// Game state update loop
setInterval(() => {
const now = Date.now();
gameRooms.forEach((room, roomId) => {
if (room.gameStarted && room.gameContext.racers.size > 0) {
let gameState = {
racers: [],
items: []
};
for (const [id, racer] of room.gameContext.racers) {
gameState.racers.push({
id: id,
position: racer.position,
angle: racer.angle,
speed: racer.speed,
drifting: racer.drifting,
currentLap: racer.currentLap,
checkpoints: racer.checkpoints,
hasForceField: racer.hasForceField,
isEMPed: racer.isEMPed,
forcefieldTimer: racer.forceFieldTimer,
empTimer: racer.empTimer,
state: racer.state,
collisionRadius: racer.collisionRadius,
nitroCrystals: racer.nitroCrystals,
finished: racer.finished
});
}
for (const item of room.gameContext.items){
gameState.items.push({
type: item.type,
position: item.position,
duration: item.duration,
velocity: item.velocity,
direction: item.direction,
collisionRadius: item.collisionRadius,
ownerId: item.ownerId,
target: item.target,
state: item.state,
id: item.id
});
}
// Send game state to all players
io.to(roomId).emit('gameStateUpdate', gameState);
}
});
}, 1000/10); // 10 times per second
//Update game state
setInterval(() => {
gameRooms.forEach((room, roomId) => {
if (room.gameStarted && room.gameContext.racers.size > 0) {
room.update();
}
});
}, 1000/60);
// Start server
const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || '0.0.0.0';
http.listen(PORT, HOST, () => {
console.log('\n=================================================================');
console.log('🏎️ Racing Game Server Started!');
console.log('=================================================================');
console.log('🌐 Local URL: http://localhost:' + PORT);
console.log('🌍 Network URL: http://' + require('os').networkInterfaces()['Wi-Fi']?.find(ip => ip.family === 'IPv4')?.address + ':' + PORT);
console.log('=================================================================');
console.log('Waiting for tunnel URL...');
console.log('=================================================================\n');
});