-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainFile.cs
More file actions
1250 lines (1111 loc) · 46.9 KB
/
MainFile.cs
File metadata and controls
1250 lines (1111 loc) · 46.9 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
using AutoPlay.Config;
using Godot;
using HarmonyLib;
using MegaCrit.Sts2.Core.CardSelection;
using MegaCrit.Sts2.Core.Combat;
using MegaCrit.Sts2.Core.Combat.History.Entries;
using MegaCrit.Sts2.Core.Commands;
using MegaCrit.Sts2.Core.Context;
using MegaCrit.Sts2.Core.Entities.Cards;
using MegaCrit.Sts2.Core.Entities.Creatures;
using MegaCrit.Sts2.Core.Entities.Players;
using MegaCrit.Sts2.Core.Entities.Potions;
using MegaCrit.Sts2.Core.Extensions;
using MegaCrit.Sts2.Core.GameActions;
using MegaCrit.Sts2.Core.GameActions.Multiplayer;
using MegaCrit.Sts2.Core.Hooks;
using MegaCrit.Sts2.Core.Logging;
using MegaCrit.Sts2.Core.Modding;
using MegaCrit.Sts2.Core.Models;
using MegaCrit.Sts2.Core.Models.Cards;
using MegaCrit.Sts2.Core.Models.Monsters;
using MegaCrit.Sts2.Core.Models.Potions;
using MegaCrit.Sts2.Core.Models.Powers;
using MegaCrit.Sts2.Core.Models.Relics;
using MegaCrit.Sts2.Core.MonsterMoves.Intents;
using MegaCrit.Sts2.Core.Nodes.Cards.Holders;
using MegaCrit.Sts2.Core.Nodes.Combat;
using MegaCrit.Sts2.Core.Nodes.Debug;
using MegaCrit.Sts2.Core.Nodes.Potions;
using MegaCrit.Sts2.Core.Nodes.Rooms;
using MegaCrit.Sts2.Core.Rooms;
using MegaCrit.Sts2.Core.Runs;
using System.Reflection;
using System.Text.Json;
using Logger = MegaCrit.Sts2.Core.Logging.Logger;
namespace AutoPlay;
public static class ModSettings
{
public static bool AutomaticDiscard { get; set; } = true;
public static bool AutomaticExhaust { get; set; } = true;
public static bool AutomaticSelect { get; set; } = true;
public static bool AutomaticRetain { get; set; } = true;
public static bool HardSelect { get; set; } = true;
}
public class AutoPlayConfigData
{
public bool AutomaticDiscard { get; set; } = true;
public bool AutomaticExhaust { get; set; } = true;
public bool AutomaticSelect { get; set; } = true;
public bool AutomaticRetain { get; set; } = true;
public bool HardSelect { get; set; } = true;
}
[ModInitializer(nameof(Initialize))]
public partial class MainFile : Node
{
private const string ModId = "AutoPlay";
private static Logger Logger { get; } = new(ModId, LogType.Generic);
public static void Initialize()
{
Harmony harmony = new(ModId);
harmony.PatchAll();
if (File.Exists("mods/AutoPlay.json"))
{
var json = File.ReadAllText("mods/AutoPlay.json");
var data = JsonSerializer.Deserialize<AutoPlayConfigData>(json);
if (data != null)
{
ModSettings.AutomaticDiscard = data.AutomaticDiscard;
ModSettings.AutomaticExhaust = data.AutomaticExhaust;
ModSettings.AutomaticSelect = data.AutomaticSelect;
ModSettings.AutomaticRetain = data.AutomaticRetain;
ModSettings.HardSelect = data.HardSelect;
}
}
ModConfigBridge.DeferredRegister();
Log("Initialized");
}
public static void Log(string message, LogLevel level = LogLevel.Info, int skipFrames = 1)
{
Logger.LogMessage(level, $"[{ModId}] {message}", skipFrames);
try
{
var console = NDevConsole.Instance;
var outputBufferField =
typeof(NDevConsole).GetField("_outputBuffer", BindingFlags.NonPublic | BindingFlags.Instance);
if (outputBufferField?.GetValue(console) is not RichTextLabel outputBuffer) return;
outputBuffer.Text += $"[color=#00ffff][{ModId}][/color] {message}";
outputBuffer.Text += "\n";
}
catch
{
// Console might not be initialized yet
}
}
}
[HarmonyPatch]
public class Patch
{
[HarmonyPatch(typeof(NCombatUi), "_Input")]
[HarmonyPostfix]
private static void GameInputHook(InputEvent inputEvent)
{
if (!ModSettings.HardSelect || inputEvent is not InputEventKey keyEvent || !keyEvent.Pressed || keyEvent.Echo || keyEvent.Keycode != Key.Tab || keyEvent.AltPressed || keyEvent.CtrlPressed || NDevConsole.Instance.Visible) return;
if (NPlayerHand.Instance?.InCardPlay != false || NTargetManager.Instance.IsInSelection || CombatManager.Instance.IsOverOrEnding || NCombatRoom.Instance == null || ModState.TargettedEnemy == null || ModState.TargettedEnemy.Entity.CombatState == null) return;
var enemies = ModState.TargettedEnemy.Entity.CombatState.HittableEnemies;
int index = enemies.IndexOf(ModState.TargettedEnemy.Entity);
if (index >= 0 && enemies.Count > 0)
{
for (int th = 1; th <= enemies.Count; th++)
{
int nextIndex = (keyEvent.ShiftPressed ? (index - th + enemies.Count) : (index + th)) % enemies.Count;
var nextEnemy = enemies[nextIndex];
if (nextEnemy.IsAlive)
{
var enemy_node = NCombatRoom.Instance.GetCreatureNode(nextEnemy);
if (enemy_node != null)
{
ModState.DoNotHideReticle = false;
ModState.TargettedEnemy.HideSingleSelectReticle();
ModState.TargettedEnemy = enemy_node;
ModState.TargettedEnemy.ShowSingleSelectReticle();
ModState.DoNotHideReticle = true;
}
break;
}
}
}
}
[HarmonyPatch(typeof(NCreatureVisuals), "_Ready")]
[HarmonyPostfix]
private static void NCreatureVisuals_Ready(NCreatureVisuals __instance)
{
if (__instance == null) return;
var parent = __instance.GetParent<NCreature>();
if (parent?.Hitbox != null && parent.Entity.IsMonster && !parent.Entity.IsPet && parent.Entity.IsAlive)
{
parent.Hitbox.GuiInput += (inputEvent) =>
{
if ((inputEvent is InputEventMouseButton mouse && mouse.Pressed && !mouse.DoubleClick && mouse.ButtonIndex == MouseButton.Left) || (inputEvent is InputEventScreenTouch touch && touch.Pressed && !touch.DoubleTap))
{
if (NTargetManager.Instance.IsInSelection || CombatManager.Instance.IsOverOrEnding || Time.GetTicksMsec() < ModState.IgnoreEnemyClickUntilMs) return;
if (ModState.DoNotHideReticle != true)
{
ModState.TargettedEnemy?.HideSingleSelectReticle();
parent.ShowSingleSelectReticle();
ModState.DoNotHideReticle = true;
ModState.TargettedEnemy = parent;
}
else
{
ModState.DoNotHideReticle = false;
ModState.TargettedEnemy?.HideSingleSelectReticle();
if (parent != ModState.TargettedEnemy)
{
parent.ShowSingleSelectReticle();
ModState.DoNotHideReticle = true;
ModState.TargettedEnemy = parent;
}
else
{
ModState.TargettedEnemy = null;
}
}
}
};
}
}
[HarmonyPatch(typeof(NCombatRoom), nameof(NCombatRoom._Ready))]
[HarmonyPostfix]
private static void CombatRoomEnter(NCombatRoom __instance)
{
if (__instance != null && __instance.Mode == CombatRoomMode.ActiveCombat && ModState.TargettedEnemy != null)
{
ModState.DoNotHideReticle = false;
ModState.TargettedEnemy.HideSingleSelectReticle();
ModState.TargettedEnemy = null;
}
}
[HarmonyPatch(typeof(NCreature), nameof(NCreature.HideSingleSelectReticle))]
[HarmonyPrefix]
private static bool HideSingleSelectReticle(NCreature __instance)
{
return !ModSettings.HardSelect || ModState.TargettedEnemy != __instance || !ModState.DoNotHideReticle;
}
[HarmonyPatch(typeof(NCreature), "StartDeathAnim")]
[HarmonyPostfix]
private static void CreatureStartDeathAnim(NCreature __instance)
{
if (ModState.TargettedEnemy != null && ModState.TargettedEnemy == __instance)
{
ModState.DoNotHideReticle = false;
ModState.TargettedEnemy.HideSingleSelectReticle();
ModState.TargettedEnemy = null;
}
}
[HarmonyPrefix]
[HarmonyPatch(typeof(NMouseCardPlay), "TargetSelection")]
private static bool TargetSelection(NMouseCardPlay __instance, ref Task __result)
{
var card = AccessTools.PropertyGetter(typeof(NCardPlay), "Card")?.Invoke(__instance, null) as CardModel;
if (card == null) return true;
if (!IsAutoPlayable(card)) return true;
// manually set _target if type == AnyEnemy
if (card is { TargetType: TargetType.AnyEnemy })
{
var target = card.CombatState?.HittableEnemies[0];
if (target is null) return true;
else if(ModSettings.HardSelect && ModState.TargettedEnemy != null && !ModState.TargettedEnemy.Entity.IsDead)
{
target = ModState.TargettedEnemy.Entity;
}
AccessTools.Field(typeof(NMouseCardPlay), "_target").SetValue(__instance, target);
}
// MegaCrit sets _target for All other types in IsAutoPlayable()
__result = Task.CompletedTask;
return false;
}
[HarmonyPrefix]
[HarmonyPatch(typeof(NControllerCardPlay), "Start")]
private static bool TargetSelection_Controller(NControllerCardPlay __instance)
{
var card = AccessTools.PropertyGetter(typeof(NCardPlay), "Card")?.Invoke(__instance, null) as CardModel;
if (__instance.Holder?.CardNode == null || !IsAutoPlayable(card)) return true;
if (card is { TargetType: TargetType.AnyEnemy })
{
var target = card.CombatState?.HittableEnemies[0];
if (target is null) return true;
else if (ModSettings.HardSelect && ModState.TargettedEnemy != null && !ModState.TargettedEnemy.Entity.IsDead)
{
target = ModState.TargettedEnemy.Entity;
}
AccessTools.Method(typeof(NCardPlay), "TryShowEvokingOrbs")?.Invoke(__instance, null);
__instance.Holder.CardNode.CardHighlight.AnimFlash();
AccessTools.Method(typeof(NCardPlay), "TryPlayCard")?.Invoke(__instance, [target]);
return false;
}
return false;
}
[HarmonyPrefix]
[HarmonyPatch(typeof(NMouseCardPlay), "IsCardInPlayZone")]
private static bool IsCardInPlayZone(ref bool __result)
{
__result = true;
return false;
}
[HarmonyPatch(typeof(NPlayerHand), "StartCardPlay")]
private static void StartCardPlay(NHandCardHolder holder, ref bool startedViaShortcut)
{
if (IsAutoPlayable(holder.CardModel)) startedViaShortcut = true;
}
[HarmonyPatch(typeof(NHandCardHolder), "OnFocus")]
[HarmonyPostfix]
private static void CardOnFocus(NHandCardHolder __instance)
{
if (__instance == null || __instance.CardModel == null || __instance?.CardModel.CombatState == null || __instance.CardModel.CombatState.HittableEnemies.Count == 0) return;
if ((__instance.CardModel.TargetType == TargetType.AnyEnemy && IsAutoPlayable(__instance.CardModel)) || (__instance.CardModel.TargetType == TargetType.AllEnemies || __instance.CardModel.TargetType == TargetType.RandomEnemy && __instance.CardModel.CombatState.HittableEnemies.Count(enemy => enemy.IsAlive) == 1))
{
var target = __instance.CardModel.CombatState.HittableEnemies[0];
if (target is null) return;
else if (ModSettings.HardSelect && ModState.TargettedEnemy != null && !ModState.TargettedEnemy.Entity.IsDead)
{
target = ModState.TargettedEnemy.Entity;
}
__instance.CardNode?.SetPreviewTarget(target);
}
else if(__instance.CardModel.TargetType == TargetType.AnyEnemy || __instance.CardModel.TargetType == TargetType.AllEnemies || __instance.CardModel.TargetType == TargetType.RandomEnemy)
{
int num_enemies = 0, num_enemies_with_same_damage_modifiers = 0;
Creature? first = null;
bool is_vulnerable = false, is_debilitated = false, is_fluttery = false, is_slippery = false;
int hardtokill_amount = 0, Hardenedshell_amount = 99;
foreach (Creature enemy in __instance.CardModel.CombatState.HittableEnemies)
{
if(enemy.IsAlive)
{
num_enemies++;
if (enemy.HasPower<VulnerablePower>() || enemy.HasPower<HardToKillPower>() || enemy.HasPower<FlutterPower>() || enemy.HasPower<SlipperyPower>() || enemy.HasPower<HardenedShellPower>())
{
if (first == null)
{
first = enemy;
num_enemies_with_same_damage_modifiers++;
is_vulnerable = enemy.HasPower<VulnerablePower>();
is_debilitated = enemy.HasPower<DebilitatePower>();
hardtokill_amount = enemy.GetPowerAmount<HardToKillPower>();
Hardenedshell_amount = 99;
var hardenedShell = enemy.GetPower<HardenedShellPower>();
if (hardenedShell != null)
{
Hardenedshell_amount = hardenedShell.DisplayAmount;
}
is_fluttery = enemy.HasPower<FlutterPower>();
is_slippery = enemy.HasPower<SlipperyPower>();
}
else if(enemy.HasPower<SlipperyPower>() == is_slippery && enemy.HasPower<VulnerablePower>() == is_vulnerable && enemy.GetPowerAmount<HardToKillPower>() == hardtokill_amount && enemy.HasPower<FlutterPower>() == is_fluttery && (enemy.GetPower<HardenedShellPower>()?.DisplayAmount ?? 99) == Hardenedshell_amount && (!is_vulnerable || is_debilitated == enemy.HasPower<SlipperyPower>()))
{
num_enemies_with_same_damage_modifiers++;
}
}
}
}
if (num_enemies_with_same_damage_modifiers > 0 && num_enemies_with_same_damage_modifiers == num_enemies)
{
__instance.CardNode?.SetPreviewTarget(first);
}
else
{
__instance?.CardNode?.SetPreviewTarget(null);
}
}
}
[HarmonyPrefix]
[HarmonyPatch(typeof(NPotionHolder), "OnRelease")]
private static bool OnPotionClicked(NPotionHolder __instance)
{
if (__instance?.Potion?.Model.Owner.Creature.CombatState == null || CombatManager.Instance.IsOverOrEnding) return true;
var isUsable_field = AccessTools.Field(typeof(NPotionHolder), "_isUsable");
var isUsable_value = isUsable_field.GetValue(__instance);
if (isUsable_value == null || (bool)isUsable_value == false) return true;
if (__instance.Potion.Model.Usage != PotionUsage.Automatic && __instance.Potion.Model.Id.Entry != "FOUL_POTION")//automatically use every potion except Foul Potion when clicked at them in combat since there is no reason to discard
{
__instance.UsePotion();
return false;
}
return true;
}
[HarmonyPrefix]
[HarmonyPatch(typeof(NPotionHolder), "UsePotion")]
private static bool UsePotion(NPotionHolder __instance, ref Task __result)
{
PotionModel? potion = __instance.Potion?.Model;
if (potion == null || potion.Usage == PotionUsage.Automatic) return true;
if (!IsAutoPlayable(potion)) return true;
var target = potion.Owner.Creature.CombatState?.HittableEnemies[0];
if (target is null) return true;
else if (ModSettings.HardSelect && ModState.TargettedEnemy != null && !ModState.TargettedEnemy.Entity.IsDead)
{
target = ModState.TargettedEnemy.Entity;
}
potion.EnqueueManualUse(target);
__result = Task.CompletedTask;
return false;
}
[HarmonyPrefix]
[HarmonyPatch(typeof(WellLaidPlansPower), "BeforeFlushLate")]
private static bool BeforeFlushLate(WellLaidPlansPower __instance, PlayerChoiceContext choiceContext, Player player, ref Task __result)
{
if (!ModSettings.AutomaticRetain) return true;
if (player != __instance.Owner.Player) return true;
CardPile handPile = PileType.Hand.GetPile(__instance.Owner.Player);
if (handPile.Cards.Count == 0) return true;
else if (handPile.Cards.Count <= __instance.Amount)//if the number of remaining cards is same or lower than required amount to choose, choose them all automatically, unless they are unplayable
{
foreach (CardModel item in handPile.Cards)
{
if ((item.Type <= CardType.Power || item is FranticEscape) && !item.Keywords.Contains(CardKeyword.Retain) && !item.Keywords.Contains(CardKeyword.Ethereal))
{
item.GiveSingleTurnRetain();
}
}
__result = Task.CompletedTask;
return false;
}
CardModel first = handPile.Cards[0];
for (int th = 0; th < handPile.Cards.Count; th++)
{
if (!CardsEqual(first, handPile.Cards[th]))
{
return true;
}
}
//if all remaining cards are identical, it will retain required amount automatically
int num_to_retain = __instance.Amount;
for (int th = 0; th < handPile.Cards.Count && num_to_retain > 0; th++)
{
CardModel card = handPile.Cards[th];
if ((card.Type <= CardType.Power || card is FranticEscape) && !card.Keywords.Contains(CardKeyword.Retain) && !card.Keywords.Contains(CardKeyword.Ethereal))
{
card.GiveSingleTurnRetain();
num_to_retain--;
}
}
__result = Task.CompletedTask;
return false;
}
[HarmonyPatch(typeof(CardModel), nameof(CardModel.OnPlayWrapper))]
[HarmonyPostfix]
private static void AfterCardPlayed(CardModel __instance, ref Task __result)
{
if (ModState.IgnoreCardPlay) return;
else if(NPlayerHand.Instance?.InCardPlay == true)
{
ModState.IgnoreCardPlay = true;
}
__result = AfterCardPlayedFinished(__result, __instance, NPlayerHand.Instance?.InCardPlay == true);
}
private static async Task AfterCardPlayedFinished(Task originalTask, CardModel __instance, bool cancel_cardplay_ignore)
{
ModState.IgnoreEnemyClickUntilMs = Time.GetTicksMsec() + 250;
await originalTask;
if (cancel_cardplay_ignore)
{
ModState.IgnoreCardPlay = false;
}
if (CombatManager.Instance.IsPlayPhase)
{
AutomaticEndTurn(__instance.Owner);
}
}
[HarmonyPatch(typeof(Hook), nameof(Hook.AfterPotionUsed))]
[HarmonyPostfix]
private static void AfterPotionUsed(PotionModel potion)
{
AutomaticEndTurn(potion.Owner);
}
[HarmonyPatch(typeof(Hook), nameof(Hook.AfterPotionDiscarded))]
[HarmonyPostfix]
private static void AfterPotionDiscarded(PotionModel potion)
{
if (CombatManager.Instance.IsPlayPhase)
{
AutomaticEndTurn(potion.Owner);
}
}
[HarmonyPatch(typeof(Hook), nameof(Hook.BeforePlayPhaseStart))]
[HarmonyPostfix]
private static void BeforePlayPhaseStart(CombatState combatState, Player player, ref Task __result)
{
__result = BeforePlayPhaseFinished(__result, combatState, player);
}
private static async Task BeforePlayPhaseFinished(Task originalTask, CombatState combatState, Player player)
{
await originalTask;
if (combatState.RoundNumber > 0 && LocalContext.NetId == player.NetId)
{
var relicPaelsEye = player.Relics.FirstOrDefault(relic => relic is PaelsEye);
if (relicPaelsEye != null)
{
var field = AccessTools.Field(typeof(PaelsEye), "_usedThisCombat");
var usedThisCombat = field.GetValue(relicPaelsEye);
if (usedThisCombat == null || (bool)usedThisCombat == false) return;
}
if (player.Relics.Any(relic => relic is PenNib or Nunchaku or TuningFork or IronClub or GalacticDust))//only end turn automatically if there are no card counting relics
{
return;
}
CardPile handPile = PileType.Hand.GetPile(player);
CardPile drawPile = PileType.Draw.GetPile(player);
CardPile discardPile = PileType.Discard.GetPile(player);
var all_reachable_cards = handPile.Cards.Concat(drawPile.Cards).Concat(discardPile.Cards);
if (all_reachable_cards.Any(card => card is Feed or TheHunt or HandOfGreed or Alchemize or NotYet && player.Creature.CurrentHp < player.Creature.MaxHp))
{
return;
}
int num_enemies_survive_this_turn = 0, num_minions_survive_this_turn = 0;
int damage_from_bomb = 0;
IReadOnlyList<Creature> allies = combatState.PlayerCreatures;
for (int th = 0; th < allies.Count; th++)
{
Creature ally = allies[th];
var bombPower = ally.GetPower<TheBombPower>();
if (bombPower != null && bombPower.Amount == 1)
{
damage_from_bomb += bombPower.DynamicVars.Damage.IntValue;
}
}
IReadOnlyList<Creature> enemies = combatState.Enemies;
for (int th = 0; th < enemies.Count; th++)
{
Creature enemy = enemies[th];
if (enemy.Monster?.Id.Entry == "DOOR") return;
int damage_from_poison = (enemy.GetPower<PoisonPower>()?.CalculateTotalDamageNextTurn() ?? 0);
if (enemy.IsAlive && (enemy.GetPowerAmount<StockPower>() > 0 || enemy.GetPowerAmount<SurprisePower>() > 0 || enemy.GetPowerAmount<InfestedPower>() > 0 || enemy.GetPowerAmount<SteamEruptionPower>() > 0 || enemy.GetPowerAmount<AdaptablePower>() > 0 || damage_from_poison + damage_from_bomb < enemy.CurrentHp))
{
num_enemies_survive_this_turn++;
if (enemy.HasPower<MinionPower>())
{
num_minions_survive_this_turn++;
}
}
}
if (num_enemies_survive_this_turn == 0 || num_enemies_survive_this_turn == num_minions_survive_this_turn)//no enemies will survive after turn started
{
int num_damage_received = 0;
for (int th = 0; th < handPile.Cards.Count; th++)
{
CardModel card = handPile.Cards[th];
if (card.Type > CardType.Power)
{
if (card.DynamicVars.ContainsKey("Damage"))
{
num_damage_received += card.DynamicVars.Damage.IntValue;
}
else if (card.DynamicVars.ContainsKey("HpLoss"))
{
num_damage_received += card.DynamicVars.HpLoss.IntValue;
}
}
}
num_damage_received += player.Creature.GetPowerAmount<DisintegrationPower>() + player.Creature.GetPowerAmount<ConstrictPower>();
int player_block = player.Creature.Block;
if (player_block == 0)
{
var relicOrichalcum = player.Relics.FirstOrDefault(relic => relic is Orichalcum);
if (relicOrichalcum != null)
{
player_block += relicOrichalcum.DynamicVars.Block.IntValue;
}
relicOrichalcum = player.Relics.FirstOrDefault(relic => relic is FakeOrichalcum);
if (relicOrichalcum != null)
{
player_block += relicOrichalcum.DynamicVars.Block.IntValue;
}
}
var relicCloakClaps = player.Relics.FirstOrDefault(relic => relic is CloakClasp);
if (relicCloakClaps != null)
{
player_block += handPile.Cards.Count;
}
var relicRipleBasin = player.Relics.FirstOrDefault(relic => relic is RippleBasin);
if (relicRipleBasin != null && !CombatManager.Instance.History.CardPlaysFinished.Any((CardPlayFinishedEntry e) => e.HappenedThisTurn(combatState) && e.CardPlay.Card.Type == CardType.Attack && e.CardPlay.Card.Owner == player))
{
player_block += relicRipleBasin.DynamicVars.Block.IntValue;
}
if (num_damage_received <= player_block + player.Creature.GetPowerAmount<PlatingPower>())
{
//we either have no damage debuffs or we can block them so no reason to play this round further
RunManager.Instance.ActionQueueSynchronizer.RequestEnqueue(new EndPlayerTurnAction(player, combatState.RoundNumber));
return;
}
}
}
}
[HarmonyPatch(typeof(NPlayerHand), nameof(NPlayerHand.SelectCards))]
public static class Patch_SelectCards
{
[HarmonyPrefix]
private static bool Prefix(NPlayerHand __instance, CardSelectorPrefs prefs, Func<CardModel, bool> filter, AbstractModel source, NPlayerHand.Mode mode, ref Task<IEnumerable<CardModel>> __result)
{
if (ModState.CurrentPlayer == null) return true;
bool IsDiscardTypeOfSelect = prefs.Prompt.LocEntryKey == "TO_DISCARD";
bool IsExhaustTypeOfSelect = prefs.Prompt.LocEntryKey == "TO_EXHAUST";
if (IsDiscardTypeOfSelect && !ModSettings.AutomaticDiscard) return true;
else if (IsExhaustTypeOfSelect && !ModSettings.AutomaticExhaust) return true;
else if (!IsExhaustTypeOfSelect && !IsDiscardTypeOfSelect && !ModSettings.AutomaticSelect) return true;
CardPile handPile = PileType.Hand.GetPile(ModState.CurrentPlayer);
var filteredPile = handPile.Cards.Where(c => filter == null || filter(c)).ToList();
if (filteredPile.Count == 0) return true;//if we have no cards, game already selects nothing by default, so we can leave it to original function
else if (prefs.MaxSelect == 999999999) return true;//Gambler's Brew potion
else if (prefs.RequireManualConfirmation || (!IsDiscardTypeOfSelect && prefs.MinSelect == 0)) return true;
var selected = new List<CardModel> { };
if (filteredPile.Count <= prefs.MinSelect)//if we have less cards than amount needed to select, select them automatically
{
for (int th = 0; th < filteredPile.Count; th++)
{
selected.Add(filteredPile[th]);
}
}
else if (IsDiscardTypeOfSelect)//discard selection
{
bool has_flechettes = handPile.Cards.Any(card => card is Flechettes && card.CanPlay());
bool has_any_exhaust_power_card = handPile.Cards.Any(card => (card is Brand || card is BurningPact || card is Scavenge || card is FlakCannon || card is SecondWind || card is Purity || card is Compact) && card.CanPlay());
List<CardModel> cards_to_discard_optimally = [];
for (int th = 0; th < filteredPile.Count; th++)
{
CardModel card = filteredPile[th];
bool can_be_played = card.CanPlay(out UnplayableReason reason, preventer: out _);
if (card.IsSlyThisTurn)
{
if (!has_flechettes || card.Type != CardType.Skill)//if Flechettes is in hand do not auto discard Sly cards unless they are not a skill
{
cards_to_discard_optimally.Add(card);
}
}
else if (card.Type > CardType.Power)
{
if (!has_any_exhaust_power_card && //only consider status cards if we can't exhaust or transform them this round
!card.Keywords.Contains(CardKeyword.Ethereal) && //if the status card is Ethereal then discarding it doesn't make a sense
card is not FranticEscape && (card is not Slimed || !can_be_played))//exclude Frantic Escape and Slimed
{
cards_to_discard_optimally.Add(card);
}
}
else if(card.Keywords.Contains(CardKeyword.Ethereal) && !can_be_played)//if it isn't Sly or status card and the card is ethereal and we can't play it then it should be optimal choice to discard it
{
cards_to_discard_optimally.Add(card);
}
else if(!can_be_played && ((reason & UnplayableReason.BlockedByHook) == UnplayableReason.BlockedByHook) && card.Affliction != null && card.Affliction.Id.Entry == "BOUND")//Bound cards are optimal to discard too
{
cards_to_discard_optimally.Add(card);
}
}
if (cards_to_discard_optimally.Count == prefs.MinSelect)//if there is only one Sly or stats card it will discard it automatically - should be always the most optimal choice
{
for (int th = 0; th < cards_to_discard_optimally.Count; th++)
{
selected.Add(cards_to_discard_optimally[th]);
}
}
else if (cards_to_discard_optimally.Count > prefs.MinSelect)
{
CardModel first = cards_to_discard_optimally[0];
for (int th = 1; th < cards_to_discard_optimally.Count; th++)
{
if (!CardsEqual(first, cards_to_discard_optimally[th]))
{
return true;
}
}
//if all optimally discardable cards are same, discard required amount automatically
int num_to_discard = prefs.MinSelect;
for (int th = 0; th < cards_to_discard_optimally.Count && num_to_discard > 0; th++)
{
selected.Add(cards_to_discard_optimally[th]);
num_to_discard--;
}
}
else
{
CardModel first = filteredPile[0];
for (int th = 1; th < filteredPile.Count; th++)
{
if (!CardsEqual(first, filteredPile[th]))
{
return true;
}
}
for (int th = 0; th < prefs.MinSelect; th++)
{
selected.Add(filteredPile[th]);
}
}
}
else if (IsExhaustTypeOfSelect)
{
List<CardModel> cards_to_exhaust_optimally = [];
for (int th = 0; th < filteredPile.Count; th++)
{
CardModel card = filteredPile[th];
if (!card.Keywords.Contains(CardKeyword.Ethereal) && ((card.Type > CardType.Power && card is not FranticEscape) || (card is Bombardment or HowlFromBeyond && !card.CanPlay())))
{
cards_to_exhaust_optimally.Add(card);
}
}
if (cards_to_exhaust_optimally.Count == prefs.MinSelect)
{
for (int th = 0; th < cards_to_exhaust_optimally.Count; th++)
{
selected.Add(cards_to_exhaust_optimally[th]);
}
}
else if (cards_to_exhaust_optimally.Count > prefs.MinSelect)//if all optimally exhaustable cards are same, exhaust required amount automatically
{
CardModel first = cards_to_exhaust_optimally[0];
for (int th = 1; th < cards_to_exhaust_optimally.Count; th++)
{
if (!CardsEqual(first, cards_to_exhaust_optimally[th]))
{
return true;
}
}
//if all optimally discardable cards are same, discard required amount automatically
int num_to_exhaust = prefs.MinSelect;
for (int th = 0; th < cards_to_exhaust_optimally.Count && num_to_exhaust > 0; th++)
{
selected.Add(cards_to_exhaust_optimally[th]);
num_to_exhaust--;
}
}
else
{
CardModel first = filteredPile[0];
for (int th = 1; th < filteredPile.Count; th++)
{
if (!CardsEqual(first, filteredPile[th]))
{
return true;
}
}
for (int th = 0; th < prefs.MinSelect; th++)
{
selected.Add(filteredPile[th]);
}
}
}
else//not discard nor exhaust selection - only select automatically when all cards in hand are identical
{
CardModel first = filteredPile[0];
for (int th = 1; th < filteredPile.Count; th++)
{
if (!CardsEqual(first, filteredPile[th]))
{
return true;
}
}
for (int th = 0; th < prefs.MinSelect; th++)
{
selected.Add(filteredPile[th]);
}
}
__result = Task.FromResult<IEnumerable<CardModel>>(selected);
return false;
}
}
[HarmonyPatch(typeof(NPlayerHand), "SelectCardInSimpleMode")]
[HarmonyPostfix]
private static void SelectCardInSimpleMode(NPlayerHand __instance)
{
var prefsField = Traverse.Create(__instance).Field<CardSelectorPrefs>("_prefs");
if (prefsField == null) return;
var prefs = prefsField.Value;
var selectedCards = Traverse.Create(__instance).Field<List<CardModel>>("_selectedCards").Value;
int selectedCount = selectedCards?.Count ?? 0;
if (prefs.MaxSelect < 1) return;
else if (selectedCards == null || selectedCount != prefs.MaxSelect) return;
// Press the confirm button to complete the selection
var confirmMethod = AccessTools.Method(__instance.GetType(), "OnSelectModeConfirmButtonPressed");
if (confirmMethod != null)
{
confirmMethod.Invoke(__instance, [null!]);
}
}
[HarmonyPatch(typeof(CardSelectCmd), nameof(CardSelectCmd.FromHand))]
[HarmonyPrefix]
private static void FromHand(PlayerChoiceContext context, Player player, CardSelectorPrefs prefs, Func<CardModel, bool>? filter, AbstractModel source)
{
ModState.CurrentPlayer = player;
}
[HarmonyPatch(typeof(CardSelectCmd), nameof(CardSelectCmd.FromSimpleGrid))]
[HarmonyPrefix]
private static bool FromSimpleGrid(PlayerChoiceContext context, IReadOnlyList<CardModel> cardsIn, Player player, CardSelectorPrefs prefs, ref Task<IEnumerable<CardModel>> __result)
{
if (!ModSettings.AutomaticDiscard) return true;
if (CombatManager.Instance.IsEnding) return true;
List<CardModel> cards = cardsIn.ToList();
if (!prefs.RequireManualConfirmation && cards.Count <= prefs.MinSelect)//if we have less cards than needed to select fall back to original function (it selects automatically)
{
return true;
}
CardModel first = cards[0];
for (int th = 1; th < cards.Count; th++)
{
if (!CardsEqual(first, cards[th]))
{
return true;
}
}
//if all remaining cards are identical, it will select required amount automatically
var selected = new List<CardModel> { };
for (int th = 0; th < prefs.MinSelect; th++)
{
selected.Add(cards[th]);
}
__result = Task.FromResult<IEnumerable<CardModel>>(selected);
return false;
}
private static void AutomaticEndTurn(Player player)
{
if (CombatManager.Instance.IsOverOrEnding || player.Creature.CombatState == null || LocalContext.NetId != player.NetId) return;
int damage_from_bomb = 0;
IReadOnlyList<Creature> allies = player.Creature.CombatState.PlayerCreatures;
for(int th = 0; th < allies.Count; th++)
{
Creature ally = allies[th];
var bombPower = ally.GetPower<TheBombPower>();
if (bombPower != null && bombPower.Amount == 1)
{
damage_from_bomb+= bombPower.DynamicVars.Damage.IntValue;
}
}
int num_enemies_survive_this_turn = 0, num_enemies_alive = 0, num_minions_survive_this_turn = 0, num_enemies_intends_attack = 0, num_weak_enemies = 0, num_damage_received = 0;
List<(Creature creature, int value)> remaining_enemies_alive = [];
bool doom_potion_useful = false;
bool no_draw = player.Creature.HasPower<NoDrawPower>();
IReadOnlyList<Creature> enemies = player.Creature.CombatState.Enemies;
for (int th = 0; th < enemies.Count; th++)
{
Creature enemy = enemies[th];
if (enemy.IsAlive || enemy.Monster is TestSubject) num_enemies_alive++;
else continue;
int damage_from_poison = (enemy.GetPower<PoisonPower>()?.CalculateTotalDamageNextTurn() ?? 0);
if (enemy.Monster is Doormaker || enemy.GetPowerAmount<StockPower>() > 0 || enemy.GetPowerAmount<SurprisePower>() > 0 || enemy.GetPowerAmount<InfestedPower>() > 0 || enemy.GetPowerAmount<SteamEruptionPower>() > 0 || enemy.GetPowerAmount<AdaptablePower>() > 0 || damage_from_poison + damage_from_bomb < enemy.CurrentHp)
{
num_enemies_survive_this_turn++;
int num_enemy_damage = 0;
if (enemy.HasPower<MinionPower>())
{
num_minions_survive_this_turn++;
}
if (enemy.HasPower<ScrutinyPower>())
{
no_draw = true;
}
if (enemy.GetPowerAmount<DoomPower>() < enemy.CurrentHp)
{
doom_potion_useful = true;
}
if (enemy.Monster?.IntendsToAttack == true)
{
num_enemies_intends_attack++;
if (enemy.GetPowerAmount<WeakPower>() > 0)
{
num_weak_enemies++;
}
foreach (var intent in enemy.Monster.NextMove.Intents)
{
if (intent is AttackIntent attackIntent)
{
num_enemy_damage += attackIntent.GetTotalDamage(allies, owner: enemy);
}
}
}
int hp_after_poison = enemy.CurrentHp - damage_from_poison - damage_from_bomb - enemy.GetPowerAmount<PlowPower>() - enemy.GetPowerAmount<ShriekPower>() + enemy.Block;
if (hp_after_poison > 0)
{
remaining_enemies_alive.Add((enemy, hp_after_poison));
num_damage_received += num_enemy_damage;
}
}
}
CardPile handPile = PileType.Hand.GetPile(player);
CardPile drawPile = PileType.Draw.GetPile(player);
CardPile discardPile = PileType.Discard.GetPile(player);
var all_reachable_cards = handPile.Cards.Concat(drawPile.Cards).Concat(discardPile.Cards);
for (int th = 0; th < handPile.Cards.Count; th++)
{
CardModel card = handPile.Cards[th];
if (card.Type > CardType.Power)
{
if (card.DynamicVars.ContainsKey("Damage"))
{
num_damage_received += card.DynamicVars.Damage.IntValue;
}
else if (card.DynamicVars.ContainsKey("HpLoss"))
{
num_damage_received += card.DynamicVars.HpLoss.IntValue;
}
}
}
num_damage_received += player.Creature.GetPowerAmount<DisintegrationPower>() + player.Creature.GetPowerAmount<ConstrictPower>();
int player_block = player.Creature.Block;
if (player_block == 0)
{
var relicOrichalcum = player.Relics.FirstOrDefault(relic => relic is Orichalcum);
if (relicOrichalcum != null)
{
player_block += relicOrichalcum.DynamicVars.Block.IntValue;
}
relicOrichalcum = player.Relics.FirstOrDefault(relic => relic is FakeOrichalcum);
if (relicOrichalcum != null)
{
player_block += relicOrichalcum.DynamicVars.Block.IntValue;
}
}
var relicCloakClaps = player.Relics.FirstOrDefault(relic => relic is CloakClasp);
if (relicCloakClaps != null)
{
player_block += handPile.Cards.Count;
}
var relicRipleBasin = player.Relics.FirstOrDefault(relic => relic is RippleBasin);
if (relicRipleBasin != null && !CombatManager.Instance.History.CardPlaysFinished.Any((CardPlayFinishedEntry e) => e.HappenedThisTurn(player.Creature.CombatState) && e.CardPlay.Card.Type == CardType.Attack && e.CardPlay.Card.Owner == player))
{
player_block += relicRipleBasin.DynamicVars.Block.IntValue;
}
num_damage_received -= player_block + player.Creature.GetPowerAmount<PlatingPower>();
if (num_enemies_survive_this_turn == 0 || num_enemies_survive_this_turn == num_minions_survive_this_turn)//no enemies will survive after this card was played
{
bool has_any_card_counting_relic = player.Relics.Any(relic => relic is PenNib or Nunchaku or TuningFork or IronClub or GalacticDust);
bool has_fatal_or_alchemize_card = all_reachable_cards.Any(card => card is Feed or TheHunt or HandOfGreed or Alchemize or NotYet && player.Creature.CurrentHp < player.Creature.MaxHp);
if (!has_fatal_or_alchemize_card && !has_any_card_counting_relic && num_damage_received <= 0)
{
//we either have no damage debuffs or we can block them so no reason to play this round further
RunManager.Instance.ActionQueueSynchronizer.RequestEnqueue(new EndPlayerTurnAction(player, player.Creature.CombatState.RoundNumber));
return;