-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
398 lines (267 loc) · 9.09 KB
/
server.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
import { readFile } from "node:fs/promises";
import { createServer } from "node:https";
import { Server as SocketIOServer } from "socket.io";
import { Http3Server } from "@fails-components/webtransport";
import express from "express";
import fs from "fs";
/* SERVER SETUP */
// using express to serve static files
// and HTTP/3 server to handle WebTransport sessions with Socket.IO
const app = express();
app.use(express.static('client'));
// required for HTTP/3
const key = fs.readFileSync('./key.pem', 'utf8');
const cert = fs.readFileSync('./cert.pem', 'utf8');
app.get('/', async (req, res) => {
try {
const content = await readFile("./client/index.html", "utf8");
res.send(content);
} catch (error) {
res.status(500).send('Error reading index.html');
}
});
const httpsServer = createServer( {key, cert}, app);
const port = process.env.PORT || 3000;
httpsServer.listen(port, () => {
console.log('HTTPS server listening on port 3000');
});
const h3Server = new Http3Server({
port,
host: "0.0.0.0",
secret: "changeit",
cert,
privKey: key,
});
h3Server.startServer();
(async () => {
try {
const stream = await h3Server.sessionStream("/socket.io/");
const sessionReader = stream.getReader();
while (true) {
const { done, value } = await sessionReader.read();
if (done) {
break;
}
io.engine.onWebTransportSession(value);
}
} catch (error) {
console.error("Error in WebTransport session stream:", error);
}
})();
const io = new SocketIOServer(httpsServer, {
transports: ["polling", "webtransport", "websocket"],
// pingInterval: 5000, // 5 seconds
// pingTimeout: 5000, // timeout for inactive users
});
/* ----------------- */
const serverPlayers = {};
let numPlayers = 0;
const serverBullets = {};
let bulletId = 0;
const serverEnemy = {
x: 0,
y: 0,
health: 100,
width: 200,
height: 160,
};
const enemyBullets = {};
let enemyBulletId = 0;
let canvasWidth = 0;
let canvasHeight = 0;
/* ----------------- */
io.on("connection", (socket) => {
numPlayers++;
serverPlayers[socket.id] = {
x: 500 * Math.random(),
y: 500 * Math.random(),
sequenceNumber: 0,
width: 60,
height: 60,
health: 100
};
console.log("user " + socket.id + " connected with transport " + socket.conn.transport.name);
io.emit("updatePlayers", serverPlayers);
io.emit("numPlayers", numPlayers);
/* ----------------- */
// handle transport upgrades (e.g., from polling to websocket)
socket.conn.on("upgrade", (transport) => {
console.log("transport upgraded to " + transport.name);
});
/* ----------------- */
// handle canvas size initialization and enemy creation
socket.on("initCanvas", ({ width, height }) => {
// displays the enemy in the center of the canvas
serverEnemy.x = (width - serverEnemy.width) / 2;
serverEnemy.y = (height - serverEnemy.height) / 2;
canvasWidth = width;
canvasHeight = height;
io.emit("createEnemy", serverEnemy);
});
/* ----------------- */
// player movement handler -> given to ticker function
const SPEED = 4;
socket.on("move", ({ direction, sequenceNumber}) => {
if(!serverPlayers[socket.id]) return;
serverPlayers[socket.id].sequenceNumber = sequenceNumber;
switch (direction) {
case "left":
serverPlayers[socket.id].x -= SPEED;
break;
case "up":
serverPlayers[socket.id].y -= SPEED;
break;
case "right":
serverPlayers[socket.id].x += SPEED;
break;
case "down":
serverPlayers[socket.id].y += SPEED;
break;
}
});
/* ----------------- */
// handle player shooting
socket.on("shoot", ({ x, y, angle }) => {
bulletId++;
const velocity = {
x: Math.cos(angle) * 5,
y: Math.sin(angle) * 5
};
serverBullets[bulletId] = {
x,
y,
width: 10,
height: 10,
type: "player",
velocity,
playerId: socket.id
};
});
/* ----------------- */
socket.on("disconnect", (reason) => {
console.log("user " + socket.id + " disconnected due to " + reason);
delete serverPlayers[socket.id];
io.emit("updatePlayers", serverPlayers);
numPlayers--;
io.emit("numPlayers", numPlayers);
});
});
/* ----------------- */
// ticker function to update player positions & bullets
// and emit the updated player positions to all clients
// this prevents clogging the network with too many messages
setInterval(() => {
const bulletsToRemove = [];
// update bullets
for (const id in serverBullets) {
serverBullets[id].x += serverBullets[id].velocity.x;
serverBullets[id].y += serverBullets[id].velocity.y;
// check for collisions with the enemy
if (checkCollision(serverBullets[id], serverEnemy)) {
console.log("collision detected");
bulletsToRemove.push(id);
serverEnemy.health -= 5;
if (serverEnemy.health <= 0) {
console.log("enemy died");
serverEnemy.health = 0;
io.emit("enemyDied");
}
io.emit("updateEnemy", serverEnemy);
}
// check for out of bounds bullets
if (checkOutOfBounds(serverBullets[id])) {
// console.log("bullet out of bounds");
bulletsToRemove.push(id);
}
}
// remove bullets that have collided with the enemy
for (const id of bulletsToRemove) {
delete serverBullets[id];
}
io.emit("updateBullets", serverBullets);
io.emit("updatePlayers", serverPlayers);
}, 15 ); // 15ms is recommended for 60fps
// increasing this -> delay in player movement
/* ----------------- */
// ENEMY BULLET EMITTING
let numBullets = 0;
setInterval(() => {
if (serverEnemy.health <= 0) return;
if (numBullets <= 50)
numBullets++;
const angleIncrement = (2 * Math.PI) / numBullets; // radius emission
const centerX = (canvasWidth - serverEnemy.width) / 2 + serverEnemy.width / 2;
const centerY = (canvasHeight - serverEnemy.height) / 2 + serverEnemy.height / 2;
const bulletDim = 5;
for (let i = 0; i < numBullets; i++) {
enemyBulletId++;
const angle = angleIncrement * i;
const velocity = {
x: Math.cos(angle) * 5,
y: Math.sin(angle) * 5
};
enemyBullets[enemyBulletId] = {
x: centerX,
y: centerY,
type: "enemy",
width: bulletDim,
height: bulletDim,
velocity
};
}
io.emit("updateEnemyBullets", enemyBullets);
}, 2000); // Enemy shoots every 2 seconds
setInterval(() => {
let damage = 10;
const enemyBulletsToRemove = [];
// Update enemy bullets
for (const id in enemyBullets) {
enemyBullets[id].x += enemyBullets[id].velocity.x;
enemyBullets[id].y += enemyBullets[id].velocity.y;
// Check for collisions with players
for (const playerId in serverPlayers) {
if (checkCollision(enemyBullets[id], serverPlayers[playerId])) {
console.log("Player hit by enemy bullet");
// Mark bullet for removal
enemyBulletsToRemove.push(id);
// Damage player
serverPlayers[playerId].health -= damage;
if (serverPlayers[playerId].health <= 0) {
console.log("Player died");
delete serverPlayers[playerId];
io.emit("updatePlayers", serverPlayers);
}
io.emit("updatePlayer", serverPlayers[playerId]);
}
}
// Check for out of bounds bullets
if (checkOutOfBounds(enemyBullets[id])) {
enemyBulletsToRemove.push(id);
}
}
// Remove bullets that have collided with players
for (const id of enemyBulletsToRemove) {
delete enemyBullets[id];
}
io.emit("updateEnemyBullets", enemyBullets);
}, 15); // Update at 60 FPS
/* ----------------- */
function checkCollision(bullet, enemy) {
// Check if the bullet is within the enemy's bounding box
return bullet.x < enemy.x + enemy.width &&
bullet.x + bullet.width > enemy.x &&
bullet.y < enemy.y + enemy.height &&
bullet.y + bullet.height > enemy.y;
}
/* ----------------- */
// function that deletes bullets that go out of bounds
function checkOutOfBounds(bullet) {
return bullet.x < 0 || bullet.x > canvasWidth
|| bullet.y < 0 || bullet.y > canvasHeight;
}
/* ----------------- */
// handle webtransport session errors
io.engine.on('webtransport-error', (error) => {
console.error("WebTransport Error:", error);
});
/* ----------------- */