-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
executable file
·383 lines (358 loc) · 12.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
'use strict';
const
http = require('http'),
path = require('path'),
fs = require('fs'),
rootFile = 'index.html',
rootFilePath = path.join(__dirname, rootFile),
server_port = process.env.PORT || 8181,
server_ip_address = process.env.IP || 'localhost',
server = http.createServer(),
WebSocket = require('ws'),
WebSocketServer = WebSocket.Server,
webSocketServer = new WebSocketServer({server: server});
const
fromJSON = function(string) {
if (typeof string === 'string') {
if (string) {
return JSON.parse(string);
}
return string
}
throw new Error('Invalid fromJSON argument')
},
safe = function(func, data) {
if (!func || typeof func !== 'function') {
throw new Error('Invalid use!');
}
let result;
try {
result = func.apply(this, data);
} catch (e) {
console.error(e);
}
return result;
},
safeFromJSON = function() {
let data = Array.from(arguments);
return safe(fromJSON, data);
};
// read async file by provided path
var readStaticFile = function(options, req, res) {
fs.stat(options.fullPath, function(err, fileStat) {
if (err) {
res.writeHead(500, {'Content-Type': 'text/json'});
res.end(toJSON(err), 'utf-8');
return;
}
fs.readFile(options.fullPath, options.encoding, function(err, fileContent) {
if (err) {
res.writeHead(500, {'Content-Type': 'text/json'});
res.end(toJSON(err), 'utf-8');
return;
}
console.log(options.fullPath, options.encoding, options.contentType, fileStat.size);
res.writeHead(200, {'Content-Type': options.contentType, 'Content-Length': fileStat.size});
res.end(fileContent, options.encoding);
});
});
};
// create server that serves static files
server.on('request', function(req, res) {
var fullPath;
if (req.url === '/') {
fullPath = rootFilePath;
} else {
fullPath = path.join(__dirname, req.url);
}
var extname = path.extname(fullPath), contentType, encoding;
switch (extname) {
case '.html':
contentType = 'text/html';
encoding = 'utf-8';
break;
case '.js':
contentType = 'text/javascript';
encoding = 'utf-8';
break;
case '.css':
contentType = 'text/css';
encoding = 'utf-8';
break;
case '.json':
contentType = 'application/json';
encoding = 'utf-8';
break;
case '.png':
contentType = 'image/png';
encoding = 'binary';
break;
case '.jpg':
contentType = 'image/jpg';
encoding = 'binary';
break;
case '.ico':
contentType = 'image/x-icon';
encoding = 'binary';
break;
case '.gif':
contentType = 'image/gif';
encoding = 'binary';
break;
case '.mp3':
contentType = 'audio/mpeg';
encoding = 'binary';
break;
case '.ogg':
contentType = 'audio/ogg';
encoding = 'binary';
break;
}
if (contentType && encoding) {
readStaticFile({contentType: contentType, encoding: encoding, fullPath: fullPath}, req, res);
} else {
res.writeHead(400, {'Content-Type': 'text/json'});
res.end(toJSON({message: "File is not found or doesn't exist!"}), 'utf-8');
}
});
server.listen(server_port, server_ip_address, (err) => {
if (err) {
return console.error(err);
}
console.log('Server is listening on http://localhost:' + server.address().port + ' Ctrl+C to stop;');
});
// Logic to determine whether a specified connection is allowed.
const
wscIsAllowed = function(wsc) {
// Check criteria such as request.origin, request.remoteAddress
return true;
},
wscIsNotAllowed = function(wsc) {
return !wscIsAllowed(wsc);
},
measureLatency = function(player) {
let wsc = player.wsc,
measurement = {start: Date.now()};
player.latencyTrips.push(measurement);
let clientMessage = {type: "latency_ping"};
wsc.send(JSON.stringify(clientMessage));
},
getRoomsStatuses = function() {
return gameRooms.map(room => room.status);
},
createRoomsStatusesMessage = function() {
return {type: "room_list", status: getRoomsStatuses()};
},
sendRoomList = function(wsc) {
let clientMessage = createRoomsStatusesMessage();
wsc.send(JSON.stringify(clientMessage));
},
sendRoomListToEveryone = function() {
let clientMessage = createRoomsStatusesMessage(),
clientMessageString = JSON.stringify(clientMessage);
// Notify all connected players of the room status changes
for (let player of players) {
player.wsc.send(clientMessageString);
}
},
initGame = function(room) {
console.log("Both players Joined. Initializing game for Room " + room.roomId);
// Number of players who have loaded the level
room.playersReady = 0;
// Load the first multiplayer level for both players
// This logic can change later to let the players pick a level
// Randomly select two spawn locations between 0 and 3 for both players.
let currentLevel = 0,
spawns = [0, 1, 2, 3],
spawnLocations = {
"blue": spawns.splice(Math.floor(Math.random() * spawns.length), 1),
"green": spawns.splice(Math.floor(Math.random() * spawns.length), 1)
};
sendRoomWebSocketMessage(room, {type: "init_level", spawnLocations: spawnLocations, level: currentLevel});
},
joinRoom = function(player, roomId) {
let room = gameRooms[roomId - 1];
console.log("Adding player to room", roomId);
// Add the player to the room
room.players.push(player);
player.room = room;
// Update room status
if (room.players.length == 1) {
room.status = "waiting";
player.color = "blue";
} else if (room.players.length == 2) {
room.status = "starting";
player.color = "green";
}
// Confirm to player that he was added
let confirmationMessageString = JSON.stringify({type: "joined_room", roomId: roomId, color: player.color});
player.wsc.send(confirmationMessageString);
return room;
},
leaveRoom = function(player, roomId) {
let room = gameRooms[roomId - 1];
console.log("Removing player from room", roomId);
for (let i = room.players.length - 1; i >= 0; i--) {
if (room.players[i] == player) {
room.players.splice(i, 1);
}
}
delete player.room;
// Update room status
if (room.players.length == 0) {
room.status = "empty";
} else if (room.players.length == 1) {
room.status = "waiting";
}
},
sendRoomWebSocketMessage = function(room, messageObject) {
let messageString = JSON.stringify(messageObject);
for (let i = room.players.length - 1; i >= 0; i--) {
room.players[i].wsc.send(messageString);
}
},
startGame = function(room) {
console.log("Both players are ready. Starting game in room", room.roomId);
room.status = "running";
sendRoomListToEveryone();
// Notify players to start the game
sendRoomWebSocketMessage(room, {type: "start_game"});
room.commands = [];
room.lastTickConfirmed = {"blue": 0, "green": 0};
room.currentTick = 0;
// Calculate tick lag for room as the max of both player's tick lags
var roomTickLag = Math.max(room.players[0].tickLag, room.players[1].tickLag);
room.interval = setInterval(function() {
// Confirm that both players have send in commands for upto present tick
if (room.lastTickConfirmed["blue"] >= room.currentTick && room.lastTickConfirmed["green"] >= room.currentTick) {
// Commands should be executed after the tick lag
sendRoomWebSocketMessage(room, {
type: "game_tick",
tick: room.currentTick + roomTickLag,
commands: room.commands
});
room.currentTick++;
room.commands = [];
} else {
// One of the players is causing the game to lag. Handle appropriately
if (room.lastTickConfirmed["blue"] < room.currentTick) {
console.log("Room", room.roomId, "Blue is lagging on Tick:", room.currentTick, "by", room.currentTick - room.lastTickConfirmed["blue"]);
}
if (room.lastTickConfirmed["green"] < room.currentTick) {
console.log("Room", room.roomId, "Green is lagging on Tick:", room.currentTick, "by", room.currentTick - room.lastTickConfirmed["green"]);
}
}
}, 100);
},
finishMeasuringLatency = function(player) {
let measurement = player.latencyTrips[player.latencyTrips.length - 1];
measurement.end = Date.now();
measurement.roundTrip = measurement.end - measurement.start;
player.averageLatency = 0;
for (let i = 0; i < player.latencyTrips.length; i++) {
player.averageLatency += measurement.roundTrip / 2;
}
player.averageLatency = player.averageLatency / player.latencyTrips.length;
player.tickLag = Math.round(player.averageLatency * 2 / 100) + 1;
console.log("Measuring Latency for player. Attempt", player.latencyTrips.length, "- Average Latency:", player.averageLatency, "Tick Lag:", player.tickLag);
},
endGame = function(room, reason) {
clearInterval(room.interval);
room.status = "empty";
sendRoomWebSocketMessage(room, {type: "end_game", reason: reason});
for (let i = room.players.length - 1; i >= 0; i--) {
leaveRoom(room.players[i], room.roomId);
}
sendRoomListToEveryone();
};
// Initialize a set of rooms
var gameRooms = [];
for (var i = 0; i < 2; i++) {
gameRooms.push({status: "empty", players: [], roomId: i + 1});
}
var players = [];
webSocketServer.on('connection', (wsc) => {
if (wscIsNotAllowed(wsc)) {
wsc.close();
return console.log('Web socket connection rejected!');
}
console.log('New web socket connection');
// Add the player to the players array
var player = {
wsc: wsc,
latencyTrips: []
};
players.push(player);
// Measure latency for player
measureLatency(player);
// Send a fresh game room status list the first time player connects
sendRoomList(wsc);
// On Message event handler for a connection
wsc.on('message', function(message) {
var clientMessage = safeFromJSON(message);
switch (clientMessage.type) {
case "join_room":
var room = joinRoom(player, clientMessage.roomId);
sendRoomListToEveryone();
if (room.players.length == 2) {
initGame(room);
}
break;
case "leave_room":
leaveRoom(player, clientMessage.roomId);
sendRoomListToEveryone();
break;
case "initialized_level":
player.room.playersReady++;
if (player.room.playersReady == 2) {
startGame(player.room);
}
break;
case "latency_pong":
finishMeasuringLatency(player, clientMessage);
// Measure latency atleast thrice
if (player.latencyTrips.length < 3) {
measureLatency(player);
}
break;
case "command":
if (player.room && player.room.status == "running") {
if (clientMessage.uids) {
player.room.commands.push({uids: clientMessage.uids, details: clientMessage.details});
}
player.room.lastTickConfirmed[player.color] = clientMessage.currentTick + player.tickLag;
}
break;
case "lose_game":
endGame(player.room, "The " + player.color + " team has been defeated.");
break;
case "chat":
if (player.room && player.room.status == "running") {
var cleanedMessage = clientMessage.message.replace(/[<>]/g, "");
sendRoomWebSocketMessage(player.room, {type: "chat", from: player.color, message: cleanedMessage});
console.log(clientMessage.message, "was cleaned to", cleanedMessage)
}
break;
}
});
wsc.on('close', function(reasonCode, description) {
console.log('Web socket connection is closed');
for (let i = players.length - 1; i >= 0; i--) {
if (players[i] == player) {
players.splice(i, 1);
}
}
// If the player is in a room, remove him from room and notify everyone
if (player.room) {
let status = player.room.status,
roomId = player.room.roomId;
// If the game was running, end the game as well
if (status == "running") {
endGame(player.room, "The " + player.color + " player has disconnected.");
} else {
leaveRoom(player, roomId);
}
sendRoomListToEveryone();
}
});
});