Repository navigation
Expand file tree
/
Copy pathruncalculator.js
More file actions
1414 lines (1336 loc) · 56 KB
/
Copy pathruncalculator.js
File metadata and controls
1414 lines (1336 loc) · 56 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
class RunCalculator {
constructor() {
//Calculate will set these base value when it starts (they are inputs)
this.baseClicks = 0;
this.basePoolCredits = 0;
this.baseOtherCredits = 0;
this.paths = [];
this.precalculated = {
runnerInstalledCardsLength: 0,
runnerInstalledIcebreakersLength: 0,
activeCards: [],
iceAIs: [],
};
this.reason = "error"; //for reporting
this.bonusBreaker = null; //for hypothetical calculations
this.runEvent = null; //for hypothetical calculations
//used by corp for hypothetical runs
this.suppressOutput = false;
this.avoidETR = false;
}
//known ice list
//creates a version of the ice that can be understood and modified by the AI
//sr effects are arrays of arrays of effect strings (each sr contains the 'or' options)
//NOTE thest must be in the same order as the choices provided by the card definition
// netDamage
// tag
// endTheRun
// loseCredits (runner) from main credit pool, not from extra credits. Will not reduce credits remaining to below zero
// payCredits will be an ignored path if cannot be afforded (i.e. only use it for sr that has an option e.g. Funhouse or if there is no alternative e.g. Tollbooth)
// misc_minor e.g. corp gains credit
// misc_moderate e.g. trash 1 program
// misc_serious e.g. install another ice inward (like endTheRun, paths that fire these will be avoided)
//encounterEffects is an array of OR arrays of effects
IceAI(ice, maxCorpCred, assumeWeakerUnknown = false, incomplete = false, startIceIdx = -1) {
var result = {
ice: ice,
subTypes: [],
sr: [],
strength: 0,
encounterEffects: [[]],
};
var iceKnown = PlayerCanLook(runner, ice);
if (!iceKnown) {
//unknown ice
var extraRezCost = RezCost(ice) - ice.rezCost; //this isn't cheating because we only check the bonus cost (easy way of summarising any card effects)
//advanceable ice assumptions
var advCounters = Counters(ice, "advancement");
if (advCounters > 0) {
if (advCounters < 4 && maxCorpCred > 6 + extraRezCost) {
//assume Pharos
result.subTypes = ["Barrier"];
result.sr = [[["tag"]], [["endTheRun"]], [["endTheRun"]]];
if (advCounters < 3) result.strength = 5;
else result.strength = 10;
}
else if (advCounters < 4 && maxCorpCred > 3 + extraRezCost) {
//assume Hortum (simplified)
result.subTypes = ["Code Gate"];
result.sr = [[["misc_moderate"]], [["endTheRun"]]];
result.strength = 4;
}
else if (advCounters > 0) {
//assume Ice Wall
result.subTypes = ["Barrier"];
result.sr = [[["endTheRun"]]];
result.strength = 1 + advCounters;
}
}
//not advanced, if corp has credits assume a general ice
else if (maxCorpCred > 0 + extraRezCost) {
result.subTypes = ["Sentry"];
result.strength = Math.min(0.6*(maxCorpCred-extraRezCost), 6); //the 0.6 is somewhat arbitrary, test and tweak
result.sr = [];
if (!assumeWeakerUnknown) {
if (maxCorpCred < 4 + extraRezCost) result.sr.push([["netDamage"]]);
else result.sr.push([["netDamage", "netDamage"]]);
}
else result.sr.push([["misc_moderate"]]); //arbitrary weak ice
//either way, account for the fact that it could be pop-up window
result.sr.push([["payCredits"], ["endTheRun"]]); //pay 1 credit or end the run
}
//or maybe pop-up window (just creating a simple/reduced version since it's hypothetical)
else if (maxCorpCred == 0 + extraRezCost) {
result.subTypes = ["Code Gate"];
result.strength = 0;
result.sr.push([["payCredits"], ["endTheRun"]]); //pay 1 credit or end the run
}
}
if (iceKnown && (ice.rezzed || maxCorpCred >= RezCost(ice))) {
//ice is known, calculate specifics
//start with basic details
//we need to pretend it's an encounter
var stored = AIIceEncounterSaveState();
AIIceEncounterModifyState(ice);
result.strength = Strength(ice);
//then restore reality
AIIceEncounterRestoreState(stored);
result.sr = [];
result.subTypes = [].concat(ice.subTypes);
//apply specific details
if (typeof ice.AIImplementIce == "function") {
result = ice.AIImplementIce.call(ice, this, result, maxCorpCred, incomplete);
} //default case - used for ice that haven't been coded specifically above
else {
for (var i = 0; i < ice.subroutines.length; i++) {
result.sr.push([["misc_moderate"]]);
}
}
//blank out subroutines that are already broken
for (var i = 0; i < ice.subroutines.length && i < result.sr.length; i++) {
if (ice.subroutines[i].broken) result.sr[i] = [[]];
}
}
//passive effects (assuming Runner only for now)
var activeCards = ActiveCards(runner);
for (var i = 0; i < activeCards.length; i++) {
if (typeof activeCards[i].AIModifyIceAI == 'function') {
result = activeCards[i].AIModifyIceAI.call(activeCards[i],result,startIceIdx);
}
}
return result;
}
//check whether the given card is a .use in the persistents of the given point
PersistentsUse(point,card) {
for (var i=0; i<point.persistents.length; i++) {
if (typeof point.persistents[i].use != 'undefined') {
if (point.persistents[i].use == card) return true;
}
}
return false;
}
SrBroken(point, srIdx) {
for (var i = 0; i < point.sr_broken.length; i++) {
if (point.sr_broken[i].idx == srIdx) return true;
}
return false;
}
//returns an array of points (results are options for breaking exactly num. For less, call this multiple times and combine)
SrBreak(
card,
iceAI,
point,
num //this doesn't include costs - handle that in the place you call this
) {
var result = [];
var unbrokensr = [];
for (var i = 0; i < iceAI.sr.length; i++) {
if (!this.SrBroken(point, i)) unbrokensr.push({ use: card, idx: i });
}
var combinations = k_combinations(unbrokensr, num);
for (var i = 0; i < combinations.length; i++) {
result.push({
iceIdx: point.iceIdx,
runner_credits_spent: point.runner_credits_spent,
runner_credits_lost: point.runner_credits_lost,
runner_clicks_spent: point.runner_clicks_spent,
virus_counters_spent: point.virus_counters_spent,
card_str_mods: point.card_str_mods,
persistents: point.persistents,
sr_broken: point.sr_broken.concat(combinations[i]),
effects: point.effects,
});
}
return result;
}
//returns a point (note that second argument is card not iceAI like SrBreak)
StrModify(
useCard,
targetCard,
point,
amt,
persist = false //this doesn't include costs - handle that in the place you call this
) {
return {
iceIdx: point.iceIdx,
runner_credits_spent: point.runner_credits_spent,
runner_credits_lost: point.runner_credits_lost,
runner_clicks_spent: point.runner_clicks_spent,
virus_counters_spent: point.virus_counters_spent,
//for strength modification, iceIdx is included so that we know when persistent changes were initially made
card_str_mods: point.card_str_mods.concat([
{
iceIdx: point.iceIdx,
card: targetCard,
use: useCard,
amt: amt,
persist: persist,
},
]),
persistents: point.persistents,
sr_broken: point.sr_broken,
effects: point.effects,
};
}
//helper for IceAct (return array for concatenation)
//empty iceSubTypes will just break any subtypes
//credits are spent, not lost
ImplementIcebreaker(
point,
card,
cardStrength,
iceAI,
iceStrength,
iceSubTypes,
costToUpStr,
amtToUpStr,
costToBreak,
amtToBreak,
creditsLeft,
persistStrMod = false,
) {
var result = [];
var typeMatches = false;
if (iceSubTypes.length == 0) typeMatches = true;
else {
for (var i = 0; i < iceSubTypes.length; i++) {
if (iceAI.subTypes.includes(iceSubTypes[i])) {
typeMatches = true;
break;
}
}
}
if (!typeMatches) return result;
//if strength matches (interface)
if (cardStrength >= iceStrength) {
if (creditsLeft >= costToBreak) {
var breakresult = [];
for (
var i = amtToBreak;
i > 0;
i-- //implements "break up to X" subroutines e.g. for 2 consider all combinations of 2 and all combinations of 1
) {
breakresult = breakresult.concat(this.SrBreak(card, iceAI, point, i));
}
for (var j = 0; j < breakresult.length; j++) {
breakresult[j].runner_credits_spent += costToBreak;
}
result = result.concat(breakresult);
}
} //need to up strength
else {
if (creditsLeft >= costToUpStr) {
var modifyresult = this.StrModify(card, card, point, amtToUpStr, persistStrMod);
modifyresult.runner_credits_spent += costToUpStr;
result.push(modifyresult);
}
}
return result;
}
IceAct(card, iceAI, point, server) {
var result = []; //array of points (directions)
var iceStrength = iceAI.strength;
for (var i = 0; i < point.card_str_mods.length; i++) {
if (point.card_str_mods[i].card == iceAI.ice)
iceStrength += point.card_str_mods[i].amt;
}
var cardStrength = Strength(card);
for (var i = 0; i < point.card_str_mods.length; i++) {
if (point.card_str_mods[i].card == card)
cardStrength += point.card_str_mods[i].amt;
}
var clicksLeft = this.baseClicks - point.runner_clicks_spent;
//assume both pool and extra credits can be used for breakers
var creditsLeft = this.basePoolCredits + this.baseOtherCredits - point.runner_credits_spent - point.runner_credits_lost;
//apply icebreaker specific details
if (typeof card.AIImplementBreaker == "function") {
result = card.AIImplementBreaker.call(card,this,result,point,server,cardStrength,iceAI,iceStrength,clicksLeft,creditsLeft);
}
return result;
}
//helper function (recursive) to consider all possibilities if subroutines have a runner choice
//input is an array of arrays of {srIdx: , choiceIdx: } objects (the options for each subroutine)
//return is an array of arrays of {srIdx: , choiceIdx: } objects (all possible combinations of subroutine choices)
//e.g. [ [ {0,0}, {0,1} ] , [ {1,0} ] ] will return [ [ {0,0}, {1,0} ] , [ {0,1}, {1,0} ] ]
SrOptions(src) {
//initialise the first options
var base = [];
for (var i = 0; i < src[0].length; i++) {
base.push([src[0][i]]);
}
for (var i = 1; i < src.length; i++) {
var oldbase = base;
base = [];
for (var j = 0; j < src[i].length; j++) {
for (var k = 0; k < oldbase.length; k++) {
base.push(oldbase[k].concat([src[i][j]]));
}
}
}
return base;
}
//create copy of point with encounter effects added, or return null if not valid
//iceAI is the ice being moved on from to experience this new encounter (if this is the first encounter, don't include iceAI)
//card_str_mods and persistents contain the card_str_mods we want to pass on to this next encounter (i.e. persist)
ValidateEncounterPoint(nextIceIdx, point, incomplete, encounter_effects, encounter_persistents, iceAI=null, card_str_mods=[], persistents=[]) {
//some pathways will not be followed e.g. unbroken ETR, misc_serious, or unaffordable payment
var exclude_path = false;
var creditPayment = 0;
var creditLoss = 0;
var clickLoss = 0;
//loop through effects in order
for (var j=0; j<encounter_effects.length; j++) {
var eff = encounter_effects[j];
//recalculate current click/financial situation (ice specific effects may rely on it)
var clicksLeft = this.baseClicks - point.runner_clicks_spent - clickLoss;
var poolCreditsLeft = this.basePoolCredits - point.runner_credits_lost - creditLoss;
var otherCreditsLeft = this.baseOtherCredits - point.runner_credits_spent - creditPayment;
var overallCreditsLeft = poolCreditsLeft + otherCreditsLeft;
//take into account pool being affected by excess other spend
if (otherCreditsLeft < 0) poolCreditsLeft += otherCreditsLeft;
//apply special per-ice unique conditional effects (from current ice, not encountering new one)
if (iceAI && eff == "iceSpecificEffect") {
var new_effs = iceAI.ice.AIIceSpecificEffect.call(iceAI.ice, poolCreditsLeft, otherCreditsLeft);
//remove from encounter_effects and insert instead any effects that are returned
encounter_effects.splice(j, 1, ...new_effs); //remove 1 item at position j and insert all returned items (not compatible with older browsers)
j--; //step back so next item isn't skipped
}
else if (eff == "endTheRun") {
//this path will not lead to a complete run
if (!incomplete || this.avoidETR) exclude_path = true;
//the effect applies right away, so no need to process other effects
break;
}
else if (eff == "misc_serious") {
//don't follow this path for a complete run, it's too dangerous
//but for incomplete runs, check it because it might be the less dangerous overall path
if (!incomplete) exclude_path = true;
}
//apply payments (exclude path if not affordable)
else if (eff == "payCredits") {
//remove from encounter_effects (will be included in total costs instead)
encounter_effects.splice(j, 1); //remove 1 item at position j
j--; //step back so next item isn't skipped
//Nisei CR 1.5 1.10.3 "spend" and "pay" are synonymous
//i.e. can be spent from credit pool or from other sources
if (overallCreditsLeft > 0) creditPayment++;
else {
//i.e. creditPayment >= overallCreditsLeft so can't afford this payment
exclude_path = true; //cannot afford this payment, not a possible option
break;
}
}
//apply credit loss
else if (eff == "loseCredits") {
//remove from encounter_effects (will be included in total costs instead)
encounter_effects.splice(j, 1); //remove 1 item at position j
j--; //step back so next item isn't skipped
//credits are lost directly from the credit pool
if (poolCreditsLeft > 0) creditLoss++;
}
//apply click loss
else if (eff == "loseClicks") {
//remove from encounter_effects (will be included in total costs instead)
encounter_effects.splice(j, 1); //remove 1 item at position j
j--; //step back so next item isn't skipped
if (clicksLeft > 0) clickLoss++;
}
}
//now put it all together to create a path branch (if not excluded)
if (!exclude_path) {
return {
iceIdx: nextIceIdx,
runner_credits_spent: point.runner_credits_spent + creditPayment,
runner_credits_lost: point.runner_credits_lost + creditLoss,
runner_clicks_spent: point.runner_clicks_spent + clickLoss,
virus_counters_spent: point.virus_counters_spent,
card_str_mods: card_str_mods,
persistents: persistents.concat(encounter_persistents),
sr_broken: [],
effects: point.effects.concat([encounter_effects]),
};
}
//not a valid branch
return null;
}
//create encounter options for next ice
//at the moment only effects and persistents
EncounterOptions(nextIceIdx, nextIceAI) {
var encounterOptions = [];
//standard from ice
var encounterEffects = nextIceAI.encounterEffects;
for (var i=0; i<encounterEffects.length; i++) {
encounterOptions.push({effects:encounterEffects[i], persistents:[]});
}
//special from card effects
//active cards
var activeCards = this.precalculated.activeCards;
for (var i = 0; i < activeCards.length; i++) {
if (typeof activeCards[i].AIEncounterOptions == 'function') {
encounterOptions = encounterOptions.concat(activeCards[i].AIEncounterOptions.call(activeCards[i],nextIceIdx,nextIceAI));
}
};
//and hypothetical
if (this.runEvent) {
if (typeof this.runEvent.AIEncounterOptions == 'function') {
encounterOptions = encounterOptions.concat(this.runEvent.AIEncounterOptions.call(this.runEvent,nextIceIdx,nextIceAI));
}
}
return encounterOptions;
}
//helper function for run 'pathfinding'
Directions(
server,
point,
max_cost,
damageLimit,
clickLimit,
poolCreditLimit,
otherCredits,
tagLimit,
incomplete
) {
var result = []; //possibilities to continue to explore path
this.reason = "error in directions"; //for reporting
var iceAI = this.precalculated.iceAIs[point.iceIdx];
//create list of unbroken subroutines (each is an array of 'or' choices)
var unbroken_sr = [];
for (var i = 0; i < iceAI.sr.length; i++) {
if (!this.SrBroken(point, i)) {
var sr_row = [];
for (var j = 0; j < iceAI.sr[i].length; j++) {
sr_row.push({ srIdx: i, choiceIdx: j });
}
unbroken_sr.push(sr_row);
}
}
//process into list of possibilities (unless no unbroken sr left, in which case it's [[]])
var sr_possibilities = [[]]; //array of arrays of { srIdx, choiceIdx } objects
//check if ice was bypassed
var bypassed = false;
for (var i = 0; i < point.persistents.length; i++) {
if (typeof point.persistents[i].iceIdx != 'undefined' && typeof point.persistents[i].action != 'undefined') {
if (point.persistents[i].iceIdx == point.iceIdx && point.persistents[i].action == "bypass") {
bypassed = true;
break;
}
}
}
//if there are still unbroken subroutines, consider possible card abilities and effects
//or skip resolving subroutines if the ice was bypassed
if (unbroken_sr.length > 0 && !bypassed) {
sr_possibilities = this.SrOptions(unbroken_sr); //this list will be used later when considering effects of completing encounter
var potential_result = [];
//all possible abilities e.g. strength up/down, break sr
var activeCards = this.precalculated.activeCards;
for (var i = 0; i < activeCards.length; i++) {
var iceact = this.IceAct(activeCards[i], iceAI, point, server);
potential_result = potential_result.concat(iceact);
}
//and a bonus card, if specified
if (this.bonusBreaker) {
potential_result = potential_result.concat(this.IceAct(this.bonusBreaker.card, iceAI, point, server));
}
//only include less than max cost
for (var i = 0; i < potential_result.length; i++) {
if (
this.PointCost(potential_result[i]) < max_cost &&
this.ValidPoint(
potential_result[i],
damageLimit,
clickLimit,
poolCreditLimit,
otherCredits,
tagLimit
).valid
)
result.push(potential_result[i]); //cost is cumulative up to and including this point
}
//sort by cost as a heuristic (so the last result is the best)
result.sort(function (a, b) {
if (a.sr_broken.length < b.sr_broken.length) return -1;
//breaking more is preferred to breaking less (or strength modification)
else if (a.sr_broken.length > b.sr_broken.length) return 1;
if (a.cost < b.cost) return 1; //cheaper abilities preferred over more expensive ones
return -1;
});
}
//for each possibility, consider the option of completing the encounter
for (var k = 0; k < sr_possibilities.length; k++) {
var sr_effects = []; //the effects that would happen if we continue encounter
for (
var i = 0;
i < sr_possibilities[k].length;
i++ //get the effects from each unbroken sr in this pathway
) {
var srIdx = sr_possibilities[k][i].srIdx;
var choiceIdx = sr_possibilities[k][i].choiceIdx;
sr_effects = sr_effects.concat(iceAI.sr[srIdx][choiceIdx]);
if (iceAI.sr[srIdx][choiceIdx].includes("endTheRun")) break; //if a subroutine ends the run, the remaining subroutines don't fire
}
//don't follow paths where a program was up strengthed but not used for something else too (e.g. to down strength or to break sr)
//start by making a list of all programs that had their strength upped during this encounter
var cards_strengthened_this_encounter = [];
for (var i = 0; i < point.card_str_mods.length; i++) {
if (point.card_str_mods[i].iceIdx == point.iceIdx) {
//it happened this ice (not persistent effect from earlier)
if (point.card_str_mods[i].amt > 0) {
//it's an up-strength
cards_strengthened_this_encounter.push(point.card_str_mods[i].card); //the target card that got strengthened
}
}
}
//now check if any of these wasn't used
var a_card_was_used_unnecessarily = false;
for (var i = 0; i < cards_strengthened_this_encounter.length; i++) {
var card = cards_strengthened_this_encounter[i];
var card_was_used_for_something_else_too = false;
//maybe to modify ice strength?
for (var j = 0; j < point.card_str_mods.length; j++) {
if (
point.card_str_mods[j].use == card &&
point.card_str_mods[j].card == iceAI.ice
) {
card_was_used_for_something_else_too = true;
break;
}
}
//or maybe to break subroutines
if (!card_was_used_for_something_else_too) {
for (var j = 0; j < point.sr_broken.length; j++) {
if (point.sr_broken[j].use == card) {
card_was_used_for_something_else_too = true;
break;
}
}
}
//wasn't used for anything else - this is not a good way to end the encounter
if (!card_was_used_for_something_else_too) {
a_card_was_used_unnecessarily = true;
this.reason = "cu_nobr"; //card used but no break
break;
}
}
//also check for if ice strength was modified but no sr were broken
if (!a_card_was_used_unnecessarily) {
var ice_strength_was_reduced = false;
for (var i = 0; i < point.card_str_mods.length; i++) {
if (point.card_str_mods[i].iceIdx == point.iceIdx) {
//it happened this ice (not persistent effect from earlier)
if (point.card_str_mods[i].card == iceAI.ice) {
//it targeted the ice
ice_strength_was_reduced = true;
break;
}
}
}
if (ice_strength_was_reduced && point.sr_broken.length < 1) {
a_card_was_used_unnecessarily = true;
this.reason = "im_nobr"; //ice modified but no break
}
}
//we could also check to make sure strength wasnt modified too much (e.g. lower/higher than needed)
//but this is complex e.g. odd number needed but +2 ability, or combination of breakers used, bioroid ice, etc.
//even as it is these checks are worth it, they reduced combinations by up to a third in testing
//all checks above good, no waste? ok lets consider option to move on
if (!a_card_was_used_unnecessarily) {
//some properties persist from one encounter to the next
//card_str_mods with .persist true
var card_str_mods = [];
for (var i = 0; i < point.card_str_mods.length; i++) {
if (point.card_str_mods[i].persist)
card_str_mods.push(point.card_str_mods[i]);
}
//and all other persistents
var persistents = [];
for (var i = 0; i < point.persistents.length; i++) {
persistents.push(point.persistents[i]);
}
//clear the point ready for the next encounter
//encounter options for non-starting ice
var encounterOptions = [{effects:[], persistents:[]}];
var nextIceAI = this.precalculated.iceAIs[point.iceIdx - 1];
//consider effects of encountering next ice (unless approaching server)
if (!incomplete) {
//incomplete paths jack out before the next ice i.e. no additional effect
if (point.iceIdx > 0) {
encounterOptions = this.EncounterOptions(point.iceIdx - 1,nextIceAI);
}
}
for (var i = 0; i < encounterOptions.length; i++) {
//compute total effects if these options are selected
var encounter_effects = sr_effects.concat(encounterOptions[i].effects); //effects of unbroken subroutines combined with effects of encountering next ice
var encounter_persistents = encounterOptions[i].persistents;
var next_encounter_point = this.ValidateEncounterPoint(point.iceIdx - 1, point, incomplete, encounter_effects, encounter_persistents, iceAI, card_str_mods, persistents);
if (next_encounter_point) {
if (sr_possibilities.length > 1)
next_encounter_point.alt = sr_possibilities[k]; //if sr choice(s) were made, record
var point_cost = this.PointCost(next_encounter_point);
if (point_cost < max_cost) {
if (
this.ValidPoint(
next_encounter_point,
damageLimit,
clickLimit,
poolCreditLimit,
otherCredits,
tagLimit
).valid
)
result.push(next_encounter_point);
//cost is cumulative up to and including this point
else this.reason = "exceeds";
} else
this.reason = "suboptimal (" + point_cost.toPrecision(3) + ")";
} else this.reason = "incomplete";
}
}
}
return result;
}
//get total effect to reach a point p, as a dictionary of effect ints
TotalEffect(p) {
var result = {};
for (var j = 0; j < p.effects.length; j++) {
for (var i = 0; i < p.effects[j].length; i++) {
if (!result.hasOwnProperty(p.effects[j][i]))
result[p.effects[j][i]] = 1;
else result[p.effects[j][i]]++;
}
}
return result;
}
//specific useful function
TotalDamage(totalEffect) {
var result = 0;
if (totalEffect.netDamage) result += totalEffect.netDamage;
if (totalEffect.meatDamage) result += totalEffect.meatDamage;
if (totalEffect.coreDamage) result += totalEffect.coreDamage;
return result;
}
PointCost(
p //p is a point (cost is cumulative up to and including this point)
) {
if (typeof p.cost == "undefined") {
//check for already calculated and stored value
var result = 0;
//reduce cost of credit spend depending on bad pub credits i.e. corp.badPublicity or runner.temporaryCredits (depending on whether run is hypothetical)
var spentCredits = p.runner_credits_spent;
if (attackedServer) spentCredits -= runner.temporaryCredits;
else spentCredits -= corp.badPublicity;
if (spentCredits < 0) spentCredits = 0;
//tweak this algorithm
result += 0.6 * spentCredits;
result += 0.7 * p.runner_credits_lost;
result += 0.8 * p.runner_clicks_spent;
result += 0.3 * p.virus_counters_spent;
var totalEffect = this.TotalEffect(p);
result += 1.3 * this.TotalDamage(totalEffect); //during 1.0 the runner seemed too willing to take damage
if (totalEffect.tag) result += 2.4 * totalEffect.tag; //not sure about this
if (totalEffect.misc_serious) result += 3.0 * totalEffect.misc_serious; //was 1.5 for quite some time but I think this wasn't enough
if (totalEffect.misc_moderate) result += 0.8 * totalEffect.misc_moderate;
if (totalEffect.misc_minor) result += 0.3 * totalEffect.misc_minor;
p.cost = result;
}
return p.cost;
}
PathCost(
p //p is a path
) {
if (p.length < 1) return Infinity;
var result = 0;
var back = p[p.length - 1];
result += this.PointCost(back);
return result;
}
//since values are cumulative, the point at the end of the path represents total
ValidPoint(p, damageLimit, clickLimit, poolCreditLimit, otherCredits, tagLimit) {
var reason = "";
if (typeof p.valid == "undefined") {
//check for already calculated and stored value
p.valid = false; //by default, then set to true if check succeeds
var clicksLeft = clickLimit - p.runner_clicks_spent;
//runner credits are 'spent' from other credits first until it is depleted, then from pool
var otherCreditsLeft = otherCredits - p.runner_credits_spent;
//whereas they are 'lost' from pool only
var poolCreditsLeft = poolCreditLimit - p.runner_credits_lost;
if (otherCreditsLeft < 0) {
poolCreditsLeft += otherCreditsLeft;
otherCreditsLeft = 0;
}
//path is invalid if attempting to reduce pool below zero
//check and apply effects
reason = "clicks";
if (clicksLeft >= 0) {
reason = "credits";
if (poolCreditsLeft >= 0) {
var totalEffect = this.TotalEffect(p);
var totalDamage = 0;
if (totalEffect.netDamage) totalDamage += totalEffect.netDamage;
if (totalEffect.meatDamage) totalDamage += totalEffect.meatDamage;
if (totalEffect.coreDamage) totalDamage += totalEffect.coreDamage;
//update damage limit based on clicks spent (unless it is set to Infinity or already mid-run)
if (clicksLeft < 1 && damageLimit != Infinity && !attackedServer) damageLimit = runner.grip.length - MaxHandSize(runner); //try to keep a full hand at end of turn
if (damageLimit < 0) damageLimit = 0;
//now check damage against limit
reason = "damage";
if (totalDamage <= damageLimit) {
var totalTag = 0;
if (totalEffect.tag) totalTag += totalEffect.tag;
//update tag limit based on clicks and credits spent (unless it is set to Infinity)
if (tagLimit != Infinity) tagLimit =
Math.min(clicksLeft, Math.floor(poolCreditsLeft * 0.5)) - runner.tags; //allow 1 tag for each click+2[c] (pool only for now) remaining but less if tagged
if (tagLimit < 0) tagLimit = 0;
//now check tags against limit
reason = "tags";
if (totalTag <= tagLimit) p.valid = true;
}
}
}
}
return {valid: p.valid, reason: reason};
}
//Check whether path p is within limits
ValidPath(p, damageLimit, clickLimit, poolCreditLimit, otherCredits, tagLimit) {
var back = p[p.length - 1];
var valid = this.ValidPoint(
back,
damageLimit,
clickLimit,
poolCreditLimit,
otherCredits,
tagLimit
);
return {valid: valid.valid, reason: valid.reason};
}
//Helper to create an empty pathing point
EmptyPoint(iceIdx) {
var ret = {
iceIdx: iceIdx,
runner_credits_spent: 0,
runner_credits_lost: 0,
runner_clicks_spent: 0,
virus_counters_spent: 0,
card_str_mods: [],
persistents: [],
sr_broken: [],
effects: [],
};
return ret;
}
//Helper to create a copy of a pathing point
//This also makes its own copies of arrays (but references the old elements within)
CopyPoint(point) {
var ret = {
iceIdx: point.iceIdx,
runner_credits_spent: point.runner_credits_spent,
runner_credits_lost: point.runner_credits_lost,
runner_clicks_spent: point.runner_clicks_spent,
virus_counters_spent: point.virus_counters_spent,
card_str_mods: point.card_str_mods.concat([]),
persistents: point.persistents.concat([]),
sr_broken: point.sr_broken.concat([]),
effects: point.effects.concat([]),
};
return ret;
}
//***Calculate has two version (Async and normal i.e. synchronous). These are the three pieces shared (begin, middle, end).
//Begin returns data, Middle and End do not have return values
CalculatePieceBegin(data) {
if (typeof data.rcOptions != 'undefined') {
if (typeof data.rcOptions.suppressOutput != 'undefined') this.suppressOutput = data.rcOptions.suppressOutput;
if (typeof data.rcOptions.avoidETR != 'undefined') this.avoidETR = data.rcOptions.avoidETR;
}
//if (!this.suppressOutput) console.log("Calculating "+(data.incomplete ? "data.incomplete" : "complete")+" run");
if (typeof data.startIceIdx == "undefined") data.startIceIdx = data.server.ice.length - 1;
if (typeof data.bonusBreaker == "undefined") data.bonusBreaker = null;
this.bonusBreaker = data.bonusBreaker;
var installedRunnerCards = InstalledCards(runner);
data.clickLimit = data.clicks; //this is maybe not ideal (e.g. Enigma might break things)
data.poolCreditLimit = data.poolCredits; //same as above, maybe
this.baseClicks = data.clicks;
this.basePoolCredits = data.poolCredits;
this.baseOtherCredits = data.otherCredits;
this.paths = []; //completed paths
//default approach cost is none (but not an empty approachOptions array - that would mean no path ever and this process would fail)
data.approachOptions = [{ clicks: 0, credits: 0, effects: 0, tags: 0 }];
//for complete runs, include known trash costs any other costs to get into server
if (!data.incomplete) {
var approachClicks = 0;
var approachCredits = 0;
var approachEffects = [];
var approachTags = 0;
var knownCardsInRoot = [];
var numUnknownCardsInRoot = 0;
var runnerAI = runner.AI;
if (runnerAI == null) runnerAI = runner.testAI;
//effects that might happen regardless of breach
//1 net damage for each House of Knives that hasn't been used this run
var activeHOKs = 0;
corp.scoreArea.forEach(function(item){
if (!attackedServer || !item.usedThisRun) {
if (CheckCounters(item, "agenda", 1)) activeHOKs++;
}
});
var hokEffect = [];
if (activeHOKs > 0) {
for (var j = 0; j < activeHOKs; j++) {
hokEffect.push("netDamage");
}
approachEffects.push(hokEffect);
}
//currently assumes the only cards that would prevent breach are installed Runner cards
var breach = !runnerAI._breachWouldBePrevented(installedRunnerCards,data.server);
//costs etc that may apply if breaching:
if (breach) {
for (var i = 0; i < data.server.root.length; i++) {
if (data.server.root[i].rezzed || data.server.root[i].knownToRunner)
knownCardsInRoot.push(data.server.root[i]);
else {
var advancement = Counters(data.server.root[i], "advancement");
if (advancement > 4 && corp.identityCard.faction == "Weyland Consortium") {
//might be Clearinghouse, in which case need to be able to pay trashcost
approachCredits += 3;
//maybe can pay with Carnivore?
var carn = runnerAI._copyOfCardExistsIn('Carnivore',runner.rig.hardware);
if (carn)
{
if (!carn.usedThisTurn) approachCredits -= 3;
}
}
else if (advancement > 0) {
//might be Urtica, in which case might do net damage (no need to trash it)
var approachEffect = [];
for (var j = 0; j < 2 + advancement; j++) {
approachEffect.push("netDamage");
}
approachEffects.push(approachEffect);
}
else numUnknownCardsInRoot++;
}
}
//simple check (not comprehensive, that would be complex e.g. random access, R&D could be shuffled, etc)
var mightAccessAnAgenda = true;
if (typeof data.server.cards == 'undefined' && knownCardsInRoot.length == data.server.root.length) {
mightAccessAnAgenda = false;
for (var i = 0; i < data.server.root.length; i++) {
if (CheckCardType(data.server.root[i], ["agenda"])) {
mightAccessAnAgenda = true;
break;
}
}
}
//if Corp is Jinteki:PE, unless all cards are known to be non-agenda or steal would win, account for min 1 net damage
if (mightAccessAnAgenda && corp.identityCard.title=="Jinteki: Personal Evolution") {
if (AgendaPoints(runner) + 1 < AgendaPointsToWin()) {
//skip this if net damage is already being assumed
var alreadyNetDamage = false;
for (var i=0; i<approachEffects.length; i++) {
if (approachEffects[i].includes("netDamage")) {
alreadyNetDamage = true;
break;
}
}
if (!alreadyNetDamage) {
approachEffects.push(["netDamage"]);
}
}
}
//effects from upgrade
var mightHitHokusai = false;
if (numUnknownCardsInRoot > 0) mightHitHokusai = true;
else {
for (var i = 0; i < data.server.root.length; i++) {
if (data.server.root[i].title == "Hokusai Grid") {
mightHitHokusai = true;
break;
}
}
}
if (mightHitHokusai) approachEffects.push(["netDamage"]);
//calculate any required trash payment, taking into account potential discount (just considering max for one known card trash cost with just one discounting ability atm)
//note cards in server (e.g. in corp hand) are not considered atm
var highestTrashCost = 0;
var htcCard = null;
for (var i = 0; i < knownCardsInRoot.length; i++) {
//special case: Urtica Cipher: no need to include trash cost but account for net damage
if (knownCardsInRoot[i].title == "Urtica Cipher") {
var approachEffect = [];
var advancement = Counters(knownCardsInRoot[i], "advancement");
for (var j = 0; j < 2 + advancement; j++) {
approachEffect.push("netDamage");
}
approachEffects.push(approachEffect);
}
//check trash cost
else if (typeof knownCardsInRoot[i].trashCost !== "undefined") {
var kctc = TrashCost(knownCardsInRoot[i]);
if (kctc > highestTrashCost) {
highestTrashCost = kctc;
htcCard = knownCardsInRoot[i];
}
}
}
var highestTrashDiscount = 0;
if (htcCard) {
for (var i=0; i<installedRunnerCards.length; i++) {
if (typeof installedRunnerCards[i].AIReducesTrashCost == "function") {
var ictd = installedRunnerCards[i].AIReducesTrashCost.call(installedRunnerCards[i],htcCard);
if (ictd > highestTrashDiscount) highestTrashDiscount = ictd;
}
}
}
approachCredits += highestTrashCost - highestTrashDiscount;
}
//combine approach costs
data.approachOptions = [
{
clicks: approachClicks,
credits: approachCredits,
effects: approachEffects,
tags: approachTags,
},
];
//Manegarm creates additional path forks
if (
runnerAI._copyOfCardExistsIn("Manegarm Skunkworks", knownCardsInRoot)
) {
//create a fork
data.approachOptions.push({
clicks: approachClicks,
credits: approachCredits,
effects: approachEffects,
tags: approachTags,
});
//add Manegarm tax to the fork costs
data.approachOptions[0].clicks += 2;
data.approachOptions[1].credits += 5;
}
}
//if there is only one approach option and it does damage, we'll treat the damage as a limit until approach time
if (data.approachOptions.length == 1) {
var totalApproachEffect = this.TotalEffect(data.approachOptions[0]);
var totalApproachDamage = this.TotalDamage(totalApproachEffect);