Repository navigation
Expand file tree
/
Copy pathai_runner.js
More file actions
2890 lines (2747 loc) · 117 KB
/
Copy pathai_runner.js
File metadata and controls
2890 lines (2747 loc) · 117 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
//AI decisionmaking
//utilities (can be used without AI)
//Helper functions for saving and restoring state for AI calculation
function AIIceEncounterSaveState() {
var stored = {};
stored.encountering = encountering;
stored.attackedServer = attackedServer;
stored.approachIce = approachIce;
return stored;
}
//returns true if state was modified
function AIIceEncounterModifyState(iceCard) {
var ics = GetServer(iceCard);
if (!ics) return false;
encountering = true;
attackedServer = ics;
approachIce = ics.ice.indexOf(iceCard);
return true;
}
function AIIceEncounterRestoreState(stored) {
encountering = stored.encountering;
attackedServer = stored.attackedServer;
approachIce = stored.approachIce;
}
//actual class
class RunnerAI {
_log(message) {
//just comment this line to suppress AI log
console.log("AI: " + message);
}
_cardsOkToTrashOnInstall(installedRunnerCards) {
var okToTrash = [];
for (var i = 0; i < installedRunnerCards.length; i++) {
if (typeof installedRunnerCards[i].AIOkToTrash == "function") {
if (installedRunnerCards[i].AIOkToTrash.call(installedRunnerCards[i])) okToTrash.push(installedRunnerCards[i]);
}
}
return okToTrash;
}
//okToTrash is a list of cards to ignore the memory usage of
_spareMemoryUnits(installedRunnerCards,destination=null) {
var okToTrash = this._cardsOkToTrashOnInstall(installedRunnerCards);
return MemoryUnits(destination) - InstalledMemoryCost(destination,okToTrash);
}
_installWouldExceedMU(card) {
if (typeof card.memoryCost === "undefined") return false;
//predetermine installed runner cards for efficiency
var installedRunnerCards = InstalledCards(runner);
//loop through install options. return false as soon as an option is found that doesn't exceed mu budget
var choices = ChoicesCardInstall(card, true); //true ignores credit cost);
for (var i = 0; i < choices.length; i++) {
var destination = null;
if (typeof choices[i].host !== "undefined") destination = choices[i].host;
if (card.memoryCost <= this._spareMemoryUnits(installedRunnerCards,destination)) return false;
}
return true;
}
_copyOfCardExistsIn(title, cards, exclude = []) {
for (var i = 0; i < cards.length; i++) {
if (GetTitle(cards[i]) == title && !exclude.includes(cards[i]))
return cards[i];
}
return null;
}
_rootKnownToContainCopyOfCard(server, title) {
if (!server) return false;
for (var j = 0; j < server.root.length; j++) {
if (PlayerCanLook(runner, server.root[j])) {
if (server.root[j].title == title) return true;
}
}
return false;
}
_uniqueCopyAlreadyInstalled(
card //returns true if is unique and a copy already installed
) {
if (!card.unique) return false; //i.e. .unique == false or undefined
var installedCards = InstalledCards(card.player);
for (var i = 0; i < installedCards.length; i++) {
if (
installedCards[i] !== card &&
GetTitle(installedCards[i]) == GetTitle(card)
)
return true;
}
return false;
}
_installedCardExistsWithSubType(subtype) {
var installedRunnerCards = InstalledCards(runner);
for (var i = 0; i < installedRunnerCards.length; i++) {
if (CheckSubType(installedRunnerCards[i], subtype)) return true;
}
return false;
}
_wastefulToInstall(card) {
if (!this._passBasicWastefulInstallCheck(card)) return true;
if (this._installWouldExceedMU(card)) return true;
if (
CheckSubType(card, "Fracter") &&
this._installedCardExistsWithSubType("Fracter")
)
return true;
if (
CheckSubType(card, "Decoder") &&
this._installedCardExistsWithSubType("Decoder")
)
return true;
if (
CheckSubType(card, "Killer") &&
this._installedCardExistsWithSubType("Killer")
)
return true;
if (
CheckSubType(card, "AI") &&
this._essentialBreakerTypesNotInHandOrArray(InstalledCards(runner)).length == 0
//this used to check if there was already an AI but there are various AIs e.g. Atman
//so put specific wasteful code on the card itself
/*
(this._essentialBreakerTypesNotInHandOrArray(InstalledCards(runner))
.length == 0) ||
this._installedCardExistsWithSubType("AI"))
*/
)
return true;
if (typeof card.AIWastefulToInstall == 'function') {
if (card.AIWastefulToInstall.call(card)) return true;
}
return false;
}
//accepts choices, if you want to check AIPreferredPlayChoice as well
_wastefulToPlay(card,choices) {
if (typeof card.AIWastefulToPlay == 'function') {
if (card.AIWastefulToPlay.call(card)) return true;
}
if (choices) {
if (typeof card.AIPreferredPlayChoice == 'function') {
//AIPreferredPlayChoice returns -1 if preference is to not play it
if (card.AIPreferredPlayChoice.call(card, choices) < 0) return true;
}
}
return false;
}
//check if a breaker matches ice, including strength check for fixed-strength breakers
_breakerMatchesIce(breakerCard, iceCard) {
if (breakerCard.AIFixedStrength) {
var strToCompare = 3; //common strength
if (PlayerCanLook(runner,iceCard)) strToCompare = Strength(iceCard);
if (Strength(breakerCard) < strToCompare) return false;
}
var ret = BreakerMatchesIce(breakerCard, iceCard);
return ret;
}
//check if a matching type breaker is installed (or AI)
//returns the matching breaker or null if none found
_matchingBreakerInstalled(iceCard,excludeIcebreakers=[]) {
var possibleBreakers = ActiveCards(runner);
for (var i = 0; i < possibleBreakers.length; i++) {
var breakerCard = possibleBreakers[i];
if (!excludeIcebreakers.includes(breakerCard)) {
//some cards can act like a matching breaker is installed
if (typeof breakerCard.AIMatchingBreakerInstalled == 'function') {
var aiMatchingBreaker = breakerCard.AIMatchingBreakerInstalled.call(breakerCard, iceCard);
if (aiMatchingBreaker) return aiMatchingBreaker;
}
//the on-card AIMatchingBreakerInstalled function takes precedence over the basic subtype check
else if (CheckSubType(breakerCard, "Icebreaker")) {
if (this._breakerMatchesIce(breakerCard, iceCard)) return breakerCard;
}
}
}
return null;
}
//creates three groupings: ice, asset/agenda/upgrade, and operation
_combinedCardType(str) {
if (str == "agenda") return "asset";
if (str == "upgrade") return "asset";
return str;
}
//get cached potential or zero
_getCachedPotential(server) {
var result = 0;
for (var i = 0; i < this.cachedPotentials.length; i++) {
if (this.cachedPotentials[i].server == server)
return this.cachedPotentials[i].potential;
}
return result;
}
//get cached complete run cost or Infinity
_getCachedCost(server) {
if (!this.runsEverCalculated.includes(server))
this._calculateBestCompleteRun(server, 0, 0, 0, 0);
var result = Infinity;
for (var i = 0; i < this.cachedCosts.length; i++) {
if (this.cachedCosts[i].server == server) return this.cachedCosts[i].cost;
}
return result;
}
//this function also includes known agendas that would be accessed
//ignoreCards is an array to not include in count
_countNewCardsThatWouldBeAccessedInRnD(depth,ignoreCards=[]) {
var ret = 0;
for (var i = corp.RnD.cards.length - 1; i > -1; i--) {
if (!ignoreCards.includes(corp.RnD.cards[i])) {
if (
!corp.RnD.cards[i].knownToRunner ||
corp.RnD.cards[i].cardType == "agenda"
)
ret += 1;
}
depth--;
if (depth == 0) return ret; //no more cards to access
}
return ret; //reached bottom of R&D
}
//hypothesise extra HQ accesses that are worthwhile
_additionalHQAccessValue(usingCard=null) {
var totalAccesses=1;
//passive effects:
var activeCards = ActiveCards(runner);
for (var i = 0; i < activeCards.length; i++) {
if (typeof activeCards[i].AIAdditionalAccess == 'function') {
totalAccesses += activeCards[i].AIAdditionalAccess.call(activeCards[i],corp.HQ);
}
}
//using card
if (usingCard) {
if (typeof usingCard.AIAdditionalAccess == 'function') {
totalAccesses += usingCard.AIAdditionalAccess.call(usingCard,corp.HQ);
}
}
//take into account size
if (totalAccesses > corp.HQ.cards.length) {
totalAccesses = corp.HQ.cards.length;
}
var ret = totalAccesses - 1;
if (ret < 0) ret = 0;
return ret;
}
//get an array of ice which have special breakers hosted
_iceHostingSpecialBreakers() {
var ret = [];
var installedCards = InstalledCards(corp);
for (var i = 0; i < installedCards.length; i++) {
if (installedCards[i].cardType == "ice") {
if (typeof installedCards[i].hostedCards !== "undefined") {
for (var j=0; j<installedCards[i].hostedCards.length; j++) {
if (installedCards[i].hostedCards[j].AISpecialBreaker) {
ret.push(installedCards[i]);
break;
}
}
}
}
}
return ret;
}
//get an approximate measure of ice threat
_iceThreatScore(iceCard,excludeIcebreakers=[],infiniteCorpCredits=false) {
var ret = 3; //most common ice printed rez cost
if (PlayerCanLook(runner,iceCard)) {
ret=iceCard.rezCost;
//no threat if cannot be rezzed
if (!infiniteCorpCredits) {
if (!iceCard.rezzed && !CheckCredits(corp, RezCost(iceCard), "rezzing", iceCard)) ret = 0;
}
//reduce threat if a matching breaker is installed
if (this._matchingBreakerInstalled(iceCard,excludeIcebreakers)) ret *= 0.2; //the 0.2 is arbitrary
} else {
//reduce threat if corp is poor and ice is unrezzed
if (!infiniteCorpCredits) {
if (!iceCard.rezzed && ret > corp.creditPool) ret=corp.creditPool;
}
}
return ret;
}
//get highest threat score ice, preferably excluding ice from excludeCards but permitting if no other option
_highestThreatScoreIcePermitExcludedIce(excludeCards=[],minimumRezCost=-1) {
var htsi = this._highestThreatScoreIce(excludeCards);
//if no target found, try without that exclusion
if (!htsi) {
htsi = this._highestThreatScoreIce();
}
return htsi;
}
//get highest-potential server
_highestPotentialServer() {
var hps = null;
var hpp = 0;
for (var i = 0; i < this.cachedPotentials.length; i++) {
if (this.cachedPotentials[i].potential > hpp) {
hpp = this.cachedPotentials[i].potential;
hps = this.cachedPotentials[i].server;
}
}
return hps;
}
//get highest threat ice (e.g. for target)
//exclusion list will exclude both ice and icebreakers
_highestThreatScoreIce(excludeCards=[],minimumRezCost=-1) {
//get highest potential server
var hps = this._highestPotentialServer();
//start with list of all PlayerCanLook(runner,iceCard)
var pcli = [];
if (hps) {
//in highest-potential server
for (var i=0; i<hps.ice.length; i++) {
if (PlayerCanLook(runner,hps.ice[i])) pcli.push(hps.ice[i]);
}
} else {
//or all servers, if no server has highest potential
for (var i=0; i<corp.HQ.ice.length; i++) {
if (PlayerCanLook(runner,corp.HQ.ice[i])) pcli.push(corp.HQ.ice[i]);
}
for (var i=0; i<corp.RnD.ice.length; i++) {
if (PlayerCanLook(runner,corp.RnD.ice[i])) pcli.push(corp.RnD.ice[i]);
}
for (var i=0; i<corp.archives.ice.length; i++) {
if (PlayerCanLook(runner,corp.archives.ice[i])) pcli.push(corp.archives.ice[i]);
}
for (var j=0; j<corp.remoteServers.length; j++) {
for (var i=0; i<corp.remoteServers[j].ice.length; i++) {
if (PlayerCanLook(runner,corp.remoteServers[j].ice[i])) pcli.push(corp.remoteServers[j].ice[i]);
}
}
}
//get highest this._iceThreatScore(iceCard) of that list
var hts = 0;
var htsi = null;
var htsis = 0;
for (var i=0; i<pcli.length; i++) {
if (!excludeCards.includes(pcli[i])) {
var thists = this._iceThreatScore(pcli[i],excludeCards);
//the 1 min here is arbitrary but basically don't waste on ice that isn't much threat
//break ties with strength
if ( thists > 1 && (thists > hts || Strength(pcli[i]) > htsis) && RezCost(pcli[i]) >= minimumRezCost ) {
hts = thists;
htsi = pcli[i];
htsis = Strength(htsi);
}
}
}
return htsi;
}
//get a rough score for ice comparison (taking into account server potential)
_iceComparisonScore(iceCard) {
var ret = 0;
//the true here means don't diminish ice strength if corp can't afford it
ret = this._getCachedPotential(GetServer(iceCard)) * this._iceThreatScore(iceCard,[],true);
return ret;
}
_serverIsProtected(server) {
if (server.ice.length == 0) {
if (server.root.length == 0) {
return false;
}
//check for obvious defensives
for (var i=0; i<server.root.length; i++) {
if (PlayerCanLook(runner,server.root[i])) {
if (typeof server.root[i].AIDefensiveValue == 'function') return true;
}
}
return false;
}
return true;
}
//list of unprotected servers (not comprehensive check, just no ice and no obvious defensives)
_unprotectedServers() {
var ret = [];
if (!this._serverIsProtected(corp.archives)) ret.push(corp.archives);
if (!this._serverIsProtected(corp.RnD)) ret.push(corp.RnD);
if (!this._serverIsProtected(corp.HQ)) ret.push(corp.HQ);
for (var i=0; i<corp.remoteServers.length; i++) {
if (!this._serverIsProtected(corp.remoteServers[i])) ret.push(corp.remoteServers[i]);
}
return ret;
}
constructor() {
this.preferred = null;
this.cardsWorthKeeping = [];
this.runsEverCalculated = []; //used to check whether calculation is needed to return cachedCost
this.cachedCosts = []; //for all servers, updated each time a *complete* run is calculated
this.cachedPotentials = []; //for all servers, calculated each time "run" action is available
this.cachedBestPath = null; //just for the most recently calculated server
this.cachedComplete = false; //indicates whether or not cachedBestPath represents a complete or incomplete path
this.cachedPathServer = null; //to remember which server cachedBestPath applies to
this.rc = new RunCalculator();
this.serverList = [];
this.suspectedHQCards = []; //each is a { title, cardType, copies, uncertainty } object
//teach the AI about cards (in order of priority, best first or better order of play)
this.economyPlay = ["Sure Gamble", "Creative Commission", "Wildcat Strike"]; //cards which can be played to gain credits
//cards which can be installed to increase maximum hand size
this.maxHandIncreasers = ["T400 Memory Diamond"];
this._temporaryValueModifications = []; //set during choice-making to consider hypotheticals (normal conditions restored after choosing)
}
//functions to use/gain/lose info about cards in HQ
_storedInfoAboutHQCards(
title //returns index in this.suspectedHQCards (or -1)
) {
for (var i = 0; i < this.suspectedHQCards.length; i++) {
if (this.suspectedHQCards[i].title == title) return i;
}
return -1;
}
_infoHQScore() { //a vague heuristic used to determine how well HQ is known (roughly equivalent to a count of known cards in HQ)
var ret = 0;
for (var i = 0; i < this.suspectedHQCards.length; i++) {
ret +=
this.suspectedHQCards[i].copies *
(1.0 - this.suspectedHQCards[i].uncertainty);
}
//debug log
var debugoutput = "Suspected HQ: ";
for (var i = 0; i < this.suspectedHQCards.length; i++) {
debugoutput +=
"[" +
this.suspectedHQCards[i].copies +
" " +
this.suspectedHQCards[i].title +
", " +
(1.0 - this.suspectedHQCards[i].uncertainty).toFixed(1) +
" certainty]";
}
debugoutput += " (info HQ score: " + ret.toFixed(1) + ")";
this._log(debugoutput);
return ret;
}
GainInfoAboutHQCard(
card //called when a known card is moved into HQ
) {
var indexOfEntry = this._storedInfoAboutHQCards(card.title);
if (indexOfEntry < 0)
this.suspectedHQCards.push({
title: card.title,
cardType: card.cardType,
copies: 1,
uncertainty: 0,
});
else {
this.suspectedHQCards[indexOfEntry].copies++;
this.suspectedHQCards[indexOfEntry].uncertainty *= 0.5; //average between certain and whatever the other cards are (this is fairly arbitrary)
}
}
GainInfoAboutHQCards(
cards //called with the access list when access list is created
) {
if (corp.HQ.cards.length < 1) return; //this shouldn't happen but it's here to avoid divide by zero
//uncertainty depends on cards being seen vs cards in HQ and is between 0 (certain) and 1 (impossible)
var uncertainty =
(corp.HQ.cards.length - cards.length) / corp.HQ.cards.length;
if (cards.length == corp.HQ.cards.length) this.suspectedHQCards = []; //simplest case is if all cards are viewed at once
//count the number of each title in the input
var counts = {};
for (var i = 0; i < cards.length; i++) {
if (counts[cards[i].title]) counts[cards[i].title]++;
else counts[cards[i].title] = 1;
}
//whenever the count exceeds the number known, update the entry
//if that card title hasn't been seen yet, add the entry
for (var i = 0; i < cards.length; i++) {
var indexOfEntry = this._storedInfoAboutHQCards(cards[i].title);
if (indexOfEntry < 0)
this.suspectedHQCards.push({
title: cards[i].title,
cardType: cards[i].cardType,
copies: counts[cards[i].title],
uncertainty: 0,
});
//the card is definitely there, we're looking at it
else {
//multi-access may create a confident count
if (
counts[cards[i].title] > this.suspectedHQCards[indexOfEntry].copies
) {
this.suspectedHQCards[indexOfEntry].copies = counts[cards[i].title];
if (uncertainty < this.suspectedHQCards[indexOfEntry].uncertainty)
this.suspectedHQCards[indexOfEntry].uncertainty = uncertainty; //may become more certain, based on this fresh information
}
//otherwise maybe there are more copies
else {
//calculate the chances of there being the another copy (basically just the fraction of unknown hand over total hand size)
var chances =
(corp.HQ.cards.length - this._infoHQScore()) / corp.HQ.cards.length;
var u_added = 1.0 - chances;
var u_original = this.suspectedHQCards[indexOfEntry].uncertainty;
var c_original = this.suspectedHQCards[indexOfEntry].copies;
//update uncertainty to take into account both old uncertainty and the chances there actually is another of the same
this.suspectedHQCards[indexOfEntry].uncertainty =
(u_original * c_original + u_added) / (1.0 + c_original);
this.suspectedHQCards[indexOfEntry].copies++;
}
}
}
}
LoseInfoAboutHQCards(
card,
cardType = "" //note: just one card at a time
) //called when a card is rezzed in Rez(), played in Play(), stolen/scored in Steal()/Score(), trashed from HQ in Trash(), or installed (null input) in Install()
//if cardType is 'ice' for null card, ice cards will gain uncertainty and non-ice will lose uncertainty (and vice-versa for 'non-ice')
{
//this approach is far from perfect (e.g. if knowledge is reset and then an already installed card is stolen, it could remove critical knowledge) but this may still be sufficient
if (corp.HQ.cards.length == 0) {
//since the card triggers fire after the move is made, if HQ has become empty we can clear the knowledge stack
this.suspectedHQCards = [];
} else if (card) {
//known cards will reduce number known (remove entry if zero) but will not change certainty
var indexOfEntry = this._storedInfoAboutHQCards(card.title);
if (indexOfEntry > -1) {
this.suspectedHQCards[indexOfEntry].copies -= 1;
if (this.suspectedHQCards[indexOfEntry].copies <= 0)
this.suspectedHQCards.splice(indexOfEntry, 1);
}
} //null cards will increase uncertainty of relevant knowns but will not change specific counts
else {
//this could be improved e.g. by calculating total suspected amount of cards of that type in HQ
for (var i = 0; i < this.suspectedHQCards.length; i++) {
var typeMatches = true; //by default, become more uncertain
//we exempt operations from this rule because we assume installing (hence knowing the type)
if (
cardType !== "" &&
this._combinedCardType(this.suspectedHQCards[i].cardType) !==
this._combinedCardType(cardType)
)
typeMatches = false;
if (typeMatches) {
if (this.suspectedHQCards[i].uncertainty == 0)
this.suspectedHQCards[i].uncertainty =
1.0 / (1.0 + corp.HQ.cards.length);
else
this.suspectedHQCards[i].uncertainty *=
1.0 - 1.0 / (1.0 + corp.HQ.cards.length);
}
}
}
}
//not currently being used, but not deleted because might need it later
_phaseCallback(optionList, choiceType) {
//console.log(currentPhase.identifier);
}
//sets this.preferred to prefs and returns indexOf cmd in optionList
//don't forget to return the result!
_returnPreference(optionList, cmd, prefs) {
prefs.command = cmd;
this.preferred = prefs;
if (optionList.indexOf(cmd) > -1) return optionList.indexOf(cmd);
else if (optionList.indexOf("n") > -1) return optionList.indexOf("n"); //cmd might be coming up next phase
LogError(
'returnPreference failed to find "' +
cmd +
'" in this optionList with these prefs:'
);
console.log(optionList);
console.log(prefs);
return 0; //arbitrary
}
//meta-wrappers for run calculator (all return the best path or null if no path found)
//for efficiency, use cached path unless none is available
_cachedOrBestRun(server, startIceIdx) {
if (!this.cachedBestPath || this.cachedPathServer !== server) { //need to recalculate
//ideally complete runs
this._calculateBestCompleteRun(server, 0, 0, 0, 0, null, startIceIdx); //0 means no credit/click/damage offset, null means no bonus breaker
//but if not, use an exit strategy (incomplete run)
if (!this.cachedBestPath) {
this._calculateBestExitStrategy(server, 0, 0, 0, 0, null, startIceIdx); //0 means no credit/click/damage offset, null means no bonus breaker
}
} else {
//remove ice before this one
for (var i=this.cachedBestPath.length-1; i>-1; i--) {
if (this.cachedBestPath[i].iceIdx > startIceIdx) this.cachedBestPath.splice(i,1);
}
}
return this.cachedBestPath;
}
async _calculateBestCompleteRunAsync(
server,
poolCreditOffset,
otherCreditOffset,
clickOffset,
damageOffset,
bonusBreaker,
startIceIdx,
) {
return await this._calculateRunPathAsync(
server,
poolCreditOffset,
otherCreditOffset,
clickOffset,
damageOffset,
false,
bonusBreaker,
startIceIdx,
); //false means don't include incomplete runs
}
_calculateBestCompleteRun(
server,
poolCreditOffset,
otherCreditOffset,
clickOffset,
damageOffset,
bonusBreaker,
startIceIdx,
) {
return this._calculateRunPath(
server,
poolCreditOffset,
otherCreditOffset,
clickOffset,
damageOffset,
false,
bonusBreaker,
startIceIdx,
); //false means don't include incomplete runs
}
_calculateBestExitStrategy(
server,
poolCreditOffset,
otherCreditOffset,
clickOffset,
damageOffset,
bonusBreaker,
startIceIdx,
) {
return this._calculateRunPath(
server,
poolCreditOffset,
otherCreditOffset,
clickOffset,
damageOffset,
true,
bonusBreaker,
startIceIdx,
); //true means include incomplete runs
}
//***_calculateRunPath has two version (Async and normal i.e. synchronous). These are the two pieces shared (begin, end).
//Begin returns data, End returns this.cachedBestPath
_calculateRunPathPieceBegin(data) {
//console.error("crp "+ServerName(data.server)+(data.incomplete?" incomplete":" complete"));
data.clicks = runner.clickTracker + data.clickOffset;
data.poolCredits = runner.creditPool + data.poolCreditOffset; //just credit pool
data.otherCredits = AvailableCredits(runner) - runner.creditPool + data.otherCreditOffset; //sources other than credit pool
data.damageLimit = runner.grip.length + data.damageOffset; //(this gets updated during the run calculation if data.clicks is used up)
//this works because potentials are calculated before costs in (optionList.includes("run")). Note the false here prevents an infinite loop
if (this._getCachedPotential(data.server) < 2.0)
data.damageLimit -= this.cardsWorthKeeping.length; //the 2.0 is arbitrary but basically don't risk stuff for lowish potential
if (data.damageLimit < 0) data.damageLimit = 0;
data.tagLimit =
Math.min(data.clicks, Math.floor(data.poolCredits * 0.5)) - runner.tags; //allow 1 tag for each click+2[c] remaining (pool only atm) but less if tagged (this gets updated during the run calculation)
if (data.tagLimit < 0) data.tagLimit = 0;
return data;
}
_calculateRunPathPieceEnd(data) {
this.cachedBestPath = null; //by default assume no paths were found
this.cachedComplete = !data.incomplete;
this.cachedPathServer = data.server;
if (!this.runsEverCalculated.includes(data.server))
this.runsEverCalculated.push(data.server);
//update/store cached cost
var bestpath = [];
if (data.paths.length > 0) {
bestpath = data.paths[data.paths.length - 1];
this.cachedBestPath = bestpath;
}
var bestcost = Infinity;
if (bestpath.length > 0) {
if (typeof bestpath[bestpath.length - 1].cost !== "undefined")
bestcost = bestpath[bestpath.length - 1].cost;
else bestcost = this.rc.PathCost(bestpath);
}
var alreadyCached = false; //or consider maybe only updating cached cost for complete runs?
for (var i = 0; i < this.cachedCosts.length; i++) {
if (this.cachedCosts[i].server == data.server) {
this.cachedCosts[i].cost = bestcost;
alreadyCached = true;
}
}
if (!alreadyCached)
this.cachedCosts.push({ server: data.server, cost: bestcost });
return this.cachedBestPath;
}
async _calculateRunPathAsync(
server,
poolCreditOffset,
otherCreditOffset,
clickOffset,
damageOffset,
incomplete,
bonusBreaker,
startIceIdx,
) {
//use shared begin code
var data = this._calculateRunPathPieceBegin({server:server, poolCreditOffset:poolCreditOffset, otherCreditOffset:otherCreditOffset, clickOffset:clickOffset, damageOffset:damageOffset, incomplete:incomplete,bonusBreaker:bonusBreaker, startIceIdx:startIceIdx});
//compute paths
data.paths = await this.rc.CalculateAsync(
data.server,
data.clicks,
data.poolCredits,
data.otherCredits,
data.damageLimit,
data.tagLimit,
data.incomplete,
data.bonusBreaker,
data.startIceIdx,
);
//use shared end code
return this._calculateRunPathPieceEnd(data);
}
//wrapper for run calculator (returns null if no path found)
_calculateRunPath(
server,
poolCreditOffset,
otherCreditOffset,
clickOffset,
damageOffset,
incomplete,
bonusBreaker,
startIceIdx,
) {
//use shared begin code
var data = this._calculateRunPathPieceBegin({server:server, poolCreditOffset:poolCreditOffset, otherCreditOffset:otherCreditOffset, clickOffset:clickOffset, damageOffset:damageOffset, incomplete:incomplete,bonusBreaker:bonusBreaker, startIceIdx:startIceIdx});
//compute paths
data.paths = this.rc.Calculate(
data.server,
data.clicks,
data.poolCredits,
data.otherCredits,
data.damageLimit,
data.tagLimit,
data.incomplete,
data.bonusBreaker,
data.startIceIdx,
);
//use shared end code
return this._calculateRunPathPieceEnd(data)
}
//returns something between [] and ["Fracter","Decoder","Killer"]
_essentialBreakerTypesNotInArray(installedRunnerCards) {
var breakersInstalled = [];
for (var j = 0; j < installedRunnerCards.length; j++) {
if (CheckSubType(installedRunnerCards[j], "Icebreaker"))
breakersInstalled.push(installedRunnerCards[j]);
}
var breakerTypes = ["Fracter", "Decoder", "Killer"];
var result = [];
for (var j = 0; j < breakerTypes.length; j++) {
//if this breaker type is not already installed, add it to result
var alreadyHaveOne = false;
for (var k = 0; k < breakersInstalled.length; k++) {
if (CheckSubType(breakersInstalled[k], breakerTypes[j])) {
alreadyHaveOne = true;
break;
}
}
if (!alreadyHaveOne) result.push(breakerTypes[j]);
}
return result;
}
//returns something between [] and ["Fracter","Decoder","Killer"]
//you can override ["Fracter","Decoder","Killer"] with your own list of subtypes to check icebreakers for
_essentialBreakerTypesNotInHandOrArray(installedRunnerCards, overrideBreakerTypes=null) {
var breakersInHandOrInstalled = [];
for (var j = 0; j < installedRunnerCards.length; j++) {
if (CheckSubType(installedRunnerCards[j], "Icebreaker"))
breakersInHandOrInstalled.push(installedRunnerCards[j]);
}
for (var j = 0; j < runner.grip.length; j++) {
if (CheckSubType(runner.grip[j], "Icebreaker"))
breakersInHandOrInstalled.push(runner.grip[j]);
}
var breakerTypes = ["Fracter", "Decoder", "Killer"];
if (overrideBreakerTypes) breakerTypes = overrideBreakerTypes;
var result = [];
for (var j = 0; j < breakerTypes.length; j++) {
//if this breaker type is not already in hand or installed, add it to result
var alreadyHaveOne = false;
for (var k = 0; k < breakersInHandOrInstalled.length; k++) {
if (CheckSubType(breakersInHandOrInstalled[k], breakerTypes[j])) {
alreadyHaveOne = true;
break;
}
}
if (!alreadyHaveOne) result.push(breakerTypes[j]);
}
return result;
}
//returns the first card found fulfilling this description (or an AI if needed, or null if none found)
//note that the AI will search first for what it considers to be higher priority cards so the override might not be followed in order
_icebreakerInPileNotInHandOrArray(pileToCheck,installedRunnerCards) {
var essentialBreakerTypesNotInHandOrArray =
this._essentialBreakerTypesNotInHandOrArray(installedRunnerCards);
if (essentialBreakerTypesNotInHandOrArray.length > 1) {
//if more than one type, match most important first (the concat avoids modifying original array)
pileToCheck = this.SortCardsWorthKeeping(pileToCheck.concat([]));
}
//need one, is there one in deck?
for (var k = 0; k < pileToCheck.length; k++) {
for (var j = 0; j < essentialBreakerTypesNotInHandOrArray.length; j++) {
if (
CheckSubType(
pileToCheck[k],
essentialBreakerTypesNotInHandOrArray[j]
)
) {
return pileToCheck[k];
}
}
}
//we need one but couldn't find it - maybe get an AI instead (if there is not already one in hand or array)
var aiNotInHandOrArray = this._essentialBreakerTypesNotInHandOrArray(installedRunnerCards, ["AI"]);
if (essentialBreakerTypesNotInHandOrArray.length > 0 && aiNotInHandOrArray.length > 0) {
for (var k = 0; k < pileToCheck.length; k++) {
if (CheckSubType(pileToCheck[k], "AI")) {
return pileToCheck[k];
}
}
}
return null;
}
//check an array for cards worth keeping
_cardsWorthKeeping(cards) {
//subtypes to ideally have at least one of each installed:
var atLeastOne = ["Console", "Fracter", "Decoder", "Killer"]; //list of subtypes desired
//loop through installed runner cards - if any have this subtype then it can be removed from the list
//could use the _installedCardExistsWithSubType helper function but this custom approach is more efficient here
var installedRunnerCards = InstalledCards(runner);
for (var i = 0; i < installedRunnerCards.length; i++) {
for (var j = atLeastOne.length - 1; j > -1; j--) {
if (CheckSubType(installedRunnerCards[i], atLeastOne[j]))
atLeastOne.splice(j, 1);
}
}
//precalculate spareMU here for efficiency
var spareMU = this._spareMemoryUnits(installedRunnerCards);
//loop through array to find cards worth keeping
var ret = [];
for (var i = 0; i < cards.length; i++) {
var keep = false;
var card = cards[i];
if (!this._wastefulToInstall(card)) {
//_wastefulToInstall makes sure we don't overwrite existing unique or exceed mu
//check for any card-specific reason
if (typeof card.AIWorthKeeping == "function") {
if (card.AIWorthKeeping.call(card,installedRunnerCards,spareMU)) keep = true;
}
//some we desire atLeastOne
for (var j = 0; j < atLeastOne.length; j++) {
if (CheckSubType(card, atLeastOne[j])) keep = true;
}
//or AI or other special breaker (e.g. Botulus, Tranquilizer) or various-type Icebreaker (e.g. Chameleon)
if ( CheckSubType(card, "AI") || card.AISpecialBreaker ||
(CheckSubType(card, "Icebreaker") && !CheckSubType(card, "Decoder") && !CheckSubType(card, "Fracter") && !CheckSubType(card, "Killer"))
) {
//keep unless all breaker types are already present in grip/programs
if (
this._essentialBreakerTypesNotInHandOrArray(installedRunnerCards)
.length > 0
)
keep = true;
}
}
if (keep) {
//don't include duplicates (for now? maybe sometimes keeping two or more is critical?)
if (!this._copyOfCardExistsIn(card.title, ret)) ret.push(card);
}
}
return ret;
}
_cardsInHandWorthKeeping() {
return this._cardsWorthKeeping(runner.grip);
}
//returns -1 (low), 0 (neither) or 1 (high) priority
EstimateCardPriority(card, priorityIceList) {
//A compatible (but not yet installed) breaker is high priority
for (var i = 0; i < priorityIceList.length; i++) {
var iceCard = priorityIceList[i];
if (PlayerCanLook(runner, iceCard)) {
if (this._breakerMatchesIce(card, iceCard)) {
//console.log("Matching breaker is " + card.title);
if (!this._matchingBreakerInstalled(iceCard)) return 1;
//high
else return -1; //low
}
}
}
return 0; //neither by default
}
//ice list (either from the highest priority server or just all ice)
_priorityIceList() {
var priorityIceList = [];
if (this.cachedPotentials.length > 0) {
//which server is highest priority?
var highestPotential = this.cachedPotentials[0].potential;
var highestPotentialServer = this.cachedPotentials[0].server;
for (var i = 1; i < this.cachedPotentials.length; i++) {
if (this.cachedPotentials[i].potential > highestPotential) {
highestPotential = this.cachedPotentials[i].potential;
highestPotentialServer = this.cachedPotentials[i].server;
}
}
if (highestPotentialServer.ice.length > 0)
priorityIceList = highestPotentialServer.ice;
}
if (priorityIceList.length == 0) {
var installedCards = InstalledCards(corp);
for (var i = 0; i < installedCards.length; i++) {
if (installedCards[i].cardType == "ice")
priorityIceList.push(installedCards[i]);
}
}
return priorityIceList;
}
//sometimes a run recalculation is needed
RecalculateRunIfNeeded() {
if (attackedServer) {
//check if server is still worthwhile target
var runStillWorthCompleting = false;
//e.g. is central (this oversimplifies the situation but may be sufficient)
if (typeof attackedServer.cards != 'undefined') runStillWorthCompleting = true;
//or has cards in its root
else if (attackedServer.root.length > 0) runStillWorthCompleting = true;
//or we were never going to breach anyway
else if (this._breachWouldBePrevented(ActiveCards(runner),attackedServer)) runStillWorthCompleting=true;
//ideally complete run, unless the server target has become pointless
var completeRun = false;
completeRun = runner.AI._calculateBestCompleteRun(attackedServer, 0, 0, 0, 0, null, approachIce); //null means no bonus breaker
//if run cost is very low then run is still worth completing just for the successful effect (arbitrary value)
if (completeRun && !runStillWorthCompleting && this.rc.PathCost(completeRun) < 0.8) {
runStillWorthCompleting = true;
}
//if no complete run, or run not worth it, use an exit strategy (incomplete run)
if (!completeRun || !runStillWorthCompleting) runner.AI._calculateBestExitStrategy(
attackedServer,
0,
0,
0,
0,
null, //no bonus breaker
approachIce
);
}
}
//recommend do this right after calculating run costs and priorities
SortCardsWorthKeeping(cwkToSort) {
if (typeof cwkToSort == 'undefined') cwkToSort = this.cardsWorthKeeping;
//console.log("Sorting: " + JSON.stringify(cwkToSort));
var splits = [];