-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
server.js
349 lines (291 loc) · 12.6 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
/*jslint bitwise: true, node: true */
'use strict';
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const SAT = require('sat');
const gameLogic = require('./game-logic');
const loggingRepositry = require('./repositories/logging-repository');
const chatRepository = require('./repositories/chat-repository');
const config = require('../../config');
const util = require('./lib/util');
const mapUtils = require('./map/map');
const {getPosition} = require("./lib/entityUtils");
let map = new mapUtils.Map(config);
let sockets = {};
let spectators = [];
const INIT_MASS_LOG = util.mathLog(config.defaultPlayerMass, config.slowBase);
let leaderboard = [];
let leaderboardChanged = false;
const Vector = SAT.Vector;
app.use(express.static(__dirname + '/../client'));
io.on('connection', function (socket) {
let type = socket.handshake.query.type;
console.log('User has connected: ', type);
switch (type) {
case 'player':
addPlayer(socket);
break;
case 'spectator':
addSpectator(socket);
break;
default:
console.log('Unknown user type, not doing anything.');
}
});
function generateSpawnpoint() {
let radius = util.massToRadius(config.defaultPlayerMass);
return getPosition(config.newPlayerInitialPosition === 'farthest', radius, map.players.data)
}
const addPlayer = (socket) => {
var currentPlayer = new mapUtils.playerUtils.Player(socket.id);
socket.on('gotit', function (clientPlayerData) {
console.log('[INFO] Player ' + clientPlayerData.name + ' connecting!');
currentPlayer.init(generateSpawnpoint(), config.defaultPlayerMass);
if (map.players.findIndexByID(socket.id) > -1) {
console.log('[INFO] Player ID is already connected, kicking.');
socket.disconnect();
} else if (!util.validNick(clientPlayerData.name)) {
socket.emit('kick', 'Invalid username.');
socket.disconnect();
} else {
console.log('[INFO] Player ' + clientPlayerData.name + ' connected!');
sockets[socket.id] = socket;
currentPlayer.clientProvidedData(clientPlayerData);
map.players.pushNew(currentPlayer);
io.emit('playerJoin', { name: currentPlayer.name });
console.log('Total players: ' + map.players.data.length);
}
});
socket.on('pingcheck', () => {
socket.emit('pongcheck');
});
socket.on('windowResized', (data) => {
currentPlayer.screenWidth = data.screenWidth;
currentPlayer.screenHeight = data.screenHeight;
});
socket.on('respawn', () => {
map.players.removePlayerByID(currentPlayer.id);
socket.emit('welcome', currentPlayer, {
width: config.gameWidth,
height: config.gameHeight
});
console.log('[INFO] User ' + currentPlayer.name + ' has respawned');
});
socket.on('disconnect', () => {
map.players.removePlayerByID(currentPlayer.id);
console.log('[INFO] User ' + currentPlayer.name + ' has disconnected');
socket.broadcast.emit('playerDisconnect', { name: currentPlayer.name });
});
socket.on('playerChat', (data) => {
var _sender = data.sender.replace(/(<([^>]+)>)/ig, '');
var _message = data.message.replace(/(<([^>]+)>)/ig, '');
if (config.logChat === 1) {
console.log('[CHAT] [' + (new Date()).getHours() + ':' + (new Date()).getMinutes() + '] ' + _sender + ': ' + _message);
}
socket.broadcast.emit('serverSendPlayerChat', {
sender: _sender,
message: _message.substring(0, 35)
});
chatRepository.logChatMessage(_sender, _message, currentPlayer.ipAddress)
.catch((err) => console.error("Error when attempting to log chat message", err));
});
socket.on('pass', async (data) => {
const password = data[0];
if (password === config.adminPass) {
console.log('[ADMIN] ' + currentPlayer.name + ' just logged in as an admin.');
socket.emit('serverMSG', 'Welcome back ' + currentPlayer.name);
socket.broadcast.emit('serverMSG', currentPlayer.name + ' just logged in as an admin.');
currentPlayer.admin = true;
} else {
console.log('[ADMIN] ' + currentPlayer.name + ' attempted to log in with incorrect password.');
socket.emit('serverMSG', 'Password incorrect, attempt logged.');
loggingRepositry.logFailedLoginAttempt(currentPlayer.name, currentPlayer.ipAddress)
.catch((err) => console.error("Error when attempting to log failed login attempt", err));
}
});
socket.on('kick', (data) => {
if (!currentPlayer.admin) {
socket.emit('serverMSG', 'You are not permitted to use this command.');
return;
}
var reason = '';
var worked = false;
for (let playerIndex in map.players.data) {
let player = map.players.data[playerIndex];
if (player.name === data[0] && !player.admin && !worked) {
if (data.length > 1) {
for (var f = 1; f < data.length; f++) {
if (f === data.length) {
reason = reason + data[f];
}
else {
reason = reason + data[f] + ' ';
}
}
}
if (reason !== '') {
console.log('[ADMIN] User ' + player.name + ' kicked successfully by ' + currentPlayer.name + ' for reason ' + reason);
}
else {
console.log('[ADMIN] User ' + player.name + ' kicked successfully by ' + currentPlayer.name);
}
socket.emit('serverMSG', 'User ' + player.name + ' was kicked by ' + currentPlayer.name);
sockets[player.id].emit('kick', reason);
sockets[player.id].disconnect();
map.players.removePlayerByIndex(playerIndex);
worked = true;
}
}
if (!worked) {
socket.emit('serverMSG', 'Could not locate user or user is an admin.');
}
});
// Heartbeat function, update everytime.
socket.on('0', (target) => {
currentPlayer.lastHeartbeat = new Date().getTime();
if (target.x !== currentPlayer.x || target.y !== currentPlayer.y) {
currentPlayer.target = target;
}
});
socket.on('1', function () {
// Fire food.
const minCellMass = config.defaultPlayerMass + config.fireFood;
for (let i = 0; i < currentPlayer.cells.length; i++) {
if (currentPlayer.cells[i].mass >= minCellMass) {
currentPlayer.changeCellMass(i, -config.fireFood);
map.massFood.addNew(currentPlayer, i, config.fireFood);
}
}
});
socket.on('2', () => {
currentPlayer.userSplit(config.limitSplit, config.defaultPlayerMass);
});
}
const addSpectator = (socket) => {
socket.on('gotit', function () {
sockets[socket.id] = socket;
spectators.push(socket.id);
io.emit('playerJoin', { name: '' });
});
socket.emit("welcome", {}, {
width: config.gameWidth,
height: config.gameHeight
});
}
const tickPlayer = (currentPlayer) => {
if (currentPlayer.lastHeartbeat < new Date().getTime() - config.maxHeartbeatInterval) {
sockets[currentPlayer.id].emit('kick', 'Last heartbeat received over ' + config.maxHeartbeatInterval + ' ago.');
sockets[currentPlayer.id].disconnect();
}
currentPlayer.move(config.slowBase, config.gameWidth, config.gameHeight, INIT_MASS_LOG);
const isEntityInsideCircle = (point, circle) => {
return SAT.pointInCircle(new Vector(point.x, point.y), circle);
};
const canEatMass = (cell, cellCircle, cellIndex, mass) => {
if (isEntityInsideCircle(mass, cellCircle)) {
if (mass.id === currentPlayer.id && mass.speed > 0 && cellIndex === mass.num)
return false;
if (cell.mass > mass.mass * 1.1)
return true;
}
return false;
};
const canEatVirus = (cell, cellCircle, virus) => {
return virus.mass < cell.mass && isEntityInsideCircle(virus, cellCircle)
}
const cellsToSplit = [];
for (let cellIndex = 0; cellIndex < currentPlayer.cells.length; cellIndex++) {
const currentCell = currentPlayer.cells[cellIndex];
const cellCircle = currentCell.toCircle();
const eatenFoodIndexes = util.getIndexes(map.food.data, food => isEntityInsideCircle(food, cellCircle));
const eatenMassIndexes = util.getIndexes(map.massFood.data, mass => canEatMass(currentCell, cellCircle, cellIndex, mass));
const eatenVirusIndexes = util.getIndexes(map.viruses.data, virus => canEatVirus(currentCell, cellCircle, virus));
if (eatenVirusIndexes.length > 0) {
cellsToSplit.push(cellIndex);
map.viruses.delete(eatenVirusIndexes)
}
let massGained = eatenMassIndexes.reduce((acc, index) => acc + map.massFood.data[index].mass, 0);
map.food.delete(eatenFoodIndexes);
map.massFood.remove(eatenMassIndexes);
massGained += (eatenFoodIndexes.length * config.foodMass);
currentPlayer.changeCellMass(cellIndex, massGained);
}
currentPlayer.virusSplit(cellsToSplit, config.limitSplit, config.defaultPlayerMass);
};
const tickGame = () => {
map.players.data.forEach(tickPlayer);
map.massFood.move(config.gameWidth, config.gameHeight);
map.players.handleCollisions(function (gotEaten, eater) {
const cellGotEaten = map.players.getCell(gotEaten.playerIndex, gotEaten.cellIndex);
map.players.data[eater.playerIndex].changeCellMass(eater.cellIndex, cellGotEaten.mass);
const playerDied = map.players.removeCell(gotEaten.playerIndex, gotEaten.cellIndex);
if (playerDied) {
let playerGotEaten = map.players.data[gotEaten.playerIndex];
io.emit('playerDied', { name: playerGotEaten.name }); //TODO: on client it is `playerEatenName` instead of `name`
sockets[playerGotEaten.id].emit('RIP');
map.players.removePlayerByIndex(gotEaten.playerIndex);
}
});
};
const calculateLeaderboard = () => {
const topPlayers = map.players.getTopPlayers();
if (leaderboard.length !== topPlayers.length) {
leaderboard = topPlayers;
leaderboardChanged = true;
} else {
for (let i = 0; i < leaderboard.length; i++) {
if (leaderboard[i].id !== topPlayers[i].id) {
leaderboard = topPlayers;
leaderboardChanged = true;
break;
}
}
}
}
const gameloop = () => {
if (map.players.data.length > 0) {
calculateLeaderboard();
map.players.shrinkCells(config.massLossRate, config.defaultPlayerMass, config.minMassLoss);
}
map.balanceMass(config.foodMass, config.gameMass, config.maxFood, config.maxVirus);
};
const sendUpdates = () => {
spectators.forEach(updateSpectator);
map.enumerateWhatPlayersSee(function (playerData, visiblePlayers, visibleFood, visibleMass, visibleViruses) {
sockets[playerData.id].emit('serverTellPlayerMove', playerData, visiblePlayers, visibleFood, visibleMass, visibleViruses);
if (leaderboardChanged) {
sendLeaderboard(sockets[playerData.id]);
}
});
leaderboardChanged = false;
};
const sendLeaderboard = (socket) => {
socket.emit('leaderboard', {
players: map.players.data.length,
leaderboard
});
}
const updateSpectator = (socketID) => {
let playerData = {
x: config.gameWidth / 2,
y: config.gameHeight / 2,
cells: [],
massTotal: 0,
hue: 100,
id: socketID,
name: ''
};
sockets[socketID].emit('serverTellPlayerMove', playerData, map.players.data, map.food.data, map.massFood.data, map.viruses.data);
if (leaderboardChanged) {
sendLeaderboard(sockets[socketID]);
}
}
setInterval(tickGame, 1000 / 60);
setInterval(gameloop, 1000);
setInterval(sendUpdates, 1000 / config.networkUpdateFactor);
// Don't touch, IP configurations.
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || process.env.IP || config.host;
var serverport = process.env.OPENSHIFT_NODEJS_PORT || process.env.PORT || config.port;
http.listen(serverport, ipaddress, () => console.log('[DEBUG] Listening on ' + ipaddress + ':' + serverport));