-
Notifications
You must be signed in to change notification settings - Fork 6
/
rockRaiders.js
2531 lines (2375 loc) · 98.6 KB
/
rockRaiders.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
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
/**
* Object update and rendering weights
*
* These values are coded into entities to determine the rendering order higher values are rendered first and covered by other objects with lower values
*
*/
const drawDepthTerrain = 1000;
const drawDepthTerrainMarker = 975;
const drawDepthSelectedSpace = 950;
const drawDepthBuildingPlacier = 900;
const drawDepthSelectedVehicle = 800;
const drawDepthSlimes = 775;
const drawDepthVehicle = 750;
const drawDepthRaider = 725;
const drawDepthMonster = 700;
const drawDepthCollectables = 650;
const drawDepthLandslide = 600;
const drawDepthHealthBar = 500;
const drawDepthIconButtonPanelBackground = 475;
const drawDepthIconButtonPanelButtons = 450;
const drawDepthCrystalSideBar = 400;
/**
* output the terrain 2d-array to the console
* @param terrain: a 2d-array representing the terrain (note that terrain is formatted as [y][x])
*/
function printTerrain(terrain) {
let str;
for (let i = 0; i < terrain.length; i++) {
str = "";
for (let r = 0; r < terrain[i].length; r++) {
str += (terrain[i][r].walkable === true ? 1 : 0) + ",";
}
str = "[" + str.slice(0, str.length - 1) + "]";
console.log(str);
}
}
/**
* output the coordinates of each space in the input path
* @param path: the path to display (note that paths are ordered from last to first space)
*/
function printPath(path) {
let pathString = "[";
for (let i = 0; i < path.length; i++) {
pathString += " (" + path[path.length - (i + 1)].listX + ", " + path[path.length - (i + 1)].listY + ") >";
}
pathString = pathString.substring(0, pathString.length - 2);
pathString += "]";
console.log(pathString);
}
/**
* update position of all sound effects for all RygameObjects based on their camera distance
*/
function updateObjectSoundPositions() {
for (let i = 0; i < GameManager.renderOrderedCompleteObjectList.length; ++i) {
updateSoundPositions(GameManager.renderOrderedCompleteObjectList[i]);
}
}
/**
* update volume of all sound effects in the input object based on linear distance from the camera
* @param obj: the object whose sounds we should update the volume of based on camera distance
*/
function updateSoundPositions(obj) {
if (typeof obj.soundList != "undefined" && obj.soundList.length > 0) {
const camDis = cameraDistance(obj);
// linear fade with distance, with a max sound distance of 2500 pixels
let vol = GameManager.fxVolume - camDis / 2500;
if (vol < 0) {
vol = 0;
}
for (let i = 0; i < obj.soundList.length; ++i) {
const sound = obj.soundList[i];
if (sound.ended || sound.paused) { // sanitize list, remove unused sounds
obj.soundList.splice(i, 1);
} else {
sound.volume = vol;
}
}
}
}
/**
* get the distance of passed in object's center from the camera
* @param obj: the object to check for camera distance
*/
function cameraDistance(obj) {
let xDis, yDis;
const x = obj.centerX();
const y = obj.centerY();
const camX = gameLayer.cameraX + GameManager.screenWidth / 2;
const camY = gameLayer.cameraY + GameManager.screenHeight / 2;
xDis = Math.abs(camX - x);
yDis = Math.abs(camY - y);
return Math.sqrt(xDis * xDis + yDis * yDis);
}
/**
* find the closest space in the given terrain to the input object
* @param terrain: the terrain to check against
* @param object: the object to whom we want the closest space
*/
function getNearestSpace(terrain, object) {
let closestDistance = -1;
let closestObject = null;
const centerX = object.centerX();
const centerY = object.centerY();
for (let i = 0; i < terrain.length; i++) {
for (let r = 0; r < terrain[i].length; r++) {
const distance = getDistance(centerX, centerY, terrain[i][r].centerX(), terrain[i][r].centerY());
if (closestDistance === -1 || distance < closestDistance) {
closestDistance = distance;
closestObject = terrain[i][r];
}
}
}
return closestObject;
}
/**
* get the adjacent space to terrain indices x,y in direction dir
* @param terrain: the terrain to check against
* @param x: the first index representing the desired terrain position
* @param y: the second index representing the desired terrain position
* @param dir: the direction (up, down, left, or right) of the adjacent space to return
* @returns Space the resulting space, or null if no such space exists
* @throws: direction error if dir is not one of the cardinal directions
*/
function adjacentSpace(terrain, x, y, dir) {
if (dir === "up") {
if (x > 0) {
return terrain[x - 1][y];
}
return null;
} else if (dir === "down") {
if (x < terrain.length - 1) {
return terrain[x + 1][y];
}
return null;
} else if (dir === "left") {
if (y > 0) {
return terrain[x][y - 1];
}
return null;
} else if (dir === "right") {
if (y < terrain[x].length - 1) {
return terrain[x][y + 1];
}
return null;
} else {
throw "ERROR: getAdjacent direction: '" + dir + "' not recognized";
}
}
function adjacentSpaceXY(terrain, x, y, dirX, dirY) {
const absX = x + dirX;
const absY = y + dirY;
if (absX >= 0 && absY >= 0 && absX < terrain.length && absY < terrain[absX].length) {
return terrain[absX][absY];
}
return null;
}
/**
* starting from the input space, mark each reachable space as 'touched' to reveal it
* @param initialSpace: the starting space to be marked as touched from which we propagate out
*/
function touchAllAdjacentSpaces(initialSpace) {
// update the type properties to adjust image and update properties like reinforcement or selectable
initialSpace.setTypeProperties(initialSpace.type);
if (!initialSpace.touched) {
if (initialSpace.isBuilding === false && (!(initialSpace.walkable || initialSpace.type === "water" || initialSpace.type === "lava"))) {
if (initialSpace.drillable || initialSpace.drillHardable || initialSpace.explodable) {
tasksAvailable.push(initialSpace);
}
initialSpace.updateTouched(initialSpace.drillable || initialSpace.explodable || initialSpace.type === "solid rock" || (initialSpace.isBuilding === true));
return;
}
initialSpace.updateTouched(true);
if (initialSpace.sweepable) {
tasksAvailable.push(initialSpace);
}
if (initialSpace.buildable && initialSpace.resourceNeeded()) {
tasksAvailable.push(initialSpace);
}
for (let i = 0; i < initialSpace.contains.objectList.length; i++) {
// add each member of contains to tasksavailable
tasksAvailable.push(initialSpace.contains.objectList[i]);
}
const adjacentSpaces = [];
for (let x = -1; x <= 1; ++x) {
for (let y = -1; y <= 1; ++y) {
adjacentSpaces.push(adjacentSpaceXY(terrain, initialSpace.listX, initialSpace.listY, x, y));
}
}
for (let i = 0; i < adjacentSpaces.length; i++) {
if (adjacentSpaces[i] != null) {
touchAllAdjacentSpaces(adjacentSpaces[i]);
}
}
}
}
/**
* determine the path from the input list whose starting space is closest to the input object
* @param startObject: the object whose position should be checked against the input paths
* @param paths: the list of potential paths to select from
* @returns the path whose start position is closest to the input object
*/
function findClosestStartPath(startObject, paths) {
if (paths == null) {
return null;
}
let closestDistance = -1;
let closestIndex = -1;
const startObjectCenterX = startObject.centerX();
const startObjectCenterY = startObject.centerY();
for (let i = 0; i < paths.length; i++) {
const curDistance = getDistance(startObjectCenterX, startObjectCenterY, paths[i][paths[i].length - 1].centerX(), paths[i][paths[i].length - 1].centerY());
if (closestDistance === -1 || curDistance < closestDistance) {
closestDistance = curDistance;
closestIndex = i;
}
}
return paths[closestIndex];
}
/**
* calculate one or all of the shortest paths in a terrain from one space to another (note that paths go from end to start, rather than from start to end)
* if goalSpace is null, the search returns the nearest task that the input raider can perform.
* @param terrain: the terrain in which to search for a path
* @param startSpace: the space on which to begin the search
* @param goalSpace: the desired goal space. If null, searches for a task that the input raider can perform instead.
* @param returnAllSolutions: whether all shortest paths should be returned (true) or just one path (false)
* @param raider: optional flag; if goalSpace is null, this is the raider who will be used to determine which tasks can be performed.
* @returns {Array} the shortest path or paths from the start space to the goal space, or to the nearest task that the input raider can perform.
*/
function calculatePath(terrain, startSpace, goalSpace, returnAllSolutions, raider) {
// if startSpace meets the desired property, return it without doing any further calculations
if (startSpace === goalSpace || (goalSpace == null && raider.canPerformTask(startSpace))) {
if (!returnAllSolutions) {
return [startSpace];
}
return [[startSpace]];
}
// initialize starting variables
if (goalSpace != null) {
goalSpace.parents = [];
}
startSpace.startDistance = 0;
startSpace.parents = [];
const closedSet = [];
const solutions = [];
let finalPathDistance = -1;
let shortestPath = null;
const openSet = [startSpace];
// main iteration: keep popping spaces from the back until we have found a solution (or all equal solutions if returnAllSolutions is True)
// or openSet is empty (in which case there is no solution)
while (openSet.length > 0) {
const currentSpace = openSet.shift();
closedSet.push(currentSpace);
const adjacentSpaces = [];
adjacentSpaces.push(adjacentSpace(terrain, currentSpace.listX, currentSpace.listY, "up"));
adjacentSpaces.push(adjacentSpace(terrain, currentSpace.listX, currentSpace.listY, "down"));
adjacentSpaces.push(adjacentSpace(terrain, currentSpace.listX, currentSpace.listY, "left"));
adjacentSpaces.push(adjacentSpace(terrain, currentSpace.listX, currentSpace.listY, "right"));
// main inner iteration: check each space in adjacentSpaces for validity
for (let k = 0; k < adjacentSpaces.length; k++) {
if ((finalPathDistance !== -1) && (currentSpace.startDistance + 1 / currentSpace.speedModifier > finalPathDistance)) {
// a shorter way is already known, so we can skip this option
continue;
}
const newSpace = adjacentSpaces[k];
// check this here so that the algorithm is a little bit faster, but also so that paths to non-walkable terrain pieces (such as for drilling) will work
// if the newSpace is a goal, find a path back to startSpace (or all equal paths if returnAllSolutions is True)
if (newSpace === goalSpace || (goalSpace == null && raider.canPerformTask(newSpace))) {
goalSpace = newSpace;
newSpace.parents = [currentSpace]; // start the path with currentSpace and work our way back
const pathsFound = [[newSpace]];
// grow out the list of paths back in pathsFound until all valid paths have been exhausted
while (pathsFound.length > 0) {
if (pathsFound[0][pathsFound[0].length - 1].parents[0] === startSpace) { // we've reached the start space, thus completing this path
const currentPathDistance = pathsFound[0].reduce((a, b) => a + 1 / b.speedModifier, 0);
if (finalPathDistance === -1 || currentPathDistance < finalPathDistance) {
finalPathDistance = currentPathDistance;
shortestPath = pathsFound[0];
solutions.unshift(pathsFound.shift());
} else {
solutions.push(pathsFound.shift());
}
continue;
}
// branch additional paths for each parent of the current path's current space
for (let i = 0; i < pathsFound[0][pathsFound[0].length - 1].parents.length; i++) {
if (i === pathsFound[0][pathsFound[0].length - 1].parents.length - 1) {
pathsFound[0].push(pathsFound[0][pathsFound[0].length - 1].parents[i]);
} else {
pathsFound.push(pathsFound[0].slice());
pathsFound[pathsFound.length - 1].push(pathsFound[0][pathsFound[0].length - 1].parents[i]);
}
}
}
}
// attempt to keep branching from newSpace as long as it is a walkable type
if ((newSpace != null) && (newSpace.walkable === true)) {
const newStartDistance = currentSpace.startDistance + 1 / currentSpace.speedModifier;
const notInOpenSet = openSet.indexOf(newSpace) === -1;
// don't bother with newSpace if it has already been visited unless our new distance from the start space is smaller than its existing startDistance
if ((closedSet.indexOf(newSpace) !== -1) && (newSpace.startDistance < newStartDistance)) {
continue;
}
// accept newSpace if newSpace has not yet been visited or its new distance from the start space is equal to its existing startDistance
if (notInOpenSet || newSpace.startDistance === newStartDistance) {
// only reset parent list if this is the first time we are visiting newSpace
if (notInOpenSet) {
newSpace.parents = [];
}
newSpace.parents.push(currentSpace);
newSpace.startDistance = newStartDistance;
// if newSpace does not yet exist in the open set, insert it into the appropriate position using a binary search
if (notInOpenSet) {
openSet.splice(binarySearch(openSet, newSpace, "startDistance", true), 0, newSpace);
}
}
}
}
}
// if solutions is null then that means that no path was found
if (solutions.length === 0) {
return null;
}
if (returnAllSolutions) {
return solutions;
} else {
return shortestPath;
}
}
/**
* determine whether or not there is a resource available of the input resource type
* @param resourceType: the type of resource to check for
* @returns boolean whether a resource of the desired type is available (true) or not (false)
*/
function resourceAvailable(resourceType) {
return (RockRaiders.rightPanel.resources[resourceType] - reservedResources[resourceType]) > 0;
}
/**
* load in level data from input level name, reading from all supported map file types
* @param levelKey: the identifier for the level
*/
function loadLevelData(levelKey) {
RockRaiders.currentLevelKey = levelKey || RockRaiders.currentLevelKey;
const levelConf = RockRaiders.levelConf[RockRaiders.currentLevelKey];
RockRaiders.themeName = levelConf["TextureSet"].split("::")[1];
// TODO maybe someday we can use the same keys...
RockRaiders.tasksAutomated = {
"sweep": false,
"collect": false, // TODO collect ore and collect crystal need to be separated (What about dropped dynamites?)
"drill": false,
"drill hard": false,
"reinforce": false,
"build": false,
"walk": false,
"dynamite": false,
"vehicle": false
};
Object.keys(levelConf["Priorities"]).forEach((taskKey) => {
const lKey = taskKey.toLowerCase();
let ourKey = null;
if (lKey === "AI_Priority_Crystal".toLowerCase() || lKey === "AI_Priority_Ore".toLowerCase()) { // TODO separate ore and crystal collect tasks
ourKey = "collect";
} else if (lKey === "AI_Priority_Destruction".toLowerCase()) {
ourKey = "dynamite"; // TODO is this correctly translated?
} else if (lKey === "AI_Priority_Clearing".toLowerCase()) {
ourKey = "sweep";
} else if (lKey === "AI_Priority_Repair".toLowerCase()) {
// TODO repair task type not yet implemented
} else if (lKey === "AI_Priority_GetIn".toLowerCase()) {
ourKey = "vehicle";
} else if (lKey === "AI_Priority_Construction".toLowerCase()) {
ourKey = "build";
} else if (lKey === "AI_Priority_Reinforce".toLowerCase()) {
ourKey = "reinforce";
} else if (lKey === "AI_Priority_GetTool".toLowerCase()) {
// TODO currently gettool is not an extra task
} else if (lKey === "AI_Priority_Train".toLowerCase()) {
// TODO currently train is not an extra task
} else if (lKey === "AI_Priority_Recharge".toLowerCase()) {
// TODO recharge task type not yet implemented
}
if (ourKey) {
RockRaiders.tasksAutomated[ourKey] = levelConf["Priorities"][taskKey].toLowerCase() === "true"; // TODO maybe check for weird values here?
}
});
const terrainMapName = levelConf["TerrainMap"];
const cryoreMapName = levelConf["CryOreMap"];
const olFileName = levelConf["OListFile"];
const predugMapName = levelConf["PreDugMap"];
const surfaceMapName = levelConf["SurfaceMap"];
const pathMapName = levelConf["PathMap"];
const fallinMapName = levelConf["FallinMap"];
// load in Space types from terrain, surface, and path maps
for (let i = 0; i < GameManager.maps[terrainMapName].level.length; i++) {
terrain.push([]);
for (let r = 0; r < GameManager.maps[terrainMapName].level[i].length; r++) {
// give the path map the highest priority, if it exists
if (GameManager.maps[pathMapName] && GameManager.maps[pathMapName].level[i][r] === 1) {
// rubble 1 Space id = 100
terrain[i].push(new Space(100, i, r, GameManager.maps[surfaceMapName].level[i][r]));
} else if (GameManager.maps[pathMapName] && GameManager.maps[pathMapName].level[i][r] === 2) {
// building power path Space id = -1
terrain[i].push(new Space(-1, i, r, GameManager.maps[surfaceMapName].level[i][r]));
} else {
if (GameManager.maps[predugMapName].level[i][r] === 0) {
// soil(5) was removed pre-release, so replace it with dirt(4)
if (GameManager.maps[terrainMapName].level[i][r] === 5) {
terrain[i].push(new Space(4, i, r, GameManager.maps[surfaceMapName].level[i][r]));
} else {
terrain[i].push(new Space(GameManager.maps[terrainMapName].level[i][r], i, r, GameManager.maps[surfaceMapName].level[i][r]));
}
} else if (GameManager.maps[predugMapName].level[i][r] === 3 || GameManager.maps[predugMapName].level[i][r] === 4) { // slug holes
terrain[i].push(new Space(GameManager.maps[predugMapName].level[i][r] * 10, i, r, GameManager.maps[surfaceMapName].level[i][r]));
} else if (GameManager.maps[predugMapName].level[i][r] === 1 || GameManager.maps[predugMapName].level[i][r] === 2) {
if (GameManager.maps[terrainMapName].level[i][r] === 6) {
terrain[i].push(new Space(6, i, r, GameManager.maps[surfaceMapName].level[i][r]));
} else if (GameManager.maps[terrainMapName].level[i][r] === 9) {
terrain[i].push(new Space(9, i, r, GameManager.maps[surfaceMapName].level[i][r]));
} else {
terrain[i].push(new Space(0, i, r, GameManager.maps[surfaceMapName].level[i][r]));
}
}
const currentCryOre = GameManager.maps[cryoreMapName].level[i][r];
if (currentCryOre % 2 === 1) {
terrain[i][r].containedCrystals = (currentCryOre + 1) / 2;
} else {
terrain[i][r].containedOre = currentCryOre / 2;
}
}
}
}
// ensure that any walls which do not meet the 'supported' requirement crumble at the start
for (let i = 0; i < GameManager.maps[predugMapName].level.length; i++) {
for (let r = 0; r < GameManager.maps[predugMapName].level[i].length; r++) {
if (terrain[i][r].isWall) {
terrain[i][r].checkWallSupported(null, true);
}
}
}
// 'touch' all exposed spaces in the predug map so that they appear as visible from the start
for (let i = 0; i < GameManager.maps[predugMapName].level.length; i++) {
for (let r = 0; r < GameManager.maps[predugMapName].level[i].length; r++) {
const currentPredug = GameManager.maps[predugMapName].level[i][r];
if (currentPredug === 1 || currentPredug === 3) {
touchAllAdjacentSpaces(terrain[i][r]);
}
}
}
// add land-slide frequency to Spaces
if (GameManager.maps[fallinMapName]) {
for (let i = 0; i < GameManager.maps[fallinMapName].level.length; i++) {
for (let r = 0; r < GameManager.maps[fallinMapName].level[i].length; r++) {
terrain[i][r].setLandSlideFrequency(GameManager.maps[fallinMapName].level[i][r]);
}
}
}
// load in non-space objects next
const objectList = GameManager.objectLists[olFileName];
Object.values(objectList).forEach(function (olObject) {
// all object positions seem to be off by one
olObject.xPos--;
olObject.yPos--;
if (olObject.type === "TVCamera") {
// coords need to be rescaled since 1 unit in LRR is 1, but 1 unit in the remake is tileSize (128)
gameLayer.cameraX = olObject.xPos * tileSize;
gameLayer.cameraY = olObject.yPos * tileSize;
// center the camera
gameLayer.cameraX -= GameManager.screenWidth / 2;
gameLayer.cameraY -= GameManager.screenHeight / 2;
} else if (olObject.type === "Pilot") {
// note inverted x/y coords for terrain list
const newRaider = new Raider(terrain[parseInt(olObject.yPos, 10)][parseInt(olObject.xPos, 10)]);
newRaider.setCenterX(olObject.xPos * tileSize);
newRaider.setCenterY(olObject.yPos * tileSize);
// convert to radians (note that heading angle is rotated 90 degrees clockwise relative to the remake angles)
newRaider.drawAngle = (olObject.heading - 90) / 180 * Math.PI;
raiders.push(newRaider);
} else if (olObject.type === "Toolstation") {
const currentSpace = terrain[Math.floor(parseFloat(olObject.yPos))][Math.floor(parseFloat(olObject.xPos))];
currentSpace.setTypeProperties(BuildingTypeEnum.toolStore);
currentSpace.headingAngle = (olObject.heading - 90) / 180 * Math.PI;
// check if this space was in a wall, but should now be touched
checkRevealSpace(currentSpace);
// set drawAngle to headingAngle now if this space isn't initially in the fog
if (currentSpace.touched) {
currentSpace.drawAngle = currentSpace.headingAngle - Math.PI / 2;
}
// check if this building's power path space was in a wall, but should now be touched
checkRevealSpace(currentSpace.powerPathSpace);
currentSpace.powerPathSpace.setTypeProperties("building power path");
} else {
// TODO implement remaining object types like: spider, drives and hovercraft
console.log("Object type " + olObject.type + " not yet implemented");
}
});
levelConf.numOfCrystals = 0;
levelConf.numOfOres = 0;
levelConf.numOfDigables = 0;
for (let x = 0; x < terrain.length; x++) {
for (let y = 0; y < terrain[x].length; y++) {
const space = terrain[x][y];
levelConf.numOfCrystals += space.containedCrystals;
levelConf.numOfOres += space.containedOre + space.getRubbleOreContained();
levelConf.numOfDigables += space.isDigable() ? 1 : 0;
}
}
}
/**
* check if this space is surrounded on any side by a touched space; if so, touch this space.
* this function should only be used when overriding spaces in OL portion of level load procedure.
* @param initialSpace: the space to check for revealing
*/
function checkRevealSpace(initialSpace) {
if (initialSpace == null) {
return;
}
const adjacentSpaces = [];
adjacentSpaces.push(adjacentSpace(terrain, initialSpace.listX, initialSpace.listY, "up"));
adjacentSpaces.push(adjacentSpace(terrain, initialSpace.listX, initialSpace.listY, "down"));
adjacentSpaces.push(adjacentSpace(terrain, initialSpace.listX, initialSpace.listY, "left"));
adjacentSpaces.push(adjacentSpace(terrain, initialSpace.listX, initialSpace.listY, "right"));
for (let i = 0; i < adjacentSpaces.length; ++i) {
if (adjacentSpaces[i] != null && adjacentSpaces[i].touched) {
touchAllAdjacentSpaces(initialSpace);
return;
}
}
}
/**
* determine the type of the input task. If optional raider flag is included, gives additional context for determining the task type.
* @param task: the task whose type we should determine
* @param raider: the raider who possesses the input task
* @returns string the type of the input task, or null if the task is invalid
*/
function taskType(task, raider) { // optional raider flag allows us to determine what the raider is doing from additional task related variables
if (typeof task == "undefined" || task == null) {
return "";
}
if (typeof task.drillable != "undefined" && task.drillable === true) {
return "drill";
}
if (typeof task.drillHardable != "undefined" && task.drillHardable === true) {
return "drill hard";
}
if (typeof task.sweepable != "undefined" && task.sweepable === true) {
return "sweep";
}
if (typeof task.buildable != "undefined" && task.buildable === true) {
return "build";
}
if (typeof task.reinforcable != "undefined" && task.reinforcable === true) {
return "reinforce";
}
if (typeof task.dynamitable != "undefined" && task.dynamitable === true) {
return "dynamite";
}
if (typeof task.space != "undefined" && task instanceof Collectable) {
return "collect";
}
if (typeof task.space != "undefined" && task instanceof Vehicle) {
return "vehicle";
}
if (typeof task.isBuilding != "undefined" && task.isBuilding === true && task.type === BuildingTypeEnum.toolStore) {
return (raider != null && raider.getToolName != null) ? "get tool" : "upgrade";
}
if (typeof task.walkable != "undefined" && task.walkable === true) {
return "walk";
}
}
/**
* create a new raider, as long as there is at least one touched toolStore to which he can teleport
*/
function createRaider() {
if (RockRaiders.raiderInQueue < 9) {
RockRaiders.raiderInQueue++;
}
}
/**
* Returns the maximum number of raiders currently allowed. Initial amount is nine plus ten per support station
*/
RockRaidersGame.prototype.getMaxAmountOfRaiders = function () {
let maxAmount = 9;
for (let c = 0; c < buildings.length; c++) {
if (buildings[c].type === BuildingTypeEnum.supportStation) {
maxAmount += 10;
}
}
return maxAmount;
};
/**
* create a new vehicle of the input type, as long as there is at least one touched toolStore to which it can teleport
* @param vehicleType: the type of vehicle to create
*/
function createVehicle(vehicleType) {
let toolStore = null;
for (let i = 0; i < buildings.length; i++) {
if (buildings[i].type === BuildingTypeEnum.toolStore) {
toolStore = buildings[i];
break;
}
}
if (toolStore == null) {
return;
}
const newVehicle = (vehicleType === "hover scout" ? new HoverScout(toolStore.powerPathSpace) :
(vehicleType === "small digger" ? new SmallDigger(toolStore.powerPathSpace) : new SmallTransportTruck(toolStore.powerPathSpace)));
vehicles.push(newVehicle);
tasksAvailable.push(newVehicle);
cancelSelection();
}
function changeIconPanel(targetIconPanel = RockRaiders.mainIconPanel) {
if (RockRaiders.activeIconPanel !== targetIconPanel) {
if (RockRaiders.activeIconPanel) {
RockRaiders.activeIconPanel.hide();
}
RockRaiders.activeIconPanel = targetIconPanel;
RockRaiders.activeIconPanel.show();
}
}
/**
* cancel the current selection, setting selection to an empty list and selectionType to null, and closing any open menus
*/
function cancelSelection() {
selection = [];
selectionType = null;
changeIconPanel();
}
function setSelectionByMouseCursor() {
// check if a raider was clicked
for (let i = 0; i < raiders.objectList.length; i++) {
if (collisionPoint(GameManager.mouseReleasedPosLeft.x, GameManager.mouseReleasedPosLeft.y, raiders.objectList[i], raiders.objectList[i].affectedByCamera)) {
// simply choose the first raider identified as having been clicked, since all raiders have the same depth regardless
selection = [raiders.objectList[i]];
selectionType = "raider";
GameManager.playSoundEffect("SFX_Okay");
return;
}
}
// check if a vehicle was clicked
for (let i = 0; i < vehicles.objectList.length; i++) {
if (collisionPoint(GameManager.mouseReleasedPosLeft.x, GameManager.mouseReleasedPosLeft.y, vehicles.objectList[i], vehicles.objectList[i].affectedByCamera)) {
selection = [vehicles.objectList[i]];
selectionType = selection[0].type;
GameManager.playSoundEffect("SFX_Okay");
return;
}
}
// check if a terrain was clicked
for (let i = 0; i < terrain.length; i++) {
for (let r = 0; r < terrain[i].length; r++) {
let terrainTile = terrain[i][r];
if (collisionPoint(GameManager.mouseReleasedPosLeft.x, GameManager.mouseReleasedPosLeft.y, terrainTile, terrainTile.affectedByCamera)) {
if (terrainTile.isSelectable() && !selection.includes(terrainTile)) {
selection = [terrainTile];
selectionType = selection[0].touched ? selection[0].type : "Hidden";
if (selectionType === "ground") {
GameManager.playSoundEffect("SFX_Floor");
} else if (terrainTile.isWall) {
GameManager.playSoundEffect("SFX_Wall");
} else {
GameManager.playSoundEffect("SFX_Okay");
}
}
return;
}
}
}
}
/**
* attempt to update the current selection in response to a left-click
*/
function checkUpdateClickSelection() {
// ignore mouse clicks if they landed on a part of the UI
if (GameManager.mouseReleasedLeft && !mousePressIsSelection) {
setSelectionByMouseCursor();
// automatically close tool menu if a raider is no longer selected
if (selectionType !== "raider" && RockRaiders.activeIconPanel === RockRaiders.raiderIconPanel) {
changeIconPanel(RockRaiders.mainIconPanel);
}
}
}
/**
* update selectionType based on current selection, setting it to null if selection is empty
*/
function checkUpdateSelectionType() {
if (selection.length === 0) {
return;
}
for (let i = selection.length - 1; i >= 0; --i) {
if (selection[i].dead === true) {
selection.splice(i, 1);
}
}
if (selection.length === 0) {
cancelSelection();
return;
}
if (selection[0] instanceof Space) {
selectionType = selection[0].touched === true ? selection[0].type : "Hidden";
tileSelectedGraphic.drawDepth = drawDepthSelectedSpace; // put tile selection graphic between space and collectable
GameManager.refreshObject(tileSelectedGraphic);
}
if (selection[0] instanceof Vehicle) {
tileSelectedGraphic.drawDepth = drawDepthSelectedVehicle;
GameManager.refreshObject(tileSelectedGraphic);
// manually update vehicle selection to raider riding it, if it has a driver
for (let i = 0; i < raiders.objectList.length; ++i) {
if (raiders.objectList[i].vehicle === selection[0] || raiders.objectList[i].holding.indexOf(selection[0]) !== -1) {
selection[0] = raiders.objectList[i];
selectionType = "raider";
}
}
}
// manually update non-primary building pieces to point to main building Space
if (selection[0] instanceof Space) {
if (nonPrimarySpaceTypes.indexOf(selection[0].type) !== -1) {
selection[0] = selection[0].parentSpace;
selectionType = selection[0].type;
}
}
}
/**
* attempt to update current mouse drag box selection. If mouse button is released, select all raiders within the box.
*/
function checkUpdateMouseSelect() {
if (GameManager.mouseDownLeft) {
if (GameManager.mousePressedLeft) {
mousePressStartPos = GameManager.mousePos;
} else if (!mousePressIsSelection) {
if (getDistance(mousePressStartPos.x, mousePressStartPos.y, GameManager.mousePos.x, GameManager.mousePos.y) > dragStartDistance) {
mousePressIsSelection = true;
selectionRectCoords.x1 = mousePressStartPos.x;
selectionRectCoords.y1 = mousePressStartPos.y;
}
}
// we are currently performing a drag select box
if (mousePressIsSelection) {
// determine top-left corner to draw rect [xMin, yMin, xMax, yMax]
selectionRectPointList = [null, null, null, null];
selectionRectCoordList = [selectionRectCoords.x1, selectionRectCoords.y1, GameManager.mousePos.x, GameManager.mousePos.y];
for (let i = 0; i < 4; i++) {
if (selectionRectPointList[i % 2] == null || selectionRectCoordList[i] < selectionRectPointList[i % 2]) {
selectionRectPointList[i % 2] = selectionRectCoordList[i];
}
if (selectionRectPointList[(i % 2) + 2] == null || selectionRectCoordList[i] > selectionRectPointList[(i % 2) + 2]) {
selectionRectPointList[(i % 2) + 2] = selectionRectCoordList[i];
}
}
}
} else {
if (mousePressIsSelection) {
mousePressIsSelection = false;
if (selectionRectCoords.x1 != null) {
selectionRectCoords.x1 = null;
selectionRectCoords.y1 = null;
selectionRectObject.rect.width = selectionRectPointList[2] - selectionRectPointList[0];
selectionRectObject.rect.height = selectionRectPointList[3] - selectionRectPointList[1];
selectionRectObject.x = selectionRectPointList[0] + selectionRectObject.drawLayer.cameraX;
selectionRectObject.y = selectionRectPointList[1] + selectionRectObject.drawLayer.cameraY;
const collidingRaiders = [];
for (let i = 0; i < raiders.objectList.length; i++) {
if (collisionRect(selectionRectObject, raiders.objectList[i])) {
collidingRaiders.push(raiders.objectList[i]);
}
}
if (collidingRaiders.length > 0) {
// set selection to all of the raiders contained within the selection Rect
selectionType = "raider";
selection = collidingRaiders;
}
}
}
}
}
/**
* attempt to assign a task to the current selection upon releasing the right mouse button
*/
function checkAssignSelectionTask() {
if (GameManager.mouseReleasedRight && selection.length !== 0 && selectionType === "raider") {
// most of this code is copied from left-click task detection
const clickedTasks = [];
// first check if we clicked a vehicle that is neither being driver already nor has a raider en route
for (let i = 0; i < vehicles.objectList.length; ++i) {
if (collisionPoint(GameManager.mouseReleasedPosRight.x, GameManager.mouseReleasedPosRight.y, vehicles.objectList[i], vehicles.objectList[i].affectedByCamera)
&& ((tasksAvailable.indexOf(vehicles.objectList[i]) !== -1) && tasksInProgress.objectList.indexOf(vehicles.objectList[i]) === -1)) {
clickedTasks.push(vehicles.objectList[i]);
}
}
// if no vehicles clicked, check spaces and their contains
if (clickedTasks.length === 0) {
for (let p = 0; p < terrain.length; p++) {
for (let r = 0; r < terrain[p].length; r++) {
let initialSpace = terrain[p][r];
for (let j = 0; j < terrain[p][r].contains.objectList.length + 1; j++) {
if (collisionPoint(GameManager.mouseReleasedPosRight.x, GameManager.mouseReleasedPosRight.y, initialSpace, initialSpace.affectedByCamera) &&
// don't do anything if the task is already taken by another raider, we don't want to re-add it to the task queue
((tasksAvailable.indexOf(initialSpace) !== -1) || initialSpace.walkable || (tasksInProgress.objectList.indexOf(initialSpace) !== -1))) {
// console.log("A");
if ((j === 0 && (initialSpace.drillable || initialSpace.drillHardable || initialSpace.sweepable ||
initialSpace.buildable || initialSpace.walkable)) || j > 0) {
// console.log("B");
clickedTasks.push(initialSpace);
if (debug) {
console.log("TERRAIN OL LENGTH + 1: " + (terrain[p][r].contains.objectList.length + 1));
}
}
}
initialSpace = terrain[p][r].contains.objectList[j];
}
}
}
}
if (clickedTasks.length > 0) {
let lowestDrawDepthValue = clickedTasks[0].drawDepth;
let lowestDrawDepthId = 0;
// prioritize tasks that are not in progress in the event that multiple tasks are clicked at once
let inProgress = tasksInProgress.objectList.indexOf(clickedTasks[0]) !== -1;
for (let p = 1; p < clickedTasks.length; p++) {
const curInProgress = tasksInProgress.objectList.indexOf(clickedTasks[p]) !== -1;
if (curInProgress === inProgress && clickedTasks[p].drawDepth < lowestDrawDepthValue || (inProgress === true && curInProgress === false)) {
lowestDrawDepthValue = clickedTasks[p].drawDepth;
lowestDrawDepthId = p;
if (curInProgress === false) {
inProgress = false;
}
}
}
if (debug) {
console.log("IN PROGESS?: " + inProgress + " CLICKED TASKS LENGTH: " + clickedTasks.length);
}
const selectedTask = clickedTasks[lowestDrawDepthId];
let assignedAtLeastOnce = false;
let taskWasAvailable = false;
const baseSelectedTask = taskType(selectedTask);
for (let i = 0; i < selection.length; i++) {
let selectedTaskType = baseSelectedTask;
// treat build commands as walk unless the raider is holding something that the building site needs
if (selectedTaskType === "build") {
if (selection[i].holding.length === 0) {
selectedTaskType = "walk";
}
// check if any of the held resources is needed
else {
let foundNeeded = false;
for (let h = 0; h < selection[i].holding.length; ++h) {
if (selectedTask.resourceNeeded(selection[i].holding[h].type)) {
foundNeeded = true;
break;
}
}
if (!foundNeeded) {
selectedTaskType = "walk";
}
}
}
// treat any other commands as walk commands if the raider does not have the necessary tool
else if (!selection[i].haveTool(selectedTaskType)) {
selectedTaskType = "walk";
}
// ignore a 'walk' command if the objective is not walkable
if (selectedTaskType === "walk" && (!selectedTask.walkable)) {
continue;
}
// console.log("can we perform? : " + selection[i].canPerformTask(selectedTask, true));
// if we changed the taskType to 'walk' override this canPerformTask check since raiders can always walk
if (selection[i].canPerformTask(selectedTask, true) || selectedTaskType === "walk") {
// if current raider is already performing a task and not holding anything, stop him before assigning the new task
if (selection[i].currentTask != null && (selection[i].holding.length === 0 || selectedTaskType === "build" || selectedTaskType === "walk")) {
stopMinifig(selection[i]);
}
// raiders are the only valid selection type for now
if (selection[i].currentTask == null && (selection[i].holding.length === 0 || selectedTaskType === "build" || selectedTaskType === "walk")) {
if (selection[i].haveTool(selectedTaskType)) {
const index = tasksAvailable.indexOf(selectedTask);
// this check will be necessary in the event that we choose a task such as walking
if (index !== -1) {
taskWasAvailable = true;
tasksAvailable.splice(index, 1);
} else {
// these task types can only be assigned to a single raider from a selection group
if (selectedTaskType === "collect" || selectedTaskType === "vehicle") {
break;
}
}
selection[i].currentTask = selectedTask;
selection[i].currentObjective = selectedTask;
selection[i].currentPath = findClosestStartPath(selection[i], calculatePath(terrain, selection[i].space,
typeof selectedTask.space == "undefined" ? selectedTask : selectedTask.space, true));
const foundCloserResource = selection[i].checkChooseCloserEquivalentResource(false);
// don't assign the task if a valid path to the task cannot be found for the raider
if (selection[i].currentPath == null) {
selection[i].currentTask = null;
selection[i].currentObjective = null;
} else {
// don't add this resource to tasksInProgress if we chose a closer resource instead
if (!foundCloserResource) {
// don't remove the task from tasksAvailable if we decided to walk due to lack of necessary tools
if (selectedTaskType !== "walk") {
assignedAtLeastOnce = true;
}
}
if (selectedTaskType === "walk") {
// set walkPosOffset to the difference from the selected space top-left corner to the walk position
selection[i].walkPosDummy.setCenterX(GameManager.mouseReleasedPosRight.x + gameLayer.cameraX);
selection[i].walkPosDummy.setCenterY(GameManager.mouseReleasedPosRight.y + gameLayer.cameraY);
selection[i].currentTask = selection[i].walkPosDummy;
selection[i].currentObjective = selection[i].walkPosDummy;
} else if (selectedTaskType === "build") {
for (let h = 0; h < selection[i].holding.length; ++h) {
if (selectedTask.resourceNeeded(selection[i].holding[h].type)) {
selectedTask.dedicatedResources[selection[i].holding[h].type]++;
this.dedicatingResource = true;
}
}
}
}
}
}
}
}
if (assignedAtLeastOnce && (tasksInProgress.objectList.indexOf(selectedTask) === -1)) {
tasksInProgress.push(selectedTask);
} else if (taskWasAvailable) {
tasksAvailable.push(selectedTask);
}
}
}
}
/**
* release any held objects from all raiders in selection
*/
function unloadMinifig() {
if (selection.length === 0) {
return;
}
for (let i = 0; i < selection.length; i++) {
if (selection[i].holding.length === 0) {
continue;
}
for (let h = 0; h < selection[i].holding.length; ++h) {
// create a new collectable of the same type, and place it on the ground. then, delete the currently held collectable.
const newCollectable = (selection[i].holding[0].type === "dynamite" ? new Dynamite(getNearestSpace(terrain, selection[i], selection[i].holding[0].centerX(), selection[i].holding[0].centerY())) :
new Collectable(getNearestSpace(terrain, selection[i]), selection[i].holding[0].type, selection[i].holding[0].centerX(), selection[i].holding[0].centerY()));
collectables.push(newCollectable);
tasksAvailable.push(newCollectable);