Repository navigation
Expand file tree
/
Copy pathSpheresServer.js
More file actions
1428 lines (1415 loc) · 44.7 KB
/
Copy pathSpheresServer.js
File metadata and controls
1428 lines (1415 loc) · 44.7 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
"use strict"
//spheres IO server code
//global variables
require("./consts.js")(global)
var gameController; var graphics; var leaderBoard; //controller objects
var gameMap = new GameMap(); //an array of all nodes
var movingUnits = []; //an array of all MovingUnit groups
var teams = {}; //a list of all teams
var clients = []; //all playerControllers that are recieving game data (players and spectators)
var players = []; //all players that are actively spawned into the game
var cores = []; //all cores on the server
//initialization block
var initialize = function()
{
console.log("beginning game");
gameController = new GameController();
leaderBoard = new LeaderBoard();
}
///logic system
function GameController()
{
//generate the neutral team
let neutralTeam = new Team("rgb(128,128,128)",new Controller(0),"")
neutralTeam.name = "" //force the neutral team to have no name
console.log(neutralTeam.name)
teams[0] = neutralTeam;
this.generateMap(MAP_SIZE,MAP_SIZE);
this.gameLoop = setInterval(gameTick,100); //ticks game updates
}
//generates a map
GameController.prototype.generateMap = function(height,width)
{
//generate the cores
gameMap.addObject(new CoreNode(new Position(width/3,height/3)));
gameMap.addObject(new CoreNode(new Position(2*width/3,height/3)));
gameMap.addObject(new CoreNode(new Position(2*width/3,2*height/3)));
gameMap.addObject(new CoreNode(new Position(width/3,2*height/3)));
//generate the special nodes
let x = 0;
while (x < FACTORIES_TO_GENERATE)
{
let tempNode = new FactoryNode(new Position(Math.random()*width,Math.random()*height));
if (this.placeNode(tempNode))
x++;
}
x = 0;
while (x < PORTALS_TO_GENERATE)
{
let tempNode = new PortalNode(new Position(Math.random()*width,Math.random()*height));
if (this.placeNode(tempNode))
x++;
}
x = 0;
while (x < TURRETS_TO_GENERATE)
{
let tempNode = new TurretNode(new Position(Math.random()*width,Math.random()*height));
if (this.placeNode(tempNode))
x++;
}
x = 0; let generatedNodes = MIN_NODES_TO_GENERATE+Math.floor(Math.random()*(MAX_NODES_TO_GENERATE-MIN_NODES_TO_GENERATE));
//adds nodes only where there is empty space available;
while (x < generatedNodes)
{
let tempNode = new Node(new Position(Math.random()*width,Math.random()*height),1+Math.floor(Math.random()*5));
//determine if there is sufficient space between this node and all other nodes
if (this.placeNode(tempNode))
x++;
}
//spawns teams to populate the map with AI bots
let t = 1;
while (t <= BOT_COUNT)
{
let node;
do
{
node = gameMap.allObjects[Math.floor(Math.random()*gameMap.allObjects.length)];
}
while (node.team != 0 || node.nodeType != undefined)//spawn fails if the node isn't neutral
this.spawnNewPlayer(new BotController(0),"Bot",node);
t++;
}
}
//attempts to place a node
GameController.prototype.placeNode = function(tempNode)
{
let isClear = true;
let potentialObstructions = gameMap.getAllInRange(tempNode.pos,250);
for (let n in potentialObstructions)
{
if (Position.getDistance(tempNode.pos,potentialObstructions[n].pos) <= (tempNode.size+potentialObstructions[n].size)*2+30)
isClear = false;
}
//push the node
if (isClear)
{
gameMap.addObject(tempNode);
tempNode.units[0] = new Units(0,10+Math.floor(Math.random()*40));
addPacket({type:"addNode",newNode:tempNode});
return true;
}
else
{
return false;
}
}
//attempts to destroy a node
GameController.prototype.destroyNode = function(node)
{
//revert the node to neutral and remove all units to purge its lingering data
node.changeTeam(0);
for (let u in node.units)
node.addUnits(node.units[u].team,-node.units[u].number);
node.destroyed = true; //tell the node to stop doing node things
//check moving groups and destroy those that lead to this target
for (let n = movingUnits.length-1; n >= 0; n--) //kill moving units
{
let group = movingUnits[n]
if (group.endNode == node)
{
addPacket({type:"groupLoss",id:group.id,number:group.number}) //send deletion to client
movingUnits.splice(n,1) //delete the moving group
}
}
//execute deletion from main grid
addPacket({type:"removeNode",node:node.id});
gameMap.removeObject(node);
}
//spawns in a new player with the given name at spawnNode
GameController.prototype.spawnNewPlayer = function(controller,name,spawnNode)
{
let team = new Team(generateRandomColor(),controller,name);
//find an index for the team
let teamIndex = 1, isIndexFound = false;
while (!isIndexFound)
{
if (teams[teamIndex] == undefined)
isIndexFound = true;
else
teamIndex++
}
controller.team = teamIndex
teams[teamIndex] = team;
addPacket({type:"addTeam",index:teamIndex,color:team.color,name:team.name})
let isValidLocationFound = false;
let counter = 0;
//clear the node's units and spawn in the player's units
if (spawnNode && spawnNode.team == 0 && spawnNode.nodeType == undefined)
{
isValidLocationFound = true;
for (let u in spawnNode.units)
spawnNode.addUnits(spawnNode.units[u].team,-spawnNode.units[u].number)
spawnNode.changeTeam(teamIndex);
spawnNode.addUnits(teamIndex,200);
//temporarily give that node a level boost
spawnNode.upgradeToCapital();
}
else //spawn checks not successful
{
console.log("Spawn failed");
return;
}
return spawnNode;
}
//restarts the server
GameController.prototype.restartGame = function(winner)
{
console.log("Restarting server")
//disconnect clients
let disconnectMessage = (winner == undefined) ? "Server Restarting" : winner.name + " Has won the game!";
for (let p in clients)
{
clients[p].sendPacket({type:"disconnectMessage",message:disconnectMessage});
}
//exits the server, foreverJS should immediately pick up and restart
setTimeout(function(){process.exit()},1000);
}
//triggers secondary timers
function gameTick()
{
for (let index in gameMap.allObjects)
{
let node = gameMap.allObjects[index];
//if a node has more than one team of units on it, start a battle
if (node.units.length > 1 && !node.fighting)
node.fight(node.units);
//if a node is under control by units from a different team than its own team, capture it
if (node.units.length == 1 && (node.units[0].team != node.team || node.capturePoints > 0) && !node.capturing)
node.capture();
//if a node is non-neutral, attempt to spawn
if (node.team != 0 && (node.getUnitsOfTeam(node.team) != 0 || node.units.length == 0) && !node.spawning)
node.spawn();
//check nonspecial nodes for attrition
if (node.nodeType == undefined && !node.attrition)
node.checkForAttrition();
}
//spawn bots every so often if conditions are met
let numTeams = Object.keys(teams).length-1; //all teams other than the neutral team
if (numTeams < MIN_PLAYERS && numTeams-players.length < BOT_COUNT && Math.random()*1000 <= 1)
{
console.log("Spawning a new bot")
let node;
do
{
node = gameMap.allObjects[Math.floor(Math.random()*gameMap.allObjects.length)];
}
while (node.team != 0 || node.nodeType != undefined)//spawn fails if the node isn't neutral
gameController.spawnNewPlayer(new BotController(teams.length),"Bot",node);
}
//change up the map
if (Math.random()*100 <= 1 && clients.length > 0)
{
//add a new node
while(!gameController.placeNode(new Node(new Position(Math.random()*MAP_SIZE,Math.random()*MAP_SIZE),
1+Math.floor(Math.random()*5)))){}
//remove a non-special node
let index = 0;
do
index = Math.floor(Math.random()*gameMap.allObjects.length)
while (gameMap.allObjects[index].nodeType != undefined)
gameController.destroyNode(gameMap.allObjects[index]);
}
}
///hash map code
function GameMap()
{
this.size = MAP_SIZE/HASH_SIZE;
this.allObjects = []; //contains all objects on the map
this.map = new Array(this.size); //create first dimension
for (let x = 0; x < this.size; x++)
{
this.map[x] = new Array(this.size); //create second dimension
for (let y = 0; y < this.size; y++)
{
this.map[x][y] = []; //creates a blank array to hold objects at this node
}
}
}
//adds an object at this location
GameMap.prototype.addObject = function(object)
{
this.allObjects.push(object);
let x = Math.floor(object.pos.x/HASH_SIZE);
let y = Math.floor(object.pos.y/HASH_SIZE);
this.map[x][y].push(object);
}
//removes an object from the grid
GameMap.prototype.removeObject = function(object)
{
//identify the object
for (let n in this.allObjects)
{
if (this.allObjects[n] == object)
{
this.allObjects.splice(n,1);
break;
}
}
//remove from the object's location in hash map
let x = Math.floor(object.pos.x/HASH_SIZE);
let y = Math.floor(object.pos.y/HASH_SIZE);
for (let n in this.map[x][y])
{
if (this.map[x][y][n] == object)
{
this.map[x][y].splice(n,1);
break;
}
}
}
//move an object, updating its hash map position if necessary
GameMap.prototype.moveObject = function(object,newPos)
{
//check if object needs to be moved on hash map
if (Math.floor(object.pos.x/HASH_SIZE) != Math.floor(newPos.x/HASH_SIZE)
|| Math.floor(object.pos.y/HASH_SIZE) != Math.floor(newPos.y/HASH_SIZE))
{
//clear from old hash map position
let x = Math.floor(object.pos.x/HASH_SIZE);
let y = Math.floor(object.pos.y/HASH_SIZE);
for (let n in this.map[x][y])
{
if (this.map[x][y][n] == object)
{
this.map[x][y].splice(n,1);
break;
}
}
//add to new hash map position
x = Math.floor(newPos.x/HASH_SIZE);
y = Math.floor(newPos.y/HASH_SIZE);
this.map[x][y].push(object);
}
object.pos = newPos;
}
//range-checking
GameMap.prototype.getAllInRange = function(pos,range)
{
let radius = Math.ceil(range/HASH_SIZE);
let x = Math.floor(pos.x/HASH_SIZE);
let y = Math.floor(pos.y/HASH_SIZE);
let output = [];
for (let dx = -radius; dx <= radius; dx++)
{
if (x+dx >= 0 && x+dx < this.size)
for (let dy = -radius; dy <= radius; dy++)
{
if (y+dy >= 0 && y+dy < this.size)
{
for (let obj in this.map[x+dx][y+dy])
{
let pos2 = this.map[x+dx][y+dy][obj];
if (Position.getDistance(pos,pos2.pos) <= range)
{
output.push(pos2);
}
}
}
}
}
return output;
}
//find the nearest node (optimized getAllInRange)
GameMap.prototype.getNearestNode = function(pos,max)
{
let radius = Math.ceil(range/HASH_SIZE);
let x = Math.floor(pos.x/HASH_SIZE);
let y = Math.floor(pos.y/HASH_SIZE);
let result = undefined;
let resultDistance = max
for (let dx = -radius; dx <= radius; dx++)
{
if (x+dx >= 0 && x+dx < this.size)
for (let dy = -radius; dy <= radius; dy++)
{
if (y+dy >= 0 && y+dy < this.size)
{
for (let obj in this.map[x+dx][y+dy])
{
let pos2 = this.map[x+dx][y+dy][obj];
let dist = Position.getDistance(pos,pos2.pos)
if (dist <= resultDistance)
{
result = pos2;
resultDistance = dist;
}
}
}
}
}
return result;
}
//class for nodes
function Node(position,level)
{
this.id = generateNodeID(); //unique ID of this node
this.pos = position; //position of the node
this.level = level; //level of the node, influences capture speed and unit production
this.size = (20+10*level)*SIZE_SCALE; //size of the node is based on level
this.team = 0; //nodes are created neutral by default
this.units = []; //a listing of all unit groups that are on this node
this.fighting = false; //whether or not the node is fighting
this.capturing = false; //whether or not the node is being captured
this.spawning = false; //whether or not the node is spawning units
this.attrition = false; //whether this node is suffering attrition
this.capturePoints = 0; //percentage of base that was captured
this.captureTeam = undefined; //the team that is capturing the node (undefined if no team is capturing)
}
//returns the amount of units of the given team on this node
Node.prototype.getUnitsOfTeam = function(team)
{
for (let index in this.units)
{
let group = this.units[index];
if (group.team == team)
return group.number;
}
//if no group is found, return 0
return 0;
}
//sums the total amount of units on this node
Node.prototype.getTotalUnits = function()
{
let sum = 0;
for (let index in this.units)
{
sum += this.units[index].number;
}
return sum;
}
//adds (or removes if parameter is negative) units to the node
Node.prototype.addUnits = function(team,number,effect)
{
let isAdded = false;
for (let index in this.units)
{
let group = this.units[index];
if (group.team == team)
{
group.number += number;
if (group.number <= 0) //delete an index with no units
{
//log when negative units occur
if (group.number < 0)
console.log("Negative units detected")
this.units.splice(index,1);
if (this.team != group.team) teams[group.team].controller.removeOccupiedNode(this);
}
isAdded = true;
}
}
if (isAdded == false && number != 0)
{
this.units.push(new Units(team,number));
teams[team].controller.addOccupiedNode(this);
}
let packet = {type:"units",node:this.id,team:team,number:number,effect:effect}
addPacket(packet)
}
//method to properly change the team of a node
Node.prototype.changeTeam = function(newTeam)
{
if (this.team != 0)
{teams[this.team].controller.removeOccupiedNode(this);} //team 0 does not have a controller
this.team = newTeam;
if (newTeam != 0)
{teams[newTeam].controller.addOccupiedNode(this);} //team 0 does not have a controller
addPacket({type:"capture",node:this.id,team:newTeam})
}
//spawns a unit at this node if conditions are right
Node.prototype.spawn = function()
{
if (this.destroyed) return;
this.spawning = true;
let unitCount = this.getUnitsOfTeam(this.team)
let delay = (SPAWN_TIME*1000)/this.level;
delay *= 1+Math.max(teams[this.team].controller.getTotalUnits()-REINFORCEMENT_CAP,0)/UNITS_PER_SPAWN_MULTIPLIER;
if (this.fighting) delay *= FIGHT_SPAWN_MULTIPLIER; //units take twice as long to spawn while in combat?
//conditions: must not be dealing with attrition, must not be at capacity, must have friendly units or no units
if (!this.attrition && !teams[this.team].controller.isCapacityReached() && (unitCount != 0 || this.units.length == 0))
{
this.addUnits(this.team,1);
setTimeout(function(_this){_this.spawn();},delay,this);
}
else //set a delay to prevent instant respawning on the next update tick
{
setTimeout(function(_this){_this.spawning = false;},delay,this);
}
}
//capturing function
Node.prototype.capture = function()
{
this.capturing = false; //set this to false by default
if (this.units.length != 1) //if there are no units here or a combat, no capture can occur
return;
if (this.captureTeam != undefined && this.units[0].team != this.captureTeam) //if another team arrives, they drain the capture points
{
if (this.capturePoints <= 0)//clear the capture
this.captureTeam = undefined;
else //slowly drain the capture points
this.capturePoints = Math.max(this.capturePoints-2,0);
addPacket({type:"assault",node:this.id,points:this.capturePoints,team:this.captureTeam}) //update the capture points on the node
return;
}
this.captureTeam = this.units[0].team;
if (this.capturePoints >= 100)
{
//node first turns to neutral before being captured
if (this.team != 0)
{
this.changeTeam(0);
}
else
{
this.changeTeam(this.units[0].team);
}
this.captureTeam = undefined;
this.capturePoints = 0;
}
else
{
this.capturePoints++;
this.capturing = true; //currently capturing, do not trigger a game update tick on this
let delay = (CAPTURE_TIME*100*this.level)/Math.min(this.units[0].number,MAX_UNITS);
setTimeout(function(_this){_this.capture();},delay,this);
}
addPacket({type:"assault",node:this.id,points:this.capturePoints,team:this.captureTeam})
}
//combat mechanics system (ported from BattleFunction program)
Node.prototype.fight = function()
{
if (this.destroyed) return;
//add the numbers of all teams to a total number
let unitNums = this.units;
var totalUnits = this.getTotalUnits()
if (totalUnits <= 0) return; //prevent a possible bug if all units leave the node at the exact same time
//choose a random unit out of all units to attack
var attackerLocation = Math.floor(Math.random()*totalUnits)+1;
var attackerFound = false;
var index = 0;
while (!attackerFound)
{
attackerLocation -= unitNums[index].number //subtract the unitnums from this
if (attackerLocation <= 0) //if this is <= 0, the attacker is in the current index
attackerFound = true;
else
index++;
}
for (let x = 0; x < unitNums.length; x++) //every array that is not the attacker loses 1 unit
{
if (x != index)
this.addUnits(unitNums[x].team,-1,true)
}
//continue fighting if a fight is still needed
if (unitNums.length > 1)
{
//find the strongest group on this node
let strongestNum = 0;
for (let n in this.units)
strongestNum = Math.max(strongestNum,unitNums[n].number)
let delay = Math.min((FIGHT_TIME*10000)/(Math.min(totalUnits,Math.max(MAX_UNITS,2*(totalUnits-strongestNum))))
,FIGHT_TIME*1000);
setTimeout(function(_this){_this.fight();},delay,this);
this.fighting = true;
}
else
{
this.fighting = false;
}
return unitNums; //returns unitNums if needed
}
//attritions away units from the node if >100 are present
Node.prototype.checkForAttrition = function()
{
this.attrition = false //will be set to true by later events
for (let index in this.units)
{
let group = this.units[index];
if (group.number > MAX_UNITS)
{
this.attrition = true;
this.addUnits(group.team,-1)
let delay = Math.min((NODE_ATRIT_TIME*5000*this.level)/(group.number-MAX_UNITS),NODE_ATRIT_TIME*1000);
setTimeout(function(_this){_this.checkForAttrition();},delay,this);
}
}
}
//upgrades the node to a capital
Node.prototype.upgradeToCapital = function()
{
addPacket({type:"addCapital",node:this.id});
this.level += SPAWN_BONUS;
this.nodeType = "capital";
//capital will return to normal in 60 seconds
setTimeout(function(_this)
{
addPacket({type:"removeCapital",node:_this.id});
_this.level -= SPAWN_BONUS;
_this.nodeType = undefined;
},60000,this)
}
//special node type: factory, high production unless fighting
FactoryNode.prototype = new Node();
FactoryNode.prototype.constructor = FactoryNode;
function FactoryNode(position)
{
Node.call(this,position,10);
this.size = 125*SIZE_SCALE;
this.nodeType = "factory";
}
FactoryNode.prototype.spawn = function() //factory nodes do not spawn if in combat
{
this.spawning = true;
//let rate = NODE_SPAWN_RATE*this.level+TEAM_SPAWN_RATE/teams[this.team].controller.occupiedNodes.length;
let delay = 1000/FACTORY_PRODUCTION
if (!teams[this.team].controller.isCapacityReached() && this.units.length <= 1)
{
this.addUnits(this.team,1);
setTimeout(function(_this){_this.spawn();},delay,this);
}
else
{
setTimeout(function(_this){_this.spawning = false;},delay,this);
}
}
//special node type: turret, shoots at nearby enemy unit groups
TurretNode.prototype = new Node();
TurretNode.prototype.constructor = TurretNode;
function TurretNode(position)
{
Node.call(this,position,5);
this.nodeType = "turret";
setInterval(function(_this){_this.checkLaser();},1000/TURRET_ROF,this);
}
//turrets do not spawn
TurretNode.prototype.spawn = function()
{
return;
}
//runs laser shot calculations
TurretNode.prototype.checkLaser = function()
{
if (this.team == 0) return; //do not activate if neutral
if ((this.fighting || this.capturing) && Math.random() < 0.5) return; //50% of all shots fail while the turret is in combat
let closestGroup,closestRange = TURRET_RANGE;
for (let u in movingUnits) //check to see if an enemy group is within turret range
{
let group = movingUnits[u]
let distance = Position.getDistance(this.pos,group.pos)
if (distance < closestRange && group.team != this.team)
{
closestGroup = group;
closestRange = distance;
}
}
if (closestGroup != undefined) //shoot the closest detected enemy group
{
closestGroup.number -= 1;
addPacket({type:"groupLoss",id:closestGroup.id,number:1,laser:this.id})
}
}
//special node type: portal, teleports units of the controlled team
PortalNode.prototype = new Node();
PortalNode.prototype.constructor = PortalNode;
function PortalNode(position)
{
Node.call(this,position,5);
this.nodeType = "portal";
this.ready = true;
}
//portals do not spawn
PortalNode.prototype.spawn = function()
{
return;
}
//function to allow the portal node to teleport units
PortalNode.prototype.teleport = function(endNode,unitsTransferred)
{
this.addUnits(this.team,-unitsTransferred);
if (unitsTransferred > MAX_UNITS)
unitsTransferred -= Math.floor((unitsTransferred-MAX_UNITS)*PORTAL_ATTRITION)
endNode.addUnits(this.team,unitsTransferred);
addPacket({type:"teleport",number:unitsTransferred,node:this.id,otherNode:endNode.id})
//put the portal in cooldown
this.ready = false;
setTimeout(function(_this){_this.ready = true},unitsTransferred*PORTAL_DELAY,this);
}
//special node type: core, cannot be directly accessed
CoreNode.prototype = new Node();
CoreNode.prototype.constructor = CoreNode;
function CoreNode(position)
{
Node.call(this,position,0);
this.size = CORE_SIZE;
this.nodeType = "core";
//generate orbitals
this.orbitals = [];
for (let angle = 0; angle < 1.99*Math.PI; angle += Math.PI/3)
{
let tempNode = new OrbitalNode(this,angle);
tempNode.addUnits(0,100);
this.orbitals.push(tempNode);
gameMap.addObject(tempNode);
}
setInterval(function(_this){_this.rotateNodes();},100/CORE_ROTATION,this);
//register this with the game controller
cores.push(this);
}
//cores do not spawn (and also cannot accept units)
CoreNode.prototype.spawn = function()
{
return;
}
//rotates all orbitals and also checks to see if this should be captured
CoreNode.prototype.rotateNodes = function()
{
//rotate the orbitals
for (let n in this.orbitals)
{
this.orbitals[n].orbit(0.1*Math.PI/180);
}
//check to see if this node should be captured
let captureTeam = this.orbitals[0].team
if (captureTeam != 0 && captureTeam == this.orbitals[1].team && captureTeam == this.orbitals[2].team
&& captureTeam == this.orbitals[3].team && captureTeam == this.orbitals[4].team && captureTeam == this.orbitals[5].team)
{
if (this.team != captureTeam)
{
this.changeTeam(captureTeam);
//check victory conditions (must control at least 75% of the cores on the map to win)
let alignedCores = 0;
for (let n in cores)
{
if (cores[n].team == this.team)
alignedCores++;
}
if (alignedCores/cores.length >= 0.75)
gameController.restartGame(teams[this.team])
}
}
else if (this.team != 0)
this.changeTeam(0);
}
//special node type: orbital nodes around a core
OrbitalNode.prototype = new Node();
OrbitalNode.prototype.constructor = OrbitalNode;
function OrbitalNode(core,angle)
{
this.corePos = core.pos;
this.angle = angle;
Node.call(this,new Position(this.corePos.x+CORE_SIZE*Math.cos(angle),this.corePos.y+CORE_SIZE*Math.sin(angle)),5);
this.nodeType = "orbital";
}
OrbitalNode.prototype.orbit = function(added)
{
this.angle += added;
gameMap.moveObject(this,new Position(this.corePos.x+CORE_SIZE*Math.cos(this.angle),this.corePos.y+CORE_SIZE*Math.sin(this.angle)))
addPacket({type:"nodemove",node:this.id,pos:this.pos});
}
//an object for a moving group of units
function MovingGroup(team,number,startNode,endNode)
{
this.id = generateMovingGroupID(); //unique ID of this moving group
this.team = team;
this.number = number;
this.startNode = startNode;
this.endNode = endNode;
this.pos = new Position(startNode.pos.x,startNode.pos.y);
this.lastEndPos = this.endNode.pos; //position that the endNode is at, will be out of date if endnode moves
this.direction = Position.getDirection(this.startNode.pos,this.endNode.pos);
this.remainingDistance = Position.getDistance(this.startNode.pos,this.endNode.pos);
this.lastMoveTime = new Date(); //time when the last move order was executed, should be at most 17 without any lag
this.attritLosses = 0; //fractional component of losses to attrition
this.nextCheckDistance = (startNode.team == team) ? CONTROL_RANGE : CONTROL_RANGE/10; //minimum distance that can be crossed before another attrition check is needed
}
//moves the group towards its destination
MovingGroup.prototype.move = function()
{
//if there are 0 units on this node, destroy it
if (this.number <= 0)
{
if (!teams[this.team] && teams[this.team].controller.getTotalUnits() <= 0) //a team cannot lose their last unit as a moving group
this.number == 1
else
return "destroyed"
}
//check if destination node has moved, if so update direction and distance
if (this.lastEndPos != this.endNode.pos)
{
this.direction = Position.getDirection(this.pos,this.endNode.pos);
this.remainingDistance = Position.getDistance(this.pos,this.endNode.pos);
this.lastEndPos = this.endNode.pos;
}
//move based on dt
let currentTime = new Date();
let distance = MOVE_SPEED*(currentTime-this.lastMoveTime)/1000
this.lastMoveTime = currentTime
this.pos.x += distance*Math.cos(this.direction);
this.pos.y += distance*Math.sin(this.direction);
this.remainingDistance -= distance;
//if close to the end node, add this group's units to that node
if (this.remainingDistance <= this.endNode.size)
{
this.endNode.addUnits(this.team,this.number);
//remove this group from array
for (let n in movingUnits)
{
let checkedGroup = movingUnits[n];
if (checkedGroup == this)
movingUnits.splice(n,1);
}
}
//otherwise, check for attrition
else
{
this.checkForAttrition(distance)
}
}
//checks for attrition
MovingGroup.prototype.checkForAttrition = function(distance)
{
if (teams[this.team] == undefined) //if the team is invalid, destroy this moving group
{
console.log("Invalid Moving Group Team");
addPacket({type:"groupLoss",id:this.id,number:this.number})
this.number = 0;
return;
}
let nearFriendly = false;
if (this.nextCheckDistance > distance) //if nearestfriendlydistance > 0, cannot need an attrition check
{
this.nextCheckDistance -= distance
nearFriendly = true;
}
else //check all nodes in control range to see if one is friendly
{
let nearbyNodes = gameMap.getAllInRange(this.pos,CONTROL_RANGE)
for (let n in nearbyNodes)
{
let node = nearbyNodes[n]
if (this.team == node.team)
{
nearFriendly = true;
//set distance before another check
this.nextCheckDistance = Math.max(this.nearestFriendlyDistance,CONTROL_RANGE-Position.getDistance(this.pos,node.pos))
break;
}
}
}
let atritNumber = this.number
if (nearFriendly)
{
atritNumber = (atritNumber-MAX_UNITS)/2
}
if (atritNumber > 0) //trigger attrition
{
//percentage of attrition per tick: (distance travelled)/(ATRIT_RATE/ln(0.5)(aka -.693))
this.attritLosses += atritNumber * (distance/ATRIT_RATE)*.693;
if (this.attritLosses >= 1)
{
let intLosses = Math.floor(this.attritLosses)
this.number -= intLosses;
addPacket({type:"groupLoss",id:this.id,number:intLosses})
this.attritLosses-= intLosses
}
}
}
//unit move loop
function moveAllGroups()
{
for (var u in movingUnits)
{
if(movingUnits[u].move() == "destroyed")
{
movingUnits.splice(u,1)
u--;
}
}
}
setInterval(moveAllGroups,1000/60)
//a simple position object, used for certain inherited methods
function Position(x,y)
{
this.x = x; this.y = y;
}
//returns the distance between two Position objects
Position.getDistance = function(pos1,pos2)
{
return Math.sqrt(Math.pow(pos2.x-pos1.x,2)+Math.pow(pos2.y-pos1.y,2));
}
//returns the direction between two Position objects
Position.getDirection = function(pos1,pos2)
{
let result = Math.atan2(pos2.y-pos1.y,pos2.x-pos1.x);
if (result == 0) //what is this for?
console.log("invalid direction");
return result;
}
//an object for a unit group (may not be needed)
function Units(team,number)
{
this.team = team;
this.number = number;
//this.unitMap = []; //a map of the angle and direction of all units for the graphics system to draw
//this.addUnits(this.number);
}
//returns a random color for a team
function generateRandomColor()
{
let isColorValid = false;
let red, green, blue;
while (!isColorValid)
{
red = Math.floor(Math.random()*256);
green = Math.floor(Math.random()*256);
blue = Math.floor(Math.random()*256);
if (red+green+blue >= 60) //color must be bright enough
isColorValid = true;
}
return 'rgb(' + red + ',' + green + ',' + blue + ')';
}
///leaderboard mechanic
function LeaderBoard()
{
this.top10 = [];
setTimeout(function(_this){_this.getLeaders();},1000,this);
}
//get the leaders
LeaderBoard.prototype.getLeaders = function()
{
let allActiveTeams = [];
//remove eliminated teams
for (let t in teams)
{
if (t != 0) //do not push neutral team
allActiveTeams.push(teams[t])
}
allActiveTeams.sort(function (a,b) //sort by unit capacity (develop a scoring system later?)
{
return b.controller.unitCapacity-a.controller.unitCapacity;
});
this.top10 = allActiveTeams.slice(0,10);
//transmit leaderboard data to players
let leaderData = []
for (let t in leaderBoard.top10)
{
let team = leaderBoard.top10[t]
if (team == undefined) //second check if undefined due to crashes here
continue;
leaderData.push({color:team.color,name:team.name,score:team.controller.unitCapacity})
}
for (let p in clients)
{
clients[p].client.emit("leaderboard",leaderData)
}
setTimeout(function(_this){_this.getLeaders();},1000,this); //automatically recalculate leaders every 5 seconds
}
///object for a team
function Team(color,controller,name)
{
this.color = color;
this.controller = controller;
this.name = name || "An Unnamed Team";
}
///main controller class, inherited by subclasses
function Controller(team)
{
this.occupiedNodes = []; //list of all nodes with this team's units on them, or that are owned by this team
this.team = team; //ID of this controller's team
this.unitCapacity = 0; //this team's unit capacity
}
//creates a moving group between the target node and the other node
Controller.prototype.moveUnits = function(startNode,endNode,unitsTransferred)
{
if (unitsTransferred != 0 && startNode != endNode) //check for valid move
{
if (unitsTransferred > startNode.getUnitsOfTeam(this.team)) //prevent moving more units than are available
unitsTransferred = startNode.getUnitsOfTeam(this.team)
if (startNode.nodeType == "portal" && startNode.team == this.team && startNode.ready) //portals teleport instead of a normal move
{
startNode.teleport(endNode,unitsTransferred);
return;
}
startNode.addUnits(this.team,-unitsTransferred);
let moveGroup = new MovingGroup(this.team,unitsTransferred,startNode,endNode);
movingUnits.push(moveGroup);
addPacket({type:"move",team:this.team,number:unitsTransferred,node:startNode.id,otherNode:endNode.id,id:moveGroup.id})
return moveGroup;
}
}
//adds a controlled node
Controller.prototype.addOccupiedNode = function(node)
{
//check for duplicates
let isDuplicate = false;
for (var n in this.occupiedNodes)
{
if (this.occupiedNodes[n] == node)
{
isDuplicate = true;
}
}
if (!isDuplicate)
{
this.occupiedNodes.push(node);
}
this.calculateUnitCapacity(); //an addOccupiedNode call triggers on a team change, so always recalculate unit capacity
}
//removes a controlled node
Controller.prototype.removeOccupiedNode = function(node)
{
for (var n in this.occupiedNodes)
{
if (this.occupiedNodes[n] == node)
{
this.occupiedNodes.splice(n,1);
//check to see if this team is eliminated
if (this.team != 0 && this.getTotalUnits() == 0 && this.occupiedNodes.length == 0)
{
console.log("Player " + teams[this.team].name + " (" + this.team + ")" + " has been eliminated")
//console.log(teams)
delete teams[this.team];
addPacket({type:"removeTeam",index:this.team});
//teams[this.team] = undefined
//console.log(teams)
}
break;
}
}
this.calculateUnitCapacity();
}
//calculates unit capacity
Controller.prototype.calculateUnitCapacity = function()
{