-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnupilot.js
11918 lines (11809 loc) · 505 KB
/
nupilot.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
/*
Copyright (C) 2017-2019 Thomas Horn
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// ==UserScript==
// @name nuPilot
// @description Planets.nu plugin to enable ship auto-pilots
// @version 0.14.44
// @date 2019-05-27
// @author drgirasol
// @include http://planets.nu/*
// @include https://planets.nu/*
// @include http://play.planets.nu/*
// @include https://play.planets.nu/*
// @include http://test.planets.nu/*
// @include https://test.planets.nu/*
// @supportURL https://github.com/drgirasol/nupilot/issues
// @homepageURL https://github.com/drgirasol/nupilot/wiki
// @updateURL https://greasyfork.org/scripts/26189-nupilot/code/nuPilot.user.js
// @downloadURL https://greasyfork.org/scripts/26189-nupilot/code/nuPilot.user.js
// @grant none
// ==/UserScript==
function wrapper () { // wrapper for injection
/*
*
* Auto Pilot Ship (APS) Object
*
*/
function APS(ship, cfgData)
{
if (typeof ship === "undefined") return;
this.moveablesMap = {
dur: "duranium",
tri: "tritanium",
mol: "molybdenum",
neu: "neutronium",
sup: "supplies",
mcs: "megacredits",
cla: "clans"
};
this.cargo = [
"duranium",
"tritanium",
"molybdenum",
"supplies",
"clans"
];
this.moveables = [
"duranium",
"tritanium",
"molybdenum",
"neutronium",
"supplies",
"megacredits",
"clans"
];
this.noteColor = "ff9900";
//
this.ship = ship;
this.hull = vgap.getHull(ship.hullid);
this.maxCapacity = false;
this.curCapacity = false;
this.minCapacity = false;
this.demand = false;
this.isAPS = false;
this.isIdle = false;
this.idleReason = [];
this.idleTurns = 0;
this.curFuelFactor = 0;
this.fuelFactor = {
t1: [0,100,800,2700,6400,12500,21600,34300,51200,72900],
t2: [0,100,430,2700,6400,12500,21600,34300,51200,72900],
t3: [0,100,425,970,5400,12500,21600,34300,51200,72900],
t4: [0,100,415,940,1700,7500,11600,24300,31200,72900],
t5: [0,100,415,940,1700,2600,10500,14300,23450,72900],
t6: [0,100,415,940,1700,2600,3733,12300,21450,72900],
t7: [0,100,415,940,1700,2600,3733,5300,19450,42900],
t8: [0,100,400,900,1600,2500,3600,5000,7000,42900],
t9: [0,100,400,900,1600,2500,3600,4900,6400,8100]
};
this.gravitonic = false;
this.radiationShielding = false;
this.terraCooler = false;
this.terraHeater = false;
this.enemySafetyZone = 81;
this.scopeRange = Math.pow(this.ship.engineid, 2); // default scope range for all APS, changed by functionModules
this.simpleRange = Math.pow(this.ship.engineid, 2); // max warp turn distance
//
this.planet = false; // toDo: planet object contained in colony
this.colony = false;
this.isOwnPlanet = false;
this.isUnownedPlanet = false;
this.base = false; // base -> planet object
this.baseColony = false;
this.atBase = false; // bool
this.inWarpWell = false; // bool
this.waypoint = false; // holds planet object if target is a planet
this.destination = false; // destination -> planet object // toDo: planet object contained in destinationColony
this.destinationColony = false; // destination -> colony object
this.secondaryDestination = false; // secondary destination -> planet object // toDo: planet object contained in secondaryDestinationColony
this.secondaryDestinationColony = false; // secondary destination -> colony object
this.lastDestination = false; // previous destination
this.objectOfInterest = false;
//
this.enemyPlanets = this.getCloseEnemyPlanets(); // enemy planets within a range of 200 ly
this.enemyShips = this.getCloseEnemyShips(); // enemy ships within a range of 200 ly
this.primaryFunction = false;
this.functionModule = false;
this.hasToSetPotDes = false;
this.deficiencies = [ "cla", "neu", "sup", "mcs" ];
this.minerals = [ "dur", "tri", "mol" ];
this.oShipMission = false;
this.potentialWaypoints = []; // potential next targets
this.potDest = []; // potential destinations
//
if (typeof cfgData !== "undefined" && cfgData !== false)
{
if (!autopilot.apsShips.findById(ship.id)) {
let newCfg = new APSdata(cfgData);
autopilot.apsShips.push(newCfg.getData());
}
this.isAPS = true;
this.initializeBoardComputer(cfgData);
} else
{
// not an APS
this.isAPS = false;
}
}
/*
* METHODS
*/
APS.prototype.initializeBoardComputer = function(configuration)
{
// console.log("APS.initializeBoardComputer:", this.ship.id);
this.setPlanet();
this.setMissionAttributes(configuration);
this.setShipAttributes(configuration);
this.setPositionAttributes(configuration);
//
// initialize ship function module
//
this.bootFunctionModule(configuration.shipFunction);
this.setFunctionAttributes();
//
// console.log("...APS:", this);
//
if (this.destination) {
//
this.setDemand();// console.log("...set demand:", this.demand);
//
if (this.planet) {
// console.log("...at planet with destination (" + this.destination.id + ") set.");
if (this.secondaryDestination)// console.log("...and 2ndary destination = " + this.secondaryDestination.id);
if (this.lastDestination.id === this.planet.id)// console.log("...planet is former destination...");
//
this.functionModule.handleCargo(this);// console.log("...handle cargo.");
//
// if we are at the destination, clear destination setting
if (this.planet.id === this.destination.id && !this.secondaryDestination) {
// console.log("...planet is destination, update configuration.");
if (this.functionModule.missionCompleted(this)) {
// console.log("...mission completed, update configuration.");
configuration.lastDestination = this.destination.id;
configuration.destination = false;
configuration.secondaryDestination = false;
configuration.idle = false;
configuration.idleReason = "";
configuration.idleTurns = 0;
// if new behaviour is requested, now is the time for change
if (configuration.newFunction) {
configuration.shipFunction = configuration.newFunction;
configuration.newFunction = false;
configuration.ooiPriority = configuration.newOoiPriority;
configuration.newOoiPriority = false;
this.bootFunctionModule(configuration.shipFunction);
this.setFunctionAttributes();
}
this.setShipIdleStatus(configuration);
this.setMissionAttributes(configuration);
this.hasToSetPotDes = true; // will determine potDest, select destination and set next target
// console.log("...scheduled for potential destination determination.");
} else
{
// console.log("...mission incomplete! Due for mission update.");
this.functionModule.setSecondaryDestination(this);
if (this.secondaryDestination || this.planet.id !== this.destination.id) {
// console.log("...setting next Target.");
this.setShipTarget();
}
}
} else if (this.secondaryDestination && this.planet.id === this.secondaryDestination.id)
{
// console.log("...planet is 2ndary destination, update configuration.");
configuration.lastDestination = this.secondaryDestination.id;
configuration.secondaryDestination = false;
if (configuration.shipFunction === "exp" && this.planet.id !== this.base.id) {
this.hasToSetPotDes = true; // expander will set new destination after re-supplying, if it didn't return to base
} else {
this.setMissionAttributes(configuration);
// console.log("...setting next Target.");
this.setShipTarget();
}
} else if (!this.destination) {
// seems destination was reset, we need to find a new one
// console.log("...destination was reset by handleCargo.");
this.hasToSetPotDes = true;
} else {
// console.log("...planet is no destination.");
if (this.getMissionConflict(this.destination)) {
// console.log("...Mission conflict! Scheduled for potential destination determination.");
this.hasToSetPotDes = true;
} else {
// console.log("...setting next Target.");
this.setShipTarget();
}
}
//this.storedData = autopilot.syncLocalApsStorage(configuration);
} else {
if (this.getMissionConflict(this.destination)) {
if (this.ship.target && this.destination.id === this.ship.target.id) {
// console.log("...Mission conflict! Scheduled for potential destination determination.");
this.hasToSetPotDes = true;
} else {
// console.log("...Mission conflict! Proceed to target planet and re-check mission conflict.");
}
} else
{
// console.log("...in space / warp-well with destination / secondary destination set.", this.destination, this.secondaryDestination);
if (!this.targetIsSet()) this.setShipTarget();
if (this.targetIsSet())
{
// target set
let wpP = vgap.planetAt(this.ship.targetx, this.ship.targety);
if (wpP) this.waypoint = wpP;
} else {
// no target is set...
// console.log("...setting next Target failed.");
//this.setShipTarget();
}
}
}
} else
{
// console.log("...no destination set.");
// console.log("...scheduled for potential destination determination.");
this.hasToSetPotDes = true; // will determine potDest, select destination and set next target
}
};
APS.prototype.bootFunctionModule = function(func)
{
if (func === "col")
{
// console.log("...Collector Mode (" + this.objectOfInterest + ")");
this.functionModule = new CollectorAPS(this);
// console.log(this.functionModule);
} else if (func === "dis")
{
// console.log("...Distributer Mode (" + this.objectOfInterest + ")");
this.functionModule = new DistributorAPS(this);
} else if (func === "bld")
{
// console.log("...Builder Mode (" + this.objectOfInterest + ")");
this.functionModule = new BuilderAPS(this);
} else if (func === "alc")
{
// console.log("...Alchemy Mode (" + this.objectOfInterest + ")");
this.functionModule = new AlchemyAPS(this);
} else if (func === "exp")
{
// console.log("...Expander Mode (" + this.objectOfInterest + ")");
this.functionModule = new ExpanderAPS(this);
} else if (func === "ter")
{
// console.log("...Terraformer Mode");
this.functionModule = new TerraformerAPS(this);
} else if (func === "hiz")
{
// console.log("...Hizzz Mode");
this.functionModule = new HizzzAPS(this);
} else
{
this.isAPS = false;
}
};
/*
* CONFIGURATION
*/
APS.prototype.setPlanet = function() {
//console.log("APS.setPlanet:");
let self = this;
let p = vgap.planetAt(this.ship.x, this.ship.y);
//console.log("...planet", p);
if (p) {
this.planet = new Proxy(p, {
set: function(target, prop, value, receiver) {
if (self.moveables.indexOf(prop) > -1) {
// console.log("APS.planet proxy: update balance");
let c = autopilot.getColony(target.id, true); // update balance
}
target[prop] = value;
return true;
}
});
this.colony = autopilot.getColony(p.id, true);
} else {
this.planet = false;
this.colony = false;
}
};
APS.prototype.setShipIdleStatus = function(cfg) {
this.isIdle = cfg.isIdle;
if (!cfg.idleReason) {
this.idleReason = [];
} else if (cfg.idleReason && this.idleReason.indexOf(cfg.idleReason) === -1) this.idleReason.push(cfg.idleReason);
if (cfg.idleTurns) this.idleTurns = cfg.idleTurns;
};
APS.prototype.setShipAttributes = function(cfg)
{
this.atBase = false; // bool
this.hasToSetPotDes = false;
this.curFuelFactor = this.fuelFactor["t" + this.ship.engineid][this.ship.warp]; // currently applicable fuel factor
if (this.hull.special && this.hull.special.match(/Gravitonic/)) this.gravitonic = true;
if (this.hull.special && this.hull.special.match(/Radiation Shielding/)) this.radiationShielding = true;
if (this.hull.special && this.hull.special.match(/Terraform/) && this.hull.special.match(/lower\splanet\stemperature/)) this.terraCooler = true;
if (this.hull.special && this.hull.special.match(/Terraform/) && this.hull.special.match(/raise\splanet\stemperature/)) this.terraHeater = true;
//if (this.inWarpWell) this.planet = false;
this.setConventionalShipMission(cfg);
this.setRange();
};
APS.prototype.setRange = function()
{
this.simpleRange = Math.pow(this.ship.engineid, 2); // max turn distance with max efficient warp (=engineid)
if (this.gravitonic) this.simpleRange *= 2;
};
APS.prototype.setConventionalShipMission = function(cfg) {
this.oShipMission = cfg.oShipMission;
if (this.oShipMission && this.oShipMission !== this.ship.mission) {
if (this.ship.mission !== 9 && this.ship.mission !== 8 && this.ship.mission !== 2 && this.ship.mission !== 1) {
this.ship.mission = this.oShipMission;
} //
} // reset to original ship mission, if we are not cloaking, hizzing (or other mission 8), laying or sweeping mines
};
APS.prototype.setPositionAttributes = function(cfg) {
//this.scopeRange = 200; // set by function module!
//if (!this.inWarpWell) this.planet = vgap.planetAt(this.ship.x, this.ship.y);
if (!this.planet) this.inWarpWell = this.isInWarpWell( { x: this.ship.x, y: this.ship.y } );
this.isOwnPlanet = (this.planet && this.planet.ownerid === vgap.player.id);
this.isUnownedPlanet = (this.planet && this.planet.ownerid === 0);
this.base = vgap.getPlanet(cfg.base);
this.baseColony = autopilot.getColony(cfg.base, true);
if (this.planet && this.planet.id === this.base.id) this.atBase = true; // are we at our base of operation
};
APS.prototype.setMissionAttributes = function(cfg)
{
// console.log("APS.setMissionAttributes:");
this.primaryFunction = cfg.shipFunction;
if (this.primaryFunction === "hiz" && this.planet && autopilot.hizzzerPlanets.indexOf(this.planet.id) === -1) autopilot.hizzzerPlanets.push(this.planet.id);
this.objectOfInterest = cfg.ooiPriority;
// console.log("...cfg.destination:", cfg.destination);
if (cfg.destination && !this.destination) {
// console.log("...setting destination", cfg.destination);
this.destination = vgap.getPlanet(cfg.destination);
this.destinationColony = autopilot.getColony(cfg.destination, true);
this.setDemand();// console.log("...set demand:", this.demand);
} else if (!cfg.destination) {
// console.log("...setting destination", false);
this.destination = false;
this.destinationColony = false;
this.demand = false;
}
if (this.destination && !this.isValidDestination(this.destination.id)) {
// console.log("...invalidating destination", this.destination.id);
this.destination = false;
this.destinationColony = false;
this.demand = false;
} // e.g. is destination (still) our planet
if (cfg.secondaryDestination) {
this.secondaryDestination = vgap.getPlanet(cfg.secondaryDestination);
this.secondaryDestinationColony = autopilot.getColony(cfg.secondaryDestination, true);
}
if (cfg.secondaryDestination === false || (this.secondaryDestination && !this.isValidDestination(this.secondaryDestination.id))) {
this.secondaryDestination = false;
this.secondaryDestinationColony = false;
} // e.g. is destination (still) our planet
if (this.destination && this.secondaryDestination && this.destination.id === this.secondaryDestination.id) {
this.secondaryDestination = false;
this.secondaryDestinationColony = false;
} // toDo: should not happen, but did happen
if (cfg.lastDestination) this.lastDestination = vgap.getPlanet(cfg.lastDestination);
};
APS.prototype.setFunctionAttributes = function()
{
if (!this.functionModule) this.bootFunctionModule(this.primaryFunction);
this.maxCapacity = this.hull.cargo;
this.curCapacity = this.getCargoCapacity();
this.minCapacity = Math.round(this.functionModule.minimalCargoRatioToGo * this.hull.cargo);
if (this.objectOfInterest === "neu")
{
this.maxCapacity = this.hull.fueltank;
this.curCapacity = this.getFuelCapacity();
this.minCapacity = Math.round(this.functionModule.minimalCargoRatioToGo * this.hull.fueltank);
} else if (this.objectOfInterest === "mcs")
{
this.maxCapacity = 10000;
this.curCapacity = 10000 - this.ship.megacredits;
this.minCapacity = Math.round(this.functionModule.minimalCargoRatioToGo * 10000);
}
};
APS.prototype.setDestination = function(dC) {
if (dC) {
this.destinationColony = dC;
this.destination = dC.planet;
this.setDemand();
} else {
this.destinationColony = false;
this.destination = false;
this.demand = false;
}
};
/*
* SHIP
*/
APS.prototype.isMakingTorpedoes = function()
{
let s = this.ship;
return (s.friendlycode.toUpperCase() === "MKT" && s.megacredits > 0 && s.duranium > 0 && s.tritanium > 0 && s.molybdenum > 0);
};
APS.prototype.getCurCapacity = function(object) {
if (typeof object === "undefined") object = "other";
if (object === "neutronium" || object === "fuel" || object === "neu") return this.getFuelCapacity();
if (object === "megacredits" || object === "cash" || object === "mcs") return (10000-this.ship.megacredits);
return this.getCargoCapacity();
};
APS.prototype.getFuelCapacity = function()
{
return (parseInt(this.hull.fueltank) - parseInt(this.ship.neutronium));
};
APS.prototype.getCargoCapacity = function()
{
let cargoCapacity = this.hull.cargo;
//console.log("cargoCapacity = " + cargoCapacity);
let components = [
this.ship.duranium,
this.ship.tritanium,
this.ship.molybdenum,
this.ship.supplies,
this.ship.ammo, // torpedos or fighters
this.ship.clans
];
components.forEach(function(comp) { cargoCapacity -= parseInt(comp); });
return cargoCapacity;
};
APS.prototype.isAPSbase = function(pid)
{
return (autopilot.apsShips.getBaseIdx().indexOf(pid) > -1);
};
APS.prototype.destinationHasSameAPStype = function(pid, sf, ooi, secondary)
{
if (typeof sf === "undefined") sf = this.primaryFunction;
if (typeof ooi === "undefined") ooi = this.objectOfInterest;
if (typeof secondary === "undefined") secondary = false;
let pool = [];
if (secondary) {
pool = autopilot.apsShips.findBySecondaryDestination(pid);
} else {
pool = autopilot.apsShips.findByDestination(pid);
}
if (pool.length > 0) {
let conflictAPS = [];
let self = this;
pool.forEach(function (aps) {
if (aps.sid !== self.ship.id && aps.shipFunction === sf) {
if (aps.ooiPriority === ooi || aps.shipFunction === "exp") conflictAPS.push(aps);
}
});
if (conflictAPS.length > 0) {
// console.log("APS.destinationHasSameAPStype: %s", pid, conflictAPS);
return conflictAPS;
}
}
return false;
};
APS.prototype.baseHasSameAPStype = function(pid, sf, ooi) {
if (typeof sf === "undefined") sf = this.primaryFunction;
if (typeof ooi === "undefined") ooi = this.objectOfInterest;
let apsByBase = autopilot.apsShips.findByPlanet(pid);
if (apsByBase.length > 0) {
for (let i = 0; i < apsByBase.length; i++) {
if (apsByBase[i].sid === this.ship.id) continue;
if (apsByBase[i].shipFunction === sf && apsByBase[i].ooiPriority === ooi) return true;
}
}
return false;
};
/*
* LOCATION
*/
APS.prototype.objectInRangeOfEnemyShip = function(object)
{
let sAt = vgap.shipsAt(object.x, object.y);
let eAtP = false;
if (sAt.length > 0)
{
sAt.forEach(function (s) {
if (s.ownerid !== vgap.player.id) eAtP = true;
});
}
if (eAtP) return true;
//
let eS = autopilot.getObjectsInRangeOf(autopilot.frnnEnemyShips, this.enemySafetyZone, object);
// avoid planets in close proximity of enemy ships
for (let j = 0; j < eS.length; j++)
{
// only when ship has weapons toDo: or when ship is capable of robbing?
if (autopilot.shipIsArmed(eS[j]))
{
// check if object is farther away from enemy than current location
let objectEnemyDist = Math.ceil(autopilot.getDistance( object, eS[j] ));
let apsEnemyDist = Math.ceil(autopilot.getDistance( this.ship, eS[j] ));
if (objectEnemyDist < apsEnemyDist) return true;
}
}
return false;
};
APS.prototype.objectInRangeOfEnemyPlanet = function (object)
{
let eP = autopilot.getObjectsInRangeOf(autopilot.frnnEnemyPlanets, this.enemySafetyZone, object);
return (eP.length > 0);
};
APS.prototype.objectInRangeOfEnemy = function(object)
{
return (this.objectInRangeOfEnemyPlanet(object) || this.objectInRangeOfEnemyShip(object));
};
APS.prototype.isInWarpWell = function(coords)
{
// console.log("APS.isInWarpWell:");
if (typeof coords === "undefined") coords = { x: this.ship.x, y: this.ship.y };
let planet = vgap.planetAt(coords.x, coords.y);
if (planet) return false; // if we are at planet, we are not in warp well
let cP = autopilot.getClosestPlanet(coords, 1, true);
if (cP)
{
return autopilot.positionIsInWarpWellOfPlanet(cP.planet, coords);
} else {
// console.log("...no closest planet found???");
return false;
}
};
APS.prototype.shipTargetInWarpWell = function()
{
// console.log("APS.shipTargetInWarpWell:");
let s = this.ship;
let planet = vgap.planetAt(s.targetx, s.targety);
if (planet) return false; // target is planet
let cP = autopilot.getClosestPlanet(s, 1, true);
if (cP) {
return autopilot.positionIsInWarpWellOfPlanet(cP.planet, s);
} else {
// console.log("...no closest planet found???");
return false;
}
};
APS.prototype.getPositions4Ships = function(sids)
{
let frnnPositions = [];
for(let i = 0; i < sids.length; i++)
{
let s = vgap.getShip(sids[i]);
if (s) frnnPositions.push( { x: s.x , y: s.y } );
}
return frnnPositions;
};
APS.prototype.getPositions4Planets = function(pids)
{
let frnnPositions = [];
for(let i = 0; i < pids.length; i++)
{
let p = vgap.getPlanet(pids[i]);
frnnPositions.push( { x: p.x , y: p.y } );
}
return frnnPositions;
};
APS.prototype.getDistanceToEnemyPlanet = function()
{
if (this.enemyPlanets)
{
this.enemyPlanets.sort(function (a, b) { return a.distance - b.distance; });
return this.enemyPlanets[0].distance;
} else
{
return false;
}
};
APS.prototype.getCloseEnemyPlanets = function()
{
// only consider planets inside a safety zone (i.e. 162 ly)
let s = this.ship;
let closeEnemyPlanets = autopilot.getTargetsInRange(autopilot.frnnEnemyPlanets, s.x, s.y, 162);
if (closeEnemyPlanets.length > 0)
{
closeEnemyPlanets.forEach(
function (eP, idx) {
closeEnemyPlanets[idx].distance = Math.floor(autopilot.getDistance( s, eP ));
}
);
return closeEnemyPlanets;
} else
{
return false;
}
};
APS.prototype.getDistanceToEnemyShip = function()
{
if (this.enemyShips)
{
this.enemyShips.sort(function (a, b) { return a.distance - b.distance; });
return this.enemyShips[0].distance;
} else
{
return false;
}
};
APS.prototype.getCloseEnemyShips = function()
{
// only consider ships inside a safety zone (i.e. 162 ly)
let s = this.ship;
let closeEnemyShips = autopilot.getTargetsInRange(autopilot.frnnEnemyShips, s.x, s.y, 162);
if (closeEnemyShips.length > 0)
{
closeEnemyShips.forEach(
function (eP, idx) {
closeEnemyShips[idx].distance = Math.floor(autopilot.getDistance( s, eP ));
}
);
return closeEnemyShips;
} else
{
return false;
}
};
/*
* MOVEMENT
*/
APS.prototype.getRandomWarpWellEntryPosition = function ()
{
if (this.planet)
{
// warp well entry from planet
let p = this.planet;
let coords = [
{ x: p.x - 1, y: p.y + 1},
{ x: p.x, y: p.y + 1},
{ x: p.x + 1, y: p.y + 1},
{ x: p.x - 1, y: p.y},
{ x: p.x + 1, y: p.y},
{ x: p.x - 1, y: p.y - 1},
{ x: p.x, y: p.y - 1},
{ x: p.x + 1, y: p.y - 1}
]; // 8 positions (0-7)
let pick = Math.floor(Math.random() * 10);
if (pick > 7) pick = Math.floor(pick / 2);
return coords[pick];
} else
{
// toDo: warp well entry from space
return { x: this.ship.x, y: this.ship.y };
}
};
/*
APS.estimateNextFuelConsumption
from (targetPlanet) -> next Destination
using direct routes:
ship -> (destination) -> new destination
ship -> (secondary destination) -> primary destination
*/
APS.prototype.estimateNextFuelConsumption = function(tP)
{
let nextFuel = false;
let curDistance = Math.ceil(autopilot.getDistance(tP, this.ship));
let thisFuel = autopilot.getOptimalFuelConsumptionEstimate(this.ship.id, [], curDistance); // [] = current cargo
if (this.ship.hullid === 96) thisFuel -= (2 * (curDistance - 1)); // cobol ramscoop
let nextMissionTarget = false;
let nextCargo = [];
if (this.destination.id === tP.id || (this.secondaryDestination && this.secondaryDestination.id === tP.id)) {
nextMissionTarget = this.getNextMissionTarget(tP); // this is either a new secondary or primary destination or the next waypoint
nextCargo = this.estimateMissionCargo(tP, nextMissionTarget);
} else
{
if (this.secondaryDestination)
{
nextMissionTarget = this.secondaryDestination;
} else {
nextMissionTarget = this.destination;
}
}
if (nextMissionTarget)
{
this.setWaypoints(tP, nextMissionTarget); // tP = next ship position
let nWP = this.getNextWaypoint(nextMissionTarget, tP);
// console.log("APS.estimateNextFuelConsumption: next waypoint:", nWP);
if (nWP)
{
let distance = Math.ceil(autopilot.getDistance(tP, nWP));
nextFuel = autopilot.getOptimalFuelConsumptionEstimate(this.ship.id, nextCargo, distance);
if (this.ship.hullid === 96) nextFuel -= (2 * (distance-1)); // cobol ramscoop
}
}
if (!nextFuel) return thisFuel; // as precaution, if no next fuel could be determined, return consumption of prior (this) trip
return nextFuel;
};
APS.prototype.checkFuel = function(cargo) {
// console.log("APS.checkFuel:");
//if (typeof this.planet === "undefined") return true;
if (typeof cargo === "undefined") cargo = [];
this.setWarp(); // set warp factor according to current circumstances
let fuel = Math.ceil(autopilot.getOptimalFuelConsumptionEstimate(this.ship.id, cargo));
// console.log("...need %d fuel for journey!", fuel);
if (!fuel) return false;
// toDo: export to own function or merge with estimateNextFuelConsumption
let tP = vgap.planetAt(this.ship.targetx, this.ship.targety);
if (tP) {
let nextFuel = 0;
if (tP.neutronium > -1) { // ownPlanet
nextFuel = this.estimateNextFuelConsumption(tP);
//console.log("...required fuel at next waypoint: " + nextFuel);
if (nextFuel > tP.neutronium) {
fuel += (nextFuel - tP.neutronium);
// console.log("...need additional %d fuel for journey!", nextFuel - tP.neutronium);
}
} else { // unowned planet (currently this means expander)
fuel += fuel; // provide basic fuel backup for (empty) return trip from unowned planet..
// console.log("...need additional %d fuel for journey (unowned planet)!", fuel);
}
}
//
//
let diff = fuel - this.ship.neutronium;
// console.log("...including onboard fuel, we need %d additional fuel.", diff);
if (diff <= 0) return true; // if there is enough, we don't need to load fuel
// else, try to load
let loadedFuel = 0;
if (this.colony && this.colony.isOwnPlanet) { // only load if we are in orbit around one of our planets
this.loadObject("fuel", this.planet, diff); // loading "FUEL" overwrites balance limitation (in contrast to "neutronium"), returns amount on board after loading
} else if (this.colony && !this.colony.isOwnPlanet) {
if (this.ship.mission !== 10) this.ship.mission = 10; // we set the ship mission to "beam up fuel"
// toDo: towing is not yet part of any APS activity, if this should change,
// toDo: this needs to be thought through: we would need to store the fact, that the ship actually was towing (storage.formerShipMission)
} else {
// we are in space // toDo: can we transfer fuel from another ship?
}
//
// after loading, there is enough! OR if gather neutronium will be enough... OR hull = 14 (Neutronic Fuel Carrier)
// OR target planet has enough...
if (this.ship.neutronium >= fuel ||
(this.planet && this.ship.mission === 10 && this.ship.neutronium + this.planet.neutronium >= fuel) ||
this.ship.hullid === 14) {
return true;
} else {
if (this.colony) this.setWarp(0);
return false;
}
};
APS.prototype.setWarp = function(warp)
{
// console.log("APS.setWarp:");
this.ship.warp = 0;
if (typeof warp === "undefined") {
this.ship.warp = this.ship.engineid;
} else {
this.ship.warp = warp;
}
if (this.targetIsSet()) {
// if target is reachable within one turn set warp to mininum speed required
if (this.ship.warp > 0 && (!this.planet && this.ship.target) || (this.planet && this.ship.target && this.ship.target.id !== this.planet.id)) {
let distance = autopilot.getDistance(this.ship, this.ship.target);
// console.log("...trying to adjust warp speed for distance", distance);
let eta = Math.ceil(autopilot.getDistance(this.ship, this.ship.target) / Math.pow(this.ship.warp, 2));
// console.log("...eta with current warp:", eta, this.ship.warp);
if (eta === 1 && this.ship.warp > 1) {
while (eta === 1 && this.ship.warp > 1) {
this.ship.warp -= 1;
eta = Math.ceil(autopilot.getDistance(this.ship, this.ship.target) / Math.pow(this.ship.warp, 2));
// console.log("...eta with adjusted warp:", eta, this.ship.warp);
}
if (eta > 1) {
this.ship.warp += 1;
}
}
} else {
// console.log("...ship.target:", this.ship.target);
}
// reduce speed to warp 4, if we are currently inside a minefield
if (autopilot.objectInsideEnemyMineField( {x: this.ship.x, y: this.ship.y} ).length > 0 && this.ship.engineid > 4) this.ship.warp = 4;
// reduce speed to warp 3, if we are currently inside a web minefield
if (autopilot.objectInsideEnemyWebMineField( {x: this.ship.x, y: this.ship.y} ).length > 0 && this.ship.engineid > 3) this.ship.warp = 3;
// set warp 1 if we are moving into or inside warp well
if (this.shipTargetInWarpWell()) this.ship.warp = 1;
}
// update fuelFactor
this.curFuelFactor = this.fuelFactor["t" + this.ship.engineid][this.ship.warp];
};
APS.prototype.targetIsSet = function()
{
return autopilot.shipTargetIsSet(this.ship);
};
APS.prototype.escapeToWarpWell = function()
{
if (this.inWarpWell)
{
// console.log("APS.escapeToWarpWell: We are in warp well...");
this.isIdle = true;
// toDo: do we have to move? are there enemy ships close by?
} else {
// console.log("APS.escapeToWarpWell: Moving into warp well...");
this.isIdle = false;
let coords = this.getRandomWarpWellEntryPosition();
this.ship.targetx = coords.x;
this.ship.targety = coords.y;
this.setWarp(1);
}
};
APS.prototype.shipPathIsSave = function(tP, oP)
{
return true;
/*
// toDo: get minefields centered within a range of the current position; range = distance to travel???
//console.log("::>shipPathIsSave");
if (typeof oP === "undefined" || oP === null) oP = this.ship;
//console.log("..." + oP.id + " -> " + tP.id);
let sx1 = oP.x;
let sy1 = oP.y;
let sx2 = tP.x;
let sy2 = tP.y;
for (let i = 0; i < autopilot.frnnEnemyMinefields.length; i++)
{
let mF = autopilot.frnnEnemyMinefields[i];
if (this.shipPathIntersectsObject(sx1, sy1, sx2, sy2, mF.x, mF.y, mF.radius))
{
//console.log("...path intersects with enemy minefield " + mF.id);
//return false; // deactivated 22.03.17: does not work as expected!
}
}
return true;
*/
};
APS.prototype.shipPathIntersectsObject = function(sx1, sy1, sx2, sy2, ox, oy, or)
{
let dx = sx2 - sx1;
let dy = sy2 - sy1;
let dr = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
//console.log([sx1, sy1, sx2, sy2, ox, oy, or]);
//console.log(Math.abs((sx2 - sx1) * ox + oy * (sy1 - sy2) + (sx1 - sx2) * sy1 + (sy1 - sy2) * ox) / Math.sqrt(Math.pow((sx2 - sx1),2) + Math.pow((sy2 - sy1),2)));
//console.log(Math.abs((sx2 - sx1) * ox + oy * (sy1 - sy2) + (sx1 - sx2) * sy1 + (sy1 - sy2) * ox) / Math.sqrt(Math.pow((sx2 - sx1),2) + Math.pow((sy2 - sy1),2)) <= or);
return (Math.abs((sx2 - sx1) * ox + oy * (sy1 - sy2) + (sx1 - sx2) * sy1 + (sy1 - sy2) * ox) / Math.sqrt(Math.pow((sx2 - sx1),2) + Math.pow((sy2 - sy1),2)) <= or);
};
/*
* setShipTarget
* determines next waypoint and sets waypoint as ship target
*
* called in setMissionDestination (phase 2)
* and initializeBoardComputer (setup APS, update configuration, setShipTarget OR set flag to determine potential destination first)
*/
APS.prototype.setShipTarget = function() {
// console.log("APS.setShipTarget:");
let dP = this.destination;
if (this.secondaryDestination) dP = this.secondaryDestination;
if (this.planet && dP.id === this.planet.id) {
if (this.secondaryDestination) {
this.secondaryDestination = false;
this.secondaryDestinationColony = false;
dP = this.destination;
} else {
return true;
}
} // toDo: What to do?
// console.log("...searching waypoints to " + dP.name + " (" + dP.id + ").");
this.setWaypoints(this.ship, dP);
let potWpIds = this.potentialWaypoints.map(function (pWp) {
return pWp.id;
});
// console.log("...potWpIds:", potWpIds, this.ship.target);
if (this.ship.target && potWpIds.indexOf(this.ship.target.id) > -1) return true; // is target is already set and a potential Waypoint, do not set another
let target = this.getNextWaypoint(dP);
if (target) {
// console.log("...fly to " + target.id);
this.ship.targetx = target.x;
this.ship.targety = target.y;
let wpP = vgap.planetAt(this.ship.targetx, this.ship.targety);
if (wpP) this.waypoint = wpP;
return true;
} else {
return false;
}
};
/*
* WAYPOINTS
*/
APS.prototype.setWaypoints = function(ship, dP)
{
// console.log("APS.setWaypoints:");
// toDo: warpwell minimum distance used, how to implement heading consideration (warpwell max dist = 3)
this.functionModule.setPotentialWaypoints(this); // set the initial pool of potential waypoints specific for the current function (e.g. frnnOwnPlanets)
let ship2dest = this.getDistance(dP, false);
let waypoints = autopilot.getTargetsInRange(this.potentialWaypoints, dP.x, dP.y, ship2dest); // targets within a range of destination->current position
let wpPlanets = waypoints.map(function (p) {
return vgap.getPlanet(p.id);
});
wpPlanets.push(dP); // including destination planet
let safeWaypoints = wpPlanets.filter(function (p) {
let c = autopilot.getColony(p.id);
return c.determineSafety();
});
// console.log("...safe waypoints:", safeWaypoints);
let eta2dest = Math.ceil(ship2dest / Math.pow(this.ship.engineid, 2));
let fWPs = [];
let self = this;
safeWaypoints.forEach(function (p, idx) {
let dist2Planet = self.getDistance(p, false); // aps-planet
let eta2Planet = Math.ceil(dist2Planet / Math.pow(self.ship.engineid, 2));
if (eta2Planet === 1 || eta2Planet <= eta2dest) { // skip waypoints that are significantly further away
let pW2dPDist = autopilot.getDistance( p, dP, false );
safeWaypoints[idx].ship2wPDist = dist2Planet;
safeWaypoints[idx].wayp2dPDist = pW2dPDist;
safeWaypoints[idx].ship2dPDist = ship2dest;
safeWaypoints[idx].ship2wP2dPDist = dist2Planet + pW2dPDist;
safeWaypoints[idx].wpETA = Math.ceil(dist2Planet / Math.pow(self.ship.engineid, 2)) + Math.ceil(pW2dPDist / Math.pow(self.ship.engineid, 2)); // ETA if using pW as next stop
fWPs.push(p);
}
});
this.potentialWaypoints = fWPs;
// console.log("...this.potentialWaypoints:", this.potentialWaypoints);
};
APS.prototype.getNextWaypoint = function(dP, cP, notDP)
{
// console.log("APS.getNextWaypoint:");
if (typeof notDP === "undefined") notDP = false;
if ((typeof cP === "undefined" || cP === null) && this.planet) cP = this.planet;
if ((typeof cP === "undefined" || cP === null) && !this.planet) cP = this.ship;
let target = false;
let closeToEnemy = (this.enemyShips || this.enemyPlanets); // use "safe" planet hopping if we are close to enemy territory
let relativelySafe = false;
let urgendWaypoint = this.getUrgentWaypoint(dP, cP);
// console.log("...urgendWaypoint:", urgendWaypoint);
let pathWithinOwnMinefield = false;
let pathWithinEnemyMinefield = false;
let pathCloseToEnemy = false;
if (urgendWaypoint) {
// check if next turn position is covered by a friendly minefield
let originalX = this.ship.targetx;
let originalY = this.ship.targety;
this.ship.targetx = urgendWaypoint.x;
this.ship.targety = urgendWaypoint.y;
let path = vgap.getPath(this.ship);
let wps = Math.floor(Object.keys(path).length / 2);
for (let i = 1; i < wps; i++) {
let obj = { x: path["x" + i], y: path["y" + i] };
if (!autopilot.objectInside(obj, autopilot.frnnFriendlyMinefields)) pathWithinOwnMinefield = false;
if (autopilot.objectInside(obj, autopilot.frnnEnemyMinefields)) pathWithinEnemyMinefield = true;
if (autopilot.objectCloseTo(obj, [].concat(autopilot.frnnEnemyPlanets, autopilot.frnnEnemyShips), 82)) pathCloseToEnemy = true;
}
this.ship.targetx = originalX;
this.ship.targety = originalY;
}
if (urgendWaypoint && !pathWithinEnemyMinefield && (!pathCloseToEnemy || (pathCloseToEnemy && pathWithinOwnMinefield)) && !notDP) {
target = urgendWaypoint;
} else {
target = this.getEtaWaypoint(dP, cP, notDP);
}
return target;
};
APS.prototype.destinationAmongWaypoints = function(dP, pW)
{
let destination = dP;
if (this.secondaryDestination)
{
destination = this.secondaryDestination;
}
for (let i = 0; i < pW.length; i++)
{
if (pW[i].pid === destination.id) return true;