-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameServer.js
More file actions
1650 lines (1412 loc) · 57.5 KB
/
Copy pathGameServer.js
File metadata and controls
1650 lines (1412 loc) · 57.5 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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Library imports
var WebSocket = require('ws');
var url = require("url");
var _ = require("underscore");
var http = require('http');
var fs = require("fs");
var myos = require("os");
var ini = require('./modules/ini.js');
var request = require('request');
// Project imports
var Packet = require('./packet');
var PlayerTracker = require('./PlayerTracker');
var PacketHandler = require('./PacketHandler');
var Entity = require('./entity');
var Gamemode = require('./gamemodes');
var Logger = require('./modules/log');
var API_URL = "http://army.ovh/apigame/army/";
// Polyfill for log10
//Math.log10 = Math.log10 || function (x) { return Math.log(x) / Math.LN10; };
// GameServer implementation
function GameServer() {
// Startup
this.run = true;
this.lastNodeId = 1;
this.lastPlayerId = 1;
this.clients = [];
this.nodes = [];
this.nodesVirus = []; // Virus nodes
this.nodesEjected = []; // Ejected mass nodes
this.nodesPlayer = []; // Nodes controlled by players
ejecMass = 30;
this.currentFood = 0;
this.movingNodes = []; // For move engine
this.pcount = 0;
this.leaderboard = [];
this.LBextraLine = '';
this.lb_packet = new ArrayBuffer(0); // Leaderboard packet
this.log = new Logger();
this.commands; // Command handler
this.banned = []; // List of banned IPs
// Main loop tick
this.time = new Date();
this.startTime = this.time;
this.tick = 0; // 1 second ticks of mainLoop
this.tickMain = 0; // 50 ms ticks, 20 of these = 1 leaderboard update
this.tickSpawn = 0; // Used with spawning food
this.master = 0; // Used for Master Ping spam protection
this.actualPlayersUpdateTick = 0;
this.sinfo = {
players: 0,
humans: 0,
spectate: 0,
bots: 0,
death: 0
}
// Config
this.sqlconfig = {
host: '',
user: '',
password: '',
database: '',
table: ''
};
this.config = { // Border - Right: X increases, Down: Y increases (as of 2015-05-20)
showServerperfomance: 1,
showUptime: 1,
showPlayersCount: 1,
showLag: 1,
serverMaxConnections: 64, // Maximum amount of connections to the server.
serverMaxConnPerIp: 9, // Max Connections from one IP.
serverKickSpectator: 0, // Kicks Spectators after x time
serverPort: 4411, // Server port
serverVersion: 1, // Protocol to use, 1 for new (v561.20 and up) and 0 for old
serverGamemode: 0, // Gamemode, 0 = FFA, 1 = Teams
serverResetTime: 24, // Time in hours to reset (0 is off)
serverBots: 0, // Amount of player bots to spawn
serverViewBaseX: 1200, // Base view distance of players. Warning: high values may cause lag
serverViewBaseY: 630,
serverStatsPort: 88, // Port for stats server. Having a negative number will disable the stats server.
serverStatsUpdate: 60, // Amount of seconds per update for the server stats
serverAutoPause: 1, // Enable or Disable audo gameworld pause
serverLiveStats: 1, // Show Info in console (needs a 127characters wide console or ssh sesion)
serverLogLevel: 2, // Logging level of the server. 0 = No logs, 1 = Logs the console, 2 = Logs console and ip connections
serverLogToFile: 1, // Log Info To File
serverName: '', // The name to display on the tracker (leave empty will show ip:port)
countDown: 3600, // Time countdown restarst server
countDownExtra: 10, // Time extra to restart server
maxNumberWinnersToShow: 3, // Number of winners to show at leaderboard when party is finished ()
serverAdminPass: '', // Remote console commands password
chatMaxMessageLength: 70, // Maximum message length
chatToConsole: 1, // Log Chat To Console
chatIntervalTime: 10000, // Set the delay between messages and commands (in millisecond)
borderLeft: 0, // Left border of map (Vanilla value: 0)
borderRight: 12000, // Right border of map (Vanilla value: 11180.3398875)
borderTop: 0, // Top border of map (Vanilla value: 0)
borderBottom: 12000, // Bottom border of map (Vanilla value: 11180.3398875)
spawnInterval: 10, // The interval between each food cell spawn in ticks (1 tick = 50 ms)
foodSpawnAmount: 100, // The amount of food to spawn per interval
foodStartAmount: 1250, // The starting amount of food in the map
foodMaxAmount: 1750, // Maximum food cells on the map
foodMass: 1, // Starting food size (In mass)
foodMassGrow: 1, // Enable or Disable food mass grow
foodMassGrowPossiblity: 50, // Chance for a food to has the ability to be self growing
foodMassLimit: 5, // Maximum mass for a food can grow
foodMassTimeout: 120, // The amount of interval for a food to grow its mass (in seconds)
virusMinAmount: 10, // Minimum amount of viruses on the map.
virusMaxAmount: 20, // Maximum amount of viruses on the map. If this amount is reached, then ejected cells will pass through viruses.
virusStartMass: 100, // Starting virus size (In mass)
virusFeedAmount: 7, // Amount of times you need to feed a virus to shoot it
virusSpirals: 0, // Disable or Enable virus ejected mass spirals
mothercellMaxMass: 5000, // Max mass the mothercell can get to. (0 for unlimited)
ejectMass: 12, // Mass of ejected cells
ejectMassLoss: 15, // Mass lost when ejecting cells
ejectMassCooldown: 200, // Time until a player can eject mass again
ejectSpeed: 100, // Base speed of ejected cells
ejectSpawnPlayer: 50, // Chance for a player to spawn from ejected mass
playerStartMass: 10, // Starting mass of the player cell.
playerBotGrowEnabled: 1, // If 0, eating a cell with less than 17 mass while cell has over 625 wont gain any mass
playerMaxMass: 22500, // Maximum mass a player can have
playerSpeed: 30, // Player base speed
playerSplitSpeed: 130, // Speed of the splitting cell.
playerSmoothSplit: 0, // Whether smooth splitting is used 1 is on
playerMinMassEject: 32, // Mass required to eject a cell
playerMinMassSplit: 36, // Mass required to split
playerMaxCells: 16, // Max cells the player is allowed to have
playerRecombineTime: 30, // Base amount of seconds before a cell is allowed to recombine
playerMassAbsorbed: 1.0, // Fraction of player cell's mass gained upon eating
playerMassDecayRate: 0.002, // Amount of mass lost per second
playerMinMassDecay: 9, // Minimum mass for decay to occur
playerMaxNickLength: 15, // Maximum nick length
playerDisconnectTime: 60, // The amount of seconds it takes for a player cell to be removed after disconnection (If set to -1, cells are never removed)
playerFastDecay: 1, // Double the decay if cell is over 5000 mass. (1 is off, 5 is decay 5x faster)
tourneyMaxPlayers: 12, // Maximum amount of participants for tournament style game modes
tourneyPrepTime: 10, // Amount of ticks to wait after all players are ready (1 tick = 1000 ms)
tourneyEndTime: 30, // Amount of ticks to wait after a player wins (1 tick = 1000 ms)
tourneyTimeLimit: 20, // Time limit of the game, in minutes.
tourneyAutoFill: 0, // If set to a value higher than 0, the tournament match will automatically fill up with bots after this amount of seconds
tourneyAutoFillPlayers: 1, // The timer for filling the server with bots will not count down unless there is this amount of real players
experimentalIgnoreMax: 0, // Ignore the foodMaxAmount when the mothercells shoot. (Set to 1 to turn it on)
gameLBlength: 10 // Number of names to display on Leaderboard (Vanilla value: 10)
};
// Parse config
this.loadConfig();
// Load Bot system in config has it enabled. -1 is disabled
/*if (this.config.serverBots != -1) {
//console.log("[" + this.formatTime() + "] * \u001B[33mLoading AI Bot System...\u001B[0m");
var BotLoader = require('./ai/BotLoader');
this.bots = new BotLoader(this);
}*/
// Gamemodes
this.gameMode = Gamemode.get(this.config.serverGamemode);
// CountDown
this.countdown = this.config.countDown;
this.white = [
{ 'r': 81, 'g': 132, 'b': 214 },
];
// Colors255, 51, 51 || 255, 255, 255
this.peru = [
{ 'r': 225, 'g': 225, 'b': 225 },
{ 'r': 225, 'g': 0, 'b': 0 },
];
this.colors = [
{ 'r': 235, 'g': 75, 'b': 0 },
{ 'r': 225, 'g': 125, 'b': 255 },
{ 'r': 180, 'g': 7, 'b': 20 },
{ 'r': 80, 'g': 170, 'b': 240 },
{ 'r': 180, 'g': 90, 'b': 135 },
{ 'r': 195, 'g': 240, 'b': 0 },
{ 'r': 150, 'g': 18, 'b': 255 },
{ 'r': 80, 'g': 245, 'b': 0 },
{ 'r': 165, 'g': 25, 'b': 0 },
{ 'r': 80, 'g': 145, 'b': 0 },
{ 'r': 80, 'g': 170, 'b': 240 },
{ 'r': 55, 'g': 92, 'b': 255 },
];
this.navidad = [
/* Navidad Colors */
{ 'r': 8, 'g': 251, 'b': 29 },
{ 'r': 8, 'g': 108, 'b': 17 },
{ 'r': 250, 'g': 54, 'b': 54 },
];
}
module.exports = GameServer;
GameServer.prototype.start = function () {
// Logging
this.log.setup(this);
if (this.banned.length > 0) {
//console.log("* \u001B[33mBan file loaded!\u001B[0m");
}
// Rcon Info
if (this.config.serverAdminPass != '') {
//console.log("* \u001B[33mRcon enabled, passkey set to " + this.config.serverAdminPass + "\u001B[0m");
//console.log("* \u001B[33mTo use in chat type /rcon " + this.config.serverAdminPass + " <server command>\u001B[0m");
}
// My SQL erver
/*if (this.sqlconfig.host != '') {
//console.log("* \u001B[33mMySQL config loaded Database set to " + this.sqlconfig.database + "." + this.sqlconfig.table + "\u001B[0m");
var MySQL = require("./modules/mysql");
this.mysql = new MySQL();
this.mysql.init(this.sqlconfig);
this.mysql.connect();
this.mysql.createTable(this.sqlconfig.table, this.sqlconfig.database);
}*/
// Gamemode configurations
this.gameMode.onServerInit(this);
// Start the server
this.socketServer = new WebSocket.Server({
port: this.config.serverPort,
disableHixie: true,
clientTracking: false,
perMessageDeflate: false
}, function () {
// Spawn starting food
this.startingFood();
// Start Main Loop
//this.MasterPing();
setInterval(this.mainLoop.bind(this), 4);
// Done
//console.log("* \u001B[33mListening on port " + this.config.serverPort + " \u001B[0m");
//console.log("* \u001B[33mCurrent game mode is " + this.gameMode.name + "\u001B[0m");
// Player bots (Experimental)
/*if (this.config.serverBots > 0) {
for (var i = 0; i < this.config.serverBots; i++) {
this.bots.addBot();
}
//console.log("* \u001B[33mLoaded " + this.config.serverBots + " player bots\u001B[0m");
}*/
/*if (this.config.serverResetTime > 0) {
//console.log("* \u001B[33mAuto shutdown after " + this.config.serverResetTime + " hours\u001B[0m");
}*/
//if (this.config.serverVersion == 1)
//console.log("* \u001B[33mProtocol set to new, clients with version 561.20 and up can connect to this server\u001B[0m");
//if (this.config.serverVersion == 0)
//console.log("* \u001B[33mProtocol set to old, clients with version 561.19 and older can connect to this server\u001B[0m");
}.bind(this));
this.socketServer.on('connection', connectionEstablished.bind(this));
// Properly handle errors because some people are too lazy to read the readme
this.socketServer.on('error', function err(e) {
switch (e.code) {
case "EADDRINUSE":
//console.log("[Error] Server could not bind to port! Please close out of Skype or change 'serverPort' in gameserver.ini to a different number.");
break;
case "EACCES":
//console.log("[Error] Please make sure you are running Ogar with root privileges.");
break;
default:
//console.log("[Error] Unhandled error code: " + e.code);
break;
}
process.exit(1); // Exits the program
});
function connectionEstablished(ws) {
if (this.config.serverMaxConnPerIp) {
for (var cons = 1, i = 0, llen = this.clients.length; i < llen; i++) {
if (this.clients[i].remoteAddress == ws._socket.remoteAddress) {
cons++;
}
}
if (cons > this.config.serverMaxConnPerIp) {
ws.close();
return;
}
}
if (this.sinfo.players >= this.config.serverMaxConnections) { // Server full
//console.log("\u001B[33mClient tried to connect, but server player limit has been reached!\u001B[0m");
ws.close();
return;
} /*else if (this.banned.indexOf(ws._socket.remoteAddress) != -1) { // Banned
console.log("\u001B[33mClient " + ws._socket.remoteAddress + ", tried to connect but is banned!\u001B[0m");
ws.close();
return;
}*/
/*var origin = ws.upgradeReq.headers.origin;
var doms = ["http://localhost", "http://happyfor.win", "http://atrix.ovh", "http://army.ovh", "http://army.ovh/web", "http://kazafito.biz"];
var sec_domain = doms.indexOf(origin);
if (sec_domain == '-1') {
ws.close();
return;
}*/
function close(error, err) {
var client = this.socket.playerTracker;
if (client.name == "" || client.name == "Spectator") client.name = "Client";
if (err == 1)
/*this.server.log.onDisconnect(client.name + " Disconnect: " + this.socket.remoteAddress + ":" + this.socket.remotePort + " Error " + error);
else
this.server.log.onDisconnect(client.name + " Disconnect: " + this.socket.remoteAddress + ":" + this.socket.remotePort);*/
for (var i = 0, llen = client.cells.length; i < llen; i++) {
var cell = client.cells[i];
if (!cell) {
continue;
}
cell.calcMove = function () { }; // Clear function so that the cell cant move
// this.server.removeNode(cell);
}
client.disconnect = this.server.config.playerDisconnectTime * 20;
this.socket.sendPacket = function () { }; // Clear function so no packets are sent
}
//this.log.onConnect("Client connect: " + ws._socket.remoteAddress + ":" + ws._socket.remotePort + " (" + cons + ") [origin " + ws.upgradeReq.headers.origin + ws.upgradeReq.url + "]");
ws.remoteAddress = ws._socket.remoteAddress;
ws.remotePort = ws._socket.remotePort;
ws.playerTracker = new PlayerTracker(this, ws);
ws.packetHandler = new PacketHandler(this, ws);
ws.on('message', ws.packetHandler.handleMessage.bind(ws.packetHandler));
if (this.config.serverKickSpectator > 0) {
setTimeout(function () {
if (ws.playerTracker.spectate && ws.playerTracker.name == "") {
ws.close();
}
}.bind(this), this.config.serverKickSpectator * 1000);
}
var bindObject = { server: this, socket: ws };
/*ws.on('pong', function() {
if(typeof ws.playerTracker.pingssent == 'object') {
var diff = process.hrtime(ws.playerTracker.pingssent);
ws.playerTracker.pingssent = ((diff[0] * 1e9 + diff[1])/1000000).toFixed(1);
} else ws.playerTracker.pingssent = 0;
});*/
ws.on('error', close.bind(bindObject, 1));
ws.on('close', close.bind(bindObject, 0));
ws.ping();
if (!ws.upgradeReq.headers['user-agent'] || !ws.upgradeReq.headers['cache-control'] ||
ws.upgradeReq.headers['user-agent'].length < 50) {
//require('./checkProxy.js').checkProxy(ws) == true;
ws.close();
return;
}
/* if (require('./checkProxy.js').checkProxy(ws) == true) {
}; */
this.clients.push(ws);
//this.MasterPing();
}
this.startStatsServer(this.config.serverStatsPort);
};
GameServer.prototype.getMode = function () {
return this.gameMode;
};
GameServer.prototype.getNextNodeId = function () {
// Resets integer
if (this.lastNodeId > 2147483647) {
this.lastNodeId = 1;
}
return this.lastNodeId++;
};
GameServer.prototype.getNewPlayerID = function () {
// Resets integer
if (this.lastPlayerId > 2147483647) {
this.lastPlayerId = 1;
}
return this.lastPlayerId++;
};
GameServer.prototype.getRandomPosition = function () {
return {
x: Math.floor(Math.random() * (this.config.borderRight - this.config.borderLeft)) + this.config.borderLeft,
y: Math.floor(Math.random() * (this.config.borderBottom - this.config.borderTop)) + this.config.borderTop
};
};
GameServer.prototype.getRandomSpawn = function () {
// Random spawns for players
var pos;
if (this.currentFood > 0) {
// Spawn from food
var node;
for (var i = (this.nodes.length - 1); i > -1; i--) {
// Find random food
node = this.nodes[i];
if (!node || node.inRange) {
// Skip if food is about to be eaten/undefined
continue;
}
if (node.getType() == 1) {
pos = { x: node.position.x, y: node.position.y };
this.removeNode(node);
break;
}
}
}
if (!pos) {
// Get random spawn if no food cell is found
pos = this.getRandomPosition();
}
return pos;
};
GameServer.prototype.getRandomColor = function () {
// get random
var colorRGB = [0xFF, 0x07, (Math.random() * 256) >> 0];
colorRGB.sort(function () {
return 0.5 - Math.random();
});
// return random
return {
r: colorRGB[0],
g: colorRGB[1],
b: colorRGB[2]
};
};
/*GameServer.prototype.getRandomColor = function () {
var colorRGB = [0xFF, 0x07, ((Math.random() * (256 - 7)) >> 0) + 7];
colorRGB.sort(function () {
return 0.5 - Math.random()
});
return {
r: Math.round((colorRGB[0] + 210) / 2),
b: Math.round((colorRGB[1] + 210) / 2),
g: Math.round((colorRGB[2] + 210) / 2)
};
};*/
GameServer.prototype.getColorPeru = function () {
var index = Math.floor(Math.random() * this.peru.length);
var color = this.peru[index];
return {
r: color.r,
b: color.b,
g: color.g
};
};
GameServer.prototype.getColorOLD = function () {
var index = Math.floor(Math.random() * this.colors.length);
var color = this.colors[index];
return {
r: color.r,
b: color.b,
g: color.g
};
};
GameServer.prototype.getWhite = function () {
var index = Math.floor(Math.random() * this.white.length);
var color = this.white[index];
return {
r: color.r,
b: color.b,
g: color.g
};
};
GameServer.prototype.getRandomNavidad = function () {
var index = Math.floor(Math.random() * this.navidad.length);
var color = this.navidad[index];
return {
r: color.r,
b: color.b,
g: color.g
};
};
GameServer.prototype.addNode = function (node) {
this.nodes.push(node);
// Adds to the owning player's screen
if (node.owner) {
node.setColor(node.owner.color);
node.owner.cells.push(node);
node.owner.socket.sendPacket(new Packet.AddNode(node));
}
// Special on-add actions
node.onAdd(this);
// Add to visible nodes
for (var client, i = 0, llen = this.clients.length; i < llen; i++) {
client = this.clients[i].playerTracker;
if (!client) {
continue;
}
// client.nodeAdditionQueue is only used by human players, not bots
// for bots it just gets collected forever, using ever-increasing amounts of memory
if ('_socket' in client.socket && node.visibleCheck(client.viewBox, client.centerPos)) {
client.nodeAdditionQueue.push(node);
}
}
};
GameServer.prototype.removeNode = function (node) {
// Remove from main nodes list
var index = this.nodes.indexOf(node);
if (index != -1) {
this.nodes.splice(index, 1);
}
// Remove from moving cells list
index = this.movingNodes.indexOf(node);
if (index != -1) {
this.movingNodes.splice(index, 1);
}
// Special on-remove actions
node.onRemove(this);
// Animation when eating
for (var client, i = 0, llen = this.clients.length; i < llen; i++) {
client = this.clients[i].playerTracker;
if (!client) {
continue;
}
// Remove from client
client.nodeDestroyQueue.push(node);
}
};
GameServer.prototype.cellTick = function () {
// Move cells
if (this.sinfo.humans >= 12) {
this.updateMoveEngineNoSrt();
} else {
this.updateMoveEngine();
}
this.updateMoveNodes();
};
GameServer.prototype.spawnTick = function () {
// Spawn food
this.tickSpawn++;
if (this.tickSpawn >= this.config.spawnInterval) {
this.updateFood(); // Spawn food
this.virusCheck(); // Spawn viruses
this.tickSpawn = 0; // Reset
}
};
GameServer.prototype.gamemodeTick = function () {
// Gamemode tick
this.gameMode.onTick(this);
};
GameServer.prototype.cellUpdateTick = function () {
// Update cells
this.updateCells();
};
GameServer.prototype.mainLoop = function () {
// Timer
var local = new Date();
this.tick += (local - this.time);
this.time = local;
// Default 50 (aka 50ms) if change here change movespeed as well
if (this.tick >= 50) {
// Loop main functions
if (this.run) {
this.cellTick();
this.spawnTick();
this.gamemodeTick();
}
/*var t = this.config.fps / 20;
if (this.lctick >= Math.round(t) - 1) {
this.liveconsole();
this.lctick = 0;
} else {
this.lctick++;
}*/
// Update the client's maps
this.updateClients();
this.getPlayers();
this.tickMain++;
if (this.config.serverLiveStats && (this.tickMain == 20 || this.tickMain >= 40)) {
this.log.onWriteConsole(this);
}
if (this.run) {
// Update cells/leaderboard loop
if (this.tickMain >= 40) { // 1 Second
this.cellUpdateTick();
// Create a Time count down in a nice string and adds to LB
// Update restart server
this.countdown--;
//console.log(this.countdown);
// Update leaderboard with the gamemode's method
var players = 0;
this.clients.forEach(function (client) {
if (client.playerTracker && client.playerTracker.cells.length > 0)
players++
});
//var playersCount = ("« " + "Online" + " : " + players + " »");
this.leaderboard = [];
this.gameMode.updateLB(this); // Repeat
// console.log("this.gameMode.packetLB: " + this.gameMode.packetLB);
var packetLB = this.gameMode.packetLB;
if (this.countdown == 0) {
packetLB = 48;
// console.log("Reiniciando luego de 5 segundos...");
// Reiniciando server y mostrando a los dos ganadores
var newLB = this.getLeaderboardWinners();
this.leaderboard = newLB;
this.gameMode.updateLB = function(gameServer) {
// console.log("Llamando a this.gameMode.updateLB");
gameServer.leaderboard = newLB;
// gameServer.leaderboardType = 48;
//this.gameMode.packetLB = 48;
};
setTimeout(function() {
process.exit(1);
}.bind(this), this.config.countDownExtra * 1000);
}
this.gameMode.packetLB = packetLB;
//console.log("this.gameMode.packetLB: " + this.gameMode.packetLB);
for (var i = 0; i < this.clients.length; i++) {
var player = this.clients[i].playerTracker;
if (player)
this.clients[i].playerTracker.socket.sendPacket(new Packet.UpdateLeaderboard(this, this.leaderboard, this.gameMode.packetLB/*, playersCount*/));
this.pcount++;
}
}
// Check Bot Min Players
if (((this.sinfo.humans + this.sinfo.bots) < this.config.serverBots) && (this.config.serverBots > 0)) {
this.bots.addBot();
}
}
// Pause and Unpause on player connects
if (this.config.serverAutoPause == 1) {
var temp = (this.sinfo.players - this.sinfo.bots);
if (!this.run && temp != 0) {
//console.log("[Auto Pause] \u001B[32mGame World Resumed!\u001B[0m");
this.run = true;
} else if (this.run && temp == 0 && (this.time - this.startTime) > 30000 && this.pcount > 60) {
//console.log("[Auto Pause] \u001B[31mGame World Paused!\u001B[0m");
this.run = false;
this.nodesEjected = [];
this.movingNodes = [];
this.leaderboard = [];
this.gameMode.updateLB(this);
}
}
// Auto Server Reset
/*if (this.config.serverResetTime > 0 && ( local - this.startTime ) > ( this.config.serverResetTime * 3600000 )) {
this.exitserver();
}*/
/*if (this.sqlconfig.host != '')
this.mysql.ping();*/
// Reset
if (this.tickMain >= 40) {
this.tickMain = 0;
}
this.tick = 0;
// Send Master Server Ping
/*if (this.time - this.master >= 1805000) {
this.MasterPing();
}*/
}
};
GameServer.prototype.getLeaderboardWinners = function () {
var winners = ["Winners"];
var numberWinners = this.config.maxNumberWinnersToShow;
for (var i = 0; i < this.leaderboard.length; i++) {
var player = this.leaderboard[i];
if (player) {
winners.push(player.getName() + " - [" + player.getScore() + "]");
if (winners.length > numberWinners) {
break;
}
}
}
// console.log(winners);
return winners;
}
GameServer.prototype.exitserver = function () {
console.log("Server Shutdown!");
if (this.sqlconfig.host != '') {
Logger.info("Closing mysql connection...");
/*var players = this.clients.length;
for (var i = 0; i < players; i++) {
var playerTracker = this.clients[i].playerTracker;
if (playerTracker.cells.length > 0) {
playerTracker.resetstats();
}
}*/
this.mysql.close();
}
}
/*GameServer.prototype.exitserver = function () {
var packet = new Packet.BroadCast("*** Automatic Server Restart in 30 seconds to clean connections and memory ***");
for (var i = 0, llen = this.clients.length; i < llen; i++) {
this.clients[i].sendPacket(packet);
}
//console.log("\u001B[31m*** Automatic Server Restart in 30 seconds ***\u001B[0m");
this.config.serverMaxConnections = 0;
var temp = setTimeout(function () {
//console.log("\u001B[31m*** Server Shutdown! ***\u001B[0m");
// Close MySQL
if (this.sqlconfig.host != '') {
//console.log("* \u001B[33mClosing mysql connection...\u001B[0m");
this.mysql.close();
}
// Store Ban File
if (this.banned.length > 0) {
//console.log("* \u001B[33mSaving ban file...\u001B[0m");
fs.writeFileSync('./gameserver.ban', ini.stringify(this.banned));
}
this.socketServer.close();
process.exit(1);
window.close();
}.bind(this), 30000);
};*/
GameServer.prototype.updateClients = function () {
for (var i = 0, llen = this.clients.length; i < llen; i++) {
if (typeof this.clients[i] == "undefined") {
this.clients.splice(i, 1);
continue;
}
this.clients[i].playerTracker.update();
}
};
GameServer.prototype.startingFood = function () {
// Spawns the starting amount of food cells
for (var i = 0, llen = 450; i < llen; i++) {
this.spawnFood();
}
};
GameServer.prototype.updateFood = function () {
var toSpawn = Math.min(50, (450 - this.currentFood));
for (var i = 0; i < toSpawn; i++) {
this.spawnFood();
}
};
GameServer.prototype.spawnFood = function () {
var f = new Entity.Food(this.getNextNodeId(), null, this.getRandomPosition(), 50, this);
f.setColor(this.getWhite());
this.addNode(f);
this.currentFood++;
};
/*GameServer.prototype.spawnFood = function() {
var f = new Entity.Food(this.getNextNodeId(), null, this.getRandomPosition(), Math.ceil(Math.random()*(15-1)+1));
f.setColor(this.getRandomColor());
this.addNode(f);
this.currentFood++;
};*/
GameServer.prototype.spawnPlayer = function (player, pos, mass) {
if (pos == null) { // Get random pos
pos = this.getRandomSpawn();
}
if (mass == null) {
mass = this.config.playerStartMass;
}
if (player.extras.selectSkin) {
var selectSkin = player.extras.selectSkin;
if (player.skins.indexOf(selectSkin) >= 0) {
player.extras.currentSkin = selectSkin;
} else {
//console.log('GameServer.js: YOU DO NOT OWN THIS SKIN!!')
}
} else {
//console.log('GameServer.js: No Skin');
}
// Verifica si alguno de los roles ha expirado
player.roles = [];
let rolesData = player.rolesData;
let indice = 0;
let timeNow = Date.now() / 1000; // segundos
//console.log("timeNow: " + timeNow);
while (indice < rolesData.length) {
let rolData = rolesData[indice];
let expirationTime = rolData.expirationTime;
if (expirationTime < timeNow) {
//console.log("Rol name expirado: " + rolData.name);
rolesData.splice(indice, 1);
this.checkRoleExpiration(player, rolData.rolId);
} else {
player.roles.push(rolData.name);
if (rolData.activeSymbol && rolData.activeSymbol == 1) {
player.playerDetails.activeRolName = rolData.name;
}
indice++;
//console.log("Rol name: " + rolData.name);
//console.log("Todavía le queda... segundos: " + (expirationTime - timeNow));
//console.log("Horas: " + (expirationTime - timeNow) / 3600);
//console.log("Días: " + (expirationTime - timeNow) / (3600 * 24));
}
}
// rol activo
//console.log("Rol con activeSymbol: " + player.playerDetails.activeRolId);
//console.log("rolesData cargados al final: ");
//console.log(player.roles);
// Spawn player and add to world
var cell = new Entity.PlayerCell(this.getNextNodeId(), player, pos, mass);
if ('_socket' in player.socket) {
/* var zname = player.name;
* if (zname === "") zname = "Un Named";
*
* var packet = new Packet.BroadCast(zname + " joined the game!");
* for (var i = 0; i < this.clients.length; i++) {
* this.clients[i].sendPacket(packet);
* }
*/
/*for (var i = 0, llen = this.clients.length; i < llen; i++) {
if (this.clients[i].remoteAddress == player.socket.remoteAddress && this.clients[i].remotePort != player.socket.remotePort) {
var packet = new Packet.BroadCast("*** You're logged in multiple times from your IP!, you might get lag due this ***");
player.socket.sendPacket(packet);
break;
}
}*/
/*if (this.config.serverResetTime > 0) {
var packet = new Packet.BroadCast("*** Remember, This server auto restarts after " + this.config.serverResetTime + " hours uptime! ***");
player.socket.sendPacket(packet);
}*/
var info = "";
if (player.skin) {
info = " (" + player.skin.slice(1) + ")";
}
//console.log("\u001B[33mCell " + player.name + info + " joined the game\u001B[0m");
}
this.addNode(cell);
// Set initial mouse coords
player.freeMouse = true;
player.mouse = { x: pos.x, y: pos.y };
player.startpos = { x: pos.x, y: pos.y };
// 30s Timer, to kick players that no move within that time frame
setTimeout(function () {
if (player.mouse.x == player.startpos.x && player.mouse.y == player.startpos.y) {
//console.log("\u001B[35mCell " + player.name + " kicked for inactivity\u001B[0m");
player.socket.close();
}
}.bind(this), 20000);
};
GameServer.prototype.virusCheck = function () {
// Checks if there are enough viruses on the map
if (this.nodesVirus.length < this.config.virusMinAmount) {
// Spawns a virus
var pos = this.getRandomPosition();
var virusSquareSize = ((this.config.virusStartMass) * 110) >> 0;
// Check for players
for (var i = 0, llen = this.nodesPlayer.length; i < llen; i++) {
var check = this.nodesPlayer[i];
if (check.mass < this.config.virusStartMass) {
continue;
}
// New way
var squareR = check.getSquareSize(); // squared Radius of checking player cell
var dx = check.position.x - pos.x;
var dy = check.position.y - pos.y;
if (dx * dx + dy * dy + virusSquareSize <= squareR) return; // Collided
}
// Check for other virus
for (var i = 0, llen = this.nodesVirus.length; i < llen; i++) {
var check = this.nodesVirus[i];
var squareR = check.getSquareSize();
var dx = check.position.x - pos.x;
var dy = check.position.y - pos.y;
if (dx * dx + dy * dy + virusSquareSize <= squareR) return; // Collided
}
// Spawn if no cells are colliding
var v = new Entity.Virus(this.getNextNodeId(), null, pos, this.config.virusStartMass);
this.addNode(v);
//v.setColor(this.getRandomColor());
this.spawnSpiral(pos, v.color);
}
};
GameServer.prototype.getDist = function (x1, y1, x2, y2) {
var deltaX = Math.abs(x1 - x2);
var deltaY = Math.abs(y1 - y2);
return Math.sqrt(deltaX * deltaX + deltaY * deltaY);
};
GameServer.prototype.updateMoveEngine = function () {
// Move player cells
for (var i = 0, len = this.nodesPlayer.length; i < len; i++) {
var cell = this.nodesPlayer[i];
// Recycle unused nodes
if (typeof cell == "undefined") {
this.nodesPlayer.splice(i, 1);
len--;
continue;
}
var client = cell.owner.mouse;
cell.calcMove(client.x, client.y, this);
// Check if cells nearby
var list = this.getCellsInRange(cell);
for (var j = 0, llen = list.length; j < llen; j++) {
var check = list[j];
// if we're deleting from this.nodesPlayer, fix outer loop variables; we need to update its length, and maybe 'i' too
if (check.cellType == 0) {
len--;
if (check.nodeId < cell.nodeId) {
i--;
}
}
// Consume effect
check.onConsume(cell, this);
// Remove cell
check.setKiller(cell);
this.removeNode(check);
}
}