using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using KernelPanic.Combat; using KernelPanic.Core; using KernelPanic.Data; using KernelPanic.Run; using KernelPanic.UI; using NUnit.Framework; using UnityEditor; using UnityEngine; public class CorruptionRecoveryTests { private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic; private GameObject owner; private CombatManager combat; private RunManager run; private CardDatabase database; private bool reducedMotion; private UnityEngine.Random.State unityRandom; private object combatRandom; private static readonly FieldInfo Rng = typeof(RandomRoll).GetField("_random", BindingFlags.Static | BindingFlags.NonPublic); private static object Call(object target, string method, params object[] args) => target.GetType().GetMethod(method, Private).Invoke(target, args); private static void Set(object target, string field, object value) => target.GetType().GetField(field, Private).SetValue(target, value); [SetUp] public void SetUp() { reducedMotion = UIPreferences.ReducedMotion; UIPreferences.ReducedMotion = true; unityRandom = UnityEngine.Random.state; combatRandom = Rng.GetValue(null); RandomRoll.Seed(91); database = AssetDatabase.LoadAssetAtPath("Assets/Data/Cards/CardDatabase.asset"); var distro = AssetDatabase.LoadAssetAtPath("Assets/Data/Distros/Gentoo.asset"); var config = new RunConfig(distro, Language.C, Language.Haskell, Array.Empty(), 91, 5); owner = new GameObject("Timed corruption regression"); run = owner.AddComponent(); combat = owner.AddComponent(); Call(combat, "OnDisable"); Call(combat, "Awake"); Call(combat, "OnEnable"); run.StartRun(config); Set(combat, "_runConfig", config); Set(combat, "_runManager", run); Set(combat, "_playerState", new CombatantState(100, 32, 100)); Set(combat, "_handController", new HandController(32)); Set(combat, "_turnNumberThisWave", 1); Set(combat, "currentPhase", TurnPhase.Execute); combat.PlayerState.Cycles = 100; combat.PlayerState.ForceMaxRolls = true; ((List)combat.Enemies).Add(new EnemyInstance("regression target", 10000, Array.Empty())); } [TearDown] public void TearDown() { Call(combat, "OnDisable"); UnityEngine.Object.DestroyImmediate(owner); UIPreferences.ReducedMotion = reducedMotion; UnityEngine.Random.state = unityRandom; Rng.SetValue(null, combatRandom); } private CardInstance Card(string id = "lang_c_malloc") => new(database.FindById(id)); private CardInstance Broken(bool timed = true) { var card = Card(); if (timed) card.CorruptForRounds(3, 1); else card.IsBroken = true; return card; } private static void Finish(IEnumerator routine) { int steps = 0; while (routine.MoveNext()) { Assert.That(++steps, Is.LessThan(1000)); if (routine.Current is IEnumerator child) Finish(child); } } private void NextRound() { Set(combat, "_skipNextAllocateDraw", true); Finish((IEnumerator)Call(combat, "AllocateTurnSequenced")); Set(combat, "currentPhase", TurnPhase.Execute); } [Test] public void SegfaultRecoversOnThirdFollowingRoundAndCannotBePlayedBeforeThen() { var card = Card(); combat.HandController.Add(card); Assert.That(combat.TryCorruptRandomHandCard("segfault"), Is.True); Assert.That(card.CorruptionRoundsRemaining, Is.EqualTo(3)); combat.SelectEnemy(0); Assert.That(combat.PlayCard(card), Is.False); Call(combat, "RecoverTimedCorruption"); Assert.That(card.CorruptionRoundsRemaining, Is.EqualTo(3), "Same-round UI/state callbacks cannot tick recovery"); NextRound(); Assert.That(card.CorruptionRoundsRemaining, Is.EqualTo(2)); NextRound(); Assert.That(card.CorruptionRoundsRemaining, Is.EqualTo(1)); Assert.That(card.IsBroken, Is.True); NextRound(); Assert.That(card.IsBroken, Is.False); Assert.That(card.CorruptionRoundsRemaining, Is.Zero); combat.SelectEnemy(0); Assert.That(combat.PlayCard(card), Is.True); } [TestCase(false)] [TestCase(true)] public void AllPilesAndGeneratedCopiesRecoverOncePerRealRound(bool motion) { UIPreferences.ReducedMotion = motion; var hand = Broken(); combat.HandController.Add(hand); ((List)run.RunDeck).Add(hand); // Same reference appears in two collections. var draw = Broken(); combat.DeckController.AddToDrawPile(draw, false); var discard = Broken(); combat.DeckController.Discard(discard); var exhaust = Broken(); combat.DeckController.Exhaust(exhaust); var queued = Broken(); combat.InterpreterQueue.Enqueue(queued); var lazy = Broken(); combat.LazyStack.Enqueue(lazy); var detached = Broken(); ((List)run.RunDeck).Add(detached); var copy = hand.CopyForCombat(); combat.HandController.Add(copy); var all = new[] { hand, draw, discard, exhaust, queued, lazy, detached, copy }; Assert.That(combat.CorruptedCardCount, Is.EqualTo(8)); NextRound(); foreach (var card in all) Assert.That(card.CorruptionRoundsRemaining, Is.EqualTo(2)); Call(combat, "RecoverTimedCorruption"); foreach (var card in all) Assert.That(card.CorruptionRoundsRemaining, Is.EqualTo(2)); NextRound(); NextRound(); Assert.That(combat.CorruptedCardCount, Is.Zero); Assert.That(all.All(card => !card.IsBroken), Is.True); Assert.That(combat.DeckController.ExhaustPile.Contains(exhaust), Is.True, "Repair must not un-exhaust cards"); Assert.That(combat.InterpreterQueue.Count, Is.EqualTo(1), "Recovery must not execute cards"); } [Test] public void ManualRepairsPrioritizeHandAndClearOnlyCorruption() { var draw = Broken(); combat.DeckController.AddToDrawPile(draw, false); var hand = Broken(false); combat.HandController.Add(hand); hand.IsLocked = true; hand.ApplyMagnitudeUpgrade(2); hand.ApplyCostUpgrade(-1); ((List)run.RunDeck).Add(hand); Assert.That(combat.RepairCorruptedCards(0), Is.Zero); Assert.That(combat.RepairCorruptedCards(1), Is.EqualTo(1)); Assert.That(hand.IsBroken, Is.False); Assert.That(draw.IsBroken, Is.True); Assert.That(hand.IsLocked, Is.True); Assert.That(hand.MagnitudeBonus, Is.EqualTo(2)); Assert.That(hand.PermanentCostDelta, Is.EqualTo(-1)); Assert.That(combat.RepairCorruptedCards(10), Is.EqualTo(1)); Assert.That(draw.CorruptionRoundsRemaining, Is.Zero); Assert.That(combat.RepairCorruptedCards(10), Is.Zero); hand.CorruptForRounds(3, 2); Assert.That(hand.AdvanceCorruptionRecovery(2), Is.False); Assert.That(hand.CorruptionRoundsRemaining, Is.EqualTo(3)); Assert.That(hand.AdvanceCorruptionRecovery(5), Is.True); } [Test] public void UntimedCorruptionStaysManualAndWaveResetClearsTimer() { var card = Card(); combat.HandController.Add(card); combat.TryCorruptRandomHandCard("custom corruption"); NextRound(); NextRound(); NextRound(); Assert.That(card.IsBroken, Is.True); Assert.That(card.CorruptionRoundsRemaining, Is.Zero); card.RepairCorruption(); card.CorruptForRounds(3, 4); card.ApplyMagnitudeUpgrade(2); ((List)run.RunDeck).Add(card); Finish((IEnumerator)Call(combat, "StartWaveSequenced", true)); Assert.That(card.IsBroken, Is.False); Assert.That(card.CorruptionRoundsRemaining, Is.Zero); Assert.That(card.MagnitudeBonus, Is.EqualTo(2)); } [TestCase("shop_c_gdb", 2, 0)] [TestCase("shop_c_gdb", 4, 2)] [TestCase("shop_c_valgrind", 3, 0)] [TestCase("shop_c_valgrind", 5, 2)] [TestCase("lang_c_printf", 1, 0)] [TestCase("shop_c_free", 1, 0)] public void RepairCardsAndAttackRidersRepairTheirDocumentedCount(string id, int repairs, int magnitude) { var card = Card(id); Assert.That(card.Definition, Is.Not.Null, id); if (magnitude > 0) card.ApplyMagnitudeUpgrade(magnitude); for (int i = 0; i < 6; i++) combat.HandController.Add(Broken(i % 2 == 0)); combat.HandController.Add(card); combat.Compilation.BeginWave(5); combat.Compilation.AdvanceFromEquipment(5, 1); combat.PlayerState.FlatEffectBonus = 10; // Repairs do not scale with damage/Shield buffs. combat.SelectEnemy(0); int uptime = combat.PlayerState.CurrentUptime; Assert.That(combat.PlayCard(card), Is.True); Assert.That(combat.CorruptedCardCount, Is.EqualTo(6 - repairs)); Assert.That(combat.PlayerState.CurrentUptime, Is.EqualTo(uptime), "Repair-only cards do not roll segfault"); } [Test] public void PrintfRepairRunsAfterItsOwnSegfaultRecoil() { var card = Card("lang_c_printf"); var victim = Card(); combat.HandController.Add(victim); combat.HandController.Add(card); combat.PlayerState.ForceMaxRolls = false; var log = new List(); combat.CombatLog += log.Add; combat.SelectEnemy(0); // Fixed damage skips an amount roll: crit is first, then segfault. int seed = Enumerable.Range(0, 10000).First(value => { var rng = new System.Random(value); rng.Next(1, 101); return rng.Next(1, 101) <= 25; }); RandomRoll.Seed(seed); Assert.That(combat.PlayCard(card), Is.True); Assert.That(log.Any(line => line.Contains("segfault: corrupted")), Is.True); Assert.That(combat.PlayerState.CurrentUptime, Is.EqualTo(97)); Assert.That(victim.IsBroken, Is.False); Assert.That(victim.CorruptionRoundsRemaining, Is.Zero); Assert.That(log.FindIndex(line => line.Contains("segfault: corrupted")), Is.LessThan(log.FindIndex(line => line.Contains("repair: restored")))); } [Test] public void EnemySegfaultUsesSameRecoveryTimer() { var card = Card(); combat.HandController.Add(card); var enemy = new EnemyInstance(EnemyArchetypeCatalog.Get("segfault"), 1); Call(combat, "ApplySegfaultDeathPayload", enemy); Assert.That(card.IsBroken, Is.True); Assert.That(card.CorruptionRoundsRemaining, Is.EqualTo(CombatTuning.SegfaultCorruptionRecoveryRounds)); Assert.That(combat.PlayerState.Statuses.Any(s => s.Type == StatusType.Segfault), Is.True); } [TestCase("lang_c_malloc", 25, true, 3)] [TestCase("lang_c_malloc", 26, false, 3)] [TestCase("shop_c_kernel_exploit", 50, true, 8)] [TestCase("shop_c_kernel_exploit", 51, false, 8)] public void SegfaultProbabilityBoundariesPreserveRecoilDamageAndThreeRoundRecovery( string id, int roll, bool triggers, int recoilDamage) { var played = Card(id); Assert.That(played.Definition, Is.Not.Null, id); var victim = Card(); combat.HandController.Add(victim); combat.PlayerState.ForceMaxRolls = false; var context = (CombatContext)Call(combat, "BuildContext", played, Array.Empty()); var recoil = typeof(CombatManager).Assembly.GetType("KernelPanic.Combat.SegfaultRecoil") .GetMethod("TryApply", BindingFlags.Static | BindingFlags.Public); int seed = Enumerable.Range(0, 10000).First(value => new System.Random(value).Next(1, 101) == roll); RandomRoll.Seed(seed); // Exercise the actual recoil hook after successful C damage, independently of the // attack's crit/amount rolls, so each boundary is the roll being tested. recoil.Invoke(null, new object[] { context, Language.C, true }); Assert.That(combat.PlayerState.CurrentUptime, Is.EqualTo(triggers ? 100 - recoilDamage : 100)); Assert.That(victim.IsBroken, Is.EqualTo(triggers)); Assert.That(victim.CorruptionRoundsRemaining, Is.EqualTo(triggers ? 3 : 0)); // A second damaging effect from the same play must not roll a second recoil. recoil.Invoke(null, new object[] { context, Language.C, true }); Assert.That(combat.PlayerState.CurrentUptime, Is.EqualTo(triggers ? 100 - recoilDamage : 100)); Assert.That(victim.CorruptionRoundsRemaining, Is.EqualTo(triggers ? 3 : 0)); if (!triggers) return; NextRound(); Assert.That(victim.IsBroken, Is.True); Assert.That(victim.CorruptionRoundsRemaining, Is.EqualTo(2)); NextRound(); Assert.That(victim.IsBroken, Is.True); Assert.That(victim.CorruptionRoundsRemaining, Is.EqualTo(1)); NextRound(); Assert.That(victim.IsBroken, Is.False); Assert.That(victim.CorruptionRoundsRemaining, Is.Zero); Assert.That(combat.PlayerState.CurrentUptime, Is.EqualTo(100 - recoilDamage), "Repairing a card does not refund recoil damage."); } }