Implement more QoL features and rebalances
This commit is contained in:
@@ -0,0 +1,373 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Run;
|
||||
using NUnit.Framework;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
public class CampaignTests
|
||||
{
|
||||
private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
private GameObject _owner;
|
||||
private RunManager _run;
|
||||
private CombatManager _combat;
|
||||
private CardDatabase _cards;
|
||||
private int _seed, _draws;
|
||||
|
||||
[SetUp]
|
||||
public void Setup()
|
||||
{
|
||||
_seed = RandomRoll.CurrentSeed; _draws = RandomRoll.DrawCount;
|
||||
_owner = new GameObject("campaign tests");
|
||||
_owner.SetActive(false);
|
||||
_run = _owner.AddComponent<RunManager>();
|
||||
_combat = _owner.AddComponent<CombatManager>();
|
||||
Call(_run, "OnEnable");
|
||||
Call(_combat, "Awake");
|
||||
_cards = AssetDatabase.LoadAssetAtPath<CardDatabase>("Assets/Data/Cards/CardDatabase.asset");
|
||||
var distro = AssetDatabase.LoadAssetAtPath<DistroDefinition>("Assets/Data/Distros/Ubuntu.asset");
|
||||
var config = new RunConfig(distro, Language.Python, Language.JavaScript, distro.ExclusiveCards.Take(4).ToArray(), 321);
|
||||
_run.StartRun(config);
|
||||
Set(_combat, "_runConfig", config);
|
||||
Set(_combat, "_playerState", new CombatantState(50, 6, 3) { CurrentUptime = 20 });
|
||||
Set(_combat, "currentPhase", TurnPhase.Execute);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
Call(_run, "OnDisable");
|
||||
UnityEngine.Object.DestroyImmediate(_owner);
|
||||
RandomRoll.Restore(_seed, _draws);
|
||||
}
|
||||
|
||||
[TestCase(1, "Boot diagnostics", 2)]
|
||||
[TestCase(2, "Firewall maintenance", 2)]
|
||||
[TestCase(3, "Process explosion", 3)]
|
||||
[TestCase(4, "Concurrency fault", 3)]
|
||||
[TestCase(5, "Kernel Overseer", 2)]
|
||||
public void AuthoredWavesIntroduceDistinctThreats(int wave, string title, int count)
|
||||
{
|
||||
int draws = RandomRoll.DrawCount;
|
||||
var plan = EncounterDirector.Plan(wave, WaveRoute.Repair);
|
||||
Assert.That(plan.Title, Is.EqualTo(title));
|
||||
Assert.That(plan.Enemies.Count, Is.EqualTo(count));
|
||||
Assert.That(plan.Enemies.All(id => EnemyArchetypeCatalog.Get(id).Id == id), Is.True);
|
||||
Assert.That(RandomRoll.DrawCount, Is.EqualTo(draws));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CampaignSpawnsPairedRacersAndTheRealBoss()
|
||||
{
|
||||
Set(_run, "currentWaveNumber", 4);
|
||||
Call(_combat, "SpawnEncounter");
|
||||
var pair = _combat.Enemies.Where(enemy => enemy.ArchetypeId == "race_condition").ToArray();
|
||||
Assert.That(pair.Length, Is.EqualTo(2));
|
||||
Assert.That(pair[0].PairId, Is.GreaterThanOrEqualTo(0));
|
||||
Assert.That(pair[1].PairId, Is.EqualTo(pair[0].PairId));
|
||||
((List<EnemyInstance>)_combat.Enemies).Clear();
|
||||
Set(_run, "currentWaveNumber", 5);
|
||||
Call(_combat, "SpawnEncounter");
|
||||
Assert.That(_combat.Enemies.Count(enemy => enemy.Archetype.Tier == EnemyTier.Boss), Is.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SeededVariantsAreStableAndDoNotConsumeCombatRandomness()
|
||||
{
|
||||
int draws = RandomRoll.DrawCount;
|
||||
for (int wave = 1; wave <= 5; wave++)
|
||||
{
|
||||
var titles = new HashSet<string>();
|
||||
for (int seed = 0; seed < 50; seed++)
|
||||
{
|
||||
var plan = EncounterDirector.Plan(wave, WaveRoute.Repair, seed, 1);
|
||||
titles.Add(plan.Title);
|
||||
Assert.That(EncounterDirector.Plan(wave, WaveRoute.Repair, seed, 1).Enemies, Is.EqualTo(plan.Enemies));
|
||||
Assert.That(plan.Enemies.All(id => EnemyArchetypeCatalog.Get(id).Id == id), Is.True);
|
||||
Assert.That(plan.Enemies.Count(id => id == "race_condition") % 2, Is.Zero);
|
||||
if (wave == 5) Assert.That(plan.Enemies.Count(id => id == "kernel_overseer"), Is.EqualTo(1));
|
||||
var elite = EncounterDirector.Plan(wave, WaveRoute.Challenge, seed, 1);
|
||||
if (wave > 1)
|
||||
{
|
||||
Assert.That(elite.Enemies.Take(plan.Enemies.Count), Is.EqualTo(plan.Enemies));
|
||||
Assert.That(elite.Enemies.Last(), Is.EqualTo("daemon"));
|
||||
if (elite.EscortShield > 0) Assert.That(elite.Advice, Does.Contain("6 Shield"));
|
||||
if (elite.EscortUptime > 0) Assert.That(elite.Advice, Does.Contain("+4 Uptime"));
|
||||
}
|
||||
}
|
||||
Assert.That(titles.Count, Is.EqualTo(3));
|
||||
Assert.That(EncounterDirector.Plan(wave, WaveRoute.Repair, 17, 0).Title,
|
||||
Is.EqualTo(EncounterDirector.Plan(wave, WaveRoute.Repair).Title));
|
||||
}
|
||||
Assert.That(RandomRoll.DrawCount, Is.EqualTo(draws));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BuildRewardBlocksDepartureAndOnlyUpgradesTheChosenCardOnce()
|
||||
{
|
||||
RepositoryAfter(2);
|
||||
Assert.That(_run.BuildRewardPending, Is.True);
|
||||
_run.PrepareNextEncounter(_combat.PlayerState);
|
||||
Assert.That(_run.RepositoryVisitActive, Is.True);
|
||||
_combat.ContinueToNextWave();
|
||||
Assert.That(_combat.AwaitingWaveContinue, Is.True);
|
||||
var chosen = _run.RunDeck[1];
|
||||
Assert.That(_run.ClaimBuildReward(new CardInstance(chosen.Definition), CardUpgradeKind.DrawRider), Is.False);
|
||||
Assert.That(_run.ClaimBuildReward(chosen, CardUpgradeKind.CostDown), Is.False);
|
||||
Assert.That(_run.ClaimBuildReward(chosen, CardUpgradeKind.DrawRider), Is.True);
|
||||
Assert.That(chosen.DrawRider, Is.EqualTo(1));
|
||||
Assert.That(_run.RunDeck[0].DrawRider, Is.Zero);
|
||||
Assert.That(_run.ClaimBuildReward(null, CardUpgradeKind.MagnitudeUp, true), Is.False);
|
||||
_run.PrepareNextEncounter(_combat.PlayerState);
|
||||
Assert.That(_run.RepositoryVisitActive, Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BuildRewardRoundTripsAndDoesNotReplayAfterClaimOrDuplicateClear()
|
||||
{
|
||||
RepositoryAfter(4);
|
||||
var journey = JsonUtility.FromJson<RunJourney>(JsonUtility.ToJson(_run.Journey));
|
||||
journey.Validate(5);
|
||||
Assert.That(journey.pendingRewardWave, Is.EqualTo(4));
|
||||
int bits = _run.Bits;
|
||||
Assert.That(_run.ClaimBuildReward(null, CardUpgradeKind.MagnitudeUp, true), Is.True);
|
||||
GameEvents.RaiseWaveCleared(new WaveClearedEvent(4));
|
||||
Assert.That(_run.BuildRewardPending, Is.False);
|
||||
Assert.That(_run.Bits, Is.EqualTo(bits + RunManager.BuildRewardBits));
|
||||
_run.Journey.Validate(5);
|
||||
journey.pendingRewardWave = 2;
|
||||
Assert.Throws<System.IO.InvalidDataException>(() => journey.Validate(5));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PrefetchPaysOnceRespectsCapacityAndCannotRunInRepositoryOrTutorial()
|
||||
{
|
||||
var hand = new HandController(6);
|
||||
Set(_combat, "_handController", hand);
|
||||
_combat.DeckController.Initialize(new[] { new CardInstance(_cards.FindById("lang_py_print")), new CardInstance(_cards.FindById("lang_py_print")) });
|
||||
_combat.PlayerState.Cycles = 6;
|
||||
Assert.That(_combat.TryPrefetch(), Is.True);
|
||||
Assert.That(hand.Cards.Count, Is.EqualTo(1));
|
||||
Assert.That(_combat.PlayerState.Cycles, Is.EqualTo(4));
|
||||
Assert.That(_combat.TryPrefetch(), Is.False);
|
||||
Set(_combat, "_prefetchUsed", false);
|
||||
hand.SetRamCapacity(2);
|
||||
int draws = RandomRoll.DrawCount;
|
||||
Assert.That(_combat.TryPrefetch(), Is.False, "Reserve enough RAM for a Java card without peeking.");
|
||||
Assert.That(RandomRoll.DrawCount, Is.EqualTo(draws));
|
||||
hand.SetRamCapacity(6);
|
||||
Set(_combat, "_awaitingWaveContinue", true);
|
||||
Assert.That(_combat.TryPrefetch(), Is.False);
|
||||
Set(_combat, "_awaitingWaveContinue", false);
|
||||
Set(_combat, "_runConfig", RunConfig.ForTutorial(_run.CurrentConfig.Distro, _run.CurrentConfig.StartingDeck, 1));
|
||||
Assert.That(_combat.TryPrefetch(), Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DaemonPicksThreeDistinctActionsReproduciblyAndHidesEveryNewIntent()
|
||||
{
|
||||
string Capture()
|
||||
{
|
||||
RandomRoll.Seed(51821);
|
||||
var daemon = new EnemyInstance(EnemyArchetypeCatalog.Get("daemon"), 14);
|
||||
var sequence = new List<string>();
|
||||
for (int round = 0; round < 48; round++)
|
||||
{
|
||||
daemon.PickNextIntent();
|
||||
Assert.That(daemon.IntentRevealed, Is.False);
|
||||
Assert.That(daemon.DisplayIntent.DisplayText, Is.EqualTo("? unknown ?"));
|
||||
var intent = daemon.CurrentIntent;
|
||||
int draws = RandomRoll.DrawCount;
|
||||
daemon.MarkDamaged();
|
||||
Assert.That(daemon.DisplayIntent, Is.EqualTo(intent));
|
||||
Assert.That(daemon.CurrentIntent, Is.EqualTo(intent), "Probing reveals; it never rerolls the action.");
|
||||
Assert.That(RandomRoll.DrawCount, Is.EqualTo(draws));
|
||||
sequence.Add(intent.DisplayLabel);
|
||||
daemon.MarkTurnSurvived();
|
||||
}
|
||||
Assert.That(sequence.Distinct(), Is.EquivalentTo(new[] { "surge", "harden", "bypass Shield" }));
|
||||
return string.Join(",", sequence);
|
||||
}
|
||||
Assert.That(Capture(), Is.EqualTo(Capture()));
|
||||
}
|
||||
|
||||
[TestCase(0)]
|
||||
[TestCase(1)]
|
||||
[TestCase(2)]
|
||||
public void DaemonActionsHaveDifferentDefensiveConsequences(int action)
|
||||
{
|
||||
var daemon = new EnemyInstance(EnemyArchetypeCatalog.Get("daemon"), 14);
|
||||
((List<EnemyInstance>)_combat.Enemies).Add(daemon);
|
||||
var intent = daemon.IntentPool[action];
|
||||
Set(daemon, "<CurrentIntent>k__BackingField", intent);
|
||||
_combat.PlayerState.Shield = 20;
|
||||
typeof(CombatManager).GetMethod("ExecuteEnemyIntent", Private).Invoke(_combat, new object[] { daemon, 0 });
|
||||
if (intent.Kind == EnemyIntentKind.Defend)
|
||||
{
|
||||
Assert.That(daemon.State.Shield, Is.InRange(6, 8));
|
||||
Assert.That(_combat.PlayerState.CurrentUptime, Is.EqualTo(20));
|
||||
Assert.That(_combat.PlayerState.Shield, Is.EqualTo(20));
|
||||
}
|
||||
else if (intent.TrueDamage)
|
||||
{
|
||||
Assert.That(_combat.PlayerState.CurrentUptime, Is.InRange(16, 17));
|
||||
Assert.That(_combat.PlayerState.Shield, Is.EqualTo(20), "Bypass ignores, rather than removes, Shield.");
|
||||
var text = typeof(KernelPanic.UI.CombatSceneController).GetMethod("IntentText", BindingFlags.Static | BindingFlags.NonPublic)
|
||||
.Invoke(null, new object[] { intent });
|
||||
Assert.That(text, Is.EqualTo("bypasses Shield"));
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.That(_combat.PlayerState.CurrentUptime, Is.EqualTo(20));
|
||||
Assert.That(_combat.PlayerState.Shield, Is.InRange(10, 12));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ShieldDamageRevealsDaemonButZeroDamageAndPreviewsDoNot()
|
||||
{
|
||||
var daemon = new EnemyInstance(EnemyArchetypeCatalog.Get("daemon"), 14);
|
||||
((List<EnemyInstance>)_combat.Enemies).Add(daemon);
|
||||
daemon.PickNextIntent(); daemon.State.Shield = 8;
|
||||
var observe = (Action<DamageDealtEvent>)Delegate.CreateDelegate(typeof(Action<DamageDealtEvent>), _combat,
|
||||
typeof(CombatManager).GetMethod("HandleEnemyDamageDealt", Private));
|
||||
GameEvents.DamageDealt += observe;
|
||||
try
|
||||
{
|
||||
int draws = RandomRoll.DrawCount;
|
||||
string hidden = ExecutionPreview.Build(_combat).Single(line => line.StartsWith("Daemon >"));
|
||||
Assert.That(hidden, Is.EqualTo("Daemon > ? unknown ?"));
|
||||
Assert.That(RandomRoll.DrawCount, Is.EqualTo(draws));
|
||||
Assert.That(daemon.IntentRevealed, Is.False);
|
||||
_combat.DamagePipeline.DealDamage(new DamageRequest(_combat.PlayerState, daemon.State, 0, Language.C, false, false));
|
||||
Assert.That(daemon.IntentRevealed, Is.False);
|
||||
_combat.DamagePipeline.DealDamage(new DamageRequest(_combat.PlayerState, daemon.State, 1, Language.C, false, false));
|
||||
Assert.That(daemon.CurrentUptime, Is.EqualTo(14));
|
||||
Assert.That(daemon.State.Shield, Is.EqualTo(7));
|
||||
Assert.That(daemon.IntentRevealed, Is.True);
|
||||
Assert.That(ExecutionPreview.Build(_combat), Does.Contain("Daemon > " + daemon.CurrentIntent.DisplayText));
|
||||
daemon.MarkTurnSurvived(); daemon.PickNextIntent();
|
||||
Assert.That(ExecutionPreview.Build(_combat), Does.Contain(hidden));
|
||||
}
|
||||
finally { GameEvents.DamageDealt -= observe; }
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BossCycleIsTelegraphedAndEnrageOnlyChangesFutureIntents()
|
||||
{
|
||||
var boss = new EnemyInstance(EnemyArchetypeCatalog.Get("kernel_overseer"), 40);
|
||||
int draws = RandomRoll.DrawCount;
|
||||
boss.PickNextIntent();
|
||||
Assert.That(boss.CurrentIntent.Kind, Is.EqualTo(EnemyIntentKind.Defend));
|
||||
boss.MarkTurnSurvived(); boss.PickNextIntent();
|
||||
Assert.That(boss.CurrentIntent.MinValue, Is.EqualTo(5));
|
||||
boss.State.CurrentUptime = 20;
|
||||
boss.MarkDamaged();
|
||||
Assert.That(boss.CurrentIntent.MinValue, Is.EqualTo(5), "Never silently strengthen an announced attack.");
|
||||
boss.MarkTurnSurvived(); boss.PickNextIntent();
|
||||
Assert.That(boss.CurrentIntent.MinValue, Is.EqualTo(13));
|
||||
Assert.That(boss.DisplayIntent.DisplayLabel, Does.Contain("overclocked"));
|
||||
boss.MarkTurnSurvived(); boss.PickNextIntent();
|
||||
Assert.That(boss.CurrentIntent.Kind, Is.EqualTo(EnemyIntentKind.Defend));
|
||||
Assert.That(RandomRoll.DrawCount, Is.EqualTo(draws));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RouteSelectionDoesNotHealAndDepartureRepairsOnlyOnce()
|
||||
{
|
||||
RepositoryAfter(1);
|
||||
Assert.That(_run.SelectRoute(WaveRoute.Challenge), Is.True);
|
||||
Assert.That(_run.SelectRoute(WaveRoute.Repair), Is.True);
|
||||
Assert.That(_combat.PlayerState.CurrentUptime, Is.EqualTo(20));
|
||||
_run.PrepareNextEncounter(_combat.PlayerState);
|
||||
_run.PrepareNextEncounter(_combat.PlayerState);
|
||||
Assert.That(_combat.PlayerState.CurrentUptime, Is.EqualTo(26));
|
||||
Assert.That(_run.SelectRoute(WaveRoute.Challenge), Is.False, "No changing route during combat.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ChallengeChangesEncounterAndPaysOneRewardOnlyAfterClear()
|
||||
{
|
||||
RepositoryAfter(1);
|
||||
_run.SelectRoute(WaveRoute.Challenge);
|
||||
_run.PrepareNextEncounter(_combat.PlayerState);
|
||||
Assert.That(_combat.PlayerState.CurrentUptime, Is.EqualTo(20));
|
||||
Assert.That(EncounterDirector.Plan(2, _run.Journey.activeRoute).Enemies.Last(), Is.EqualTo("daemon"));
|
||||
Assert.That(_run.RunDeck.Sum(card => card.DrawRider), Is.Zero);
|
||||
GameEvents.RaiseWaveCleared(new WaveClearedEvent(2));
|
||||
GameEvents.RaiseWaveCleared(new WaveClearedEvent(2));
|
||||
Assert.That(_run.Bits, Is.EqualTo(RunJourney.ChallengeBits));
|
||||
Assert.That(_run.RunDeck.Sum(card => card.DrawRider), Is.EqualTo(1));
|
||||
Assert.That(_run.CurrentWaveNumber, Is.EqualTo(3));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CompletedCampaignIsAVictoryAndCannotContinueOrCompleteTwice()
|
||||
{
|
||||
RepositoryAfter(5);
|
||||
Assert.That(_run.CampaignChoicePending, Is.True);
|
||||
_combat.ContinueToNextWave();
|
||||
Assert.That(_combat.AwaitingWaveContinue, Is.True);
|
||||
Assert.That(_combat.CompleteCampaign(), Is.True);
|
||||
Assert.That(_combat.RunCompleted, Is.True);
|
||||
Assert.That(_combat.RunLost, Is.False);
|
||||
Assert.That(_run.IsPlayerDead, Is.False);
|
||||
Assert.That(_run.IsRunActive, Is.False);
|
||||
Assert.That(_combat.CompleteCampaign(), Is.False);
|
||||
Assert.That(_combat.ContinueEndless(), Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EndlessIsExplicitAndKeepsTheSameRunAndRewards()
|
||||
{
|
||||
Assert.That(_run.EnterEndless(), Is.False);
|
||||
RepositoryAfter(5);
|
||||
string id = _run.RunId;
|
||||
int bandwidth = _run.AccruedBandwidth;
|
||||
Assert.That(_run.EnterEndless(), Is.True);
|
||||
Assert.That(_run.EnterEndless(), Is.False);
|
||||
Assert.That(_run.CampaignChoicePending, Is.False);
|
||||
Assert.That(_run.CurrentWaveNumber, Is.EqualTo(6));
|
||||
Assert.That(_run.AccruedBandwidth, Is.EqualTo(bandwidth));
|
||||
Assert.That(_run.RunId, Is.EqualTo(id));
|
||||
Assert.That(_run.RewardsSettled, Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PreviewUsesFifoThenLifoCapturedTargetsAndDoesNotConsumeAnything()
|
||||
{
|
||||
var enemy = new EnemyInstance(EnemyArchetypeCatalog.Get("memory_leak"), 20);
|
||||
((List<EnemyInstance>)_combat.Enemies).Add(enemy);
|
||||
enemy.PickNextIntent();
|
||||
var python = new CardInstance(_cards.FindById("lang_py_print"));
|
||||
var map = new CardInstance(_cards.FindById("lang_hs_map"));
|
||||
var thunk = new CardInstance(_cards.FindById("lang_hs_thunk"));
|
||||
foreach (var card in new[] { python, map, thunk }) card.SetTargetSnapshot(new[] { enemy.State });
|
||||
_combat.InterpreterQueue.Enqueue(python);
|
||||
_combat.LazyStack.Enqueue(map); _combat.LazyStack.Enqueue(thunk);
|
||||
int draws = RandomRoll.DrawCount;
|
||||
var lines = ExecutionPreview.Build(_combat);
|
||||
Assert.That(lines[1], Does.Contain(python.Definition.DisplayName).And.Contain("FIFO").And.Contain("Memory Leak"));
|
||||
Assert.That(lines[2], Does.Contain(thunk.Definition.DisplayName).And.Contain("LIFO x1.5"));
|
||||
Assert.That(lines[3], Does.Contain(map.Definition.DisplayName));
|
||||
Assert.That(ExecutionPreview.Build(_combat), Is.EqualTo(lines));
|
||||
Assert.That(RandomRoll.DrawCount, Is.EqualTo(draws));
|
||||
Assert.That(_combat.InterpreterQueue.Count, Is.EqualTo(1));
|
||||
Assert.That(_combat.LazyStack.Count, Is.EqualTo(2));
|
||||
Assert.That(enemy.CurrentUptime, Is.EqualTo(20));
|
||||
}
|
||||
|
||||
private void RepositoryAfter(int wave)
|
||||
{
|
||||
GameEvents.RaiseWaveCleared(new WaveClearedEvent(wave));
|
||||
Set(_combat, "_awaitingWaveContinue", true);
|
||||
_run.GenerateRepositoryOffers(_cards, null);
|
||||
}
|
||||
private static void Set(object obj, string name, object value) => obj.GetType().GetField(name, Private).SetValue(obj, value);
|
||||
private static void Call(object obj, string name) => obj.GetType().GetMethod(name, Private).Invoke(obj, null);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 19a89fe17af2495fa18661f1bd2a18e4
|
||||
@@ -0,0 +1,402 @@
|
||||
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 NUnit.Framework;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
public class CardCatalogTests
|
||||
{
|
||||
private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
private static CardDatabase Database => AssetDatabase.LoadAssetAtPath<CardDatabase>("Assets/Data/Cards/CardDatabase.asset");
|
||||
|
||||
// Migration snapshots taken from the previous factory before replacing its four independent
|
||||
// switches. These lock down every runtime constructor value, target rule and scaled rule text.
|
||||
private static IEnumerable AuthoredCases()
|
||||
{
|
||||
yield return new TestCaseData("gentoo_emerge_sync", "ShieldEffect|_amount=2;DrawEffect|_count=1", false, false, false,
|
||||
"stack: gain 2 Shield. draw 1.",
|
||||
"stack: gain 4 Shield. draw 3. [upgraded]").SetName("Catalog_preserves_gentoo_emerge_sync");
|
||||
yield return new TestCaseData("gentoo_ebuild", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=Haskell|_maxAmount=4|_minAmount=4|_trueDamage=False", true, false, false,
|
||||
"stack: deal 4.",
|
||||
"stack: deal 6. [upgraded]").SetName("Catalog_preserves_gentoo_ebuild");
|
||||
yield return new TestCaseData("gentoo_use_flags", "ShieldEffect|_amount=4;CompilationDrawEffect", false, false, false,
|
||||
"gain 4 Shield. if Compilation >= 2, draw 1.",
|
||||
"gain 6 Shield. if Compilation >= 2, draw 3. [upgraded]").SetName("Catalog_preserves_gentoo_use_flags");
|
||||
yield return new TestCaseData("gentoo_make_j4", "MakeJ4Effect", true, false, true,
|
||||
"deal 8; 11 if Compilation >= 3. one C hit; 50% of overkill spills per jump (rounded down); 25%: segfault, uptime -3 and corrupt a hand card.",
|
||||
"deal 10; 13 if Compilation >= 3. one C hit; 50% of overkill spills per jump (rounded down); 25%: segfault, uptime -3 and corrupt a hand card. [upgraded]").SetName("Catalog_preserves_gentoo_make_j4");
|
||||
yield return new TestCaseData("gentoo_emerge_world", "DealDamageEffect|_allEnemies=True|_canCrit=True|_language=Haskell|_maxAmount=3|_minAmount=3|_trueDamage=False;ShieldEffect|_amount=2", false, true, false,
|
||||
"stack: deal 3 to all living enemies. gain 2 Shield.",
|
||||
"stack: deal 5 to all living enemies. gain 4 Shield. [upgraded]").SetName("Catalog_preserves_gentoo_emerge_world");
|
||||
yield return new TestCaseData("lang_hs_map", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=Haskell|_maxAmount=2|_minAmount=2|_trueDamage=False", true, false, false,
|
||||
"stack: deal 2.",
|
||||
"stack: deal 4. [upgraded]").SetName("Catalog_preserves_lang_hs_map");
|
||||
yield return new TestCaseData("lang_hs_foldr", "ShieldEffect|_amount=3;DrawEffect|_count=1", false, false, false,
|
||||
"stack: gain 3 Shield. draw 1.",
|
||||
"stack: gain 5 Shield. draw 3. [upgraded]").SetName("Catalog_preserves_lang_hs_foldr");
|
||||
yield return new TestCaseData("lang_hs_thunk", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=Haskell|_maxAmount=4|_minAmount=4|_trueDamage=False", true, false, false,
|
||||
"stack: deal 4.",
|
||||
"stack: deal 6. [upgraded]").SetName("Catalog_preserves_lang_hs_thunk");
|
||||
yield return new TestCaseData("shop_hs_filter", "HaskellFilterEffect", true, false, false,
|
||||
"stack: deal 4; 6 if target has a harmful status. one hit.",
|
||||
"stack: deal 6; 8 if target has a harmful status. one hit. [upgraded]").SetName("Catalog_preserves_shop_hs_filter");
|
||||
yield return new TestCaseData("shop_hs_fmap", "ShieldEffect|_amount=2", false, false, false,
|
||||
"stack: gain 2 Shield.",
|
||||
"stack: gain 4 Shield. [upgraded]").SetName("Catalog_preserves_shop_hs_fmap");
|
||||
yield return new TestCaseData("shop_hs_zipwith", "DealDamageEffect|_allEnemies=True|_canCrit=True|_language=Haskell|_maxAmount=2|_minAmount=2|_trueDamage=False", false, true, false,
|
||||
"stack: deal 2 to all living enemies.",
|
||||
"stack: deal 4 to all living enemies. [upgraded]").SetName("Catalog_preserves_shop_hs_zipwith");
|
||||
yield return new TestCaseData("shop_hs_maybe", "HaskellMaybeEffect", false, false, false,
|
||||
"stack: if below maximum Uptime, restore 3 Uptime. otherwise gain 4 Shield.",
|
||||
"stack: if below maximum Uptime, restore 5 Uptime. otherwise gain 6 Shield. [upgraded]").SetName("Catalog_preserves_shop_hs_maybe");
|
||||
yield return new TestCaseData("shop_hs_sequence", "DrawEffect|_count=2", false, false, false,
|
||||
"stack: draw 2.",
|
||||
"stack: draw 4. [upgraded]").SetName("Catalog_preserves_shop_hs_sequence");
|
||||
yield return new TestCaseData("shop_hs_const", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=Haskell|_maxAmount=2|_minAmount=2|_trueDamage=False", true, false, false,
|
||||
"stack: deal 2.",
|
||||
"stack: deal 4. [upgraded]").SetName("Catalog_preserves_shop_hs_const");
|
||||
yield return new TestCaseData("shop_hs_scanl", "ShieldEffect|_amount=4;DrawEffect|_count=1", false, false, false,
|
||||
"stack: gain 4 Shield. draw 1.",
|
||||
"stack: gain 6 Shield. draw 3. [upgraded]").SetName("Catalog_preserves_shop_hs_scanl");
|
||||
yield return new TestCaseData("shop_hs_foldmap", "DealDamageEffect|_allEnemies=True|_canCrit=True|_language=Haskell|_maxAmount=4|_minAmount=4|_trueDamage=False", false, true, false,
|
||||
"stack: deal 4 to all living enemies.",
|
||||
"stack: deal 6 to all living enemies. [upgraded]").SetName("Catalog_preserves_shop_hs_foldmap");
|
||||
yield return new TestCaseData("shop_hs_deepseq", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=Haskell|_maxAmount=9|_minAmount=9|_trueDamage=False", true, false, false,
|
||||
"stack: deal 9.",
|
||||
"stack: deal 11. [upgraded]").SetName("Catalog_preserves_shop_hs_deepseq");
|
||||
yield return new TestCaseData("shop_hs_dollar_bang", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=Haskell|_maxAmount=5|_minAmount=5|_trueDamage=False;ShieldEffect|_amount=2", true, false, false,
|
||||
"stack: deal 5. gain 2 Shield.",
|
||||
"stack: deal 7. gain 4 Shield. [upgraded]").SetName("Catalog_preserves_shop_hs_dollar_bang");
|
||||
yield return new TestCaseData("lang_py_print", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=Python|_maxAmount=3|_minAmount=3|_trueDamage=False", false, false, false,
|
||||
"queue: deal 3.",
|
||||
"queue: deal 5. [upgraded]").SetName("Catalog_preserves_lang_py_print");
|
||||
yield return new TestCaseData("lang_py_import_antigravity", "DrawEffect|_count=2", false, false, false,
|
||||
"queue: draw 2.",
|
||||
"queue: draw 4. [upgraded]").SetName("Catalog_preserves_lang_py_import_antigravity");
|
||||
yield return new TestCaseData("lang_py_for_loop", "DealDamageEffect|_allEnemies=True|_canCrit=True|_language=Python|_maxAmount=2|_minAmount=2|_trueDamage=False", false, true, false,
|
||||
"queue: deal 2 to all enemies.",
|
||||
"queue: deal 4 to all enemies. [upgraded]").SetName("Catalog_preserves_lang_py_for_loop");
|
||||
yield return new TestCaseData("lang_js_console_log", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=JavaScript|_maxAmount=9|_minAmount=3|_trueDamage=False", true, false, true,
|
||||
"deal 3-9.",
|
||||
"deal 5-11. [upgraded]").SetName("Catalog_preserves_lang_js_console_log");
|
||||
yield return new TestCaseData("lang_js_fetch", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=JavaScript|_maxAmount=13|_minAmount=5|_trueDamage=False", true, false, true,
|
||||
"deal 5-13.",
|
||||
"deal 7-15. [upgraded]").SetName("Catalog_preserves_lang_js_fetch");
|
||||
yield return new TestCaseData("lang_rs_fn_main", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=Rust|_maxAmount=6|_minAmount=6|_trueDamage=False", true, false, true,
|
||||
"deal 6. overkill becomes shield.",
|
||||
"deal 8. overkill becomes shield. [upgraded]").SetName("Catalog_preserves_lang_rs_fn_main");
|
||||
yield return new TestCaseData("lang_rs_unwrap", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=Rust|_maxAmount=9|_minAmount=9|_trueDamage=False;DrawEffect|_count=1", true, false, true,
|
||||
"deal 9. overkill becomes shield. draw 1.",
|
||||
"deal 11. overkill becomes shield. draw 3. [upgraded]").SetName("Catalog_preserves_lang_rs_unwrap");
|
||||
yield return new TestCaseData("lang_rs_borrow", "ShieldEffect|_amount=5", false, false, false,
|
||||
"gain 5 shield.",
|
||||
"gain 7 shield. [upgraded]").SetName("Catalog_preserves_lang_rs_borrow");
|
||||
yield return new TestCaseData("lang_c_malloc", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=C|_maxAmount=12|_minAmount=12|_trueDamage=False", true, false, true,
|
||||
"deal 12. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card.",
|
||||
"deal 14. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card. [upgraded]").SetName("Catalog_preserves_lang_c_malloc");
|
||||
yield return new TestCaseData("lang_c_printf", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=C|_maxAmount=7|_minAmount=7|_trueDamage=False;RepairCorruptedCardsEffect|_count=1", true, false, true,
|
||||
"deal 7. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card. then repair up to 1 corrupted card in your active deck.",
|
||||
"deal 9. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card. then repair up to 3 corrupted cards in your active deck. [upgraded]").SetName("Catalog_preserves_lang_c_printf");
|
||||
yield return new TestCaseData("lang_c_pointer", "PreviousLanguageDamageEffect|_baseAmount=9|_language=C|_matchingAmount=15", true, false, true,
|
||||
"deal 9; 15 if the previous card was C. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card.",
|
||||
"deal 11; 17 if the previous card was C. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card. [upgraded]").SetName("Catalog_preserves_lang_c_pointer");
|
||||
yield return new TestCaseData("lang_java_public_static_main", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=Java|_maxAmount=7|_minAmount=7|_trueDamage=False", true, false, true,
|
||||
"uses 2 RAM. deal 7. overkill spills. JIT: Java cards cost 1 less this combat each time you play a Java card; discount decays by 1 after each wave.",
|
||||
"uses 2 RAM. deal 9. overkill spills. JIT: Java cards cost 1 less this combat each time you play a Java card; discount decays by 1 after each wave. [upgraded]").SetName("Catalog_preserves_lang_java_public_static_main");
|
||||
yield return new TestCaseData("lang_java_system_out_println", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=Java|_maxAmount=5|_minAmount=5|_trueDamage=False", true, false, true,
|
||||
"uses 2 RAM. deal 5. overkill spills. JIT applies; discount decays by 1 after each wave.",
|
||||
"uses 2 RAM. deal 7. overkill spills. JIT applies; discount decays by 1 after each wave. [upgraded]").SetName("Catalog_preserves_lang_java_system_out_println");
|
||||
yield return new TestCaseData("lang_java_new_object", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=Java|_maxAmount=3|_minAmount=3|_trueDamage=False", true, false, true,
|
||||
"uses 2 RAM. deal 3. overkill spills. JIT applies; discount decays by 1 after each wave.",
|
||||
"uses 2 RAM. deal 5. overkill spills. JIT applies; discount decays by 1 after each wave. [upgraded]").SetName("Catalog_preserves_lang_java_new_object");
|
||||
yield return new TestCaseData("ubuntu_ask_ubuntu", "AskUbuntuEffect", false, false, false,
|
||||
"queue: draw 2.",
|
||||
"queue: draw 4. [upgraded]").SetName("Catalog_preserves_ubuntu_ask_ubuntu");
|
||||
yield return new TestCaseData("ubuntu_unattended_upgrades", "ShieldEffect|_amount=4;ApplyStatusEffect|_duration=2|_skipNextTick=True|_stacks=4|_statusType=UnattendedUpgrades|_targetSelf=True", false, false, false,
|
||||
"queue: gain 4 shield now and next 2 turns.",
|
||||
"queue: gain 6 shield now and next 2 turns. [upgraded]").SetName("Catalog_preserves_ubuntu_unattended_upgrades");
|
||||
yield return new TestCaseData("mint_fix_broken", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=JavaScript|_maxAmount=8|_minAmount=8|_trueDamage=False;CleanseEffect|_harmfulOnly=True", true, false, true,
|
||||
"deal 8. cleanse harmful statuses.",
|
||||
"deal 10. cleanse harmful statuses. [upgraded]").SetName("Catalog_preserves_mint_fix_broken");
|
||||
yield return new TestCaseData("lang_js_typeof", "ChanceDamageEffect|_damageAmount=8|_language=JavaScript|_successPercent=75", true, false, true,
|
||||
"75%: deal 8. 25%: deal 0.",
|
||||
"75%: deal 10. 25%: deal 0. [upgraded]").SetName("Catalog_preserves_lang_js_typeof");
|
||||
yield return new TestCaseData("shop_py_list_append", "QueuedGrowthDamageEffect|_baseAmount=4|_language=Python", true, false, false,
|
||||
"queue: deal 4; +1 each time re-queued.",
|
||||
"queue: deal 8; +1 each time re-queued. [upgraded]").SetName("Catalog_preserves_shop_py_list_append");
|
||||
yield return new TestCaseData("shop_py_async_def", "DrawEffect|_count=2;NextTurnCycleEffect|_amount=1", false, false, false,
|
||||
"queue: draw 2. gain 1 cycle next turn.",
|
||||
"queue: draw 4. gain 3 cycle next turn. [upgraded]").SetName("Catalog_preserves_shop_py_async_def");
|
||||
yield return new TestCaseData("shop_py_zip", "QueueRepeatEffect|_count=2", false, false, false,
|
||||
"next 2 queued cards resolve twice.",
|
||||
"next 4 queued cards resolve twice. [upgraded]").SetName("Catalog_preserves_shop_py_zip");
|
||||
yield return new TestCaseData("shop_js_math_random", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=JavaScript|_maxAmount=20|_minAmount=2|_trueDamage=False", true, false, true,
|
||||
"deal 2-20.",
|
||||
"deal 4-22. [upgraded]").SetName("Catalog_preserves_shop_js_math_random");
|
||||
yield return new TestCaseData("shop_js_promise_all", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=JavaScript|_maxAmount=10|_minAmount=4|_trueDamage=False;DealDamageEffect|_allEnemies=False|_canCrit=True|_language=JavaScript|_maxAmount=10|_minAmount=4|_trueDamage=False;DealDamageEffect|_allEnemies=False|_canCrit=True|_language=JavaScript|_maxAmount=10|_minAmount=4|_trueDamage=False", true, false, true,
|
||||
"deal 4-10 three times.",
|
||||
"deal 6-12 three times. [upgraded]").SetName("Catalog_preserves_shop_js_promise_all");
|
||||
yield return new TestCaseData("shop_js_spread", "CopyLowestCostHandCardEffect", false, false, false,
|
||||
"copy the lowest-cost card in hand.",
|
||||
"copy the lowest-cost card in hand. [upgraded]").SetName("Catalog_preserves_shop_js_spread");
|
||||
yield return new TestCaseData("ubuntu_snap_install", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=JavaScript|_maxAmount=14|_minAmount=6|_trueDamage=False;ShuffleTokenIntoDrawPileEffect|_tokenId=ubuntu_pro_trial", true, false, true,
|
||||
"deal 6-14. shuffle an ubuntu pro trial into your draw pile.",
|
||||
"deal 8-16. shuffle an ubuntu pro trial into your draw pile. [upgraded]").SetName("Catalog_preserves_ubuntu_snap_install");
|
||||
yield return new TestCaseData("ubuntu_do_release_upgrade", "UpgradeHandCardsEffect|_maxCount=3|_minCount=1", false, false, false,
|
||||
"upgrade 1-3 random hand cards.",
|
||||
"upgrade 3-5 random hand cards. [upgraded]").SetName("Catalog_preserves_ubuntu_do_release_upgrade");
|
||||
yield return new TestCaseData("ubuntu_apt_install", "GenerateCardEffect|_language=Python|_rarity=Common", false, false, false,
|
||||
"queue: generate a random common Python card at 0c.",
|
||||
"queue: generate a random common Python card at 0c. [upgraded]").SetName("Catalog_preserves_ubuntu_apt_install");
|
||||
yield return new TestCaseData("ubuntu_pro_trial", "NoOpCardEffect|_message=ubuntu pro trial is unplayable", false, false, false,
|
||||
"unplayable. exhausts at end of combat.",
|
||||
"unplayable. exhausts at end of combat. [upgraded]").SetName("Catalog_preserves_ubuntu_pro_trial");
|
||||
yield return new TestCaseData("mint_update_manager", "UpdateManagerEffect|_amount=5", false, false, false,
|
||||
"queue: deal 5 to all enemies. repeats at the end of your next turn.",
|
||||
"queue: deal 7 to all enemies. repeats at the end of your next turn. [upgraded]").SetName("Catalog_preserves_mint_update_manager");
|
||||
yield return new TestCaseData("mint_cinnamon", "ShieldEffect|_amount=3;DrawEffect|_count=1", false, false, false,
|
||||
"queue: gain 3 shield. draw 1.",
|
||||
"queue: gain 5 shield. draw 3. [upgraded]").SetName("Catalog_preserves_mint_cinnamon");
|
||||
yield return new TestCaseData("mint_nemo", "ConditionalShieldRepeatDamageEffect|_amount=6|_language=JavaScript", true, false, true,
|
||||
"deal 6. if you have shield, deal it again.",
|
||||
"deal 8. if you have shield, deal it again. [upgraded]").SetName("Catalog_preserves_mint_nemo");
|
||||
yield return new TestCaseData("mint_timeshift", "TimeshiftSnapshotEffect", false, false, false,
|
||||
"queue: record uptime now. at end of your next turn, restore to it if lower.",
|
||||
"queue: record uptime now. at end of your next turn, restore to it if lower. [upgraded]").SetName("Catalog_preserves_mint_timeshift");
|
||||
yield return new TestCaseData("fedora_dnf_autoremove", "DnfAutoremoveEffect|_cycleGain=1|_damageAmount=7", true, false, true,
|
||||
"deal 7. exhaust a junk/NOP/broken card from hand; if you do, gain 1 cycle. if not, do nothing.",
|
||||
"deal 9. exhaust a junk/NOP/broken card from hand; if you do, gain 3 cycle. if not, do nothing. [upgraded]").SetName("Catalog_preserves_fedora_dnf_autoremove");
|
||||
yield return new TestCaseData("fedora_first_to_package", "FirstToPackageEffect|_amount=7", true, false, true,
|
||||
"deal 7. Java cards cost 1 less this turn.",
|
||||
"deal 9. Java cards cost 1 less this turn. [upgraded]").SetName("Catalog_preserves_fedora_first_to_package");
|
||||
yield return new TestCaseData("fedora_dnf_update", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=Java|_maxAmount=9|_minAmount=9|_trueDamage=False", true, false, true,
|
||||
"deal 9. overkill spills. costs 1 less per Java card played this combat.",
|
||||
"deal 11. overkill spills. costs 1 less per Java card played this combat. [upgraded]").SetName("Catalog_preserves_fedora_dnf_update");
|
||||
yield return new TestCaseData("fedora_rawhide", "RawhideEffect", false, false, false,
|
||||
"draw 2. next card this turn gains bleeding edge.",
|
||||
"draw 4. next card this turn gains bleeding edge. [upgraded]").SetName("Catalog_preserves_fedora_rawhide");
|
||||
yield return new TestCaseData("fedora_selinux", "IncomingAttackHalveEffect|_charges=2", false, false, false,
|
||||
"next 2 enemy attacks deal half damage.",
|
||||
"next 4 enemy attacks deal half damage. [upgraded]").SetName("Catalog_preserves_fedora_selinux");
|
||||
yield return new TestCaseData("arch_pacman_syu", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=C|_maxAmount=14|_minAmount=14|_trueDamage=False", true, false, true,
|
||||
"deal 14. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card.",
|
||||
"deal 16. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card. [upgraded]").SetName("Catalog_preserves_arch_pacman_syu");
|
||||
yield return new TestCaseData("arch_consult_wiki", "ConsultWikiEffect", true, false, true,
|
||||
"fix a broken card and draw 1; if none, deal 6.",
|
||||
"fix a broken card and draw 3; if none, deal 8. [upgraded]").SetName("Catalog_preserves_arch_consult_wiki");
|
||||
yield return new TestCaseData("arch_makepkg", "BtwScaledDamageEffect|_baseAmount=7|_language=C|_perBtw=3", true, false, true,
|
||||
"deal 7 + btw x3; x4 at Arch v3+. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card.",
|
||||
"deal 9 + btw x3; x4 at Arch v3+. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card. [upgraded]").SetName("Catalog_preserves_arch_makepkg");
|
||||
yield return new TestCaseData("arch_aur_helper", "RandomCommonLanguageCardEffect", false, false, false,
|
||||
"add a random C/Rust common card to hand; it costs 0 this turn.",
|
||||
"add a random C/Rust common card to hand; it costs 0 this turn. [upgraded]").SetName("Catalog_preserves_arch_aur_helper");
|
||||
yield return new TestCaseData("arch_minimal_install", "MinimalInstallEffect", false, false, false,
|
||||
"exhaust up to 2 hand cards. per card: gain 3 Shield and 1 Cycle.",
|
||||
"exhaust up to 2 hand cards. per card: gain 3 Shield and 1 Cycle. [upgraded]").SetName("Catalog_preserves_arch_minimal_install");
|
||||
yield return new TestCaseData("shop_c_free", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=C|_maxAmount=18|_minAmount=18|_trueDamage=False;RepairCorruptedCardsEffect|_count=1", true, false, true,
|
||||
"deal 18. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3, corrupt a hand card, and draw 2. then repair up to 1 corrupted card in your active deck.",
|
||||
"deal 20. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3, corrupt a hand card, and draw 2. then repair up to 3 corrupted cards in your active deck. [upgraded]").SetName("Catalog_preserves_shop_c_free");
|
||||
yield return new TestCaseData("shop_c_sizeof", "SizeofDamageEffect", true, false, true,
|
||||
"deal 5 x C cards in hand. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card.",
|
||||
"deal 5 x C cards in hand. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card. [upgraded]").SetName("Catalog_preserves_shop_c_sizeof");
|
||||
yield return new TestCaseData("shop_c_kernel_exploit", "DealDamageEffect|_allEnemies=False|_canCrit=True|_language=C|_maxAmount=36|_minAmount=36|_trueDamage=True", true, false, true,
|
||||
"deal 36 ignoring Shield. 50% of overkill spills per jump (rounded down). 50%: segfault, uptime -8 and corrupt a hand card.",
|
||||
"deal 38 ignoring Shield. 50% of overkill spills per jump (rounded down). 50%: segfault, uptime -8 and corrupt a hand card. [upgraded]").SetName("Catalog_preserves_shop_c_kernel_exploit");
|
||||
yield return new TestCaseData("shop_c_gdb", "RepairCorruptedCardsEffect|_count=2;DrawEffect|_count=1", false, false, false,
|
||||
"repair up to 2 corrupted cards in your active deck. draw 1.",
|
||||
"repair up to 4 corrupted cards in your active deck. draw 3. [upgraded]").SetName("Catalog_authors_shop_c_gdb");
|
||||
yield return new TestCaseData("shop_c_valgrind", "RepairCorruptedCardsEffect|_count=3;ShieldEffect|_amount=6", false, false, false,
|
||||
"repair up to 3 corrupted cards in your active deck. gain 6 Shield.",
|
||||
"repair up to 5 corrupted cards in your active deck. gain 8 Shield. [upgraded]").SetName("Catalog_authors_shop_c_valgrind");
|
||||
}
|
||||
|
||||
[TestCaseSource(nameof(AuthoredCases))]
|
||||
public void PreservesAuthoredEffectsTargetingAndRules(string id, string effectSignature,
|
||||
bool single, bool all, bool bleeding, string baseRules, string upgradedRules)
|
||||
{
|
||||
var asset = Database.FindById(id);
|
||||
Assert.That(asset, Is.Not.Null, id);
|
||||
var definition = UnityEngine.Object.Instantiate(asset);
|
||||
try
|
||||
{
|
||||
Assert.That(CardCatalog.TryGet(id, out var entry), Is.True);
|
||||
Assert.That(entry.Id, Is.EqualTo(id));
|
||||
Assert.That(CardEffectFactory.CreateEffects(definition).Select(Signature), Is.EqualTo(effectSignature.Split(';')));
|
||||
Assert.That(CardEffectFactory.RequiresSingleTarget(definition), Is.EqualTo(single));
|
||||
Assert.That(CardEffectFactory.TargetsAllEnemies(definition), Is.EqualTo(all));
|
||||
typeof(CardDefinition).GetField("resolutionTrack", Private).SetValue(definition, ResolutionTrack.Native);
|
||||
Assert.That(CardEffectFactory.CanReceiveBleedingEdgeDamageBonus(definition), Is.EqualTo(bleeding));
|
||||
typeof(CardDefinition).GetField("resolutionTrack", Private).SetValue(definition, ResolutionTrack.InterpreterQueue);
|
||||
Assert.That(CardEffectFactory.CanReceiveBleedingEdgeDamageBonus(definition), Is.False);
|
||||
|
||||
var card = new CardInstance(definition);
|
||||
Assert.That(CardEffectFactory.GetRulesText(card), Is.EqualTo(baseRules));
|
||||
card.ApplyMagnitudeUpgrade(2);
|
||||
card.MarkQueued(); card.MarkQueued(); card.MarkQueued();
|
||||
Assert.That(CardEffectFactory.GetRulesText(card), Is.EqualTo(upgradedRules));
|
||||
}
|
||||
finally { UnityEngine.Object.DestroyImmediate(definition); }
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CatalogCoversEveryPersistedCardIncludingTokenAndReturnsFreshRuntimeEffects()
|
||||
{
|
||||
Assert.That(CardCatalog.Entries.Select(entry => entry.Id), Is.EquivalentTo(Database.AllCards.Select(card => card.Id)));
|
||||
Assert.That(CardCatalog.Entries.Select(entry => entry.Id).Distinct().Count(), Is.EqualTo(65));
|
||||
foreach (var entry in CardCatalog.Entries)
|
||||
{
|
||||
var first = entry.CreateEffects();
|
||||
var second = entry.CreateEffects();
|
||||
Assert.That(first.Count, Is.GreaterThan(0), entry.Id);
|
||||
Assert.That(first.Count, Is.EqualTo(entry.Effects.Count), entry.Id);
|
||||
for (int i = 0; i < first.Count; i++) Assert.That(first[i], Is.Not.SameAs(second[i]), entry.Id);
|
||||
}
|
||||
var exposedEntries = (IList<CardCatalogEntry>)CardCatalog.Entries;
|
||||
Assert.That(exposedEntries.IsReadOnly, Is.True);
|
||||
Assert.That(((IList<CardEffectSpec>)CardCatalog.Entries[0].Effects).IsReadOnly, Is.True);
|
||||
}
|
||||
|
||||
[TestCase("shop_c_gdb", Rarity.Common, 1)]
|
||||
[TestCase("shop_c_valgrind", Rarity.Rare, 2)]
|
||||
public void RepairCardsAreObtainableThroughEitherCLanguageRepositoryPool(string id, Rarity rarity, int cost)
|
||||
{
|
||||
var definition = Database.FindById(id);
|
||||
Assert.That(definition.Rarity, Is.EqualTo(rarity));
|
||||
Assert.That(definition.Language, Is.EqualTo(Language.C));
|
||||
Assert.That(definition.CycleCost, Is.EqualTo(cost));
|
||||
Assert.That(definition.ResolutionTrack, Is.EqualTo(ResolutionTrack.Native));
|
||||
Assert.That(definition.IsRunOnly, Is.True);
|
||||
Assert.That(definition.IsToken, Is.False);
|
||||
Assert.That(definition.DistroExclusive, Is.False);
|
||||
var languages = AssetDatabase.LoadAssetAtPath<LanguageDeckDatabase>("Assets/Data/Cards/Languages/LanguageDeckDatabase.asset");
|
||||
Assert.That(languages.FindByLanguage(Language.C).Entries.Select(entry => entry.Card.Id),
|
||||
Is.EquivalentTo(new[] { "lang_c_malloc", "lang_c_printf", "lang_c_pointer" }), "The existing C starter composition is unchanged.");
|
||||
var owner = new GameObject("Repair repository integration");
|
||||
var random = UnityEngine.Random.state;
|
||||
try
|
||||
{
|
||||
var run = owner.AddComponent<RunManager>();
|
||||
var distro = AssetDatabase.LoadAssetAtPath<DistroDefinition>("Assets/Data/Distros/Gentoo.asset");
|
||||
foreach (bool primaryC in new[] { true, false })
|
||||
{
|
||||
run.StartRun(new RunConfig(distro, primaryC ? Language.C : Language.Haskell,
|
||||
primaryC ? Language.Haskell : Language.C, Array.Empty<CardDefinition>(),
|
||||
Array.Empty<PackageInstance>(), 17, 1));
|
||||
var pool = (List<CardDefinition>)typeof(RunManager).GetMethod("BuildCardOfferPool", Private)
|
||||
.Invoke(run, new object[] { Database, languages });
|
||||
Assert.That(pool, Does.Contain(definition));
|
||||
}
|
||||
run.StartRun(new RunConfig(distro, Language.Python, Language.Haskell, Array.Empty<CardDefinition>(),
|
||||
Array.Empty<PackageInstance>(), 17, 1));
|
||||
var unrelated = (List<CardDefinition>)typeof(RunManager).GetMethod("BuildCardOfferPool", Private)
|
||||
.Invoke(run, new object[] { Database, languages });
|
||||
Assert.That(unrelated, Has.No.Member(definition));
|
||||
Assert.That(RepositoryOffer.NewCard(definition, CombatTuning.NewCardOfferCost + 1).Description,
|
||||
Is.EqualTo(CardEffectFactory.GetRulesText(new CardInstance(definition))));
|
||||
}
|
||||
finally
|
||||
{
|
||||
UnityEngine.Object.DestroyImmediate(owner);
|
||||
UnityEngine.Random.state = random;
|
||||
}
|
||||
}
|
||||
|
||||
[TestCase(0)] [TestCase(2)]
|
||||
public void RepairCapacityUsesCardMagnitudeWithoutDamageOrCompilationMultipliers(int magnitudeBonus)
|
||||
{
|
||||
var owner = new GameObject("Repair magnitude integration");
|
||||
var combat = owner.AddComponent<CombatManager>();
|
||||
var hand = new HandController(12);
|
||||
var player = new CombatantState(50, 12, 4) { FlatEffectBonus = 10, DamageMultiplierPercent = 200 };
|
||||
typeof(CombatManager).GetField("_handController", Private).SetValue(combat, hand);
|
||||
typeof(CombatManager).GetField("_playerState", Private).SetValue(combat, player);
|
||||
var broken = Enumerable.Range(0, 6).Select(_ => new CardInstance(Database.FindById("lang_c_malloc"))).ToArray();
|
||||
var random = UnityEngine.Random.state;
|
||||
try
|
||||
{
|
||||
foreach (var card in broken)
|
||||
{
|
||||
card.CorruptForRounds(3, 1);
|
||||
Assert.That(hand.Add(card), Is.True);
|
||||
}
|
||||
combat.Compilation.BeginWave(5);
|
||||
combat.Compilation.AdvanceFromEquipment(10, 1);
|
||||
var repair = new CardInstance(Database.FindById("shop_c_gdb"));
|
||||
repair.ApplyMagnitudeUpgrade(magnitudeBonus);
|
||||
var context = new CombatContext(repair, player, Array.Empty<CombatantState>(), combat,
|
||||
combat.DamagePipeline, new StatusEffectController(), combat.DeckController, hand, combat.Enemies);
|
||||
CardEffectFactory.CreateEffects(repair.Definition)[0].Execute(context);
|
||||
Assert.That(broken.Count(card => !card.IsBroken), Is.EqualTo(2 + magnitudeBonus));
|
||||
Assert.That(broken.Take(2 + magnitudeBonus).All(card => card.CorruptionRoundsRemaining == 0), Is.True);
|
||||
Assert.That(hand.Cards, Is.EqualTo(broken), "Repair never draws, removes or rearranges cards.");
|
||||
Assert.That(UnityEngine.Random.state, Is.EqualTo(random));
|
||||
}
|
||||
finally
|
||||
{
|
||||
UnityEngine.Object.DestroyImmediate(owner);
|
||||
UnityEngine.Random.state = random;
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SerializedOverrideStillWinsAndUsesItsOwnDescription()
|
||||
{
|
||||
var definition = UnityEngine.Object.Instantiate(Database.FindById("lang_c_malloc"));
|
||||
var custom = ScriptableObject.CreateInstance<CardCatalogTestEffect>();
|
||||
try
|
||||
{
|
||||
typeof(CardDefinition).GetField("effects", Private).SetValue(definition, new List<CardEffectDefinition> { null, custom });
|
||||
typeof(CardDefinition).GetField("description", Private).SetValue(definition, "gain a custom barrier.");
|
||||
Assert.That(CardEffectFactory.CreateEffects(definition).Select(Signature),
|
||||
Is.EqualTo(new[] { "ShieldEffect|_amount=37" }));
|
||||
Assert.That(CardEffectFactory.GetRulesText(new CardInstance(definition)), Is.EqualTo("gain a custom barrier."));
|
||||
custom.ReturnNull = true;
|
||||
Assert.That(CardEffectFactory.CreateEffects(definition)[0], Is.TypeOf<NoOpCardEffect>(),
|
||||
"An invalid serialized override must not execute an unrelated catalog effect.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
UnityEngine.Object.DestroyImmediate(custom);
|
||||
UnityEngine.Object.DestroyImmediate(definition);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NullAndUnknownDefinitionsKeepSafeFallbacks()
|
||||
{
|
||||
Assert.That(CardCatalog.TryGet(null, out _), Is.False);
|
||||
Assert.That(CardEffectFactory.CreateEffects(null).Single(), Is.TypeOf<NoOpCardEffect>());
|
||||
Assert.That(CardEffectFactory.RequiresSingleTarget(null), Is.False);
|
||||
Assert.That(CardEffectFactory.TargetsAllEnemies(null), Is.False);
|
||||
Assert.That(CardEffectFactory.CanReceiveBleedingEdgeDamageBonus(null), Is.False);
|
||||
Assert.That(CardEffectFactory.GetRulesText(null), Is.EqualTo("--"));
|
||||
var unknown = ScriptableObject.CreateInstance<CardDefinition>();
|
||||
try
|
||||
{
|
||||
Assert.That(CardEffectFactory.GetRulesText(new CardInstance(unknown)), Is.EqualTo("effect not authored."));
|
||||
typeof(CardDefinition).GetField("description", Private).SetValue(unknown, "external card");
|
||||
Assert.That(CardEffectFactory.GetRulesText(new CardInstance(unknown)), Is.EqualTo("external card"));
|
||||
}
|
||||
finally { UnityEngine.Object.DestroyImmediate(unknown); }
|
||||
}
|
||||
|
||||
private static string Signature(ICardEffect effect)
|
||||
{
|
||||
return effect.GetType().Name + string.Concat(effect.GetType().GetFields(Private)
|
||||
.OrderBy(field => field.Name, StringComparer.Ordinal)
|
||||
.Select(field => "|" + field.Name + "=" + field.GetValue(effect)));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CardCatalogTestEffect : CardEffectDefinition
|
||||
{
|
||||
public bool ReturnNull;
|
||||
public override ICardEffect CreateRuntimeEffect() => ReturnNull ? null : new ShieldEffect(37);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 64c67631f8c94fbf96527bc0d79588ce
|
||||
@@ -0,0 +1,179 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using NUnit.Framework;
|
||||
using UnityEngine;
|
||||
|
||||
public class CardDrawTimingTests
|
||||
{
|
||||
private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
private readonly List<CardDefinition> definitions = new();
|
||||
private readonly List<string> messages = new();
|
||||
private GameObject owner;
|
||||
private CombatManager combat;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
owner = new GameObject(nameof(CardDrawTimingTests));
|
||||
combat = owner.AddComponent<CombatManager>();
|
||||
typeof(CombatManager).GetMethod("OnDisable", Private).Invoke(combat, null);
|
||||
Set(combat, "_playerState", new CombatantState(100, 4, 10));
|
||||
Set(combat, "_handController", new HandController(4));
|
||||
Set(combat, "currentPhase", TurnPhase.Interpret);
|
||||
combat.CombatLog += messages.Add;
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
if (combat != null) combat.CombatLog -= messages.Add;
|
||||
UnityEngine.Object.DestroyImmediate(owner);
|
||||
foreach (var definition in definitions) UnityEngine.Object.DestroyImmediate(definition);
|
||||
definitions.Clear();
|
||||
messages.Clear();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DrawSequenceDoesNotRedrawSourceDiscardedDuringAnimation()
|
||||
{
|
||||
var available = Card("available", Language.Python);
|
||||
var source = Card("resolving_source", Language.Python);
|
||||
PutOnDeck(available);
|
||||
var sequence = DrawSequence(2);
|
||||
|
||||
Assert.That(sequence.MoveNext(), Is.True);
|
||||
Assert.That(combat.HandController.Cards, Is.EqualTo(new[] { available }));
|
||||
combat.DeckController.Discard(source);
|
||||
Finish(sequence);
|
||||
|
||||
Assert.That(combat.HandController.Cards, Is.EqualTo(new[] { available }),
|
||||
"The resolving card is discarded after drawing starts and must not join this draw request.");
|
||||
Assert.That(combat.DeckController.DrawPile, Is.Empty);
|
||||
Assert.That(combat.DeckController.DiscardPile, Is.EqualTo(new[] { source }));
|
||||
Assert.That(messages, Has.Member("timing test: drew 1 (deck empty)"),
|
||||
"The stopping reason describes the deck when the draw request was reserved.");
|
||||
}
|
||||
|
||||
[TestCase("end turn")]
|
||||
[TestCase("surrender")]
|
||||
[TestCase("play card")]
|
||||
public void WaveTransitionIgnoresPlayerCommandsWhileOpeningHandIsBeingDrawn(string command)
|
||||
{
|
||||
// The preceding wave can end in Execute. Reproduce the interval after the repository
|
||||
// closes but before the new opening-hand draw coroutine reaches Allocate.
|
||||
Set(combat, "currentPhase", TurnPhase.Execute);
|
||||
Set(combat, "_awaitingWaveContinue", false);
|
||||
Set(combat, "_waveTransitionActive", true);
|
||||
var card = Card("transition_card", Language.Python);
|
||||
combat.HandController.Add(card);
|
||||
Set(combat, "_pendingTargetCard", card);
|
||||
Set(combat, "_selectedEnemyIndex", 0);
|
||||
|
||||
Assert.That(combat.CanSurrenderRun, Is.False);
|
||||
switch (command)
|
||||
{
|
||||
case "end turn": combat.EndPlayerTurn(); break;
|
||||
case "surrender": combat.SurrenderRun(); break;
|
||||
case "play card": Assert.That(combat.PlayCard(card), Is.False); break;
|
||||
}
|
||||
|
||||
Assert.That(combat.CurrentPhase, Is.EqualTo(TurnPhase.Execute));
|
||||
Assert.That(combat.PlayerState.CurrentUptime, Is.EqualTo(100));
|
||||
Assert.That(combat.PlayerState.Cycles, Is.EqualTo(10));
|
||||
Assert.That(combat.PlayerState.IsDefeated, Is.False);
|
||||
Assert.That(combat.RunLost, Is.False);
|
||||
Assert.That(combat.RunEndedBySurrender, Is.False);
|
||||
Assert.That(combat.PendingTargetCard, Is.SameAs(card));
|
||||
Assert.That(combat.SelectedEnemyIndex, Is.EqualTo(0));
|
||||
CollectionAssert.AreEqual(new[] { card }, combat.HandController.Cards);
|
||||
Assert.That(combat.DeckController.DiscardPile, Is.Empty);
|
||||
|
||||
Set(combat, "_waveTransitionActive", false);
|
||||
Assert.That(combat.CanSurrenderRun, Is.True, "Only the in-progress wave transition blocks these otherwise valid controls.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CapacityReductionReturnsRemainingReservedCardsInOriginalOrder()
|
||||
{
|
||||
var first = Card("first", Language.Python);
|
||||
var second = Card("second", Language.Java);
|
||||
var third = Card("third", Language.Rust);
|
||||
var tail = Card("tail", Language.C);
|
||||
PutOnDeck(first, second, third, tail);
|
||||
var sequence = DrawSequence(4);
|
||||
|
||||
Assert.That(sequence.MoveNext(), Is.True);
|
||||
Assert.That(combat.HandController.Cards, Is.EqualTo(new[] { first }));
|
||||
Assert.That(combat.DeckController.DrawPile, Is.EqualTo(new[] { tail }),
|
||||
"The entire RAM-fitting prefix is reserved before the first animation yield.");
|
||||
combat.HandController.SetRamCapacity(1);
|
||||
Finish(sequence);
|
||||
|
||||
Assert.That(combat.HandController.Cards, Is.EqualTo(new[] { first }));
|
||||
Assert.That(combat.DeckController.DrawPile, Is.EqualTo(new[] { tail, third, second }));
|
||||
Assert.That(combat.DeckController.DiscardPile, Is.Empty);
|
||||
|
||||
combat.HandController.SetRamCapacity(5);
|
||||
Finish(DrawSequence(3));
|
||||
Assert.That(combat.HandController.Cards, Is.EqualTo(new[] { first, second, third, tail }),
|
||||
"Restored reservations must be drawn before the untouched tail in their original order.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LazyCardDrawRiderStopsAtJavaCardThatCannotFit()
|
||||
{
|
||||
var source = Card("lazy_rider_source", Language.Haskell);
|
||||
source.ApplyDrawRider(2);
|
||||
var java = Card("blocked_java", Language.Java);
|
||||
var python = Card("cheaper_python", Language.Python);
|
||||
combat.HandController.SetRamCapacity(1);
|
||||
PutOnDeck(java, python);
|
||||
((List<EnemyInstance>)combat.Enemies).Add(new EnemyInstance("idle target", 100, Array.Empty<EnemyIntent>()));
|
||||
combat.LazyStack.Enqueue(source);
|
||||
|
||||
var sequence = (IEnumerator)typeof(CombatManager).GetMethod("EvaluateLazyStackSequenced", Private)
|
||||
.Invoke(combat, null);
|
||||
Finish(sequence);
|
||||
|
||||
Assert.That(combat.HandController.Cards, Is.Empty,
|
||||
"The lazy rider must not skip a blocked Java card to draw the cheaper card underneath.");
|
||||
Assert.That(combat.DeckController.DrawPile, Is.EqualTo(new[] { python, java }));
|
||||
Assert.That(combat.DeckController.DiscardPile, Is.EqualTo(new[] { source }));
|
||||
Assert.That(combat.LazyStack.Count, Is.Zero);
|
||||
}
|
||||
|
||||
private IEnumerator DrawSequence(int count) =>
|
||||
(IEnumerator)typeof(CombatManager).GetMethod("DrawCardsToHandSequenced", Private)
|
||||
.Invoke(combat, new object[] { count, "timing test" });
|
||||
|
||||
private static void Finish(IEnumerator sequence)
|
||||
{
|
||||
int steps = 0;
|
||||
while (sequence.MoveNext())
|
||||
Assert.That(++steps, Is.LessThan(20), "The draw/evaluation sequence must finish.");
|
||||
}
|
||||
|
||||
private CardInstance Card(string id, Language language)
|
||||
{
|
||||
var definition = ScriptableObject.CreateInstance<CardDefinition>();
|
||||
definitions.Add(definition);
|
||||
Set(definition, "id", id);
|
||||
Set(definition, "language", language);
|
||||
if (language == Language.Haskell) Set(definition, "resolutionTrack", ResolutionTrack.LazyStack);
|
||||
return new CardInstance(definition);
|
||||
}
|
||||
|
||||
private void PutOnDeck(params CardInstance[] drawOrder)
|
||||
{
|
||||
for (int i = drawOrder.Length - 1; i >= 0; i--)
|
||||
combat.DeckController.AddToDrawPile(drawOrder[i], false);
|
||||
}
|
||||
|
||||
private static void Set(object target, string field, object value) =>
|
||||
target.GetType().GetField(field, Private).SetValue(target, value);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a0f253595a584b6499175c92ccbb25f4
|
||||
@@ -0,0 +1,480 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Run;
|
||||
using NUnit.Framework;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
public class CardPreviewTests
|
||||
{
|
||||
private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
private GameObject owner;
|
||||
private CombatManager combat;
|
||||
private RunManager run;
|
||||
private CardDatabase cards;
|
||||
private readonly List<UnityEngine.Object> temporary = new();
|
||||
private CombatantState Player => combat.PlayerState;
|
||||
private CombatantState Target => combat.Enemies[0].State;
|
||||
private static object Call(object instance, string method, params object[] args) => instance.GetType().GetMethod(method, Private).Invoke(instance, args);
|
||||
private static void Set(object instance, string field, object value) => instance.GetType().GetField(field, Private).SetValue(instance, value);
|
||||
private static T Asset<T>(string path) where T : UnityEngine.Object => AssetDatabase.LoadAssetAtPath<T>(path);
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
cards = Asset<CardDatabase>("Assets/Data/Cards/CardDatabase.asset");
|
||||
owner = new GameObject("Read-only card preview integration");
|
||||
run = owner.AddComponent<RunManager>();
|
||||
combat = owner.AddComponent<CombatManager>();
|
||||
Call(combat, "OnDisable"); Call(combat, "Awake"); Call(combat, "OnEnable");
|
||||
Configure("Gentoo", 1);
|
||||
((List<EnemyInstance>)combat.Enemies).Add(new EnemyInstance("preview target", 10000, Array.Empty<EnemyIntent>()));
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
if (combat != null) Call(combat, "OnDisable");
|
||||
UnityEngine.Object.DestroyImmediate(owner);
|
||||
foreach (var item in temporary) UnityEngine.Object.DestroyImmediate(item);
|
||||
temporary.Clear();
|
||||
}
|
||||
|
||||
private void Configure(string distro, int version, params PackageInstance[] packages)
|
||||
{
|
||||
var definition = Asset<DistroDefinition>($"Assets/Data/Distros/{distro}.asset");
|
||||
Assert.That(definition, Is.Not.Null, distro);
|
||||
var config = new RunConfig(definition, Language.C, Language.Haskell,
|
||||
Array.Empty<CardDefinition>(), packages, 37, version);
|
||||
run.StartRun(config);
|
||||
Set(combat, "_runConfig", config);
|
||||
Set(combat, "_runManager", run);
|
||||
Set(combat, "_playerState", new CombatantState(60, 32, 100));
|
||||
Set(combat, "_handController", new HandController(32));
|
||||
Set(combat, "currentPhase", TurnPhase.Execute);
|
||||
Call(combat, "ApplyVersionState", Player);
|
||||
Call(combat, "ApplyPackageState", Player);
|
||||
Player.ForceMaxRolls = true;
|
||||
combat.Compilation.BeginWave(distro == "Gentoo" ? version : 0);
|
||||
}
|
||||
|
||||
private CardInstance Card(string id)
|
||||
{
|
||||
var definition = cards.FindById(id);
|
||||
Assert.That(definition, Is.Not.Null, id);
|
||||
return new CardInstance(definition);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CPreviewExplainsReducedCritChanceAndSpillWithoutChangingDirectDamageRange()
|
||||
{
|
||||
Player.ForceMaxRolls = false;
|
||||
combat.Compilation.CompleteRound(1); // Neutral 100% Compilation for the base damage assertion.
|
||||
var preview = CardPreviewService.Build(combat, Card("lang_c_malloc"), Target);
|
||||
Assert.That(preview.Details, Does.Contain("C 35%"));
|
||||
Assert.That(preview.Details, Does.Contain("50% of remaining overkill per jump, rounded down"));
|
||||
Assert.That(preview.MinimumDamage, Is.EqualTo(12));
|
||||
Assert.That(preview.MaximumDamage, Is.EqualTo(18));
|
||||
}
|
||||
|
||||
private void Play(CardInstance card)
|
||||
{
|
||||
if (!combat.HandController.Cards.Contains(card)) Assert.That(combat.HandController.Add(card), Is.True);
|
||||
combat.SelectEnemy(0);
|
||||
Assert.That(combat.PlayCard(card), Is.True);
|
||||
}
|
||||
|
||||
private void ResolveEffects(CardInstance card, int lazy = 100)
|
||||
{
|
||||
var context = new CombatContext(card, Player, new[] { Target }, combat, combat.DamagePipeline,
|
||||
new StatusEffectController(), combat.DeckController, combat.HandController, combat.Enemies);
|
||||
typeof(CombatContext).GetProperty("LazyMultiplierPercent").SetValue(context, lazy);
|
||||
foreach (var effect in CardEffectFactory.CreateEffects(card.Definition)) effect.Execute(context);
|
||||
}
|
||||
|
||||
private PackageInstance Package(PackageEffectKind kind, int amount)
|
||||
{
|
||||
var definition = ScriptableObject.CreateInstance<PackageDefinition>(); temporary.Add(definition);
|
||||
Set(definition, "id", "preview_" + kind);
|
||||
Set(definition, "displayName", kind.ToString());
|
||||
Set(definition, "offDistroEffect", new PackageEffectData(kind, amount, 0, false, false, false));
|
||||
return new PackageInstance(definition, 0);
|
||||
}
|
||||
|
||||
[TestCase(1, false)] [TestCase(1, true)] [TestCase(5, false)] [TestCase(5, true)]
|
||||
public void GentooNativeDamageMatchesRealPlayAtInitialAndCappedCompilation(int version, bool capped)
|
||||
{
|
||||
Configure("Gentoo", version);
|
||||
if (capped) for (int i = 1; i <= 8; i++) combat.Compilation.CompleteRound(i);
|
||||
var card = Card("gentoo_make_j4");
|
||||
card.ApplyMagnitudeUpgrade(2);
|
||||
var preview = CardPreviewService.Build(combat, card, Target);
|
||||
int before = Target.CurrentUptime;
|
||||
Play(card);
|
||||
Assert.That(before - Target.CurrentUptime, Is.EqualTo(preview.MinimumDamage));
|
||||
Assert.That(preview.MaximumDamage, Is.EqualTo(preview.MinimumDamage));
|
||||
Assert.That(preview.Details, Does.Contain("Compilation"));
|
||||
}
|
||||
|
||||
[TestCase(0, false)] [TestCase(5, false)]
|
||||
[TestCase(0, true)] [TestCase(5, true)]
|
||||
public void DnfPreviewPreservesNativeAndDeferredHookTimingWithoutBuffingShield(int level, bool deferred)
|
||||
{
|
||||
Configure("Gentoo", 1, new PackageInstance(Asset<PackageDefinition>("Assets/Data/Packages/DNF.asset"), level));
|
||||
var card = Card(deferred ? "lang_hs_map" : "gentoo_make_j4");
|
||||
var shield = Card("gentoo_use_flags");
|
||||
int originalShield = CardPreviewService.Build(combat, shield).Shield;
|
||||
var preview = CardPreviewService.Build(combat, card, Target);
|
||||
Assert.That(Player.FlatCardDamageBonus, Is.Zero, "Preview must not activate DNF.");
|
||||
int before = Target.CurrentUptime;
|
||||
Play(card);
|
||||
if (deferred)
|
||||
{
|
||||
var queuedPreview = CardPreviewService.Build(combat, card, Target);
|
||||
Assert.That(queuedPreview.MinimumDamage, Is.EqualTo(preview.MinimumDamage), "Queued preview must not add the play hook twice.");
|
||||
ResolveEffects(card);
|
||||
}
|
||||
Assert.That(before - Target.CurrentUptime, Is.EqualTo(preview.MinimumDamage));
|
||||
Assert.That(preview.MaximumDamage, Is.EqualTo(preview.MinimumDamage));
|
||||
Assert.That(Player.FlatCardDamageBonus, Is.EqualTo(2 + level));
|
||||
Assert.That(Player.FlatEffectBonus, Is.Zero);
|
||||
Assert.That(CardPreviewService.Build(combat, shield).Shield, Is.EqualTo(originalShield));
|
||||
|
||||
var subsequent = Card("gentoo_make_j4");
|
||||
preview = CardPreviewService.Build(combat, subsequent, Target);
|
||||
before = Target.CurrentUptime;
|
||||
Play(subsequent);
|
||||
Assert.That(before - Target.CurrentUptime, Is.EqualTo(preview.MinimumDamage));
|
||||
Assert.That(preview.Details, Does.Contain("does not increase draw"));
|
||||
}
|
||||
|
||||
[TestCase(1)] [TestCase(5)]
|
||||
public void GentooShieldUsesCompilationAndMagnitudeAtCap(int version)
|
||||
{
|
||||
Configure("Gentoo", version);
|
||||
for (int i = 1; i <= 8; i++) combat.Compilation.CompleteRound(i);
|
||||
var card = Card("gentoo_use_flags");
|
||||
card.ApplyMagnitudeUpgrade(2);
|
||||
var preview = CardPreviewService.Build(combat, card);
|
||||
ResolveEffects(card);
|
||||
Assert.That(preview.Shield, Is.EqualTo(Player.Shield));
|
||||
Assert.That(preview.Shield, Is.EqualTo(version == 5 ? 8 : 6));
|
||||
}
|
||||
|
||||
[TestCase(1)] [TestCase(5)]
|
||||
public void FedoraPreviewIncludesNonCrashMultiplierAndGrowthWithoutMutatingCard(int version)
|
||||
{
|
||||
Configure("Fedora", version);
|
||||
var card = Card("lang_js_console_log");
|
||||
card.ApplyMagnitudeUpgrade(2);
|
||||
var preview = CardPreviewService.Build(combat, card, Target);
|
||||
Assert.That(card.MagnitudeBonus, Is.EqualTo(2));
|
||||
int before = Target.CurrentUptime;
|
||||
Play(card);
|
||||
Assert.That(before - Target.CurrentUptime, Is.EqualTo(preview.MaximumDamage));
|
||||
Assert.That(preview.Details, Does.Contain("Bleeding Edge"));
|
||||
Assert.That(card.MagnitudeBonus, Is.EqualTo(version >= 3 ? 3 : 2));
|
||||
}
|
||||
|
||||
[TestCase(1)] [TestCase(5)]
|
||||
public void MintPreviewHonorsMaxRollsFlatBonusAndBlockedShield(int version)
|
||||
{
|
||||
Configure("Mint", version);
|
||||
Player.DamageMultiplierPercent = 250;
|
||||
var damage = Card("shop_js_math_random");
|
||||
var preview = CardPreviewService.Build(combat, damage, Target);
|
||||
Assert.That(preview.MinimumDamage, Is.EqualTo(version == 5 ? 22 : 20));
|
||||
int before = Target.CurrentUptime;
|
||||
Play(damage);
|
||||
Assert.That(before - Target.CurrentUptime, Is.EqualTo(preview.MaximumDamage));
|
||||
var shield = Card("lang_rs_borrow");
|
||||
var shieldPreview = CardPreviewService.Build(combat, shield);
|
||||
Assert.That(shieldPreview.Shield, Is.Zero);
|
||||
Assert.That(shieldPreview.Details, Does.Contain("blocked by Mint"));
|
||||
ResolveEffects(shield);
|
||||
Assert.That(Player.Shield, Is.Zero);
|
||||
}
|
||||
|
||||
[TestCase(1)] [TestCase(5)]
|
||||
public void ArchPreviewIncludesTheAcceptedCardsOwnBtwStack(int version)
|
||||
{
|
||||
Configure("Arch", version);
|
||||
Player.ArchBtwStacks = 3;
|
||||
var card = Card("arch_makepkg");
|
||||
var preview = CardPreviewService.Build(combat, card, Target);
|
||||
Assert.That(Player.ArchBtwStacks, Is.EqualTo(3));
|
||||
int before = Target.CurrentUptime;
|
||||
Play(card);
|
||||
Assert.That(before - Target.CurrentUptime, Is.EqualTo(preview.MaximumDamage));
|
||||
Assert.That(Player.ArchBtwStacks, Is.EqualTo(4));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MultipleRandomHitsIncludeIndependentCritRangesAndAllFlatModifiers()
|
||||
{
|
||||
Configure("Ubuntu", 1);
|
||||
Player.ForceMaxRolls = false;
|
||||
Player.FlatEffectBonus = 1;
|
||||
Player.JavaScriptFlatDamageBonus = 2;
|
||||
var card = Card("shop_js_promise_all");
|
||||
card.ApplyMagnitudeUpgrade(2);
|
||||
var preview = CardPreviewService.Build(combat, card, Target);
|
||||
Assert.That((preview.MinimumDamage, preview.MaximumDamage), Is.EqualTo((27, 69)));
|
||||
Assert.That(preview.Details, Does.Contain("3 hits"));
|
||||
RandomRoll.Seed(73);
|
||||
int before = Target.CurrentUptime;
|
||||
Play(card);
|
||||
Assert.That(before - Target.CurrentUptime, Is.InRange(preview.MinimumDamage, preview.MaximumDamage));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ChanceDamageFailureRetainsTheRuntimeLanguageFlatBonus()
|
||||
{
|
||||
Configure("Ubuntu", 1);
|
||||
Player.ForceMaxRolls = false;
|
||||
Player.JavaScriptFlatDamageBonus = 2;
|
||||
var preview = CardPreviewService.Build(combat, Card("lang_js_typeof"), Target);
|
||||
Assert.That((preview.MinimumDamage, preview.MaximumDamage), Is.EqualTo((2, 15)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HaskellPreviewUsesCapturedMultiplierAndProspectiveStackDepth()
|
||||
{
|
||||
Configure("Gentoo", 5);
|
||||
var first = Card("lang_hs_thunk");
|
||||
var second = Card("lang_hs_thunk");
|
||||
Play(first);
|
||||
Play(second);
|
||||
var third = Card("lang_hs_thunk");
|
||||
Assert.That(CardPreviewService.Build(combat, first, Target).MaximumDamage, Is.EqualTo(4));
|
||||
Assert.That(CardPreviewService.Build(combat, second, Target).MaximumDamage, Is.EqualTo(6));
|
||||
Assert.That(CardPreviewService.Build(combat, third, Target).MaximumDamage, Is.EqualTo(8));
|
||||
Assert.That(CardPreviewService.Build(combat, second).Details, Does.Contain("captured: x1.5"));
|
||||
Assert.That(CardPreviewService.Build(combat, third).Details, Does.Contain("next stack: x2.0"));
|
||||
int before = Target.CurrentUptime;
|
||||
ResolveEffects(second, combat.LazyStack.Entries.First(entry => entry.Card == second).MultiplierPercent);
|
||||
Assert.That(before - Target.CurrentUptime, Is.EqualTo(6));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TargetResistanceUsesPureResolverAndMatchesRealDamage()
|
||||
{
|
||||
Configure("Ubuntu", 1);
|
||||
var rootkit = new EnemyInstance(EnemyArchetypeCatalog.Get("rootkit"), 10000);
|
||||
((List<EnemyInstance>)combat.Enemies).Insert(0, rootkit);
|
||||
var card = Card("lang_c_malloc");
|
||||
var preview = CardPreviewService.Build(combat, card, rootkit.State);
|
||||
int before = rootkit.CurrentUptime;
|
||||
Play(card);
|
||||
Assert.That(preview.MaximumDamage, Is.EqualTo(2));
|
||||
Assert.That(before - rootkit.CurrentUptime, Is.EqualTo(preview.MaximumDamage));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PreviewNeverInvokesAnUnknownRuntimeResistanceHook()
|
||||
{
|
||||
int calls = 0;
|
||||
combat.DamagePipeline.ResistanceResolver = (request, amount) => { calls++; return 0; };
|
||||
Assert.That(combat.DamagePipeline.PreviewResistanceResolver, Is.Null, "Replacing the runtime hook invalidates its old preview.");
|
||||
var preview = CardPreviewService.Build(combat, Card("lang_c_malloc"), Target);
|
||||
Assert.That(calls, Is.Zero);
|
||||
Assert.That(preview.IsConditional, Is.True);
|
||||
Assert.That(preview.Details, Does.Contain("custom resistance hook"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FirstCEquipmentMultiplierIsAppliedExactlyOnceAndBecomesUsed()
|
||||
{
|
||||
Configure("Gentoo", 5, Package(PackageEffectKind.FirstCThisTurnDamageMultiplier, 150));
|
||||
var first = Card("gentoo_make_j4");
|
||||
var preview = CardPreviewService.Build(combat, first, Target);
|
||||
Assert.That(preview.MaximumDamage, Is.EqualTo(12));
|
||||
int before = Target.CurrentUptime;
|
||||
Play(first);
|
||||
Assert.That(before - Target.CurrentUptime, Is.EqualTo(preview.MaximumDamage));
|
||||
Assert.That(CardPreviewService.Build(combat, Card("gentoo_make_j4"), Target).MaximumDamage, Is.EqualTo(8));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EquipmentShieldAndDiscountAreReadWithoutConsumingReadiness()
|
||||
{
|
||||
Configure("Gentoo", 5,
|
||||
Package(PackageEffectKind.FirstShieldEachTurnBonus, 3),
|
||||
Package(PackageEffectKind.FirstCardEachRoundDiscountAndShield, 5));
|
||||
var first = Card("lang_rs_borrow");
|
||||
var preview = CardPreviewService.Build(combat, first);
|
||||
Assert.That(preview.Shield, Is.EqualTo(13)); // round(5 * 1.05) + first play 5 + first shield 3.
|
||||
Assert.That(preview.Cost, Is.EqualTo(Math.Max(0, CombatManager.GetCardCost(first) - 1)));
|
||||
Assert.That(combat.PreviewFirstShieldBonus(), Is.EqualTo(3));
|
||||
Assert.That(combat.PreviewCardPlayShield(first), Is.EqualTo(5));
|
||||
Play(first);
|
||||
Assert.That(Player.Shield, Is.EqualTo(preview.Shield));
|
||||
Assert.That(combat.PreviewFirstShieldBonus(), Is.Zero);
|
||||
var second = Card("lang_rs_borrow");
|
||||
Assert.That(CardPreviewService.Build(combat, second).Shield, Is.EqualTo(5));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ConditionalAutoremoveShowsNoDamageWithoutJunkAndExactNestedScalingWithJunk()
|
||||
{
|
||||
Configure("Fedora", 5);
|
||||
var card = Card("fedora_dnf_autoremove");
|
||||
Assert.That(CardPreviewService.Build(combat, card, Target).HasDamage, Is.False);
|
||||
var junk = Card("ubuntu_pro_trial");
|
||||
combat.HandController.Add(junk);
|
||||
card.ApplyMagnitudeUpgrade(2);
|
||||
var preview = CardPreviewService.Build(combat, card, Target);
|
||||
int before = Target.CurrentUptime;
|
||||
Play(card);
|
||||
Assert.That(before - Target.CurrentUptime, Is.EqualTo(preview.MaximumDamage));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RepeatedPreviewLeavesCombatCardResourcesHooksAndRandomSequenceUntouched()
|
||||
{
|
||||
Configure("Fedora", 5);
|
||||
Player.ForceMaxRolls = false;
|
||||
var card = Card("shop_js_promise_all");
|
||||
combat.HandController.Add(card);
|
||||
Player.Shield = 17;
|
||||
Target.Shield = 19;
|
||||
var before = (Player.CurrentUptime, Player.Cycles, Player.Shield, Player.FlatEffectBonus,
|
||||
Player.ArchBtwStacks, Target.CurrentUptime, Target.Shield, card.MagnitudeBonus,
|
||||
card.QueuePlayCount, combat.FedoraCrashChance, combat.CardsPlayedThisRound, combat.LazyStack.Count);
|
||||
int events = 0;
|
||||
Action<DamageDealtEvent> onDamage = _ => events++;
|
||||
GameEvents.DamageDealt += onDamage;
|
||||
RandomRoll.Seed(9182);
|
||||
int expectedRandom = RandomRoll.RollRange(1, 1000000, RollContext.None);
|
||||
RandomRoll.Seed(9182);
|
||||
try
|
||||
{
|
||||
for (int i = 0; i < 40; i++) CardPreviewService.Build(combat, card, Target);
|
||||
Assert.That(RandomRoll.RollRange(1, 1000000, RollContext.None), Is.EqualTo(expectedRandom));
|
||||
Assert.That(events, Is.Zero);
|
||||
Assert.That((Player.CurrentUptime, Player.Cycles, Player.Shield, Player.FlatEffectBonus,
|
||||
Player.ArchBtwStacks, Target.CurrentUptime, Target.Shield, card.MagnitudeBonus,
|
||||
card.QueuePlayCount, combat.FedoraCrashChance, combat.CardsPlayedThisRound, combat.LazyStack.Count), Is.EqualTo(before));
|
||||
Assert.That(combat.HandController.Cards.Single(), Is.SameAs(card));
|
||||
Assert.That(card.TargetSnapshot, Is.Empty);
|
||||
}
|
||||
finally { GameEvents.DamageDealt -= onDamage; }
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AllCatalogCardsPreviewWithoutExecutingEffects()
|
||||
{
|
||||
foreach (var definition in cards.AllCards)
|
||||
{
|
||||
var preview = CardPreviewService.Build(combat, new CardInstance(definition), Target);
|
||||
Assert.That(preview.Summary, Is.Not.Empty, definition.Id);
|
||||
Assert.That(preview.MinimumDamage, Is.GreaterThanOrEqualTo(0), definition.Id);
|
||||
Assert.That(preview.MaximumDamage, Is.GreaterThanOrEqualTo(preview.MinimumDamage), definition.Id);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CustomSerializedEffectsAreNotExecutedDuringPreview()
|
||||
{
|
||||
var definition = ScriptableObject.CreateInstance<CardDefinition>(); temporary.Add(definition);
|
||||
var effect = ScriptableObject.CreateInstance<PreviewSentinelEffect>(); temporary.Add(effect);
|
||||
Set(definition, "id", "lang_c_malloc");
|
||||
Set(definition, "effects", new List<CardEffectDefinition> { effect });
|
||||
var preview = CardPreviewService.Build(combat, new CardInstance(definition), Target);
|
||||
Assert.That(effect.FactoryCalls, Is.Zero);
|
||||
Assert.That(preview.IsConditional, Is.True);
|
||||
Assert.That(preview.Details, Does.Contain("Custom effect"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RecoveryCountdownUpdatesPreviewAndManifestWithoutConsumingRounds()
|
||||
{
|
||||
var card = Card("lang_c_malloc");
|
||||
card.CorruptForRounds(3, 1);
|
||||
var populate = typeof(CombatManager).Assembly.GetType("KernelPanic.UI.SoftwareCardView").GetMethod("Populate");
|
||||
var face = new VisualElement();
|
||||
populate.Invoke(null, new object[] { face, card, 3 });
|
||||
var preview = CardPreviewService.Build(combat, card);
|
||||
Assert.That(preview.Summary, Does.Contain("recovers in 3 rounds"));
|
||||
Assert.That(preview.Details, Does.Contain("restore it sooner"));
|
||||
Assert.That(face.Q<Label>(className: "software-state").text, Does.Contain("RECOVER 3 ROUNDS"));
|
||||
Assert.That(face.tooltip, Does.Contain("Automatic recovery in 3 rounds"));
|
||||
Assert.That(card.CorruptionRoundsRemaining, Is.EqualTo(3));
|
||||
|
||||
card.AdvanceCorruptionRecovery(3);
|
||||
Assert.That(CardPreviewService.Build(combat, card).Summary, Does.Contain("recovers in 1 round"));
|
||||
face.Clear();
|
||||
populate.Invoke(null, new object[] { face, card, 3 });
|
||||
Assert.That(face.Q<Label>(className: "software-state").text, Does.EndWith("1 ROUND"));
|
||||
card.AdvanceCorruptionRecovery(4);
|
||||
face.Clear();
|
||||
populate.Invoke(null, new object[] { face, card, 3 });
|
||||
Assert.That(face.ClassListContains("software-corrupted"), Is.False);
|
||||
Assert.That(CardPreviewService.Build(combat, card).HasDamage, Is.True);
|
||||
Assert.That(face.tooltip, Does.Not.Contain("Automatic recovery in"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UntimedCorruptionDoesNotPromiseAutomaticRecovery()
|
||||
{
|
||||
var card = Card("lang_c_malloc");
|
||||
card.IsBroken = true;
|
||||
var preview = CardPreviewService.Build(combat, card);
|
||||
Assert.That(preview.Summary, Does.Contain("repair required"));
|
||||
Assert.That(preview.Details, Does.Contain("no automatic recovery timer"));
|
||||
Assert.That(preview.Summary, Does.Not.Contain("recovers in"));
|
||||
Assert.That(card.IsBroken, Is.True);
|
||||
Assert.That(card.CorruptionRoundsRemaining, Is.Zero);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RepairPreviewCountsDistinctPileCardsAndScalesOnlyWithCardMagnitude()
|
||||
{
|
||||
Configure("Gentoo", 5);
|
||||
for (int i = 1; i <= 8; i++) combat.Compilation.CompleteRound(i);
|
||||
Player.FlatEffectBonus = 9;
|
||||
var handCard = Card("lang_c_malloc"); handCard.CorruptForRounds(3, 1);
|
||||
var discarded = Card("lang_rs_fn_main"); discarded.IsBroken = true;
|
||||
var exhausted = Card("lang_js_fetch"); exhausted.CorruptForRounds(3, 1);
|
||||
combat.HandController.Add(handCard);
|
||||
combat.DeckController.Discard(discarded);
|
||||
combat.DeckController.Exhaust(exhausted);
|
||||
var card = Card("shop_c_valgrind");
|
||||
card.ApplyMagnitudeUpgrade(2);
|
||||
var preview = CardPreviewService.Build(combat, card);
|
||||
Assert.That(preview.RepairCapacity, Is.EqualTo(5));
|
||||
Assert.That(preview.Repairs, Is.EqualTo(3));
|
||||
Assert.That(preview.Summary, Does.Contain("repair up to 5"));
|
||||
Assert.That(preview.Details, Does.Contain("3 currently corrupted"));
|
||||
Assert.That(combat.CorruptedCardCount, Is.EqualTo(3));
|
||||
Assert.That(handCard.CorruptionRoundsRemaining, Is.EqualTo(3));
|
||||
Play(card);
|
||||
Assert.That(combat.CorruptedCardCount, Is.Zero);
|
||||
Assert.That(Player.Shield, Is.EqualTo(preview.Shield));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CRepairRiderPreviewExplainsRepairAfterPossibleRecoil()
|
||||
{
|
||||
Configure("Ubuntu", 1);
|
||||
Player.ForceMaxRolls = false;
|
||||
var preview = CardPreviewService.Build(combat, Card("lang_c_printf"), Target);
|
||||
Assert.That(preview.HasDamage, Is.True);
|
||||
Assert.That(preview.RepairCapacity, Is.EqualTo(1));
|
||||
Assert.That(preview.Repairs, Is.Zero);
|
||||
Assert.That(preview.Details, Does.Contain("repair a newly corrupted card"));
|
||||
Assert.That(preview.Details, Does.Contain("automatically after 3 rounds"));
|
||||
}
|
||||
|
||||
public sealed class PreviewSentinelEffect : CardEffectDefinition
|
||||
{
|
||||
public int FactoryCalls;
|
||||
public override ICardEffect CreateRuntimeEffect() { FactoryCalls++; throw new InvalidOperationException("Preview must not create effects."); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b22d01a08d5042d2a99293be1ff43823
|
||||
@@ -0,0 +1,260 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Run;
|
||||
using NUnit.Framework;
|
||||
using UnityEngine;
|
||||
|
||||
public class CardUtilityEffectTests
|
||||
{
|
||||
private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
private readonly List<UnityEngine.Object> _temporary = new();
|
||||
private GameObject _owner;
|
||||
private CombatManager _combat;
|
||||
private CombatantState Player => _combat.PlayerState;
|
||||
|
||||
private static object Call(object owner, string method, params object[] args) =>
|
||||
owner.GetType().GetMethod(method, Private).Invoke(owner, args);
|
||||
|
||||
private static void Set(object owner, string field, object value) =>
|
||||
owner.GetType().GetField(field, Private).SetValue(owner, value);
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_owner = new GameObject("card utility regression");
|
||||
_combat = _owner.AddComponent<CombatManager>();
|
||||
Call(_combat, "OnDisable");
|
||||
Call(_combat, "Awake");
|
||||
Set(_combat, "_playerState", new CombatantState(100, 32, 10));
|
||||
Set(_combat, "_handController", new HandController(32));
|
||||
Set(_combat, "currentPhase", TurnPhase.Execute);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
if (_combat != null) Call(_combat, "OnDisable");
|
||||
UnityEngine.Object.DestroyImmediate(_owner);
|
||||
foreach (var item in _temporary) UnityEngine.Object.DestroyImmediate(item);
|
||||
_temporary.Clear();
|
||||
}
|
||||
|
||||
[TestCase("ubuntu", 2, 2)]
|
||||
[TestCase("ubuntu", 3, 3)]
|
||||
[TestCase("ubuntu", 5, 3)]
|
||||
[TestCase("UBUNTU", 3, 3)]
|
||||
[TestCase("mint", 5, 2)]
|
||||
[TestCase(null, 3, 2)]
|
||||
public void CatalogAskUbuntuUsesBonusOnlyForUbuntuVersionThreeAndLater(string distro, int version, int expected)
|
||||
{
|
||||
if (distro != null) Configure(distro, version);
|
||||
FillDeck(10);
|
||||
var card = Card("ubuntu_ask_ubuntu");
|
||||
|
||||
ExecuteCatalog(card);
|
||||
|
||||
Assert.That(_combat.HandController.Cards.Count, Is.EqualTo(expected));
|
||||
Assert.That(_combat.DeckController.DrawPile.Count, Is.EqualTo(10 - expected));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AskUbuntuAppliesSourceAndMagnitudeBonusesOnce()
|
||||
{
|
||||
Configure("ubuntu", 3);
|
||||
FillDeck(12);
|
||||
var card = Card("ubuntu_ask_ubuntu");
|
||||
card.ApplyMagnitudeUpgrade(3);
|
||||
Player.FlatEffectBonus = 2;
|
||||
|
||||
ExecuteCatalog(card);
|
||||
|
||||
Assert.That(_combat.HandController.Cards.Count, Is.EqualTo(8), "Three base draws plus two flat and three magnitude.");
|
||||
Assert.That(_combat.DeckController.DrawPile.Count, Is.EqualTo(4));
|
||||
}
|
||||
|
||||
[TestCase(2)]
|
||||
[TestCase(7)]
|
||||
public void CardDamageBonusDoesNotIncreaseDrawShieldHealStatusesCyclesOrUpgradeCount(int damageBonus)
|
||||
{
|
||||
Configure("ubuntu", 3);
|
||||
Player.FlatEffectBonus = 2; // Existing generic bonuses, including Mint's, remain supported.
|
||||
Player.FlatCardDamageBonus = damageBonus;
|
||||
FillDeck(16);
|
||||
var card = Card("utility_scope");
|
||||
var context = Context(card);
|
||||
new DrawEffect(1).Execute(context);
|
||||
Assert.That(_combat.HandController.Cards.Count, Is.EqualTo(3));
|
||||
new ShieldEffect(1).Execute(context);
|
||||
Assert.That(Player.Shield, Is.EqualTo(3));
|
||||
Player.CurrentUptime = 50;
|
||||
new HaskellMaybeEffect().Execute(context);
|
||||
Assert.That(Player.CurrentUptime, Is.EqualTo(55));
|
||||
new ApplyStatusEffect(StatusType.UnattendedUpgrades, 1, 3, true).Execute(context);
|
||||
Assert.That(Player.StacksOf(StatusType.UnattendedUpgrades), Is.EqualTo(3));
|
||||
new NextTurnCycleEffect(1).Execute(context);
|
||||
Assert.That((int)typeof(CombatManager).GetField("_nextTurnCycleBonus", Private).GetValue(_combat), Is.EqualTo(1));
|
||||
new DrawEffect(1).Execute(context);
|
||||
new UpgradeHandCardsEffect(1, 1).Execute(context);
|
||||
Assert.That(System.Linq.Enumerable.Count(_combat.HandController.Cards, item => item.IsUpgraded), Is.EqualTo(3));
|
||||
Assert.That(Player.FlatCardDamageBonus, Is.EqualTo(damageBonus), "Utility execution does not consume damage stacks.");
|
||||
}
|
||||
|
||||
[TestCase("ubuntu_ask_ubuntu", false)]
|
||||
[TestCase("external_draw", false)]
|
||||
[TestCase("ubuntu_ask_ubuntu", true)]
|
||||
public void GenericDrawHonorsItsCountRegardlessOfCardIdIncludingSerializedOverride(string id, bool serialized)
|
||||
{
|
||||
Configure("ubuntu", 3);
|
||||
FillDeck(12);
|
||||
var card = Card(id);
|
||||
card.ApplyMagnitudeUpgrade(3);
|
||||
Player.FlatEffectBonus = 2;
|
||||
if (serialized)
|
||||
{
|
||||
var authored = ScriptableObject.CreateInstance<CardUtilityDrawTestEffect>();
|
||||
_temporary.Add(authored);
|
||||
Set(card.Definition, "effects", new List<CardEffectDefinition> { authored });
|
||||
ExecuteCatalog(card);
|
||||
}
|
||||
else
|
||||
{
|
||||
new DrawEffect(1).Execute(Context(card));
|
||||
}
|
||||
|
||||
Assert.That(_combat.HandController.Cards.Count, Is.EqualTo(6), "One requested draw plus two flat and three magnitude.");
|
||||
Assert.That(_combat.DeckController.DrawPile.Count, Is.EqualTo(6));
|
||||
}
|
||||
|
||||
[TestCase(true)]
|
||||
[TestCase(false)]
|
||||
public void CleanseHonorsHarmfulOnlyAndReportsEveryRemovedStatus(bool harmfulOnly)
|
||||
{
|
||||
var context = Context(Card("cleanse_test"));
|
||||
var other = new CombatantState(50, 0, 0);
|
||||
context.StatusEffects.Apply(Player, StatusType.MemoryLeak, 2, 3);
|
||||
context.StatusEffects.Apply(Player, StatusType.Segfault, 1, 2);
|
||||
context.StatusEffects.Apply(Player, StatusType.UnattendedUpgrades, 4, 2);
|
||||
context.StatusEffects.Apply(other, StatusType.MemoryLeak, 1, 2);
|
||||
var removed = new List<StatusType>();
|
||||
Action<StatusCleansedEvent> onCleansed = e =>
|
||||
{
|
||||
Assert.That(e.Target, Is.SameAs(Player));
|
||||
removed.Add(e.StatusType);
|
||||
};
|
||||
GameEvents.StatusCleansed += onCleansed;
|
||||
try
|
||||
{
|
||||
new CleanseEffect(harmfulOnly).Execute(context);
|
||||
}
|
||||
finally
|
||||
{
|
||||
GameEvents.StatusCleansed -= onCleansed;
|
||||
}
|
||||
|
||||
Assert.That(Player.HasStatus(StatusType.MemoryLeak), Is.False);
|
||||
Assert.That(Player.HasStatus(StatusType.Segfault), Is.False);
|
||||
Assert.That(Player.HasStatus(StatusType.UnattendedUpgrades), Is.EqualTo(harmfulOnly));
|
||||
Assert.That(Player.Statuses.Count, Is.EqualTo(harmfulOnly ? 1 : 0));
|
||||
Assert.That(other.HasStatus(StatusType.MemoryLeak), Is.True, "Cleanse only affects its source.");
|
||||
Assert.That(removed, Is.EquivalentTo(harmfulOnly
|
||||
? new[] { StatusType.MemoryLeak, StatusType.Segfault }
|
||||
: new[] { StatusType.MemoryLeak, StatusType.Segfault, StatusType.UnattendedUpgrades }));
|
||||
}
|
||||
|
||||
[TestCase(false)]
|
||||
[TestCase(true)]
|
||||
public void CardEffectAndSequencedDrawStopAtBlockedCardAndResumeInOriginalOrder(bool sequenced)
|
||||
{
|
||||
Set(_combat, "_handController", new HandController(4));
|
||||
var first = Card("first", Language.Python);
|
||||
var second = Card("second", Language.Java);
|
||||
var blocked = Card("blocked", Language.Java);
|
||||
var fourth = Card("fourth", Language.C);
|
||||
var fifth = Card("fifth", Language.Rust);
|
||||
SetDrawOrder(first, second, blocked, fourth, fifth);
|
||||
|
||||
Draw(5, sequenced);
|
||||
|
||||
Assert.That(_combat.HandController.Cards, Is.EqualTo(new[] { first, second }));
|
||||
Assert.That(_combat.HandController.RemainingRam, Is.EqualTo(1));
|
||||
Assert.That(_combat.DeckController.DrawPile, Is.EqualTo(new[] { fifth, fourth, blocked }),
|
||||
"Insufficient RAM must not reorder the blocked card or skip it to draw cheaper cards.");
|
||||
|
||||
_combat.HandController.SetRamCapacity(7);
|
||||
Draw(3, sequenced);
|
||||
|
||||
Assert.That(_combat.HandController.Cards, Is.EqualTo(new[] { first, second, blocked, fourth, fifth }));
|
||||
Assert.That(_combat.HandController.UsedRam, Is.EqualTo(7));
|
||||
Assert.That(_combat.DeckController.DrawPile, Is.Empty);
|
||||
}
|
||||
|
||||
private void Configure(string distroId, int version)
|
||||
{
|
||||
var distro = ScriptableObject.CreateInstance<DistroDefinition>();
|
||||
_temporary.Add(distro);
|
||||
Set(distro, "id", distroId);
|
||||
Set(_combat, "_runConfig", new RunConfig(distro, Language.Python, Language.C,
|
||||
Array.Empty<CardDefinition>(), 17, version));
|
||||
}
|
||||
|
||||
private CardInstance Card(string id, Language language = Language.Python)
|
||||
{
|
||||
var definition = ScriptableObject.CreateInstance<CardDefinition>();
|
||||
_temporary.Add(definition);
|
||||
Set(definition, "id", id);
|
||||
Set(definition, "language", language);
|
||||
return new CardInstance(definition);
|
||||
}
|
||||
|
||||
private CombatContext Context(CardInstance card) => new(card, Player, Array.Empty<CombatantState>(),
|
||||
_combat, _combat.DamagePipeline, new StatusEffectController(), _combat.DeckController,
|
||||
_combat.HandController, _combat.Enemies);
|
||||
|
||||
private void ExecuteCatalog(CardInstance card)
|
||||
{
|
||||
var context = Context(card);
|
||||
foreach (var effect in CardEffectFactory.CreateEffects(card.Definition)) effect.Execute(context);
|
||||
}
|
||||
|
||||
private void FillDeck(int count)
|
||||
{
|
||||
for (int i = 0; i < count; i++) _combat.DeckController.AddToDrawPile(Card($"draw_{i}"), false);
|
||||
}
|
||||
|
||||
private void SetDrawOrder(params CardInstance[] cards)
|
||||
{
|
||||
for (int i = cards.Length - 1; i >= 0; i--) _combat.DeckController.AddToDrawPile(cards[i], false);
|
||||
}
|
||||
|
||||
private void Draw(int count, bool sequenced)
|
||||
{
|
||||
if (sequenced)
|
||||
{
|
||||
Finish((IEnumerator)Call(_combat, "DrawCardsToHandSequenced", count, "test draw"));
|
||||
}
|
||||
else
|
||||
{
|
||||
new DrawEffect(count).Execute(Context(Card("draw_effect")));
|
||||
}
|
||||
}
|
||||
|
||||
private static void Finish(IEnumerator routine)
|
||||
{
|
||||
int steps = 0;
|
||||
while (routine.MoveNext())
|
||||
{
|
||||
Assert.That(++steps, Is.LessThan(100), "Draw sequence must terminate.");
|
||||
if (routine.Current is IEnumerator child) Finish(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CardUtilityDrawTestEffect : CardEffectDefinition
|
||||
{
|
||||
public override ICardEffect CreateRuntimeEffect() => new DrawEffect(1);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 608497ea0527498d97a4fe338199e158
|
||||
@@ -0,0 +1,143 @@
|
||||
using System.Collections;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Meta;
|
||||
using KernelPanic.UI;
|
||||
using NUnit.Framework;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using UnityEngine.TestTools;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
public class CollectionLayoutTests
|
||||
{
|
||||
private static readonly Vector2[] Viewports =
|
||||
{
|
||||
new(1280, 720), new(1080, 600), new(390, 844), new(960, 400)
|
||||
};
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator EveryDistroOverviewKeepsReadableSpacingAndWrappedTextAcrossViewports()
|
||||
{
|
||||
if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Null)
|
||||
Assert.Ignore("Collection layout tests require an editor panel; run Unity without -nographics.");
|
||||
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
var originalTextSize = UIPreferences.TextSize;
|
||||
var originalDensity = UIPreferences.Density;
|
||||
try
|
||||
{
|
||||
window.titleContent = new GUIContent("Collection layout verification");
|
||||
window.minSize = new Vector2(100, 100);
|
||||
window.maxSize = new Vector2(4000, 3000);
|
||||
window.Show();
|
||||
var root = window.rootVisualElement;
|
||||
root.styleSheets.Add(AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/UI/MainMenu.uss"));
|
||||
typeof(MainMenuController).Assembly.GetType("KernelPanic.UI.TerminalTheme")
|
||||
.GetMethod("Attach", BindingFlags.Public | BindingFlags.Static)
|
||||
.Invoke(null, new object[] { root });
|
||||
|
||||
var template = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/CollectionScreen.uxml").CloneTree();
|
||||
var panel = template.Q("CollectionPanel");
|
||||
panel.RemoveFromClassList("hidden");
|
||||
root.Add(panel);
|
||||
var database = AssetDatabase.LoadAssetAtPath<DistroDatabase>("Assets/Data/Distros/DistroDatabase.asset");
|
||||
Assert.That(database.AllDistros, Is.Not.Empty);
|
||||
var owned = new PlayerCollection();
|
||||
foreach (var unit in database.AllDistros) owned.Add(unit);
|
||||
var screen = new CollectionScreenController();
|
||||
screen.Bind(root, null, null, null, owned);
|
||||
var scroll = root.Q<ScrollView>("CollectionDetail");
|
||||
|
||||
foreach (var size in Viewports)
|
||||
foreach (var textSize in new[] { UITextSize.Standard, UITextSize.Large })
|
||||
foreach (var density in new[] { UILayoutDensity.Compact, UILayoutDensity.Comfortable })
|
||||
foreach (var unit in database.AllDistros)
|
||||
{
|
||||
UIPreferences.TextSize = textSize;
|
||||
UIPreferences.Density = density;
|
||||
window.position = new Rect(32, 32, size.x, size.y);
|
||||
root.style.width = size.x;
|
||||
root.style.height = size.y;
|
||||
screen.RefreshUnits(new[] { unit });
|
||||
screen.ActivateSelected();
|
||||
for (int frame = 0; frame < 6; frame++) yield return null;
|
||||
|
||||
string context = $"{unit.Id}, {size}, {textSize}, {density}";
|
||||
var identity = scroll.Q(className: "unit-identity-section");
|
||||
var passive = scroll.Q(className: "unit-passive-section");
|
||||
Assert.That(identity, Is.Not.Null, context);
|
||||
Assert.That(passive, Is.Not.Null, context);
|
||||
var identityTitle = identity.Q<Label>(className: "detail-section-title");
|
||||
var languages = identity.Q(className: "kv-row");
|
||||
var description = identity.Q<Label>(className: "collection-detail-description");
|
||||
var passiveTitle = passive.Q<Label>(className: "detail-section-title");
|
||||
var rules = passive.Q<Label>(className: "collection-detail-description");
|
||||
Assert.That(description.text, Is.EqualTo(unit.Description), context);
|
||||
Assert.That(passiveTitle.text, Is.EqualTo(unit.Passive.Name), context);
|
||||
Assert.That(rules.text, Is.EqualTo(unit.Passive.RulesText), context);
|
||||
float copyGap = density == UILayoutDensity.Comfortable ? 14 : 10;
|
||||
float sectionGap = density == UILayoutDensity.Comfortable ? 31.5f : 23.5f;
|
||||
AssertVerticalGap(identityTitle, languages, copyGap, context + ": identity heading");
|
||||
AssertVerticalGap(languages, description, copyGap, context + ": language row");
|
||||
AssertVerticalGap(description, passiveTitle, sectionGap, context + ": passive section");
|
||||
AssertVerticalGap(passiveTitle, rules, copyGap, context + ": passive heading");
|
||||
Assert.That(rules.resolvedStyle.fontSize, Is.EqualTo(textSize == UITextSize.Large ? 17 : 15), context);
|
||||
|
||||
foreach (var section in new[] { identity, passive })
|
||||
{
|
||||
AssertContainedHorizontally(section, scroll.contentViewport, context);
|
||||
foreach (var label in section.Query<Label>().ToList())
|
||||
{
|
||||
AssertContainedHorizontally(label, section, context + ": " + label.text);
|
||||
AssertTextFits(label, context);
|
||||
Assert.That(label.worldBound.yMin, Is.GreaterThanOrEqualTo(section.worldBound.yMin - 1), context);
|
||||
Assert.That(label.worldBound.yMax, Is.LessThanOrEqualTo(section.worldBound.yMax + 1), context);
|
||||
}
|
||||
}
|
||||
var flavor = passive.Q<Label>(className: "flavor-text");
|
||||
if (flavor != null) AssertVerticalGap(rules, flavor, copyGap, context + ": flavor text");
|
||||
|
||||
// On a short viewport the document must scroll, retaining the same gaps and text height.
|
||||
if (size.y == 400)
|
||||
{
|
||||
Assert.That(scroll.contentContainer.layout.height,
|
||||
Is.GreaterThan(scroll.contentViewport.layout.height), context + ": scrollable content");
|
||||
Assert.That(scroll.verticalScroller.highValue, Is.GreaterThan(0), context);
|
||||
scroll.ScrollTo(passive);
|
||||
for (int frame = 0; frame < 2; frame++) yield return null;
|
||||
Assert.That(scroll.scrollOffset.y, Is.GreaterThan(0), context);
|
||||
AssertVerticalGap(passiveTitle, rules, copyGap, context + ": scrolled passive heading");
|
||||
AssertTextFits(rules, context);
|
||||
}
|
||||
}
|
||||
LogAssert.NoUnexpectedReceived();
|
||||
}
|
||||
finally
|
||||
{
|
||||
window.Close();
|
||||
UIPreferences.TextSize = originalTextSize;
|
||||
UIPreferences.Density = originalDensity;
|
||||
}
|
||||
}
|
||||
|
||||
private static void AssertVerticalGap(VisualElement above, VisualElement below, float minimum, string context)
|
||||
{
|
||||
Assert.That(below.worldBound.yMin - above.worldBound.yMax, Is.GreaterThanOrEqualTo(minimum), context);
|
||||
}
|
||||
|
||||
private static void AssertContainedHorizontally(VisualElement child, VisualElement parent, string context)
|
||||
{
|
||||
Assert.That(child.worldBound.xMin, Is.GreaterThanOrEqualTo(parent.worldBound.xMin - 1), context);
|
||||
Assert.That(child.worldBound.xMax, Is.LessThanOrEqualTo(parent.worldBound.xMax + 1), context);
|
||||
}
|
||||
|
||||
private static void AssertTextFits(Label label, string context)
|
||||
{
|
||||
Assert.That(label.contentRect.width, Is.GreaterThan(0), context + ": text width");
|
||||
float requiredHeight = label.MeasureTextSize(label.text, label.contentRect.width,
|
||||
VisualElement.MeasureMode.Exactly, 0, VisualElement.MeasureMode.Undefined).y;
|
||||
Assert.That(label.contentRect.height, Is.GreaterThanOrEqualTo(requiredHeight - 1),
|
||||
context + ": clipped text: " + label.text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2c66c4ce66914695aa3f2c5dcc39eec7
|
||||
@@ -0,0 +1,803 @@
|
||||
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;
|
||||
using UnityEngine.TestTools;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
public class CombatLayoutTests
|
||||
{
|
||||
private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
private static readonly Vector2[] Viewports =
|
||||
{
|
||||
new(1920, 1080), new(1280, 720), new(1080, 600), new(390, 844), new(960, 400)
|
||||
};
|
||||
|
||||
private GameObject _owner;
|
||||
private CombatManager _combat;
|
||||
private RunManager _run;
|
||||
private CombatSceneController _view;
|
||||
private TerminalFocusTestWindow _window;
|
||||
private VisualElement _root;
|
||||
private DistroDefinition _gentoo;
|
||||
private bool _reducedMotion;
|
||||
private UITextSize _textSize;
|
||||
private UILayoutDensity _density;
|
||||
private UnityEngine.Random.State _random;
|
||||
|
||||
private static object Call(object owner, string method, params object[] args) =>
|
||||
owner.GetType().GetMethod(method, Private).Invoke(owner, args);
|
||||
private static void Set(object owner, string field, object value) =>
|
||||
owner.GetType().GetField(field, Private).SetValue(owner, value);
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Null)
|
||||
Assert.Ignore("Layout regression tests require an editor panel; run Unity without -nographics.");
|
||||
_random = UnityEngine.Random.state;
|
||||
_reducedMotion = UIPreferences.ReducedMotion;
|
||||
_textSize = UIPreferences.TextSize;
|
||||
_density = UIPreferences.Density;
|
||||
UIPreferences.ReducedMotion = true;
|
||||
UIPreferences.TextSize = UITextSize.Standard;
|
||||
UIPreferences.Density = UILayoutDensity.Compact;
|
||||
_gentoo = AssetDatabase.LoadAssetAtPath<DistroDefinition>("Assets/Data/Distros/Gentoo.asset");
|
||||
_owner = new GameObject("Combat layout regression");
|
||||
_run = _owner.AddComponent<RunManager>();
|
||||
_combat = _owner.AddComponent<CombatManager>();
|
||||
Call(_combat, "OnDisable");
|
||||
Call(_combat, "Awake");
|
||||
_view = _owner.AddComponent<CombatSceneController>();
|
||||
_window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
_window.titleContent = new GUIContent("Combat layout verification");
|
||||
_window.minSize = new Vector2(100, 100);
|
||||
_window.maxSize = new Vector2(4000, 3000);
|
||||
_window.Show();
|
||||
_root = _window.rootVisualElement;
|
||||
Set(_view, "_root", _root);
|
||||
Set(_view, "_runManager", _run);
|
||||
Set(_view, "_combatManager", _combat);
|
||||
Set(_view, "_distroAccent", _gentoo.AccentColor);
|
||||
Call(_view, "LoadStyles");
|
||||
var theme = typeof(CombatSceneController).Assembly.GetType("KernelPanic.UI.TerminalTheme");
|
||||
theme.GetMethod("Attach").Invoke(null, new object[] { _root });
|
||||
theme.GetMethod("SetDistro").Invoke(null, new object[] { _root, _gentoo });
|
||||
Call(_view, "BuildLayout");
|
||||
Configure(1);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
if (_view != null) Call(_view, "OnDisable");
|
||||
if (_combat != null) Call(_combat, "OnDisable");
|
||||
if (_owner != null)
|
||||
{
|
||||
UIPreferences.ReducedMotion = _reducedMotion;
|
||||
UIPreferences.TextSize = _textSize;
|
||||
UIPreferences.Density = _density;
|
||||
UnityEngine.Random.state = _random;
|
||||
UnityEngine.Object.DestroyImmediate(_owner);
|
||||
}
|
||||
if (_window != null) _window.Close();
|
||||
}
|
||||
|
||||
private void Configure(int version)
|
||||
{
|
||||
var config = new RunConfig(_gentoo, Language.Haskell, Language.C,
|
||||
_gentoo.ExclusiveCards.Take(4).ToArray(), 628207484, version);
|
||||
_run.StartRun(config);
|
||||
Set(_combat, "_runConfig", config);
|
||||
Set(_combat, "_runManager", _run);
|
||||
Set(_combat, "_playerState", new CombatantState(55, 6, 3));
|
||||
Set(_combat, "_handController", new HandController(6));
|
||||
Set(_combat, "currentPhase", TurnPhase.Execute);
|
||||
_combat.Compilation.BeginWave(version);
|
||||
var cards = AssetDatabase.LoadAssetAtPath<CardDatabase>("Assets/Data/Cards/CardDatabase.asset");
|
||||
foreach (var id in new[] { "lang_hs_thunk", "gentoo_emerge_world", "lang_hs_map" })
|
||||
_combat.HandController.Add(new CardInstance(cards.FindById(id)));
|
||||
var enemies = (List<EnemyInstance>)_combat.Enemies;
|
||||
enemies.Clear();
|
||||
enemies.Add(new EnemyInstance(EnemyArchetypeCatalog.Get("zombie_process"), 9));
|
||||
enemies.Add(new EnemyInstance(EnemyArchetypeCatalog.Get("memory_leak"), 4));
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator FirstBattleGuideAndReplayControlFitAcrossViewports()
|
||||
{
|
||||
var guide = (FirstBattleGuide)typeof(CombatSceneController).GetField("_firstBattleGuide", Private).GetValue(_view);
|
||||
guide.Begin(_run.CurrentConfig, true);
|
||||
Call(_view, "RefreshTurnPanel");
|
||||
foreach (var size in Viewports)
|
||||
foreach (var textSize in new[] { UITextSize.Standard, UITextSize.Large })
|
||||
foreach (bool expanded in new[] { false, true })
|
||||
{
|
||||
guide.Element.Q<Foldout>().value = expanded;
|
||||
UIPreferences.TextSize = textSize;
|
||||
Resize(size);
|
||||
for (int frame = 0; frame < 5; frame++) yield return null;
|
||||
string context = $"{size}, {textSize}";
|
||||
foreach (var label in guide.Element.Query<Label>().ToList())
|
||||
AssertContainedHorizontally(label, guide.Element, context);
|
||||
foreach (var chip in guide.Element.Query<Label>(className: "guide-resource").ToList().Where(_ => expanded))
|
||||
{
|
||||
Assert.That(chip.resolvedStyle.paddingLeft, Is.GreaterThanOrEqualTo(8), context);
|
||||
Assert.That(chip.resolvedStyle.marginRight, Is.GreaterThanOrEqualTo(6), context);
|
||||
}
|
||||
foreach (var button in guide.Element.Query<Button>().ToList())
|
||||
AssertContainedHorizontally(button, guide.Element, context);
|
||||
var replay = _root.Q<Button>("ReplayBattleGuide");
|
||||
AssertContainedHorizontally(replay, replay.parent, context);
|
||||
var resources = _root.Q(className: "turn-resource-grid");
|
||||
var endTurn = _root.Q<Button>(className: "primary-action");
|
||||
Assert.That(endTurn.worldBound.yMin, Is.GreaterThanOrEqualTo(resources.worldBound.yMax), context);
|
||||
var prefetch = _root.Q<Button>("PrefetchButton");
|
||||
AssertContainedHorizontally(prefetch, _root, context);
|
||||
float prefetchText = prefetch.MeasureTextSize(prefetch.text, prefetch.contentRect.width,
|
||||
VisualElement.MeasureMode.Exactly, 0, VisualElement.MeasureMode.Undefined).y;
|
||||
Assert.That(prefetch.contentRect.height, Is.GreaterThanOrEqualTo(prefetchText - 1), context);
|
||||
}
|
||||
}
|
||||
|
||||
private void Resize(Vector2 size)
|
||||
{
|
||||
_window.position = new Rect(32, 32, size.x, size.y);
|
||||
// Fixed panel dimensions also cover viewports larger than the available desktop.
|
||||
_root.style.width = size.x;
|
||||
_root.style.height = size.y;
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator TutorialSpotlightKeepsTargetAndControlsReachableAtEveryViewport()
|
||||
{
|
||||
var cards = AssetDatabase.LoadAssetAtPath<CardDatabase>("Assets/Data/Cards/CardDatabase.asset");
|
||||
var config = TutorialCampaign.CreateConfig(_gentoo, cards, 1);
|
||||
_run.StartRun(config); Set(_combat, "_runConfig", config);
|
||||
var overlay = _root.Q(className: "overlay");
|
||||
var type = typeof(CombatSceneController).Assembly.GetType("KernelPanic.UI.TutorialFlow");
|
||||
var flow = Activator.CreateInstance(type, new object[] { overlay, _run, _combat, cards, null, null, config, (Action)(() => {}) });
|
||||
Set(_view, "_tutorial", flow);
|
||||
Call(_view, "RefreshPlayer"); Call(_view, "RefreshTurnPanel");
|
||||
type.GetMethod("Refresh").Invoke(flow, null);
|
||||
foreach (var size in Viewports)
|
||||
foreach (var textSize in new[] { UITextSize.Standard, UITextSize.Large })
|
||||
{
|
||||
UIPreferences.TextSize = textSize; Resize(size);
|
||||
for (int frame = 0; frame < 5; frame++) yield return null;
|
||||
string context = $"tutorial {size}, {textSize}";
|
||||
var panel = overlay.Q("TutorialCallout");
|
||||
var next = panel.Q<Button>("TutorialNext");
|
||||
AssertContainedHorizontally(panel, _root, context);
|
||||
Assert.That(panel.worldBound.width, Is.LessThanOrEqualTo(371), context);
|
||||
Assert.That(panel.worldBound.Overlaps(overlay.Q("TutorialHighlight").worldBound), Is.False, context);
|
||||
Assert.That(overlay.Q("TutorialHighlight").worldBound.width, Is.GreaterThan(20), context);
|
||||
AssertContainedHorizontally(next, panel, context);
|
||||
Assert.That(next.worldBound.yMax, Is.LessThanOrEqualTo(_root.worldBound.yMax + 1), context);
|
||||
Assert.That(next.worldBound.yMin, Is.GreaterThanOrEqualTo(panel.worldBound.yMin), context);
|
||||
Assert.That(panel.Q<ScrollView>("TutorialStepScroll").contentViewport.worldBound.height, Is.GreaterThan(25), context);
|
||||
using var key = KeyDownEvent.GetPooled('e', KeyCode.E, EventModifiers.None);
|
||||
Call(_view, "HandleKeyDown", key);
|
||||
Assert.That(key.isPropagationStopped, Is.True);
|
||||
Assert.That(_combat.CurrentPhase, Is.EqualTo(TurnPhase.Execute));
|
||||
}
|
||||
((IDisposable)flow).Dispose(); Set(_view, "_tutorial", null);
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator GuidedCardIsFullyVisibleOnNarrowScreensAndCannotBeSkipped()
|
||||
{
|
||||
var cards = AssetDatabase.LoadAssetAtPath<CardDatabase>("Assets/Data/Cards/CardDatabase.asset");
|
||||
var config = TutorialCampaign.CreateConfig(_gentoo, cards, 1);
|
||||
_run.StartRun(config); Set(_combat, "_runConfig", config);
|
||||
Set(_combat, "_handController", new HandController(6));
|
||||
foreach (var card in _run.RunDeck) _combat.HandController.Add(card);
|
||||
var overlay = _root.Q(className: "overlay");
|
||||
var type = typeof(CombatSceneController).Assembly.GetType("KernelPanic.UI.TutorialFlow");
|
||||
var flow = Activator.CreateInstance(type, new object[] { overlay, _run, _combat, cards, null, null, config, (Action)(() => {}) });
|
||||
Set(_view, "_tutorial", flow);
|
||||
for (int i = 0; i < 6; i++) _combat.TutorialGuide.Acknowledge(_combat);
|
||||
foreach (var textSize in new[] { UITextSize.Standard, UITextSize.Large })
|
||||
{
|
||||
UIPreferences.TextSize = textSize; Resize(new Vector2(390, 844));
|
||||
Call(_view, "RefreshHand"); Call(_view, "RefreshEnemies");
|
||||
type.GetMethod("Refresh").Invoke(flow, null);
|
||||
for (int frame = 0; frame < 8; frame++) yield return null;
|
||||
var button = _root.Query<Button>(className: "hand-card").ToList().Single(b => b.userData == _combat.TutorialGuide.Card);
|
||||
Assert.That(button.enabledInHierarchy, Is.True);
|
||||
AssertContainedHorizontally(button, _root.Q<ScrollView>(className: "hand-scroll").contentViewport, textSize.ToString());
|
||||
Assert.That(overlay.Q("TutorialCallout").worldBound.Overlaps(overlay.Q("TutorialHighlight").worldBound), Is.False);
|
||||
Assert.That(overlay.Q("TutorialNext").resolvedStyle.display, Is.EqualTo(DisplayStyle.None));
|
||||
type.GetMethod("AdvancePage").Invoke(flow, null);
|
||||
Assert.That(_combat.TutorialGuide.Step.Id, Is.EqualTo("select-attack"));
|
||||
}
|
||||
((IDisposable)flow).Dispose(); Set(_view, "_tutorial", null);
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator VictoryUsesSuccessColourAndExplainsAnUnavailableResumedRecap()
|
||||
{
|
||||
Set(_combat, "<RunCompleted>k__BackingField", true);
|
||||
Set(_run, "currentWaveNumber", 6);
|
||||
Set(_run, "_wavesCleared", 5);
|
||||
var overlay = _root.Q(className: "overlay");
|
||||
overlay.style.display = DisplayStyle.Flex;
|
||||
overlay.Add((VisualElement)Call(_view, "BuildRunEndOverlay"));
|
||||
for (int frame = 0; frame < 5; frame++) yield return null;
|
||||
var title = overlay.Q<Label>(className: "overlay-title");
|
||||
Assert.That(title.text, Is.EqualTo("KERNEL SECURED"));
|
||||
Assert.That(title.resolvedStyle.color.g, Is.GreaterThan(title.resolvedStyle.color.r), "Success must override the shared danger theme.");
|
||||
Assert.That(overlay.Query<Label>().ToList().Any(label => label.text.Contains("recap unavailable")), Is.True);
|
||||
Assert.That(overlay.Query<Label>().ToList().Any(label => label.text.Contains("FINAL ROUND 0")), Is.False);
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator RouteChoicesAndMilestoneRemainReadableAndReachable()
|
||||
{
|
||||
// EditMode does not run the controller's OnEnable subscription.
|
||||
_run.RepositoryChanged += () => Call(_view, "RefreshOverlay");
|
||||
foreach (var size in Viewports)
|
||||
foreach (var textSize in new[] { UITextSize.Standard, UITextSize.Large })
|
||||
foreach (int nextWave in new[] { 2, 3, 6 })
|
||||
{
|
||||
bool milestone = nextWave == 6;
|
||||
UIPreferences.TextSize = textSize;
|
||||
Resize(size);
|
||||
Set(_run, "currentWaveNumber", nextWave);
|
||||
Set(_run, "_wavesCleared", nextWave - 1);
|
||||
_run.Journey.pendingRewardWave = nextWave == 3 ? 2 : 0;
|
||||
_run.GenerateRepositoryOffers(null, null);
|
||||
Set(_combat, "_awaitingWaveContinue", true);
|
||||
Set(_view, "_routeSelectionOpen", false);
|
||||
var overlay = _root.Q(className: "overlay");
|
||||
overlay.Clear(); overlay.style.display = DisplayStyle.Flex;
|
||||
overlay.Add((VisualElement)Call(_view, "BuildRepositoryView"));
|
||||
Assert.That(overlay.Q("RunRouteChoices"), Is.Null, "Shopping must not contain departure choices.");
|
||||
var boot = overlay.Q<Button>("BootNextWaveButton");
|
||||
Assert.That(boot.enabledInHierarchy, Is.True, "Pending rewards and milestones must allow opening departure.");
|
||||
using (var submit = NavigationSubmitEvent.GetPooled())
|
||||
{
|
||||
submit.target = boot;
|
||||
boot.SendEvent(submit);
|
||||
}
|
||||
for (int frame = 0; frame < 6; frame++) yield return null;
|
||||
var section = overlay.Q("RunRouteChoices");
|
||||
var scroll = overlay.Q<ScrollView>(className: "repository-body");
|
||||
string context = $"{size}, {textSize}, milestone={milestone}";
|
||||
Assert.That(section, Is.Not.Null, context);
|
||||
Assert.That(overlay.Q(className: "repository-offers"), Is.Null, context);
|
||||
Assert.That(_combat.AwaitingWaveContinue, Is.True, "Opening departure must not start the wave.");
|
||||
var confirm = overlay.Q<Button>("ConfirmRouteButton");
|
||||
if (milestone) Assert.That(confirm, Is.Null, context);
|
||||
else Assert.That(confirm.enabledInHierarchy, Is.EqualTo(nextWave != 3), context);
|
||||
if (nextWave == 3)
|
||||
{
|
||||
var target = section.Q<Label>("BuildRewardTarget");
|
||||
Assert.That(target, Is.Not.Null, context);
|
||||
Assert.That(target.text, Does.Contain(_run.RunDeck[0].Definition.DisplayName), context);
|
||||
AssertContainedHorizontally(target, scroll.contentViewport, context);
|
||||
Assert.That(section.Q<Button>("RewardBits"), Is.Not.Null, context);
|
||||
}
|
||||
Assert.That(scroll.contentViewport.worldBound.height, Is.GreaterThan(35), context);
|
||||
foreach (var label in section.Query<Label>().ToList())
|
||||
{
|
||||
AssertContainedHorizontally(label, scroll.contentViewport, context);
|
||||
float height = label.MeasureTextSize(label.text, label.contentRect.width,
|
||||
VisualElement.MeasureMode.AtMost, 0, VisualElement.MeasureMode.Undefined).y;
|
||||
Assert.That(height, Is.LessThanOrEqualTo(label.contentRect.height + 2), context + ": " + label.text);
|
||||
}
|
||||
foreach (var button in section.Query<Button>().ToList())
|
||||
{
|
||||
scroll.ScrollTo(button);
|
||||
for (int frame = 0; frame < 2; frame++) yield return null;
|
||||
AssertContainedHorizontally(button, scroll.contentViewport, context);
|
||||
Assert.That(button.worldBound.yMin, Is.GreaterThanOrEqualTo(scroll.contentViewport.worldBound.yMin - 1), context);
|
||||
Assert.That(button.worldBound.yMax, Is.LessThanOrEqualTo(scroll.contentViewport.worldBound.yMax + 1), context);
|
||||
}
|
||||
var back = overlay.Q<Button>("BackToRepositoryButton");
|
||||
AssertContainedHorizontally(back, overlay, context);
|
||||
Assert.That(back.worldBound.yMax, Is.LessThanOrEqualTo(overlay.worldBound.yMax + 1), context);
|
||||
if (!milestone)
|
||||
{
|
||||
AssertContainedHorizontally(confirm, overlay, context);
|
||||
Assert.That(confirm.worldBound.yMax, Is.LessThanOrEqualTo(overlay.worldBound.yMax + 1), context);
|
||||
var challenge = overlay.Q<Button>("RouteChallenge");
|
||||
using (var submit = NavigationSubmitEvent.GetPooled())
|
||||
{
|
||||
submit.target = challenge;
|
||||
challenge.SendEvent(submit);
|
||||
}
|
||||
Assert.That(_run.Journey.selectedRoute, Is.EqualTo(WaveRoute.Challenge), context);
|
||||
Assert.That(overlay.Q("RouteSelectionScreen"), Is.Not.Null, "Route selection must survive refresh.");
|
||||
if (nextWave == 3)
|
||||
{
|
||||
int bitsBefore = _run.Bits;
|
||||
var reward = overlay.Q<Button>("RewardBits");
|
||||
using (var submit = NavigationSubmitEvent.GetPooled())
|
||||
{
|
||||
submit.target = reward;
|
||||
reward.SendEvent(submit);
|
||||
}
|
||||
Assert.That(_run.Bits, Is.EqualTo(bitsBefore + RunManager.BuildRewardBits), context);
|
||||
Assert.That(overlay.Q<Button>("ConfirmRouteButton").enabledInHierarchy, Is.True, context);
|
||||
}
|
||||
}
|
||||
back = overlay.Q<Button>("BackToRepositoryButton");
|
||||
using (var submit = NavigationSubmitEvent.GetPooled())
|
||||
{
|
||||
submit.target = back;
|
||||
back.SendEvent(submit);
|
||||
}
|
||||
Assert.That(overlay.Q("RunRouteChoices"), Is.Null, context);
|
||||
Assert.That(overlay.Q(className: "repository-offers"), Is.Not.Null, context);
|
||||
Assert.That(overlay.Q<Button>("SaveAndExitRunButton").enabledInHierarchy, Is.True, context);
|
||||
if (!milestone) Assert.That(_run.Journey.selectedRoute, Is.EqualTo(WaveRoute.Challenge));
|
||||
LogAssert.NoUnexpectedReceived();
|
||||
}
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator ExecutionPreviewWrapsAndDoesNotDisplaceDispatchControls()
|
||||
{
|
||||
var preview = _root.Q<Foldout>("ExecutionPreview");
|
||||
var view = typeof(CombatSceneController).GetField("_executionPreview", Private).GetValue(_view);
|
||||
view.GetType().GetMethod("Refresh").Invoke(view, new object[] { _combat });
|
||||
foreach (var size in Viewports)
|
||||
foreach (var textSize in new[] { UITextSize.Standard, UITextSize.Large })
|
||||
{
|
||||
UIPreferences.TextSize = textSize;
|
||||
preview.value = false;
|
||||
Resize(size);
|
||||
Call(_view, "RefreshTurnPanel");
|
||||
for (int frame = 0; frame < 3; frame++) yield return null;
|
||||
preview.value = true;
|
||||
for (int frame = 0; frame < 5; frame++) yield return null;
|
||||
var popup = _root.Q("ExecutionPreviewPopup");
|
||||
var scroll = popup == null ? preview.Q<ScrollView>() : popup.Q<ScrollView>();
|
||||
var workspace = _root.Q<ScrollView>(className: "combat-workspace");
|
||||
var visiblePreview = popup == null ? (VisualElement)preview : popup.Q("ExecutionPreviewDialog");
|
||||
var availableArea = popup == null ? workspace.contentViewport : _root;
|
||||
Assert.That(visiblePreview.worldBound.yMin, Is.GreaterThanOrEqualTo(availableArea.worldBound.yMin - 1));
|
||||
Assert.That(visiblePreview.worldBound.yMax, Is.LessThanOrEqualTo(availableArea.worldBound.yMax + 1));
|
||||
foreach (var label in scroll.Query<Label>(className: "terminal-body").ToList())
|
||||
AssertContainedHorizontally(label, scroll.contentViewport, $"{size}/{textSize}");
|
||||
Assert.That(_root.Q<Button>(className: "primary-action").worldBound.yMax,
|
||||
Is.LessThanOrEqualTo(_root.worldBound.yMax + 1));
|
||||
if (popup != null)
|
||||
{
|
||||
var close = popup.Q<Button>("CloseExecutionPreview");
|
||||
using (var endTurn = KeyDownEvent.GetPooled('e', KeyCode.E, EventModifiers.None))
|
||||
{ endTurn.target = close; close.SendEvent(endTurn); }
|
||||
Assert.That(_combat.CurrentPhase, Is.EqualTo(TurnPhase.Execute), "Preview must consume combat shortcuts.");
|
||||
using (var escape = KeyDownEvent.GetPooled('\0', KeyCode.Escape, EventModifiers.None))
|
||||
{ escape.target = close; close.SendEvent(escape); }
|
||||
Assert.That(_root.Q("ExecutionPreviewPopup"), Is.Null);
|
||||
Assert.That(preview.value, Is.False);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator PileInspectorKeepsSearchAndCloseVisibleAndCardDetailsWithinViewport()
|
||||
{
|
||||
var cards = AssetDatabase.LoadAssetAtPath<CardDatabase>("Assets/Data/Cards/CardDatabase.asset");
|
||||
var inventory = cards.AllCards.Where(card => card != null).Take(20).Select(card => new CardInstance(card)).ToArray();
|
||||
foreach (var size in Viewports)
|
||||
foreach (var textSize in new[] { UITextSize.Standard, UITextSize.Large })
|
||||
{
|
||||
UIPreferences.TextSize = textSize;
|
||||
Resize(size);
|
||||
Call(_view, "RefreshTurnPanel");
|
||||
Call(_view, "OpenPileInspector", "draw", inventory);
|
||||
for (int frame = 0; frame < 6; frame++) yield return null;
|
||||
string context = $"{size}, {textSize}";
|
||||
var panel = _root.Q("CardPileInspector");
|
||||
Assert.That(panel, Is.Not.Null, context);
|
||||
AssertContainedHorizontally(panel, _root, context);
|
||||
Assert.That(panel.worldBound.yMin, Is.GreaterThanOrEqualTo(_root.worldBound.yMin - 1), context);
|
||||
Assert.That(panel.worldBound.yMax, Is.LessThanOrEqualTo(_root.worldBound.yMax + 1), context);
|
||||
Assert.That(Mathf.Abs(panel.worldBound.center.x - _root.worldBound.center.x), Is.LessThanOrEqualTo(2), context);
|
||||
Assert.That(Mathf.Abs(panel.worldBound.center.y - _root.worldBound.center.y), Is.LessThanOrEqualTo(2), context);
|
||||
var close = panel.Q<Button>("ClosePileInspector");
|
||||
Assert.That(close.worldBound.yMin, Is.GreaterThanOrEqualTo(panel.worldBound.yMin), context);
|
||||
Assert.That(close.worldBound.yMax, Is.LessThanOrEqualTo(panel.worldBound.yMax), context);
|
||||
var search = panel.Q<TextField>("PileSearch");
|
||||
AssertContainedHorizontally(search, panel, context);
|
||||
if (search.labelElement.resolvedStyle.display != DisplayStyle.None)
|
||||
AssertSingleLineFits(search.labelElement, context);
|
||||
var clear = panel.Q<Button>("ClearPileSearch");
|
||||
Assert.That(clear, Is.Not.Null, context);
|
||||
AssertContainedHorizontally(clear, panel, context);
|
||||
var scroll = panel.Q<ScrollView>("PileCards");
|
||||
foreach (string controlName in new[] { "PileTabs", "PileLanguageFilter", "PileCostFilter", "PileGroupCopies", "ResetPileFilters" })
|
||||
{
|
||||
var control = panel.Q(controlName);
|
||||
AssertContainedHorizontally(control, panel, context + ": " + controlName);
|
||||
Assert.That(control.worldBound.yMax, Is.LessThanOrEqualTo(scroll.worldBound.yMin + 1), context);
|
||||
}
|
||||
Assert.That(scroll.contentViewport.worldBound.height, Is.GreaterThan(40), context);
|
||||
var grid = scroll.Q("PileCardGrid");
|
||||
Assert.That(grid, Is.Not.Null, context);
|
||||
var faces = grid.Query(className: "pile-card").ToList();
|
||||
Assert.That(faces, Has.Count.EqualTo(inventory.Length), context);
|
||||
int expectedColumns = scroll.contentViewport.contentRect.width >= 900 ? 3 :
|
||||
scroll.contentViewport.contentRect.width >= 600 ? 2 : 1;
|
||||
var firstRow = faces.Where(face => Mathf.Abs(face.worldBound.yMin - faces[0].worldBound.yMin) <= 2).ToList();
|
||||
Assert.That(firstRow, Has.Count.EqualTo(expectedColumns), context + ": responsive columns");
|
||||
for (int i = 1; i < firstRow.Count; i++)
|
||||
Assert.That(firstRow[i].worldBound.xMin, Is.GreaterThan(firstRow[i - 1].worldBound.xMax),
|
||||
context + ": cards have a visible gutter");
|
||||
foreach (var card in faces)
|
||||
{
|
||||
AssertContainedHorizontally(card, scroll.contentViewport, context);
|
||||
foreach (var label in card.Query<Label>().ToList())
|
||||
{
|
||||
bool hidden = false;
|
||||
for (var ancestor = (VisualElement)label; ancestor != card; ancestor = ancestor.parent)
|
||||
if (ancestor.resolvedStyle.display == DisplayStyle.None || ancestor is Foldout { value: false }) hidden = true;
|
||||
if (hidden) continue; // Collapsed cost explanations are tested when expanded separately.
|
||||
AssertContainedHorizontally(label, card, context);
|
||||
Assert.That(label.worldBound.yMin, Is.GreaterThanOrEqualTo(card.worldBound.yMin - 1), context);
|
||||
Assert.That(label.worldBound.yMax, Is.LessThanOrEqualTo(card.worldBound.yMax + 1), context);
|
||||
if (!string.IsNullOrEmpty(label.text))
|
||||
{
|
||||
float textHeight = label.MeasureTextSize(label.text, label.contentRect.width,
|
||||
VisualElement.MeasureMode.AtMost, 0, VisualElement.MeasureMode.Undefined).y;
|
||||
Assert.That(textHeight, Is.LessThanOrEqualTo(label.contentRect.height + 2),
|
||||
context + ": label must show every line: " + label.text);
|
||||
}
|
||||
}
|
||||
}
|
||||
using (var pageDown = KeyDownEvent.GetPooled('\0', KeyCode.PageDown, EventModifiers.None))
|
||||
{
|
||||
pageDown.target = search;
|
||||
search.SendEvent(pageDown);
|
||||
}
|
||||
for (int frame = 0; frame < 2; frame++) yield return null;
|
||||
Assert.That(scroll.scrollOffset.y, Is.GreaterThan(0), context + ": PageDown scrolls the inventory");
|
||||
using (var pageUp = KeyDownEvent.GetPooled('\0', KeyCode.PageUp, EventModifiers.None))
|
||||
{
|
||||
pageUp.target = search;
|
||||
search.SendEvent(pageUp);
|
||||
}
|
||||
for (int frame = 0; frame < 2; frame++) yield return null;
|
||||
Assert.That(scroll.scrollOffset.y, Is.EqualTo(0).Within(1), context + ": PageUp returns to the first row");
|
||||
search.value = "no-such-card";
|
||||
Assert.That(scroll.Query(className: "pile-card").ToList(), Is.Empty, context);
|
||||
Assert.That(scroll.Q<Label>("PileEmptyState").text, Does.StartWith("No matching cards."), context);
|
||||
Assert.That(clear.enabledInHierarchy, Is.True, context);
|
||||
using (var submit = NavigationSubmitEvent.GetPooled())
|
||||
{
|
||||
submit.target = clear;
|
||||
clear.SendEvent(submit);
|
||||
}
|
||||
for (int frame = 0; frame < 3; frame++) yield return null;
|
||||
Assert.That(search.value, Is.Empty, context);
|
||||
Assert.That(clear.enabledInHierarchy, Is.False, context);
|
||||
Assert.That(scroll.scrollOffset.y, Is.EqualTo(0).Within(1), context);
|
||||
Assert.That(scroll.Q("PileEmptyState"), Is.Null, context);
|
||||
Assert.That(scroll.Query(className: "pile-card").ToList(), Has.Count.EqualTo(inventory.Length), context);
|
||||
var focused = _root.focusController.focusedElement as VisualElement;
|
||||
Assert.That(focused == search || search.Contains(focused), Is.True, context + ": clearing restores search focus");
|
||||
Call(_view, "ClosePileInspector");
|
||||
for (int frame = 0; frame < 2; frame++) yield return null;
|
||||
Assert.That(_root.focusController.focusedElement, Is.SameAs(_root.Q<Button>("InspectPile_draw")), context);
|
||||
}
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator PileTabsPreserveIndependentSearchFiltersGroupingAndScroll()
|
||||
{
|
||||
var definitions = AssetDatabase.LoadAssetAtPath<CardDatabase>("Assets/Data/Cards/CardDatabase.asset")
|
||||
.AllCards.Where(card => card != null).Take(20).ToArray();
|
||||
var inventory = definitions.SelectMany(card => new[] { new CardInstance(card), new CardInstance(card) }).ToArray();
|
||||
Resize(new Vector2(1280, 720));
|
||||
Call(_view, "OpenPileInspector", "draw", inventory);
|
||||
for (int frame = 0; frame < 6; frame++) yield return null;
|
||||
var panel = _root.Q("CardPileInspector");
|
||||
var grid = panel.Q("PileCardGrid");
|
||||
var scroll = panel.Q<ScrollView>("PileCards");
|
||||
var search = panel.Q<TextField>("PileSearch");
|
||||
var language = panel.Q<DropdownField>("PileLanguageFilter");
|
||||
var cost = panel.Q<DropdownField>("PileCostFilter");
|
||||
var grouped = panel.Q<Toggle>("PileGroupCopies");
|
||||
void Submit(string name)
|
||||
{
|
||||
var button = panel.Q<Button>(name);
|
||||
using var evt = NavigationSubmitEvent.GetPooled();
|
||||
evt.target = button;
|
||||
button.SendEvent(evt);
|
||||
}
|
||||
Assert.That(panel.Q<Button>("PileTab_draw").text, Is.EqualTo("Draw (40)"));
|
||||
Assert.That(grid.Query("PileCard").ToList(), Has.Count.EqualTo(20));
|
||||
Assert.That(grid.Query("PileCard").ToList().Sum(face => (int)face.userData), Is.EqualTo(40));
|
||||
scroll.scrollOffset = new Vector2(0, 150);
|
||||
for (int frame = 0; frame < 3; frame++) yield return null;
|
||||
float previousScroll = scroll.scrollOffset.y;
|
||||
Assert.That(previousScroll, Is.GreaterThan(0));
|
||||
Submit("PileTab_discard");
|
||||
search.value = "independent discard search";
|
||||
Submit("PileTab_draw");
|
||||
for (int frame = 0; frame < 6; frame++) yield return null;
|
||||
Assert.That(search.value, Is.Empty);
|
||||
Assert.That(scroll.scrollOffset.y, Is.EqualTo(previousScroll).Within(1));
|
||||
var definition = definitions.First(card => card.CycleCost <= 2);
|
||||
search.value = definition.Id;
|
||||
language.value = definition.Language.ToString().Replace("CPlusPlus", "C++");
|
||||
cost.value = definition.CycleCost == 1 ? "1 cycle" : definition.CycleCost + " cycles";
|
||||
grouped.value = false;
|
||||
Assert.That(grid.Query("PileCard").ToList(), Has.Count.EqualTo(2));
|
||||
Submit("PileTab_discard");
|
||||
Assert.That(search.value, Is.EqualTo("independent discard search"));
|
||||
Assert.That(language.value, Is.EqualTo("All languages"));
|
||||
Assert.That(cost.value, Is.EqualTo("Any stored cost"));
|
||||
Assert.That(grouped.value, Is.True);
|
||||
Submit("PileTab_draw");
|
||||
Assert.That(search.value, Is.EqualTo(definition.Id));
|
||||
Assert.That(language.value, Is.EqualTo(definition.Language.ToString().Replace("CPlusPlus", "C++")));
|
||||
Assert.That(grouped.value, Is.False);
|
||||
Assert.That(grid.Query("PileCard").ToList(), Has.Count.EqualTo(2));
|
||||
Submit("ResetPileFilters");
|
||||
Assert.That(grid.Query("PileCard").ToList(), Has.Count.EqualTo(40));
|
||||
grouped.value = true;
|
||||
var foldout = grid.Q<Foldout>("PileCostDetails");
|
||||
foldout.value = true;
|
||||
for (int frame = 0; frame < 6; frame++) yield return null;
|
||||
var explanation = foldout.Q<Label>(className: "pile-cost-explanation");
|
||||
Assert.That(explanation.worldBound.height, Is.GreaterThan(0));
|
||||
Assert.That(explanation.text, Does.Contain("Drawing or playing cards can change it"));
|
||||
AssertContainedHorizontally(explanation, foldout, "Expanded cost explanation");
|
||||
language.Focus();
|
||||
for (int frame = 0; frame < 2; frame++) yield return null;
|
||||
var focusedLanguage = _root.focusController.focusedElement as VisualElement;
|
||||
Assert.That(focusedLanguage == language || language.Contains(focusedLanguage), Is.True,
|
||||
"The language dropdown must receive focus before testing keyboard traversal.");
|
||||
using (var tab = KeyDownEvent.GetPooled('\t', KeyCode.Tab, EventModifiers.None))
|
||||
{
|
||||
tab.target = language;
|
||||
language.SendEvent(tab);
|
||||
}
|
||||
for (int frame = 0; frame < 2; frame++) yield return null;
|
||||
var focusedCost = _root.focusController.focusedElement as VisualElement;
|
||||
Assert.That(focusedCost == cost || cost.Contains(focusedCost), Is.True, "Tab advances exactly once, including Unity's generated navigation event.");
|
||||
using (var tab = KeyDownEvent.GetPooled('\t', KeyCode.Tab, EventModifiers.Shift))
|
||||
{
|
||||
tab.target = cost;
|
||||
cost.SendEvent(tab);
|
||||
}
|
||||
for (int frame = 0; frame < 2; frame++) yield return null;
|
||||
Assert.That(_root.focusController.focusedElement, Is.SameAs(language), "Shift+Tab returns to the language filter.");
|
||||
}
|
||||
|
||||
private static void AssertContainedHorizontally(VisualElement child, VisualElement parent, string context)
|
||||
{
|
||||
Assert.That(child.worldBound.xMin, Is.GreaterThanOrEqualTo(parent.worldBound.xMin - 1), context);
|
||||
Assert.That(child.worldBound.xMax, Is.LessThanOrEqualTo(parent.worldBound.xMax + 1), context);
|
||||
}
|
||||
|
||||
private static void AssertSingleLineFits(Label label, string context)
|
||||
{
|
||||
Assert.That(label, Is.Not.Null, context);
|
||||
float textWidth = label.MeasureTextSize(label.text, 0, VisualElement.MeasureMode.Undefined,
|
||||
0, VisualElement.MeasureMode.Undefined).x;
|
||||
Assert.That(textWidth, Is.LessThanOrEqualTo(label.contentRect.width + 2), context + ": " + label.text);
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator PendingStackTooltipsUseCapturedMultipliersAndCurrentCompilation()
|
||||
{
|
||||
var first = _combat.HandController.Cards[0];
|
||||
var second = _combat.HandController.Cards[1];
|
||||
_combat.LazyStack.Enqueue(first);
|
||||
_combat.LazyStack.Enqueue(second);
|
||||
Resize(new Vector2(1280, 720));
|
||||
Call(_view, "RefreshTracks");
|
||||
for (int frame = 0; frame < 4; frame++) yield return null;
|
||||
var chip = _root.Query(className: "card-chip").ToList().Single(item => item.userData == second);
|
||||
Assert.That(chip.focusable, Is.True);
|
||||
Assert.That(chip.tooltip, Does.Contain("Haskell captured: x1.5"));
|
||||
Assert.That(chip.tooltip, Does.Contain("Already played"));
|
||||
Assert.That(chip.tooltip, Does.Not.Contain("Successful play package Shield"));
|
||||
Assert.That(chip.tooltip, Does.Contain("Compilation 0/4"));
|
||||
_combat.Compilation.CompleteRound(1);
|
||||
chip.Focus();
|
||||
Call(_view, "RefreshTracks");
|
||||
Assert.That(_root.focusController.focusedElement, Is.SameAs(chip));
|
||||
Assert.That(chip.tooltip, Does.Contain("Compilation 1/4"));
|
||||
Assert.That(chip.tooltip, Does.Contain("Haskell captured: x1.5"));
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator LivePreviewsAndPackageReadinessWrapAndRetainKeyboardFocus()
|
||||
{
|
||||
var packages = AssetDatabase.LoadAssetAtPath<PackageDatabase>("Assets/Data/Packages/PackageDatabase.asset");
|
||||
var config = new RunConfig(_gentoo, Language.Haskell, Language.C, _gentoo.ExclusiveCards.Take(4).ToArray(),
|
||||
new[] { "pkg_gentoo_portage", "pkg_gentoo_ccache", "pkg_gentoo_openrc" }
|
||||
.Select(id => new PackageInstance(packages.FindById(id), 5)).ToArray(), 628207484, 5);
|
||||
Set(_combat, "_runConfig", config);
|
||||
_combat.Compilation.BeginWave(5);
|
||||
foreach (var size in Viewports)
|
||||
foreach (var textSize in new[] { UITextSize.Standard, UITextSize.Large })
|
||||
foreach (var density in new[] { UILayoutDensity.Compact, UILayoutDensity.Comfortable })
|
||||
{
|
||||
UIPreferences.TextSize = textSize;
|
||||
UIPreferences.Density = density;
|
||||
Resize(size);
|
||||
Call(_view, "RefreshPackageReadiness");
|
||||
Call(_view, "RefreshHand");
|
||||
for (int frame = 0; frame < 6; frame++) yield return null;
|
||||
string context = $"{size}, {textSize}, {density}";
|
||||
var strip = _root.Q("PackageReadiness");
|
||||
var chips = strip.Query(className: "package-readiness-chip").ToList();
|
||||
Assert.That(chips.Count, Is.EqualTo(3), context);
|
||||
foreach (var chip in chips)
|
||||
{
|
||||
AssertContainedHorizontally(chip, strip, context);
|
||||
Assert.That(chip.worldBound.height, Is.GreaterThan(16), context);
|
||||
Assert.That(chip.tooltip, Does.Contain("\n"), context);
|
||||
foreach (var label in chip.Query<Label>().ToList())
|
||||
AssertContainedHorizontally(label, chip, context);
|
||||
}
|
||||
var ccache = _root.Q("Readiness_pkg_gentoo_ccache");
|
||||
ccache.Focus();
|
||||
Call(_view, "RefreshPackageReadiness");
|
||||
Assert.That(_root.focusController.focusedElement, Is.SameAs(ccache), context);
|
||||
foreach (var face in _root.Query(className: "hand-card").ToList())
|
||||
{
|
||||
var preview = face.Q<Label>(className: "software-live-preview");
|
||||
Assert.That(preview, Is.Not.Null, context);
|
||||
AssertContainedHorizontally(preview, face, context);
|
||||
Assert.That(preview.text, Does.StartWith("preview:"), context);
|
||||
Assert.That(face.tooltip, Is.EqualTo("Current estimate; targets, defenses and later effects can change the result."), context);
|
||||
Assert.That(face.tooltip.Length, Is.LessThan(160), "Hover help must not repeat the full calculation breakdown.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator CompilationReadoutKeepsEveryLevelAndModifierDistinctAcrossViewports()
|
||||
{
|
||||
foreach (var size in Viewports)
|
||||
foreach (var textSize in new[] { UITextSize.Standard, UITextSize.Large })
|
||||
foreach (var density in new[] { UILayoutDensity.Compact, UILayoutDensity.Comfortable })
|
||||
foreach (int version in new[] { 1, 5 })
|
||||
foreach (bool atCap in new[] { false, true })
|
||||
{
|
||||
UIPreferences.TextSize = textSize;
|
||||
UIPreferences.Density = density;
|
||||
Configure(version);
|
||||
if (atCap)
|
||||
for (int round = 1; round <= 6; round++) _combat.Compilation.CompleteRound(round);
|
||||
Resize(size);
|
||||
Call(_view, "RefreshPlayer");
|
||||
Call(_view, "RefreshTracks");
|
||||
Call(_view, "RefreshEnemies");
|
||||
Call(_view, "RefreshHand");
|
||||
Call(_view, "RefreshTurnPanel");
|
||||
for (int frame = 0; frame < 6; frame++) yield return null;
|
||||
|
||||
string context = $"{size}, V{version}, level {_combat.Compilation.Level}, {textSize}, {density}";
|
||||
var panel = _root.Q(className: "compilation-panel");
|
||||
Assert.That(panel, Is.Not.Null, context);
|
||||
AssertContainedHorizontally(panel, _root.Q(className: "player-panel"), context);
|
||||
var title = panel.Q<Label>(className: "compilation-title");
|
||||
var level = panel.Q<Label>(className: "compilation-level");
|
||||
Assert.That(title.text, Is.EqualTo("Compilation"));
|
||||
Assert.That(level.text, Is.EqualTo($"{_combat.Compilation.Level}/{_combat.Compilation.Maximum}"));
|
||||
AssertSingleLineFits(title, context);
|
||||
AssertSingleLineFits(level, context);
|
||||
Assert.That(title.worldBound.xMax, Is.LessThanOrEqualTo(level.worldBound.xMin + 1), context);
|
||||
|
||||
var progress = panel.Q(className: "compilation-progress");
|
||||
var steps = progress.Query(className: "compilation-step").ToList();
|
||||
Assert.That(steps.Count, Is.EqualTo(version == 5 ? 6 : 4), context);
|
||||
Assert.That(steps.Count(s => s.ClassListContains("compilation-step-filled")),
|
||||
Is.EqualTo(_combat.Compilation.Level), context);
|
||||
for (int i = 0; i < steps.Count; i++)
|
||||
{
|
||||
Assert.That(steps[i].worldBound.width, Is.GreaterThan(4), context);
|
||||
Assert.That(steps[i].worldBound.height, Is.GreaterThan(2), context);
|
||||
AssertContainedHorizontally(steps[i], panel, context);
|
||||
if (i > 0)
|
||||
Assert.That(steps[i - 1].worldBound.xMax, Is.LessThanOrEqualTo(steps[i].worldBound.xMin + 1), context);
|
||||
}
|
||||
Assert.That(progress.worldBound.yMin, Is.GreaterThanOrEqualTo(title.worldBound.yMax - 1), context);
|
||||
var modifiers = panel.Query(className: "compilation-modifier").ToList();
|
||||
Assert.That(modifiers.Count, Is.EqualTo(version == 5 ? 2 : 1), context);
|
||||
float precedingBottom = progress.worldBound.yMax;
|
||||
foreach (var row in modifiers)
|
||||
{
|
||||
var label = row.Q<Label>(className: "compilation-label");
|
||||
var value = row.Q<Label>(className: "compilation-value");
|
||||
AssertSingleLineFits(label, context);
|
||||
AssertSingleLineFits(value, context);
|
||||
Assert.That(label.worldBound.xMax, Is.LessThanOrEqualTo(value.worldBound.xMin + 1), context);
|
||||
Assert.That(row.worldBound.yMin, Is.GreaterThanOrEqualTo(precedingBottom - 1), context);
|
||||
AssertContainedHorizontally(value, panel, context);
|
||||
precedingBottom = row.worldBound.yMax;
|
||||
}
|
||||
Assert.That(panel.worldBound.yMax, Is.GreaterThanOrEqualTo(precedingBottom - 1), context);
|
||||
LogAssert.NoUnexpectedReceived();
|
||||
}
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator RunEndReportCentersAndKeepsRewardsAndReturnReachableAcrossViewports()
|
||||
{
|
||||
Configure(5);
|
||||
Set(_run, "currentWaveNumber", 5);
|
||||
Set(_run, "_wavesCleared", 4);
|
||||
Set(_run, "_accruedBandwidth", 70);
|
||||
Set(_run, "_accruedEntropy", 0);
|
||||
foreach (var size in Viewports)
|
||||
foreach (var textSize in new[] { UITextSize.Standard, UITextSize.Large })
|
||||
foreach (var density in new[] { UILayoutDensity.Compact, UILayoutDensity.Comfortable })
|
||||
foreach (bool surrendered in new[] { false, true })
|
||||
{
|
||||
UIPreferences.TextSize = textSize;
|
||||
UIPreferences.Density = density;
|
||||
Resize(size);
|
||||
Set(_view, "_runEndedBySurrender", surrendered);
|
||||
var overlay = _root.Q(className: "overlay");
|
||||
overlay.Clear();
|
||||
overlay.style.display = DisplayStyle.Flex;
|
||||
overlay.Add((VisualElement)Call(_view, "BuildRunEndOverlay"));
|
||||
for (int frame = 0; frame < 8; frame++) yield return null;
|
||||
|
||||
string context = $"{size}, surrendered={surrendered}, {textSize}, {density}";
|
||||
var scroll = overlay.Q<ScrollView>(className: "death-scroll");
|
||||
var content = overlay.Q(className: "death-content");
|
||||
var viewport = scroll.contentViewport;
|
||||
Assert.That(viewport.worldBound.yMin, Is.GreaterThanOrEqualTo(_root.worldBound.yMin - 1), context);
|
||||
Assert.That(viewport.worldBound.yMax, Is.LessThanOrEqualTo(_root.worldBound.yMax + 1), context);
|
||||
if (size.x >= 1080 && size.y >= 600 && textSize == UITextSize.Standard && density == UILayoutDensity.Compact)
|
||||
Assert.That(content.worldBound.height, Is.LessThanOrEqualTo(viewport.worldBound.height), context);
|
||||
var button = content.Q<Button>(className: "death-return-action");
|
||||
Assert.That(content.Q<Label>(className: "overlay-title").text,
|
||||
Is.EqualTo(surrendered ? "SYSTEM HALTED" : "KERNEL PANIC"), context);
|
||||
Assert.That(button, Is.Not.Null, context);
|
||||
Assert.That(button.enabledInHierarchy, Is.True, context);
|
||||
Assert.That(content.Q<Label>(className: "death-session").text, Does.Contain("Gentoo"), context);
|
||||
Assert.That(content.Q<Label>(className: "death-seed").text, Does.Contain("628207484"), context);
|
||||
var stats = content.Q(className: "death-wave-stats").Query(className: "death-stat-row").ToList();
|
||||
Assert.That(stats.Count, Is.EqualTo(2), context);
|
||||
Assert.That(stats[0].Q<Label>(className: "death-stat-value").text, Is.EqualTo("5"), context);
|
||||
Assert.That(stats[1].Q<Label>(className: "death-stat-value").text, Is.EqualTo("4"), context);
|
||||
Assert.That(content.Q(className: "death-reward-bandwidth").Q<Label>(className: "death-reward-value").text,
|
||||
Is.EqualTo("+70"), context);
|
||||
Assert.That(content.Q(className: "death-reward-entropy").Q<Label>(className: "death-reward-value").text,
|
||||
Is.EqualTo("+0"), context);
|
||||
AssertContainedHorizontally(content, viewport, context);
|
||||
Assert.That(Mathf.Abs(content.worldBound.center.x - viewport.worldBound.center.x), Is.LessThanOrEqualTo(2), context);
|
||||
foreach (var label in content.Query<Label>().ToList())
|
||||
AssertContainedHorizontally(label, content, context + ": " + label.text);
|
||||
foreach (var value in content.Query<Label>(className: "death-reward-value").ToList())
|
||||
AssertSingleLineFits(value, context);
|
||||
|
||||
if (content.worldBound.height <= viewport.worldBound.height)
|
||||
Assert.That(Mathf.Abs(content.worldBound.center.y - viewport.worldBound.center.y), Is.LessThanOrEqualTo(2), context);
|
||||
else
|
||||
{
|
||||
Assert.That(content.worldBound.yMin, Is.GreaterThanOrEqualTo(viewport.worldBound.yMin - 1), context);
|
||||
Assert.That(scroll.contentContainer.layout.height, Is.GreaterThan(viewport.layout.height), context);
|
||||
scroll.ScrollTo(button);
|
||||
for (int frame = 0; frame < 3; frame++) yield return null;
|
||||
Assert.That(scroll.scrollOffset.y, Is.GreaterThan(0), context);
|
||||
Assert.That(button.worldBound.yMin, Is.GreaterThanOrEqualTo(viewport.worldBound.yMin - 1), context);
|
||||
Assert.That(button.worldBound.yMax, Is.LessThanOrEqualTo(viewport.worldBound.yMax + 1), context);
|
||||
}
|
||||
AssertContainedHorizontally(button, viewport, context);
|
||||
LogAssert.NoUnexpectedReceived();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: df6cef7e08934d48be32e3bd3a271a8b
|
||||
@@ -0,0 +1,181 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.UI;
|
||||
using NUnit.Framework;
|
||||
using UnityEngine;
|
||||
using UnityEngine.TestTools;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
public class CombatPresentationTests
|
||||
{
|
||||
static Type UiType(string name) => typeof(MainMenuController).Assembly.GetType("KernelPanic.UI." + name);
|
||||
static object Invoke(object owner, string method, params object[] args) => owner.GetType().GetMethod(method).Invoke(owner, args);
|
||||
static string Presentation(string method, object value) => (string)UiType("EnemyProcessPresentation").GetMethod(method).Invoke(null, new[] { value });
|
||||
CardDefinition _definition;
|
||||
|
||||
[SetUp] public void CreateCard()
|
||||
{
|
||||
_definition = ScriptableObject.CreateInstance<CardDefinition>();
|
||||
typeof(CardDefinition).GetField("displayName", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(_definition, "test operation");
|
||||
}
|
||||
[TearDown] public void DestroyCard() => UnityEngine.Object.DestroyImmediate(_definition);
|
||||
|
||||
[TestCase(false)] [TestCase(true)]
|
||||
public void ExecutionObservationPreservesFifoAndLifo(bool stack)
|
||||
{
|
||||
var cards = new[] { new CardInstance(_definition), new CardInstance(_definition), new CardInstance(_definition) };
|
||||
IResolutionTrack track = stack ? new LazyStack() : new InterpreterQueue();
|
||||
var observed = new List<CardInstance>();
|
||||
var completed = new List<CardInstance>();
|
||||
Action<CardResolvedEvent> start = e => observed.Add(e.Card);
|
||||
Action<CardResolvedEvent> end = e => { Assert.That(observed[observed.Count - 1], Is.SameAs(e.Card)); completed.Add(e.Card); };
|
||||
GameEvents.CardResolving += start;
|
||||
GameEvents.CardResolved += end;
|
||||
try
|
||||
{
|
||||
foreach (var card in cards) track.Enqueue(card);
|
||||
if (track is LazyStack lazy)
|
||||
{
|
||||
// Storage cannot execute without CombatManager now. Observe explicit pops;
|
||||
// GentooHaskellTests separately exercises real effects and exactly-once disposal.
|
||||
track.Resolve(null);
|
||||
Assert.That(observed, Is.Empty);
|
||||
while (lazy.TryPop(out var card))
|
||||
GameEvents.RaiseCardResolved(new CardResolvedEvent(card, ResolutionTrack.LazyStack));
|
||||
}
|
||||
else track.Resolve(null);
|
||||
var expected = stack ? new[] { cards[2], cards[1], cards[0] } : cards;
|
||||
CollectionAssert.AreEqual(expected, observed);
|
||||
CollectionAssert.AreEqual(expected, completed);
|
||||
track.Resolve(null);
|
||||
Assert.That(completed.Count, Is.EqualTo(3), "Empty resolution does not replay observations");
|
||||
}
|
||||
finally { GameEvents.CardResolving -= start; GameEvents.CardResolved -= end; }
|
||||
}
|
||||
|
||||
[TestCase(false)] [TestCase(true)]
|
||||
public void SchedulerKeepsPendingIdentityAndCompletedReceipt(bool stack)
|
||||
{
|
||||
var zone = new VisualElement();
|
||||
var contents = new VisualElement { userData = zone };
|
||||
zone.Add(contents);
|
||||
var view = Activator.CreateInstance(UiType("ExecutionTrackView"), contents, stack);
|
||||
var first = new CardInstance(_definition);
|
||||
var next = new CardInstance(_definition);
|
||||
try
|
||||
{
|
||||
Invoke(view, "Sync", (object)new[] { first, next });
|
||||
var chip = contents.ElementAt(0);
|
||||
Invoke(view, "Sync", (object)new[] { first, next });
|
||||
Assert.That(contents.ElementAt(0), Is.SameAs(chip));
|
||||
Assert.That(chip.Q<Label>(className: "execution-order").text, Is.EqualTo(stack ? "TOP >" : "01 >"));
|
||||
Invoke(view, "Resolving", first);
|
||||
Invoke(view, "Sync", (object)new[] { next });
|
||||
Assert.That(chip.ClassListContains("operation-active"), Is.True);
|
||||
Invoke(view, "Resolved", first, 1);
|
||||
Invoke(view, "Sync", (object)new[] { next });
|
||||
Assert.That(chip.ClassListContains("operation-complete"), Is.True);
|
||||
Assert.That(chip.Q<Label>(className: "execution-order").text, Is.EqualTo("01 OK"));
|
||||
Assert.That(contents.Query(className: "card-chip").ToList().Count, Is.EqualTo(2));
|
||||
Invoke(view, "Resolving", next);
|
||||
Invoke(view, "Resolved", next, 2);
|
||||
Assert.That(contents.ElementAt(0), Is.SameAs(chip), "Completion receipts retain chronological order");
|
||||
}
|
||||
finally { ((IDisposable)view).Dispose(); }
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator CompletedReceiptExpiresWithoutChangingQueue()
|
||||
{
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
window.Show();
|
||||
var contents = new VisualElement { userData = window.rootVisualElement };
|
||||
window.rootVisualElement.Add(contents);
|
||||
var view = Activator.CreateInstance(UiType("ExecutionTrackView"), contents, false);
|
||||
var card = new CardInstance(_definition);
|
||||
try
|
||||
{
|
||||
Invoke(view, "Sync", (object)new[] { card });
|
||||
Invoke(view, "Resolving", card);
|
||||
Invoke(view, "Resolved", card, 1);
|
||||
yield return new WaitForSecondsRealtime(.9f);
|
||||
Assert.That(contents.Query(className: "card-chip").ToList(), Is.Empty);
|
||||
Assert.That(contents.Q<Label>(className: "track-empty").text, Is.EqualTo("empty"));
|
||||
}
|
||||
finally { ((IDisposable)view).Dispose(); window.Close(); }
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RevivalIsNotPermanentTermination()
|
||||
{
|
||||
var zombie = new EnemyInstance(EnemyArchetypeCatalog.Get("zombie_process"), 30);
|
||||
zombie.MarkPendingRevive();
|
||||
Assert.That(Presentation("Lifecycle", zombie), Is.EqualTo("RESTART PENDING"));
|
||||
Assert.That(zombie.State.IsDefeated, Is.False, "MarkPendingRevive clears defeat before the pipeline's post-hit check");
|
||||
zombie.ReviveAtHalfUptime();
|
||||
Assert.That(Presentation("Lifecycle", zombie), Is.EqualTo("RUNNING / RESTART USED"));
|
||||
Assert.That(zombie.CurrentUptime, Is.EqualTo(15));
|
||||
zombie.State.IsDefeated = true;
|
||||
Assert.That(Presentation("Lifecycle", zombie), Is.EqualTo("TERMINATED"));
|
||||
}
|
||||
|
||||
[TestCase("zombie_process", "[Z]")] [TestCase("memory_leak", "[++]")]
|
||||
[TestCase("fork_bomb", ":|:")] [TestCase("firewalld", "[#]")]
|
||||
[TestCase("cron_job", "[@]")] [TestCase("rootkit", "[?]")]
|
||||
public void ProcessIdentityUsesActualArchetype(string id, string symbol) => Assert.That(Presentation("Symbol", id), Is.EqualTo(symbol));
|
||||
|
||||
[Test]
|
||||
public void GrowthReadoutUsesTurnsNotInventedMultiplier()
|
||||
{
|
||||
var leak = new EnemyInstance(EnemyArchetypeCatalog.Get("memory_leak"), 20);
|
||||
leak.MarkTurnSurvived(); leak.MarkTurnSurvived();
|
||||
Assert.That(Presentation("Behavior", leak), Is.EqualTo("Growing attack / 2 turns survived"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PendingRestartTakesPrecedenceOverPipelineDefeatFlag()
|
||||
{
|
||||
var owner = new GameObject("combat observation test");
|
||||
try
|
||||
{
|
||||
var manager = owner.AddComponent<CombatManager>();
|
||||
// EditMode does not run the normal MonoBehaviour activation lifecycle.
|
||||
var observeDamage = (Action<DamageDealtEvent>)Delegate.CreateDelegate(typeof(Action<DamageDealtEvent>), manager,
|
||||
typeof(CombatManager).GetMethod("HandlePackageDamageDealt", BindingFlags.NonPublic | BindingFlags.Instance));
|
||||
GameEvents.DamageDealt -= observeDamage;
|
||||
GameEvents.DamageDealt += observeDamage;
|
||||
var zombie = new EnemyInstance(EnemyArchetypeCatalog.Get("zombie_process"), 30);
|
||||
((List<EnemyInstance>)manager.Enemies).Add(zombie);
|
||||
try { manager.DamagePipeline.DealDamage(new DamageRequest(new CombatantState(20, 0, 0), zombie.State, 31, Language.Python, false, false)); }
|
||||
finally { GameEvents.DamageDealt -= observeDamage; }
|
||||
Assert.That(zombie.PendingRevive, Is.True);
|
||||
Assert.That(Presentation("Lifecycle", zombie), Is.EqualTo("RESTART PENDING"));
|
||||
Assert.That(zombie.CurrentUptime, Is.Zero);
|
||||
}
|
||||
finally { UnityEngine.Object.DestroyImmediate(owner); }
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DamagePayloadKeepsShieldAndUptimeSeparate()
|
||||
{
|
||||
var source = new CombatantState(30, 0, 0);
|
||||
var target = new CombatantState(30, 0, 0) { Shield = 4 };
|
||||
DamageDealtEvent observed = default;
|
||||
Action<DamageDealtEvent> handler = e => observed = e;
|
||||
GameEvents.DamageDealt += handler;
|
||||
try
|
||||
{
|
||||
new DamagePipeline().DealDamage(new DamageRequest(source, target, 10, Language.Python, false, false));
|
||||
Assert.That(observed.ShieldDamage, Is.EqualTo(4));
|
||||
Assert.That(observed.UptimeDamage, Is.EqualTo(6));
|
||||
Assert.That(target.CurrentUptime, Is.EqualTo(24));
|
||||
Assert.That(target.Shield, Is.Zero);
|
||||
}
|
||||
finally { GameEvents.DamageDealt -= handler; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0b1305c877c00d34d8cf479d15cf6c13
|
||||
@@ -0,0 +1,265 @@
|
||||
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<CardDatabase>("Assets/Data/Cards/CardDatabase.asset");
|
||||
var distro = AssetDatabase.LoadAssetAtPath<DistroDefinition>("Assets/Data/Distros/Gentoo.asset");
|
||||
var config = new RunConfig(distro, Language.C, Language.Haskell, Array.Empty<CardDefinition>(), 91, 5);
|
||||
owner = new GameObject("Timed corruption regression");
|
||||
run = owner.AddComponent<RunManager>();
|
||||
combat = owner.AddComponent<CombatManager>();
|
||||
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<EnemyInstance>)combat.Enemies).Add(new EnemyInstance("regression target", 10000, Array.Empty<EnemyIntent>()));
|
||||
}
|
||||
|
||||
[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<CardInstance>)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<CardInstance>)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<CardInstance>)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<CardInstance>)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<string>(); 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<CombatantState>());
|
||||
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.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9c26165cf4cd44c29a064f6effbcfcbe
|
||||
@@ -0,0 +1,318 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using NUnit.Framework;
|
||||
using UnityEngine;
|
||||
|
||||
public class DamageEffectExecutionTests
|
||||
{
|
||||
private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
private static readonly FieldInfo CombatRandom = typeof(RandomRoll).GetField("_random", BindingFlags.Static | BindingFlags.NonPublic);
|
||||
private readonly List<CardDefinition> _definitions = new();
|
||||
private GameObject _owner;
|
||||
private CombatManager _combat;
|
||||
private object _random;
|
||||
private CombatantState Player => _combat.PlayerState;
|
||||
|
||||
private static object Call(object owner, string method) => owner.GetType().GetMethod(method, Private).Invoke(owner, null);
|
||||
private static void Set(object owner, string field, object value) => owner.GetType().GetField(field, Private).SetValue(owner, value);
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_random = CombatRandom.GetValue(null);
|
||||
_owner = new GameObject("damage execution regression");
|
||||
_combat = _owner.AddComponent<CombatManager>();
|
||||
Call(_combat, "OnDisable");
|
||||
Call(_combat, "Awake");
|
||||
Set(_combat, "_playerState", new CombatantState(100, 32, 10) { ForceMaxRolls = true });
|
||||
Set(_combat, "_handController", new HandController(32));
|
||||
Set(_combat, "currentPhase", TurnPhase.Execute);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
if (_combat != null) Call(_combat, "OnDisable");
|
||||
UnityEngine.Object.DestroyImmediate(_owner);
|
||||
foreach (var definition in _definitions) UnityEngine.Object.DestroyImmediate(definition);
|
||||
_definitions.Clear();
|
||||
CombatRandom.SetValue(null, _random);
|
||||
}
|
||||
|
||||
private CardInstance Card(string id, Language language)
|
||||
{
|
||||
var definition = ScriptableObject.CreateInstance<CardDefinition>();
|
||||
_definitions.Add(definition);
|
||||
Set(definition, "id", id);
|
||||
Set(definition, "language", language);
|
||||
return new CardInstance(definition);
|
||||
}
|
||||
|
||||
private CombatantState Enemy(int uptime = 100)
|
||||
{
|
||||
var enemy = new EnemyInstance("test target", uptime, Array.Empty<EnemyIntent>());
|
||||
((List<EnemyInstance>)_combat.Enemies).Add(enemy);
|
||||
return enemy.State;
|
||||
}
|
||||
|
||||
private CombatContext Context(CardInstance card, params CombatantState[] targets) => new(
|
||||
card, Player, targets, _combat, _combat.DamagePipeline, new StatusEffectController(),
|
||||
_combat.DeckController, _combat.HandController, _combat.Enemies);
|
||||
|
||||
[TestCase("fedora_first_to_package", Language.Java, 18)]
|
||||
[TestCase("fedora_dnf_autoremove", Language.Rust, 18)]
|
||||
[TestCase("mint_update_manager", Language.Python, 15)]
|
||||
public void WrappersAndPreviewApplyFlatAndMagnitudeBonusesExactlyOnce(string id, Language language, int expected)
|
||||
{
|
||||
var card = Card(id, language);
|
||||
card.ApplyMagnitudeUpgrade(2);
|
||||
Player.FlatEffectBonus = 3;
|
||||
Player.DamageMultiplierPercent = 150;
|
||||
var target = Enemy();
|
||||
var junk = Card("damaged_dependency", Language.Python);
|
||||
junk.IsBroken = true;
|
||||
Assert.That(_combat.HandController.Add(junk), Is.True);
|
||||
|
||||
var preview = CardPreviewService.Build(_combat, card, target);
|
||||
foreach (var effect in CardEffectFactory.CreateEffects(card.Definition)) effect.Execute(Context(card, target));
|
||||
|
||||
Assert.That(100 - target.CurrentUptime, Is.EqualTo(expected));
|
||||
Assert.That(preview.MinimumDamage, Is.EqualTo(expected));
|
||||
Assert.That(preview.MaximumDamage, Is.EqualTo(expected));
|
||||
if (id == "fedora_dnf_autoremove")
|
||||
{
|
||||
Assert.That(_combat.HandController.Cards, Has.No.Member(junk));
|
||||
Assert.That(Player.Cycles, Is.EqualTo(13), "Cycle gain retains its own magnitude scaling.");
|
||||
}
|
||||
}
|
||||
|
||||
[TestCase(false, 30, 15)]
|
||||
[TestCase(true, 10, 5)]
|
||||
public void UpdateManagerCapturesBaseBonusesButRepeatUsesCurrentModifiersAndDefenses(
|
||||
bool ignoreMultipliers, int initialIncoming, int repeatIncoming)
|
||||
{
|
||||
var card = Card("mint_update_manager", Language.Python);
|
||||
card.ApplyMagnitudeUpgrade(2);
|
||||
Player.FlatEffectBonus = 1;
|
||||
Player.FlatCardDamageBonus = 2;
|
||||
Player.DamageMultiplierPercent = 150;
|
||||
Player.IgnoreDamageMultipliers = ignoreMultipliers;
|
||||
_combat.Compilation.BeginWave(5);
|
||||
var target = Enemy(200);
|
||||
var context = Context(card, target);
|
||||
typeof(CombatContext).GetProperty(nameof(CombatContext.LazyMultiplierPercent)).SetValue(context, 200);
|
||||
|
||||
new UpdateManagerEffect(5).Execute(context);
|
||||
Assert.That(200 - target.CurrentUptime, Is.EqualTo(initialIncoming));
|
||||
|
||||
Player.FlatEffectBonus = 20;
|
||||
Player.FlatCardDamageBonus = 90;
|
||||
card.ApplyMagnitudeUpgrade(9);
|
||||
Player.DamageMultiplierPercent = 200;
|
||||
_combat.Compilation.AdvanceFromEquipment(5, 1);
|
||||
target.Shield = 4;
|
||||
var newcomer = Enemy();
|
||||
_combat.DamagePipeline.ResistanceResolver = (_, amount) => amount / 2;
|
||||
|
||||
Call(_combat, "ResolveDelayedEndOfTurnEffects");
|
||||
Assert.That(target.CurrentUptime, Is.EqualTo(200 - initialIncoming), "No repeat on the original turn.");
|
||||
Assert.That(newcomer.CurrentUptime, Is.EqualTo(100));
|
||||
Call(_combat, "ResolveDelayedEndOfTurnEffects");
|
||||
Assert.That(target.CurrentUptime, Is.EqualTo(200 - initialIncoming - (repeatIncoming - 4)));
|
||||
Assert.That(target.Shield, Is.Zero);
|
||||
Assert.That(newcomer.CurrentUptime, Is.EqualTo(100 - repeatIncoming), "The repeat hits currently living enemies.");
|
||||
|
||||
Call(_combat, "ResolveDelayedEndOfTurnEffects");
|
||||
Assert.That(newcomer.CurrentUptime, Is.EqualTo(100 - repeatIncoming), "A scheduled repeat executes only once.");
|
||||
Assert.That(CardPreviewService.Build(_combat, card, target).Details, Does.Contain("captures"));
|
||||
}
|
||||
|
||||
private static ICardEffect DamageEffect(string kind, Language language) => kind switch
|
||||
{
|
||||
"chance" => new ChanceDamageEffect(7, 100, language),
|
||||
"overkill" => new OverkillToShieldDamageEffect(7, language),
|
||||
_ => new DealDamageEffect(7, 7, language)
|
||||
};
|
||||
|
||||
[TestCase("direct")]
|
||||
[TestCase("chance")]
|
||||
[TestCase("overkill")]
|
||||
public void RustOverkillGrantsShieldOnlyOnceAcrossDamageEffects(string kind)
|
||||
{
|
||||
var card = Card("rust_damage_test", Language.Rust);
|
||||
card.ApplyMagnitudeUpgrade(2);
|
||||
Player.FlatEffectBonus = 3;
|
||||
Player.DamageMultiplierPercent = 200;
|
||||
// A standalone target isolates damage and Shield from enemy death presentation.
|
||||
var target = new CombatantState(5, 0, 0) { Shield = 2 };
|
||||
|
||||
DamageEffect(kind, Language.Rust).Execute(Context(card, target));
|
||||
|
||||
Assert.That(target.IsDefeated, Is.True);
|
||||
Assert.That(Player.Shield, Is.EqualTo(17), "24 incoming minus 5 Uptime and 2 Shield, granted exactly once.");
|
||||
}
|
||||
|
||||
[TestCase("direct", Language.C)]
|
||||
[TestCase("chance", Language.C)]
|
||||
[TestCase("overkill", Language.C)]
|
||||
[TestCase("direct", Language.Java)]
|
||||
[TestCase("chance", Language.Java)]
|
||||
[TestCase("overkill", Language.Java)]
|
||||
public void CAndJavaSpillUseRemainingDamageWithoutRepeatingSourceScaling(string kind, Language language)
|
||||
{
|
||||
var card = Card("spill_damage_test", language);
|
||||
card.ApplyMagnitudeUpgrade(2);
|
||||
Player.FlatEffectBonus = 3;
|
||||
Player.DamageMultiplierPercent = 200;
|
||||
var first = new CombatantState(5, 0, 0) { Shield = 2 };
|
||||
var next = Enemy();
|
||||
next.Shield = 3;
|
||||
_combat.DamagePipeline.ResistanceResolver = (request, amount) => request.Target == next ? amount / 2 : amount;
|
||||
|
||||
DamageEffect(kind, language).Execute(Context(card, first));
|
||||
|
||||
Assert.That(first.IsDefeated, Is.True);
|
||||
Assert.That(next.Shield, Is.Zero);
|
||||
Assert.That(next.CurrentUptime, Is.EqualTo(language == Language.C ? 99 : 95),
|
||||
"C halves 17 excess to 8, resistance halves it to 4, then 3 Shield absorbs damage. Java still carries all 17.");
|
||||
Assert.That(Player.Shield, Is.EqualTo(kind == "overkill" ? 17 : 0));
|
||||
}
|
||||
|
||||
[TestCase(false)]
|
||||
[TestCase(true)]
|
||||
public void CombinedUptimeAndShieldBeyondIntCapacityDoesNotCreatePhantomOverkill(bool explicitShield)
|
||||
{
|
||||
var card = Card("large_capacity_test", Language.Rust);
|
||||
var target = new CombatantState(int.MaxValue, 0, 0) { Shield = int.MaxValue };
|
||||
ICardEffect effect = explicitShield
|
||||
? new OverkillToShieldDamageEffect(int.MaxValue, Language.Rust)
|
||||
: new DealDamageEffect(int.MaxValue, int.MaxValue, Language.Rust);
|
||||
|
||||
effect.Execute(Context(card, target));
|
||||
|
||||
Assert.That(target.Shield, Is.Zero);
|
||||
Assert.That(target.CurrentUptime, Is.EqualTo(int.MaxValue));
|
||||
Assert.That(target.IsDefeated, Is.False);
|
||||
Assert.That(Player.Shield, Is.Zero, "A hit that only consumes the target's Shield has no excess damage.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SpillNeverRevisitsOriginalTargetSavedFromLethalDamage()
|
||||
{
|
||||
var card = Card("saved_spill_target_test", Language.Java);
|
||||
var beforeOriginal = Enemy(2);
|
||||
beforeOriginal.ArchRollingReleaseSavesRemaining = 1;
|
||||
var original = Enemy(5);
|
||||
original.ArchRollingReleaseSavesRemaining = 1;
|
||||
var afterOriginal = Enemy();
|
||||
|
||||
new DealDamageEffect(12, 12, Language.Java).Execute(Context(card, original));
|
||||
|
||||
Assert.That(beforeOriginal.CurrentUptime, Is.EqualTo(1));
|
||||
Assert.That(original.CurrentUptime, Is.EqualTo(1));
|
||||
Assert.That(original.IsDefeated, Is.False,
|
||||
"The original target remains excluded after the spill moves to an earlier enemy in the list.");
|
||||
Assert.That(original.ArchRollingReleaseSavesRemaining, Is.Zero);
|
||||
Assert.That(afterOriginal.CurrentUptime, Is.EqualTo(95),
|
||||
"Seven excess damage passes the two-Uptime enemy, then the remaining five skips the saved original target.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FailedChanceDamageKeepsLanguageBonusButDoesNotApplyBaseBonuses()
|
||||
{
|
||||
var card = Card("chance_failure_test", Language.JavaScript);
|
||||
card.ApplyMagnitudeUpgrade(2);
|
||||
Player.FlatEffectBonus = 3;
|
||||
Player.JavaScriptFlatDamageBonus = 2;
|
||||
Player.DamageMultiplierPercent = 200;
|
||||
var target = Enemy();
|
||||
|
||||
new ChanceDamageEffect(7, 0, Language.JavaScript).Execute(Context(card, target));
|
||||
|
||||
Assert.That(target.CurrentUptime, Is.EqualTo(96), "A miss still carries the language bonus through the damage pipeline.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MultipleEffectsInOneCardContextApplySegfaultRecoilAtMostOnce()
|
||||
{
|
||||
CombatRandom.SetValue(null, new MinimumRandom());
|
||||
Player.ForceMaxRolls = false;
|
||||
var card = Card("segfault_test", Language.C);
|
||||
var context = Context(card, Enemy(), Enemy());
|
||||
|
||||
new ChanceDamageEffect(7, 100, Language.C).Execute(context);
|
||||
new OverkillToShieldDamageEffect(7, Language.C).Execute(context);
|
||||
|
||||
Assert.That(Player.CurrentUptime, Is.EqualTo(97), "Guaranteed segfault rolls still produce only one recoil per card resolution.");
|
||||
}
|
||||
|
||||
private sealed class MinimumRandom : System.Random
|
||||
{
|
||||
public override int Next(int minValue, int maxValue) => minValue;
|
||||
}
|
||||
|
||||
[TestCase(Language.C, 35, true)]
|
||||
[TestCase(Language.C, 36, false)]
|
||||
[TestCase(Language.C, 50, false)]
|
||||
[TestCase(Language.Java, 25, true)]
|
||||
[TestCase(Language.Java, 26, false)]
|
||||
[TestCase(Language.Rust, 26, false)]
|
||||
public void CriticalChanceUsesTheReducedCBoundaryWithoutChangingOtherLanguages(Language language, int roll, bool critical)
|
||||
{
|
||||
Player.ForceMaxRolls = false;
|
||||
CombatRandom.SetValue(null, new FixedRollRandom(roll));
|
||||
var result = _combat.DamagePipeline.DealDamage(new DamageRequest(Player, Enemy(), 10, language, false, true));
|
||||
Assert.That(result.WasCritical, Is.EqualTo(critical));
|
||||
Assert.That(result.IncomingAmount, Is.EqualTo(critical ? 15 : 10), "Crit magnitude is unchanged.");
|
||||
}
|
||||
|
||||
private sealed class FixedRollRandom : System.Random
|
||||
{
|
||||
private readonly int _roll;
|
||||
public FixedRollRandom(int roll) => _roll = roll;
|
||||
public override int Next(int minValue, int maxValue) => _roll;
|
||||
}
|
||||
|
||||
[TestCase(Language.C, false, 13, 4, 97)]
|
||||
[TestCase(Language.C, true, 15, 6, 94)]
|
||||
[TestCase(Language.Java, false, 27, 22, 79)]
|
||||
[TestCase(Language.Java, true, 31, 28, 72)]
|
||||
public void SpillAttenuatesEveryCJumpOnlyAndReportsActualTravelDamage(Language language, bool trueDamage,
|
||||
int firstSpill, int secondSpill, int lastUptime)
|
||||
{
|
||||
Set(_combat, "_enemyExitQueueDraining", true);
|
||||
var first = new CombatantState(5, 0, 0) { Shield = 4 };
|
||||
Enemy().IsDefeated = true; // Skipped targets must not consume another attenuation step.
|
||||
var middle = Enemy(3);
|
||||
middle.Shield = 2;
|
||||
var last = Enemy();
|
||||
last.Shield = 1;
|
||||
var travel = new List<int>();
|
||||
void Record(OverflowDamageTravelEvent evt) => travel.Add(evt.Amount);
|
||||
GameEvents.OverflowDamageTravel += Record;
|
||||
try
|
||||
{
|
||||
new DealDamageEffect(36, 36, language, trueDamage).Execute(Context(Card("chain_test", language), first));
|
||||
Assert.That(travel, Is.EqualTo(new[] { firstSpill, secondSpill }));
|
||||
Assert.That(last.CurrentUptime, Is.EqualTo(lastUptime));
|
||||
Assert.That(last.Shield, Is.EqualTo(trueDamage ? 1 : 0));
|
||||
}
|
||||
finally { GameEvents.OverflowDamageTravel -= Record; }
|
||||
}
|
||||
|
||||
[TestCase(5, 0)]
|
||||
[TestCase(6, 0)]
|
||||
[TestCase(8, 1)]
|
||||
[TestCase(int.MaxValue, 1073741821)]
|
||||
public void CSpillRoundsDownAndHandlesLargeDamageWithoutOverflow(int damage, int expectedSpill)
|
||||
{
|
||||
var first = new CombatantState(5, 0, 0);
|
||||
var last = Enemy(int.MaxValue);
|
||||
new DealDamageEffect(damage, damage, Language.C).Execute(Context(Card("rounding_test", Language.C), first));
|
||||
Assert.That(last.CurrentUptime, Is.EqualTo(int.MaxValue - expectedSpill));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f9b49c02767246a98dfe53d0641c1f1f
|
||||
@@ -0,0 +1,213 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using NUnit.Framework;
|
||||
using UnityEngine;
|
||||
|
||||
public class DeckDrawTests
|
||||
{
|
||||
private readonly List<CardDefinition> _definitions = new();
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
foreach (var definition in _definitions) Object.DestroyImmediate(definition);
|
||||
_definitions.Clear();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MixedLanguageDrawsConsumeActualRamAndPreserveDrawOrder()
|
||||
{
|
||||
var first = Card(Language.Python);
|
||||
var second = Card(Language.Java);
|
||||
var third = Card(Language.Rust);
|
||||
var fourth = Card(Language.C);
|
||||
var deck = Deck(first, second, third, fourth);
|
||||
var hand = new HandController(4);
|
||||
|
||||
Assert.That(deck.TryDrawToHand(hand, out var drawn), Is.True);
|
||||
Assert.That(drawn, Is.SameAs(first));
|
||||
Assert.That(hand.RemainingRam, Is.EqualTo(3));
|
||||
Assert.That(deck.TryDrawToHand(hand, out drawn), Is.True);
|
||||
Assert.That(drawn, Is.SameAs(second));
|
||||
Assert.That(hand.RemainingRam, Is.EqualTo(1));
|
||||
Assert.That(deck.TryDrawToHand(hand, out drawn), Is.True);
|
||||
Assert.That(drawn, Is.SameAs(third));
|
||||
Assert.That(hand.UsedRam, Is.EqualTo(4));
|
||||
Assert.That(deck.TryDrawToHand(hand, out drawn), Is.False);
|
||||
Assert.That(drawn, Is.Null);
|
||||
Assert.That(hand.Cards, Is.EqualTo(new[] { first, second, third }));
|
||||
Assert.That(deck.DrawPile, Is.EqualTo(new[] { fourth }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BlockedJavaCardDoesNotSkipOrReorderCheaperCardsBelowIt()
|
||||
{
|
||||
var first = Card(Language.Java);
|
||||
var second = Card(Language.Python);
|
||||
var third = Card(Language.Rust);
|
||||
var discarded = Card(Language.C);
|
||||
var deck = Deck(first, second, third);
|
||||
deck.Discard(discarded);
|
||||
var hand = new HandController(1);
|
||||
|
||||
Assert.That(deck.TryDrawToHand(hand, out var drawn), Is.False);
|
||||
Assert.That(drawn, Is.Null);
|
||||
Assert.That(deck.TryDrawToHand(hand, out drawn), Is.False, "Retrying cannot bypass the blocked top card.");
|
||||
Assert.That(hand.Cards, Is.Empty);
|
||||
Assert.That(deck.DrawPile, Is.EqualTo(new[] { third, second, first }));
|
||||
Assert.That(deck.DiscardPile, Is.EqualTo(new[] { discarded }));
|
||||
|
||||
hand.SetRamCapacity(4);
|
||||
Assert.That(deck.TryDrawToHand(hand, out drawn), Is.True);
|
||||
Assert.That(drawn, Is.SameAs(first));
|
||||
Assert.That(deck.TryDrawToHand(hand, out drawn), Is.True);
|
||||
Assert.That(drawn, Is.SameAs(second));
|
||||
Assert.That(deck.TryDrawToHand(hand, out drawn), Is.True);
|
||||
Assert.That(drawn, Is.SameAs(third));
|
||||
Assert.That(hand.Cards, Is.EqualTo(new[] { first, second, third }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FullHandDoesNotReshuffleDiscardPile()
|
||||
{
|
||||
var deck = new DeckController();
|
||||
var first = Card(Language.Python);
|
||||
var second = Card(Language.Java);
|
||||
deck.Discard(first);
|
||||
deck.Discard(second);
|
||||
var hand = new HandController(1);
|
||||
var held = Card(Language.C);
|
||||
Assert.That(hand.Add(held), Is.True);
|
||||
|
||||
Assert.That(deck.TryDrawToHand(hand, out var drawn), Is.False);
|
||||
|
||||
Assert.That(drawn, Is.Null);
|
||||
Assert.That(deck.DrawPile, Is.Empty);
|
||||
Assert.That(deck.DiscardPile, Is.EqualTo(new[] { first, second }));
|
||||
Assert.That(hand.Cards, Is.EqualTo(new[] { held }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ReshuffledJavaCardStaysOnTopUntilEnoughRamIsAvailable()
|
||||
{
|
||||
var deck = new DeckController();
|
||||
var java = Card(Language.Java);
|
||||
deck.Discard(java);
|
||||
var hand = new HandController(1);
|
||||
|
||||
Assert.That(deck.TryDrawToHand(hand, out var drawn), Is.False);
|
||||
Assert.That(drawn, Is.Null);
|
||||
Assert.That(deck.DiscardPile, Is.Empty);
|
||||
Assert.That(deck.DrawPile, Is.EqualTo(new[] { java }));
|
||||
Assert.That(hand.Cards, Is.Empty);
|
||||
|
||||
hand.SetRamCapacity(2);
|
||||
Assert.That(deck.TryDrawToHand(hand, out drawn), Is.True);
|
||||
Assert.That(drawn, Is.SameAs(java));
|
||||
Assert.That(deck.DrawPile, Is.Empty);
|
||||
Assert.That(hand.Cards, Is.EqualTo(new[] { java }));
|
||||
Assert.That(hand.RemainingRam, Is.Zero);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NullHandDoesNotReshuffleDiscardPile()
|
||||
{
|
||||
var deck = new DeckController();
|
||||
var card = Card(Language.Python);
|
||||
deck.Discard(card);
|
||||
|
||||
Assert.That(deck.TryDrawToHand(null, out var drawn), Is.False);
|
||||
|
||||
Assert.That(drawn, Is.Null);
|
||||
Assert.That(deck.DrawPile, Is.Empty);
|
||||
Assert.That(deck.DiscardPile, Is.EqualTo(new[] { card }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EmptyDeckDoesNotChangeHand()
|
||||
{
|
||||
var deck = new DeckController();
|
||||
var hand = new HandController(4);
|
||||
var held = Card(Language.Python);
|
||||
Assert.That(hand.Add(held), Is.True);
|
||||
|
||||
Assert.That(deck.TryDrawToHand(hand, out var drawn), Is.False);
|
||||
|
||||
Assert.That(drawn, Is.Null);
|
||||
Assert.That(hand.Cards, Is.EqualTo(new[] { held }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ReservedBatchHonorsRamOrderAndRequestedCount()
|
||||
{
|
||||
var first = Card(Language.Python);
|
||||
var second = Card(Language.Java);
|
||||
var blocked = Card(Language.Java);
|
||||
var fourth = Card(Language.C);
|
||||
var deck = Deck(first, second, blocked, fourth);
|
||||
|
||||
var reserved = deck.DrawFittingCards(4, 4);
|
||||
|
||||
Assert.That(reserved, Is.EqualTo(new[] { first, second }));
|
||||
Assert.That(deck.DrawPile, Is.EqualTo(new[] { fourth, blocked }),
|
||||
"The next Java card costs more than the remaining one RAM; the cheaper card below stays put.");
|
||||
|
||||
var next = deck.DrawFittingCards(1, 10);
|
||||
|
||||
Assert.That(next, Is.EqualTo(new[] { blocked }), "Spare RAM does not increase the requested count.");
|
||||
Assert.That(deck.DrawPile, Is.EqualTo(new[] { fourth }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ReservedBatchExcludesCardsDiscardedAfterReservation()
|
||||
{
|
||||
var first = Card(Language.Python);
|
||||
var second = Card(Language.Java);
|
||||
var existingDiscard = Card(Language.C);
|
||||
var resolvingCard = Card(Language.Python);
|
||||
var deck = Deck(first, second);
|
||||
deck.Discard(existingDiscard);
|
||||
|
||||
var reserved = deck.DrawFittingCards(5, 8);
|
||||
deck.Discard(resolvingCard);
|
||||
|
||||
Assert.That(reserved, Is.EqualTo(new[] { first, second, existingDiscard }),
|
||||
"The batch includes only cards available when drawing began, even when the request was not filled.");
|
||||
Assert.That(deck.DrawPile, Is.Empty);
|
||||
Assert.That(deck.DiscardPile, Is.EqualTo(new[] { resolvingCard }));
|
||||
}
|
||||
|
||||
[TestCase(0, 5)]
|
||||
[TestCase(-1, 5)]
|
||||
[TestCase(5, 0)]
|
||||
[TestCase(5, -1)]
|
||||
public void ReservationWithoutCountOrRamDoesNotReshuffle(int count, int availableRam)
|
||||
{
|
||||
var deck = new DeckController();
|
||||
var discarded = Card(Language.Python);
|
||||
deck.Discard(discarded);
|
||||
|
||||
Assert.That(deck.DrawFittingCards(count, availableRam), Is.Empty);
|
||||
|
||||
Assert.That(deck.DrawPile, Is.Empty);
|
||||
Assert.That(deck.DiscardPile, Is.EqualTo(new[] { discarded }));
|
||||
}
|
||||
|
||||
private CardInstance Card(Language language)
|
||||
{
|
||||
var definition = ScriptableObject.CreateInstance<CardDefinition>();
|
||||
_definitions.Add(definition);
|
||||
typeof(CardDefinition).GetField("language", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(definition, language);
|
||||
return new CardInstance(definition);
|
||||
}
|
||||
|
||||
private static DeckController Deck(params CardInstance[] drawOrder)
|
||||
{
|
||||
var deck = new DeckController();
|
||||
for (int i = drawOrder.Length - 1; i >= 0; i--) deck.AddToDrawPile(drawOrder[i], false);
|
||||
return deck;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5dfd94d787c94a0ca10b9374e47b9c2b
|
||||
@@ -0,0 +1,57 @@
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Run;
|
||||
using KernelPanic.UI;
|
||||
using NUnit.Framework;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
public class FirstBattleGuideTests
|
||||
{
|
||||
[Test]
|
||||
public void GuideFollowsRealRoundAndOnlyRemembersDismissal()
|
||||
{
|
||||
int remembered = 0;
|
||||
var guide = new FirstBattleGuide(() => remembered++);
|
||||
guide.Begin(new RunConfig(null, Language.Python, Language.Haskell, null, 42), true);
|
||||
Assert.That(guide.Instruction.Length, Is.LessThan(110));
|
||||
Assert.That(guide.Element.Q<UnityEngine.UIElements.Foldout>().value, Is.False);
|
||||
Assert.That(guide.Element.Query<UnityEngine.UIElements.Label>(className: "guide-resource").ToList().Count, Is.EqualTo(4));
|
||||
guide.Advance();
|
||||
guide.CardPlayed(ResolutionTrack.InterpreterQueue, "print");
|
||||
guide.PhaseChanged(TurnPhase.Interpret);
|
||||
Assert.That(guide.Instruction, Does.Contain("oldest first"));
|
||||
guide.CardResolved("print", ResolutionTrack.InterpreterQueue);
|
||||
guide.PhaseChanged(TurnPhase.Execute);
|
||||
Assert.That(guide.Instruction, Does.Contain("next enemy intents"));
|
||||
Assert.That(remembered, Is.Zero);
|
||||
guide.Advance();
|
||||
Assert.That(guide.Visible, Is.False);
|
||||
Assert.That(remembered, Is.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EarlyWaveClearDoesNotLeaveGuideWaitingForEndTurn()
|
||||
{
|
||||
var guide = new FirstBattleGuide(() => { });
|
||||
guide.Begin(null, true);
|
||||
guide.CardPlayed(ResolutionTrack.Native, "attack");
|
||||
guide.Refresh(true, false);
|
||||
Assert.That(guide.Instruction, Does.Contain("repository"));
|
||||
guide.Advance();
|
||||
Assert.That(guide.Visible, Is.False);
|
||||
guide.Begin(null, true);
|
||||
Assert.That(guide.Visible, Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GuideDoesNotRequireUnavailableTracks()
|
||||
{
|
||||
var config = new RunConfig(null, Language.C, Language.Rust, null, 42);
|
||||
Assert.That(FirstBattleGuide.TrackLesson(config), Is.EqualTo("Native cards execute now."));
|
||||
var guide = new FirstBattleGuide(() => { });
|
||||
guide.Begin(config, true);
|
||||
guide.PhaseChanged(TurnPhase.Interpret);
|
||||
guide.PhaseChanged(TurnPhase.Execute);
|
||||
guide.Advance();
|
||||
Assert.That(guide.Visible, Is.False);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a66f5e357279402584e4c7b70432e9f8
|
||||
@@ -0,0 +1,710 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Meta;
|
||||
using KernelPanic.UI;
|
||||
using NUnit.Framework;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using UnityEngine.TestTools;
|
||||
using UnityEngine.UIElements;
|
||||
using Random = UnityEngine.Random;
|
||||
|
||||
public class GachaRevealTests
|
||||
{
|
||||
private bool _motion;
|
||||
private UITextSize _textSize;
|
||||
[SetUp] public void SetUp()
|
||||
{
|
||||
_motion = UIPreferences.ReducedMotion;
|
||||
_textSize = UIPreferences.TextSize;
|
||||
UIPreferences.ReducedMotion = false;
|
||||
UIPreferences.TextSize = UITextSize.Standard;
|
||||
}
|
||||
[TearDown] public void TearDown()
|
||||
{
|
||||
UIPreferences.ReducedMotion = _motion;
|
||||
UIPreferences.TextSize = _textSize;
|
||||
}
|
||||
|
||||
[TestCase(false, false, 3)]
|
||||
[TestCase(false, true, 3)]
|
||||
[TestCase(false, false, 4)]
|
||||
[TestCase(false, true, 5)]
|
||||
[TestCase(true, false, 4)]
|
||||
[TestCase(true, true, 4)]
|
||||
[TestCase(true, false, 5)]
|
||||
[TestCase(true, true, 5)]
|
||||
public void SingleRewardsShowActualIdentityAndExactConversion(bool distro, bool duplicate, int stars)
|
||||
{
|
||||
var reward = Reward(1, distro, duplicate, stars);
|
||||
var root = new VisualElement();
|
||||
using var view = new GachaRevealView(root, Receipt(reward), () => { });
|
||||
view.RevealAll();
|
||||
Assert.That(view.IsComplete, Is.True);
|
||||
Assert.That(view.SelectedIndex, Is.Zero);
|
||||
var detail = root.Q("PullRewardDetail");
|
||||
Assert.That(detail.Q(className: distro ? "distribution-detail" : "package-detail"), Is.Not.Null);
|
||||
Assert.That(detail.Q(className: distro ? "package-detail" : "distribution-detail"), Is.Null);
|
||||
string text = Copy(detail);
|
||||
if (duplicate)
|
||||
{
|
||||
Assert.That(text, Does.Contain("DUPLICATE CONVERTED"));
|
||||
Assert.That(text, Does.Contain("137 " + (distro ? "Merges" : "Cache")), "Use receipt values, not tuning constants.");
|
||||
}
|
||||
else Assert.That(text, Does.Contain("Added to your collection."));
|
||||
if (distro)
|
||||
{
|
||||
Assert.That(detail.Q<Label>(className: "reveal-art").text, Is.EqualTo(reward.DisplayData.Distro.AsciiArt.text));
|
||||
Assert.That(text, Does.Contain(DistroPresentation.FormatLanguages(reward.DisplayData.Distro)));
|
||||
Assert.That(text, Does.Contain(DistroVersionCatalog.GetReleaseLabel(reward.DisplayData.Distro.Id, 3)));
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.That(text, Does.Contain(reward.DisplayData.Package.Description));
|
||||
Assert.That(text, Does.Contain(reward.DisplayData.Package.Slot.ToString().ToUpperInvariant()));
|
||||
Assert.That(detail.Q(className: "reveal-art"), Is.Null);
|
||||
}
|
||||
}
|
||||
|
||||
[TestCase(false)]
|
||||
[TestCase(true)]
|
||||
public void TenPullsKeepOrderAndFeatureDistributions(bool mixed)
|
||||
{
|
||||
var rewards = Enumerable.Range(1, 10).Select(i => Reward(i, mixed && (i == 4 || i == 6), i % 2 == 0, i == 6 ? 5 : i % 3 + 3)).ToArray();
|
||||
var root = new VisualElement();
|
||||
using var view = new GachaRevealView(root, new CompletedGachaPull("test", "paid", rewards), () => { });
|
||||
for (int i = 0; i < 3; i++) view.RevealNext();
|
||||
Assert.That(view.RevealedCount, Is.EqualTo(3));
|
||||
Assert.That(root.Q("PullContinue").enabledSelf, Is.False);
|
||||
Assert.That(root.Q("PullReward-04").ClassListContains("reveal-sealed"), Is.True);
|
||||
view.RevealAll();
|
||||
Assert.That(view.RevealedCount, Is.EqualTo(10));
|
||||
Assert.That(root.Q("PullContinue").enabledSelf, Is.True);
|
||||
if (mixed) Assert.That(view.SelectedIndex, Is.EqualTo(5), "5-star distro is the final focal point.");
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
var tile = root.Q($"PullReward-{i + 1:00}");
|
||||
Assert.That(tile.Q<Label>(className: "reveal-index").text, Is.EqualTo($"{i + 1:00}"));
|
||||
Assert.That(tile.Q<Label>(className: "reveal-name").text, Is.EqualTo(rewards[i].DisplayName));
|
||||
view.Select(i);
|
||||
Assert.That(view.SelectedIndex, Is.EqualTo(i));
|
||||
}
|
||||
Assert.That(Copy(root.Q("PullSummaryTotals")), Does.Contain("10 pulls"));
|
||||
view.RevealNext(); view.RevealAll();
|
||||
Assert.That(view.RevealedCount, Is.EqualTo(10));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ReducedMotionCompletesImmediatelyAndMissingMetadataNeverClaimsInstallation()
|
||||
{
|
||||
UIPreferences.ReducedMotion = true;
|
||||
var root = new VisualElement();
|
||||
var missing = new CompletedGachaReward(1, 5, "unavailable", GachaRewardType.Distro, PullOutcomeKind.Invalid, 0, null, true, false);
|
||||
using var view = new GachaRevealView(root, Receipt(missing), () => { });
|
||||
view.Begin();
|
||||
Assert.That(view.IsComplete, Is.True);
|
||||
Assert.That(Copy(root), Does.Contain("NOT GRANTED"));
|
||||
Assert.That(Copy(root), Does.Not.Contain("UNIT INSTALLED"));
|
||||
Assert.That(root.Q(className: "just-unpacked"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PackagePreviewKeepsExactRulesAndInspectorShowsFullPassive()
|
||||
{
|
||||
var root = new VisualElement();
|
||||
var package = Reward(1, false, true, 4);
|
||||
var distro = Reward(2, true, false, 5);
|
||||
using var view = new GachaRevealView(root, Receipt(package, distro), () => { });
|
||||
view.RevealAll();
|
||||
Assert.That(root.Q("PullReward-01").Q<Label>(className: "reveal-package-role").text,
|
||||
Is.EqualTo(package.DisplayData.Package.Description), "Clip the visual preview, never rewrite the rules.");
|
||||
Assert.That(Copy(root.Q("PullRewardDetail")), Does.Contain(distro.DisplayData.Distro.Passive.RulesText));
|
||||
Assert.That(root.Q("PullReward-02").Q(className: "reveal-body"), Is.Null);
|
||||
Assert.That(Copy(root.Q("PullSummaryTotals")), Does.Contain("+137 Cache"));
|
||||
Assert.That(Copy(root.Q("PullSummaryTotals")), Does.Contain("highest 5★"));
|
||||
}
|
||||
|
||||
[TestCase(false)]
|
||||
[TestCase(true)]
|
||||
public void FiveStarSignatureIsDistinctSkippableAndDoesNotGrantAnything(bool duplicate)
|
||||
{
|
||||
var root = new VisualElement();
|
||||
var reward = Reward(1, true, duplicate, 5);
|
||||
int continued = 0;
|
||||
using var view = new GachaRevealView(root, Receipt(reward), () => continued++);
|
||||
view.RevealNext();
|
||||
Assert.That(view.IsSignatureRevealing, Is.True);
|
||||
Assert.That(view.IsComplete, Is.False, "The last signature must finish before Continue is enabled.");
|
||||
Assert.That(root.Q("PullContinue").enabledSelf, Is.False);
|
||||
var signature = root.Q("DistributionSignature");
|
||||
Assert.That(signature, Is.Not.Null);
|
||||
Assert.That(signature.Q<Label>(className: "reveal-art").text, Is.EqualTo(reward.DisplayData.Distro.AsciiArt.text));
|
||||
Assert.That(Copy(signature), Does.Contain(duplicate ? "DISTRIBUTION ALREADY INSTALLED" : "UNIT INSTALLED"));
|
||||
if (duplicate) Assert.That(Copy(signature), Does.Not.Contain("UNIT INSTALLED"));
|
||||
view.RevealNext(); // Space skips the current signature, not another reward.
|
||||
Assert.That(view.IsSignatureRevealing, Is.False);
|
||||
Assert.That(view.IsComplete, Is.True);
|
||||
Assert.That(root.Q("DistributionSignature"), Is.Null);
|
||||
Assert.That(continued, Is.Zero);
|
||||
view.RevealAll(); view.RevealNext();
|
||||
Assert.That(view.RevealedCount, Is.EqualTo(1));
|
||||
}
|
||||
|
||||
[TestCase(true, false)]
|
||||
[TestCase(true, true)]
|
||||
[TestCase(false, false)]
|
||||
[TestCase(false, true)]
|
||||
public void AcquisitionStateDoesNotReplaceTypeOrRarity(bool distro, bool duplicate)
|
||||
{
|
||||
var root = new VisualElement();
|
||||
using var view = new GachaRevealView(root, Receipt(Reward(1, distro, duplicate, 5)), () => { });
|
||||
view.RevealAll();
|
||||
var tile = root.Q("PullReward-01");
|
||||
Assert.That(tile.ClassListContains("rarity-5"), Is.True);
|
||||
Assert.That(tile.ClassListContains(distro ? "reveal-distribution" : "reveal-package"), Is.True);
|
||||
Assert.That(tile.ClassListContains("acquisition-new"), Is.EqualTo(!duplicate));
|
||||
Assert.That(tile.ClassListContains("acquisition-duplicate"), Is.EqualTo(duplicate));
|
||||
string status = tile.Q<Label>(className: "reveal-outcome").text;
|
||||
Assert.That(status, Does.Contain(duplicate ? "DUPLICATE" : distro ? "NEW DISTRO" : "NEW PACKAGE"));
|
||||
if (duplicate) Assert.That(status, Does.Contain(distro ? "+137 Merges" : "+137 Cache"));
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator LongPackagePreviewEndsAtWordBoundaryAndExpandsWithAvailableWidth()
|
||||
{
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
var package = UnityEngine.Object.Instantiate(AssetDatabase.LoadAssetAtPath<PackageDefinition>("Assets/Data/Packages/SnapStore.asset"));
|
||||
GachaRevealView view = null;
|
||||
try
|
||||
{
|
||||
window.Show();
|
||||
var root = window.rootVisualElement;
|
||||
Attach(root);
|
||||
root.style.width = 1093; root.style.height = 614;
|
||||
string full = package.Description + " Additional fixture rules remain available in the full inspector, without cutting a word in half.";
|
||||
typeof(PackageDefinition).GetField("description", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(package, full);
|
||||
var longReward = new CompletedGachaReward(1,4,"A deliberately long runtime package name",GachaRewardType.Package,PullOutcomeKind.Granted,0,null,false,false,new GachaRewardDisplayData(null,package,1,0));
|
||||
view = new GachaRevealView(root, Receipt(new[] { longReward }.Concat(Enumerable.Range(2,9).Select(i => Reward(i,false,true,3))).ToArray()), () => { });
|
||||
view.RevealAll();
|
||||
for (int frame = 0; frame < 8; frame++) yield return null;
|
||||
var preview = root.Q("PullReward-01").Q<Label>(className: "reveal-package-role");
|
||||
string small = preview.text;
|
||||
Assert.That(small, Does.EndWith(" …"));
|
||||
Assert.That(full, Does.StartWith(small.Substring(0,small.Length-2) + " "), "Only whole words from the actual rules are shown.");
|
||||
Assert.That(preview.tooltip, Is.EqualTo(full));
|
||||
Assert.That(preview.resolvedStyle.fontSize, Is.GreaterThanOrEqualTo(15));
|
||||
Assert.That(preview.MeasureTextSize(preview.text,preview.contentRect.width-1,VisualElement.MeasureMode.AtMost,0,VisualElement.MeasureMode.Undefined).y, Is.LessThanOrEqualTo(preview.layout.height+1));
|
||||
view.Select(0);
|
||||
Assert.That(Copy(root.Q("PullRewardDetail")), Does.Contain(full));
|
||||
root.style.width = 1920;
|
||||
for (int frame = 0; frame < 8; frame++) yield return null;
|
||||
Assert.That(preview.text.Length, Is.GreaterThan(small.Length));
|
||||
Assert.That(package.Description, Is.EqualTo(full));
|
||||
LogAssert.NoUnexpectedReceived();
|
||||
}
|
||||
finally { view?.Dispose(); window.Close(); UnityEngine.Object.DestroyImmediate(package); }
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator DistroArtworkFitsItsFrameAndFocusDoesNotResizeTiles()
|
||||
{
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
GachaRevealView view = null;
|
||||
try
|
||||
{
|
||||
window.Show();
|
||||
var root = window.rootVisualElement;
|
||||
root.style.width = 1093; root.style.height = 614;
|
||||
Attach(root);
|
||||
var rewards = new[] { "Arch", "Mint", "Fedora", "Ubuntu" }.Select((id,i) =>
|
||||
{
|
||||
var distro = AssetDatabase.LoadAssetAtPath<DistroDefinition>($"Assets/Data/Distros/{id}.asset");
|
||||
return new CompletedGachaReward(i+1,i==0?5:4,distro.DisplayName,GachaRewardType.Distro,PullOutcomeKind.Granted,0,null,false,false,new GachaRewardDisplayData(distro,null,1,0));
|
||||
}).Concat(Enumerable.Range(5,6).Select(i => Reward(i,false,false,3))).ToArray();
|
||||
view = new GachaRevealView(root, Receipt(rewards), () => { });
|
||||
view.RevealAll();
|
||||
for (int frame = 0; frame < 8; frame++) yield return null;
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
var tile = root.Q<Button>($"PullReward-{i+1:00}");
|
||||
float width = tile.layout.width, height = tile.layout.height;
|
||||
tile.Focus();
|
||||
for (int frame = 0; frame < 4; frame++) yield return null;
|
||||
Assert.That(view.SelectedIndex, Is.EqualTo(i));
|
||||
Assert.That(tile.layout.width, Is.EqualTo(width).Within(1));
|
||||
Assert.That(tile.layout.height, Is.EqualTo(height).Within(1));
|
||||
var art = tile.Q<Label>(className: "reveal-mini-art");
|
||||
Assert.That(art.text, Is.EqualTo(rewards[i].DisplayData.Distro.AsciiArt.text));
|
||||
var inspectorArt = root.Q("PullRewardDetail").Q<Label>(className:"reveal-art");
|
||||
foreach (var fitted in new[] { art, inspectorArt })
|
||||
{
|
||||
Vector2 measured = fitted.MeasureTextSize(fitted.text,0,VisualElement.MeasureMode.Undefined,0,VisualElement.MeasureMode.Undefined);
|
||||
Assert.That(measured.y, Is.LessThanOrEqualTo(fitted.contentRect.height+1), "All ASCII rows fit with actual font line spacing.");
|
||||
Assert.That(measured.x, Is.LessThanOrEqualTo(fitted.contentRect.width+1), "ASCII columns fit without changing their spacing.");
|
||||
}
|
||||
Assert.That(inspectorArt.resolvedStyle.fontSize, Is.GreaterThan(art.resolvedStyle.fontSize));
|
||||
Assert.That(Copy(root.Q("PullRewardDetail")), Does.Contain(rewards[i].DisplayName));
|
||||
}
|
||||
LogAssert.NoUnexpectedReceived();
|
||||
}
|
||||
finally { view?.Dispose(); window.Close(); }
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator SkipRestoresFocusWithoutArmingContinueForHeldSpace()
|
||||
{
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
GachaRevealView view = null;
|
||||
try
|
||||
{
|
||||
window.Show();
|
||||
var root = window.rootVisualElement;
|
||||
Attach(root);
|
||||
int continued = 0;
|
||||
view = new GachaRevealView(root, Receipt(Reward(1,true,true,5)), () => continued++);
|
||||
var skip = root.Query<Button>().ToList().First(b => b.text == "[R] reveal all");
|
||||
Assert.That(root.Q<Label>(className: "reveal-help").text, Does.Contain("[Esc] reveal all"));
|
||||
skip.Focus();
|
||||
yield return null;
|
||||
Key(root,KeyCode.R);
|
||||
Assert.That(root.focusController.focusedElement, Is.SameAs(root));
|
||||
Assert.That(root.Q<Label>(className: "reveal-help").text, Does.Contain("[Esc] back"));
|
||||
Key(root,KeyCode.Space);
|
||||
Assert.That(continued, Is.Zero);
|
||||
Key(root,KeyCode.Return);
|
||||
Assert.That(continued, Is.EqualTo(1));
|
||||
}
|
||||
finally { view?.Dispose(); window.Close(); }
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EnablingReducedMotionDuringSignatureCancelsAllPresentationDelays()
|
||||
{
|
||||
var root = new VisualElement();
|
||||
using var view = new GachaRevealView(root, Receipt(Reward(1, true, true, 5), Reward(2, false, false, 3)), () => { });
|
||||
view.RevealNext();
|
||||
UIPreferences.ReducedMotion = true;
|
||||
view.Begin();
|
||||
Assert.That(view.IsComplete, Is.True);
|
||||
Assert.That(root.ClassListContains("reduced-motion"), Is.True);
|
||||
Assert.That(root.Q("DistributionSignature"), Is.Null);
|
||||
Assert.That(root.Q(className: "just-unpacked"), Is.Null);
|
||||
Assert.That(Copy(root.Q("PullSummaryTotals")), Does.Contain("+137 Merges"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RevealAllCancelsSignatureAndAllPendingTileTransitions()
|
||||
{
|
||||
var root = new VisualElement();
|
||||
using var view = new GachaRevealView(root, Receipt(Reward(1, true, true, 5), Reward(2, false, false, 3)), () => { });
|
||||
view.RevealNext();
|
||||
view.RevealAll();
|
||||
Assert.That(view.IsComplete, Is.True);
|
||||
Assert.That(root.Q(className: "signature-active"), Is.Null);
|
||||
Assert.That(root.Q(className: "just-unpacked"), Is.Null);
|
||||
Assert.That(root.Q("DistributionSignature"), Is.Null);
|
||||
Assert.That(view.SelectedIndex, Is.Zero);
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator SignatureAdvancesThroughVerificationAndResumesUnpacking()
|
||||
{
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
GachaRevealView view = null;
|
||||
try
|
||||
{
|
||||
window.Show();
|
||||
var root = window.rootVisualElement;
|
||||
Attach(root);
|
||||
view = new GachaRevealView(root, Receipt(Reward(1, true, false, 5), Reward(2, false, true, 4)), () => { });
|
||||
view.RevealNext();
|
||||
Assert.That(root.Q("DistributionSignature").ClassListContains("signature-verified"), Is.False);
|
||||
double deadline = EditorApplication.timeSinceStartup + 4;
|
||||
bool verified = false, resolved = false;
|
||||
while (!view.IsComplete && EditorApplication.timeSinceStartup < deadline)
|
||||
{
|
||||
var signature = root.Q("DistributionSignature");
|
||||
verified |= signature?.ClassListContains("signature-verified") == true;
|
||||
resolved |= signature?.ClassListContains("signature-resolved") == true;
|
||||
yield return null;
|
||||
}
|
||||
Assert.That(verified, Is.True);
|
||||
Assert.That(resolved, Is.True);
|
||||
Assert.That(view.IsComplete, Is.True);
|
||||
Assert.That(view.RevealedCount, Is.EqualTo(2));
|
||||
LogAssert.NoUnexpectedReceived();
|
||||
}
|
||||
finally { view?.Dispose(); window.Close(); }
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator EnterDoesNotBothRevealAndContinueOrRepeatWhileHeld()
|
||||
{
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
GachaRevealView view = null;
|
||||
try
|
||||
{
|
||||
window.Show();
|
||||
var root = window.rootVisualElement;
|
||||
Attach(root);
|
||||
int continued = 0;
|
||||
view = new GachaRevealView(root, Receipt(Reward(1, false, false, 3)), () => continued++);
|
||||
root.Focus();
|
||||
yield return null;
|
||||
Key(root, KeyCode.Return);
|
||||
using (var submit = NavigationSubmitEvent.GetPooled()) { submit.target = root; root.SendEvent(submit); }
|
||||
Assert.That(view.IsComplete, Is.True);
|
||||
Assert.That(continued, Is.Zero);
|
||||
yield return null;
|
||||
Key(root, KeyCode.Return);
|
||||
Assert.That(continued, Is.Zero, "A held Enter must not dismiss newly completed results.");
|
||||
using (var release = KeyUpEvent.GetPooled('\0', KeyCode.Return, EventModifiers.None)) { release.target = root; root.SendEvent(release); }
|
||||
yield return null;
|
||||
Key(root, KeyCode.Return);
|
||||
Assert.That(continued, Is.EqualTo(1));
|
||||
}
|
||||
finally { view?.Dispose(); window.Close(); }
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator SingleReceiptsUseAvailableWidthWithoutHidingSummaryOrContinue()
|
||||
{
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
GachaRevealView view = null;
|
||||
try
|
||||
{
|
||||
window.Show();
|
||||
var root = window.rootVisualElement;
|
||||
Attach(root);
|
||||
foreach (var size in new[] { new Vector2(1536,864), new Vector2(1093,614), new Vector2(1024,576), new Vector2(819,614), new Vector2(312,675) })
|
||||
foreach (bool distro in new[] { false, true })
|
||||
{
|
||||
view?.Dispose(); root.Clear();
|
||||
root.style.width = size.x; root.style.height = size.y;
|
||||
view = new GachaRevealView(root, Receipt(Reward(1, distro, true, 5)), () => { });
|
||||
view.RevealAll();
|
||||
for (int frame = 0; frame < 5; frame++) yield return null;
|
||||
var detail = root.Q<ScrollView>("PullRewardDetail");
|
||||
Assert.That(detail.worldBound.xMax, Is.LessThanOrEqualTo(root.worldBound.xMax + 1));
|
||||
Assert.That(detail.horizontalScroller.highValue, Is.LessThanOrEqualTo(1));
|
||||
Assert.That(root.Q("PullContinue").worldBound.yMax, Is.LessThanOrEqualTo(root.worldBound.yMax + 1));
|
||||
Assert.That(root.Q("PullSummaryTotals").worldBound.width, Is.GreaterThan(250));
|
||||
if (size.x >= 760) Assert.That(detail.worldBound.width, Is.GreaterThan(400), "Use the space released by the single-result grid.");
|
||||
}
|
||||
LogAssert.NoUnexpectedReceived();
|
||||
}
|
||||
finally { view?.Dispose(); window.Close(); }
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator LayoutMatrixKeepsOrderReadableTilesAndAccessibleControls()
|
||||
{
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
GachaRevealView view = null;
|
||||
try
|
||||
{
|
||||
window.position = new Rect(0, 0, 1150, 800);
|
||||
window.Show();
|
||||
var root = window.rootVisualElement;
|
||||
Attach(root);
|
||||
// Include the 125% DPI logical sizes used by the actual runtime panel.
|
||||
foreach (var size in new[] { new Vector2(1920,1080), new Vector2(1366,768), new Vector2(1280,720), new Vector2(1024,768), new Vector2(390,844), new Vector2(740,480), new Vector2(1093,614), new Vector2(1024,576), new Vector2(819,614), new Vector2(312,675) })
|
||||
foreach (int units in new[] { 0, 1, 3, 10 })
|
||||
{
|
||||
view?.Dispose(); root.Clear();
|
||||
root.style.width = size.x; root.style.height = size.y;
|
||||
view = new GachaRevealView(root, Receipt(Enumerable.Range(1,10).Select(i =>
|
||||
{
|
||||
bool distro = units == 10 || units == 1 && i == 6 || units == 3 && (i == 4 || i == 6 || i == 9);
|
||||
return Reward(i, distro, i % 2 == 0, distro ? 5 : i % 3 + 3);
|
||||
}).ToArray()), () => { });
|
||||
view.RevealAll();
|
||||
for (int frame = 0; frame < 5; frame++) yield return null;
|
||||
string context = $"{size}, {units} distributions";
|
||||
var next = root.Q("PullContinue");
|
||||
Assert.That(next.worldBound.yMax, Is.LessThanOrEqualTo(root.worldBound.yMax + 1), context);
|
||||
Assert.That(next.worldBound.xMax, Is.LessThanOrEqualTo(root.worldBound.xMax + 1), context);
|
||||
var grid = root.Q<ScrollView>("PullRewardScroll");
|
||||
var detail = root.Q<ScrollView>("PullRewardDetail");
|
||||
Assert.That(detail.contentViewport.worldBound.height, Is.GreaterThan(60), context);
|
||||
Assert.That(detail.horizontalScroller.highValue, Is.LessThanOrEqualTo(1), context);
|
||||
if (size.x >= 760) Assert.That(grid.horizontalScroller.highValue, Is.LessThanOrEqualTo(1), context);
|
||||
if (size.x >= 760) Assert.That(grid.scrollOffset.y, Is.EqualTo(0).Within(1), "Overview starts at pull 01: " + context);
|
||||
if (size.x >= 1024)
|
||||
{
|
||||
Assert.That(root.Q("PullReward-01").worldBound.y, Is.EqualTo(root.Q("PullReward-05").worldBound.y).Within(1), "Five columns: " + context);
|
||||
Assert.That(root.Q("PullReward-06").worldBound.y, Is.GreaterThan(root.Q("PullReward-01").worldBound.y), context);
|
||||
}
|
||||
for (int i = 1; i <= 10; i++)
|
||||
{
|
||||
var tile = root.Q($"PullReward-{i:00}");
|
||||
var rarity = tile.Q(className: "reveal-stars");
|
||||
Assert.That(rarity.worldBound.xMax, Is.LessThanOrEqualTo(tile.worldBound.xMax + 1), "Rarity fits: " + context);
|
||||
var art = tile.Q<Label>(className: "reveal-mini-art");
|
||||
if (art != null && size.x >= 760)
|
||||
{
|
||||
Assert.That(art.worldBound.xMax, Is.LessThanOrEqualTo(tile.worldBound.xMax + 1), "ASCII frame stays inside its card: " + context);
|
||||
Vector2 measured = art.MeasureTextSize(art.text,0,VisualElement.MeasureMode.Undefined,0,VisualElement.MeasureMode.Undefined);
|
||||
Assert.That(measured.x, Is.LessThanOrEqualTo(art.contentRect.width + 1), "All ASCII columns fit: " + context);
|
||||
Assert.That(measured.y, Is.LessThanOrEqualTo(art.contentRect.height + 1), "All ASCII rows fit: " + context);
|
||||
}
|
||||
}
|
||||
}
|
||||
LogAssert.NoUnexpectedReceived();
|
||||
}
|
||||
finally { view?.Dispose(); window.Close(); }
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator TileHeadersKeepFullIndexAndFiveStarRarityWithoutOverlapAtBothTextSizes()
|
||||
{
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
GachaRevealView view = null;
|
||||
try
|
||||
{
|
||||
window.position = new Rect(0, 0, 1150, 800);
|
||||
window.Show();
|
||||
var root = window.rootVisualElement;
|
||||
Attach(root);
|
||||
foreach (var textSize in new[] { UITextSize.Standard, UITextSize.Large })
|
||||
foreach (var size in new[] { new Vector2(1366, 768), new Vector2(1024, 768), new Vector2(819, 614), new Vector2(312, 675) })
|
||||
{
|
||||
view?.Dispose(); root.Clear();
|
||||
UIPreferences.TextSize = textSize;
|
||||
root.style.width = size.x; root.style.height = size.y;
|
||||
view = new GachaRevealView(root, Receipt(Enumerable.Range(1, 10)
|
||||
.Select(i => Reward(i, i % 2 == 0, i % 3 == 0, 5)).ToArray()), () => { });
|
||||
view.RevealAll();
|
||||
for (int frame = 0; frame < 5; frame++) yield return null;
|
||||
string context = $"{size}, {textSize}";
|
||||
for (int i = 1; i <= 10; i++)
|
||||
{
|
||||
var tile = root.Q($"PullReward-{i:00}");
|
||||
var header = tile.Q(className: "reveal-tile-top");
|
||||
var index = header.Q<Label>(className: "reveal-index");
|
||||
var rarity = header.Q<Label>(className: "reveal-stars");
|
||||
Assert.That(index.text, Is.EqualTo($"{i:00}"), context);
|
||||
Assert.That(rarity.text, Is.EqualTo("[" + RarityPresentation.ForStars(5).Stars + "]"), context);
|
||||
foreach (var label in new[] { index, rarity })
|
||||
{
|
||||
Assert.That(label.worldBound.xMin, Is.GreaterThanOrEqualTo(header.worldBound.xMin - 1), context);
|
||||
Assert.That(label.worldBound.xMax, Is.LessThanOrEqualTo(header.worldBound.xMax + 1), context);
|
||||
Assert.That(label.worldBound.yMax, Is.LessThanOrEqualTo(header.worldBound.yMax + 1), context);
|
||||
var measured = label.MeasureTextSize(label.text, 0, VisualElement.MeasureMode.Undefined,
|
||||
0, VisualElement.MeasureMode.Undefined);
|
||||
Assert.That(measured.x, Is.LessThanOrEqualTo(label.contentRect.width + 1), "Full header text fits: " + context);
|
||||
}
|
||||
Assert.That(index.worldBound.Overlaps(rarity.worldBound), Is.False, "Index and rarity never overlap: " + context);
|
||||
Assert.That(tile.Q(className: "reveal-kind").worldBound.yMin,
|
||||
Is.GreaterThanOrEqualTo(header.worldBound.yMax - 1), "Wrapped rarity does not overlap reward kind: " + context);
|
||||
}
|
||||
}
|
||||
LogAssert.NoUnexpectedReceived();
|
||||
}
|
||||
finally { view?.Dispose(); window.Close(); }
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GrantingAndPresentingPackagesAreSeparateAndIdempotent()
|
||||
{
|
||||
var database = ScriptableObject.CreateInstance<PackageDatabase>();
|
||||
var package = AssetDatabase.LoadAssetAtPath<PackageDefinition>("Assets/Data/Packages/Zram.asset");
|
||||
typeof(PackageDatabase).GetField("allPackages", BindingFlags.Instance | BindingFlags.NonPublic)
|
||||
.SetValue(database, new List<PackageDefinition> { package });
|
||||
var random = Random.state;
|
||||
try
|
||||
{
|
||||
var save = SaveData.CreateDefault();
|
||||
var collection = new PlayerCollection();
|
||||
var grant = typeof(GamblingSceneController).GetMethod("GrantRandomPackageByRarity", BindingFlags.Static | BindingFlags.NonPublic);
|
||||
var args = new object[] { database, collection, save, 3, false, 0 };
|
||||
grant.Invoke(null, args);
|
||||
Assert.That(args[4], Is.EqualTo(false));
|
||||
Assert.That(collection.OwnedPackageInstances.Count, Is.EqualTo(1));
|
||||
grant.Invoke(null, args);
|
||||
Assert.That(args[4], Is.EqualTo(true));
|
||||
Assert.That(args[5], Is.EqualTo(PackageTuning.GetCacheForRarity(3)));
|
||||
int cache = save.cacheBalance;
|
||||
string committed = JsonUtility.ToJson(save);
|
||||
var stateAfterGrant = Random.state;
|
||||
var reward = new CompletedGachaReward(1, 3, package.DisplayName, GachaRewardType.Package, PullOutcomeKind.Dupe,
|
||||
(int)args[5], null, false, false, new GachaRewardDisplayData(null, package, 1, 0));
|
||||
for (int repeat = 0; repeat < 3; repeat++)
|
||||
{
|
||||
using var view = new GachaRevealView(new VisualElement(), Receipt(reward), () => { });
|
||||
view.RevealNext(); view.RevealAll(); view.Select(0); view.RevealAll();
|
||||
}
|
||||
Assert.That(JsonUtility.ToJson(save), Is.EqualTo(committed));
|
||||
Assert.That(save.cacheBalance, Is.EqualTo(cache));
|
||||
Assert.That(collection.OwnedPackageInstances.Count, Is.EqualTo(1));
|
||||
Assert.That(JsonUtility.ToJson(Random.state), Is.EqualTo(JsonUtility.ToJson(stateAfterGrant)));
|
||||
}
|
||||
finally { Random.state = random; UnityEngine.Object.DestroyImmediate(database); }
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EmptyReceiptsAndRebuildingDoNotReplayTransactions()
|
||||
{
|
||||
var root = new VisualElement();
|
||||
using (var empty = new GachaRevealView(root, Receipt(), () => { }))
|
||||
{
|
||||
empty.Begin();
|
||||
Assert.That(empty.IsComplete, Is.True);
|
||||
Assert.That(root.Q("PullContinue").enabledSelf, Is.True);
|
||||
}
|
||||
root.Clear();
|
||||
var rewards = new List<CompletedGachaReward> { Reward(1, false, false, 3) };
|
||||
using var view = new GachaRevealView(root, new CompletedGachaPull("test", "paid", rewards), () => { });
|
||||
rewards.Clear();
|
||||
view.RevealAll();
|
||||
Assert.That(view.RevealedCount, Is.EqualTo(1), "Presentation owns a snapshot of the receipt order.");
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator NarrowReceiptUsesAResultStripAndKeepsContinueVisible()
|
||||
{
|
||||
if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Null) Assert.Ignore("Requires an editor panel.");
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
GachaRevealView view = null;
|
||||
try
|
||||
{
|
||||
window.position = new Rect(0, 0, 1150, 800);
|
||||
window.Show();
|
||||
var root = window.rootVisualElement;
|
||||
root.style.width = 390;
|
||||
root.style.height = 720;
|
||||
Attach(root);
|
||||
view = new GachaRevealView(root, Receipt(Enumerable.Range(1, 10).Select(i => Reward(i, i == 6, i % 2 == 0, i == 6 ? 5 : 3)).ToArray()), () => { });
|
||||
view.RevealAll();
|
||||
for (int frame = 0; frame < 5; frame++) yield return null;
|
||||
Assert.That(root.Q<ScrollView>("PullRewardScroll").mode, Is.EqualTo(ScrollViewMode.Horizontal));
|
||||
var next = root.Q<Button>("PullContinue");
|
||||
Assert.That(next.worldBound.yMax, Is.LessThanOrEqualTo(root.worldBound.yMax));
|
||||
Assert.That(next.worldBound.xMax, Is.LessThanOrEqualTo(root.worldBound.xMax));
|
||||
Assert.That(root.Q<ScrollView>("PullRewardDetail").horizontalScroller.highValue, Is.LessThanOrEqualTo(1));
|
||||
root.style.width = 1100;
|
||||
for (int frame = 0; frame < 5; frame++) yield return null;
|
||||
Assert.That(root.Q<ScrollView>("PullRewardScroll").mode, Is.EqualTo(ScrollViewMode.Vertical));
|
||||
Assert.That(root.Q<ScrollView>("PullRewardScroll").horizontalScroller.highValue, Is.LessThanOrEqualTo(1));
|
||||
LogAssert.NoUnexpectedReceived();
|
||||
}
|
||||
finally { view?.Dispose(); window.Close(); }
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DistroNewDuplicateAndMaxReleaseConversionsComeFromResolver()
|
||||
{
|
||||
var distro = AssetDatabase.LoadAssetAtPath<DistroDefinition>("Assets/Data/Distros/Mint.asset");
|
||||
var save = SaveData.CreateDefault();
|
||||
var owned = new PlayerCollection();
|
||||
var context = new PullResolutionContext(save, owned, focusUnitId: distro.Id);
|
||||
var first = PullResolver.Resolve(new[] { distro, distro }, context);
|
||||
Assert.That(first.Outcomes[0].Kind, Is.EqualTo(PullOutcomeKind.Granted));
|
||||
Assert.That(first.Outcomes[1].Kind, Is.EqualTo(PullOutcomeKind.Dupe));
|
||||
save.FindOwnedUnit(distro.Id).version = GachaTuning.MaxVersion;
|
||||
var overflow = PullResolver.Resolve(new[] { distro }, context).Outcomes[0];
|
||||
Assert.That(overflow.Kind, Is.EqualTo(PullOutcomeKind.DupeOverflow));
|
||||
var reward = new CompletedGachaReward(1, 4, distro.DisplayName, GachaRewardType.Distro, overflow.Kind,
|
||||
overflow.MergesAwarded, overflow.LanguagesNewlyUnlocked, false, false, new GachaRewardDisplayData(distro, null, 5, 0));
|
||||
string committed = JsonUtility.ToJson(save);
|
||||
var root = new VisualElement();
|
||||
using var view = new GachaRevealView(root, Receipt(reward), () => { });
|
||||
view.RevealAll(); view.RevealAll();
|
||||
Assert.That(Copy(root), Does.Contain($"+{overflow.MergesAwarded} Merges"));
|
||||
Assert.That(Copy(root), Does.Contain("Maximum release already installed."));
|
||||
Assert.That(JsonUtility.ToJson(save), Is.EqualTo(committed));
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator RevealControlsSupportKeyboardInspectionAndDoNotExitOnArrowsOrTab()
|
||||
{
|
||||
if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Null) Assert.Ignore("Requires an editor panel.");
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
GachaRevealView view = null;
|
||||
try
|
||||
{
|
||||
window.position = new Rect(0, 0, 1000, 700);
|
||||
window.Show();
|
||||
var root = window.rootVisualElement;
|
||||
Attach(root);
|
||||
int continued = 0;
|
||||
view = new GachaRevealView(root, Receipt(Reward(1, false, false, 3), Reward(2, true, true, 5)), () => continued++);
|
||||
root.Focus();
|
||||
yield return null;
|
||||
Key(root, KeyCode.Space);
|
||||
Assert.That(view.RevealedCount, Is.EqualTo(1));
|
||||
Assert.That(continued, Is.Zero);
|
||||
Key(root, KeyCode.Escape);
|
||||
Assert.That(view.IsComplete, Is.True);
|
||||
Key(root, KeyCode.Escape);
|
||||
Assert.That(continued, Is.Zero, "Holding skip must not immediately dismiss the receipt.");
|
||||
using (var release = KeyUpEvent.GetPooled('\0', KeyCode.Escape, EventModifiers.None)) { release.target = root; root.SendEvent(release); }
|
||||
Key(root, KeyCode.R);
|
||||
Key(root, KeyCode.LeftArrow);
|
||||
Assert.That(view.SelectedIndex, Is.Zero);
|
||||
Key(root, KeyCode.Tab);
|
||||
Assert.That(continued, Is.Zero);
|
||||
var button = root.Q<Button>("PullReward-02");
|
||||
button.Focus();
|
||||
using (var submit = NavigationSubmitEvent.GetPooled()) { submit.target = button; button.SendEvent(submit); }
|
||||
Assert.That(view.SelectedIndex, Is.EqualTo(1));
|
||||
Assert.That(continued, Is.Zero);
|
||||
Key(root, KeyCode.Escape);
|
||||
Key(root, KeyCode.Escape);
|
||||
Assert.That(continued, Is.EqualTo(1));
|
||||
LogAssert.NoUnexpectedReceived();
|
||||
}
|
||||
finally { view?.Dispose(); window.Close(); }
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator AutoRevealCompletesAndDisposalCancelsPendingWork()
|
||||
{
|
||||
if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Null) Assert.Ignore("Requires an editor panel.");
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
GachaRevealView view = null;
|
||||
try
|
||||
{
|
||||
window.Show();
|
||||
var root = window.rootVisualElement;
|
||||
Attach(root);
|
||||
view = new GachaRevealView(root, Receipt(Reward(1, false, false, 3), Reward(2, true, false, 4)), () => { });
|
||||
view.Begin();
|
||||
double until = EditorApplication.timeSinceStartup + 5;
|
||||
while (!view.IsComplete && EditorApplication.timeSinceStartup < until) yield return null;
|
||||
Assert.That(view.IsComplete, Is.True);
|
||||
view.Dispose();
|
||||
root.Clear();
|
||||
view = new GachaRevealView(root, Receipt(Reward(1, false, false, 3)), () => { });
|
||||
view.Begin();
|
||||
view.Dispose();
|
||||
view.RevealNext(); view.RevealAll();
|
||||
Assert.That(view.RevealedCount, Is.Zero);
|
||||
LogAssert.NoUnexpectedReceived();
|
||||
}
|
||||
finally { view?.Dispose(); window.Close(); }
|
||||
}
|
||||
|
||||
private static CompletedGachaPull Receipt(params CompletedGachaReward[] rewards) => new("fixture", "spent fixture currency", rewards);
|
||||
private static CompletedGachaReward Reward(int index, bool distro, bool duplicate, int stars)
|
||||
{
|
||||
var unit = distro ? AssetDatabase.LoadAssetAtPath<DistroDefinition>($"Assets/Data/Distros/{(stars == 5 ? "Arch" : "Mint")}.asset") : null;
|
||||
var package = distro ? null : AssetDatabase.LoadAssetAtPath<PackageDefinition>($"Assets/Data/Packages/{(stars == 5 ? "Apt" : stars == 4 ? "Aur" : "Zram")}.asset");
|
||||
return new CompletedGachaReward(index, stars, distro ? unit.DisplayName : package.DisplayName, distro ? GachaRewardType.Distro : GachaRewardType.Package,
|
||||
duplicate ? PullOutcomeKind.Dupe : PullOutcomeKind.Granted, duplicate ? 137 : 0, Array.Empty<Language>(), false, false,
|
||||
new GachaRewardDisplayData(unit, package, 3, 2));
|
||||
}
|
||||
private static string Copy(VisualElement root) => string.Join("\n", root.Query<Label>().ToList().Select(l => l.text));
|
||||
private static void Key(VisualElement target, KeyCode key) { using var evt = KeyDownEvent.GetPooled('\0', key, EventModifiers.None); evt.target = target; target.SendEvent(evt); }
|
||||
private static void Attach(VisualElement root)
|
||||
{
|
||||
root.styleSheets.Add(Resources.Load<StyleSheet>("GamblingScene"));
|
||||
root.styleSheets.Add(Resources.Load<StyleSheet>("RarityPresentation"));
|
||||
typeof(MainMenuController).Assembly.GetType("KernelPanic.UI.TerminalTheme").GetMethod("Attach").Invoke(null, new object[] { root });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7b57a0909576e1c4187bbe7611ebc56e
|
||||
@@ -0,0 +1,711 @@
|
||||
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.Meta;
|
||||
using KernelPanic.Run;
|
||||
using KernelPanic.UI;
|
||||
using NUnit.Framework;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using UnityEngine.TestTools;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
public class GentooHaskellTests
|
||||
{
|
||||
const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
GameObject _owner;
|
||||
CombatManager _combat;
|
||||
RunManager _run;
|
||||
CardDatabase _cards;
|
||||
DistroDefinition _gentoo;
|
||||
UnityEngine.Random.State _random;
|
||||
bool _motion;
|
||||
static object Call(object owner, string method, params object[] args) => owner.GetType().GetMethod(method, Private).Invoke(owner, args);
|
||||
static void Set(object owner, string field, object value) => owner.GetType().GetField(field, Private).SetValue(owner, value);
|
||||
static T Asset<T>(string path) where T : UnityEngine.Object => AssetDatabase.LoadAssetAtPath<T>(path);
|
||||
CardInstance Card(string id) { var def = _cards.FindById(id); Assert.That(def, Is.Not.Null, id); return new CardInstance(def); }
|
||||
CombatantState Player => _combat.PlayerState;
|
||||
EnemyInstance Target => _combat.Enemies[0];
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_random = UnityEngine.Random.state;
|
||||
_motion = UIPreferences.ReducedMotion;
|
||||
UIPreferences.ReducedMotion = true;
|
||||
_cards = Asset<CardDatabase>("Assets/Data/Cards/CardDatabase.asset");
|
||||
_gentoo = Asset<DistroDefinition>("Assets/Data/Distros/Gentoo.asset");
|
||||
Assert.That(_gentoo, Is.Not.Null);
|
||||
_owner = new GameObject("Gentoo Haskell integration");
|
||||
_run = _owner.AddComponent<RunManager>();
|
||||
_combat = _owner.AddComponent<CombatManager>();
|
||||
Call(_combat, "OnDisable"); Call(_combat, "Awake"); Call(_combat, "OnEnable");
|
||||
Configure(1);
|
||||
AddEnemy("memory_leak", 10000);
|
||||
}
|
||||
|
||||
void Configure(int version, DistroDefinition distro = null, params PackageInstance[] packages)
|
||||
{
|
||||
var config = new RunConfig(distro ?? _gentoo, Language.Haskell, Language.C,
|
||||
_gentoo.ExclusiveCards.Take(4).ToArray(), packages, 17, version);
|
||||
_run.StartRun(config);
|
||||
Set(_combat, "_runConfig", config);
|
||||
Set(_combat, "_runManager", _run);
|
||||
Set(_combat, "_playerState", new CombatantState(55, 32, 100));
|
||||
Set(_combat, "_handController", new HandController(32));
|
||||
Set(_combat, "currentPhase", TurnPhase.Execute);
|
||||
Call(_combat, "ApplyVersionState", Player);
|
||||
Call(_combat, "ApplyPackageState", Player);
|
||||
Player.ForceMaxRolls = true; // No crit/recoil; does NOT bypass damage modifiers.
|
||||
_combat.Compilation.BeginWave(distro == null || distro.Id == "gentoo" ? version : 0);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
if (_combat != null) Call(_combat, "OnDisable");
|
||||
UnityEngine.Object.DestroyImmediate(_owner);
|
||||
UnityEngine.Random.state = _random;
|
||||
UIPreferences.ReducedMotion = _motion;
|
||||
}
|
||||
|
||||
EnemyInstance AddEnemy(string id, int hp)
|
||||
{
|
||||
var enemy = new EnemyInstance(EnemyArchetypeCatalog.Get(id), hp);
|
||||
enemy.State.MaxUptime = hp; enemy.State.CurrentUptime = hp;
|
||||
((List<EnemyInstance>)_combat.Enemies).Add(enemy);
|
||||
return enemy;
|
||||
}
|
||||
|
||||
CombatContext Context(CardInstance card, int multiplier = 100)
|
||||
{
|
||||
var context = new CombatContext(card, Player, new[] { Target.State }, _combat, _combat.DamagePipeline,
|
||||
new StatusEffectController(), _combat.DeckController, _combat.HandController, _combat.Enemies);
|
||||
typeof(CombatContext).GetProperty("LazyMultiplierPercent").SetValue(context, multiplier);
|
||||
return context;
|
||||
}
|
||||
|
||||
void Effect(CardInstance card, int multiplier = 100)
|
||||
{
|
||||
var context = Context(card, multiplier);
|
||||
foreach (var effect in CardEffectFactory.CreateEffects(card.Definition)) effect.Execute(context);
|
||||
}
|
||||
|
||||
void FillDrawPile() => _combat.DeckController.Initialize(Enumerable.Range(0, 24).Select(_ => Card("lang_hs_map")));
|
||||
|
||||
void Play(CardInstance card)
|
||||
{
|
||||
Assert.That(_combat.HandController.Add(card), Is.True);
|
||||
_combat.SelectEnemy(0);
|
||||
Assert.That(_combat.PlayCard(card), Is.True);
|
||||
}
|
||||
|
||||
void Drain(string method = "EvaluateLazyStackSequenced")
|
||||
{
|
||||
Set(_combat, "currentPhase", TurnPhase.Interpret);
|
||||
Finish((IEnumerator)Call(_combat, method));
|
||||
}
|
||||
|
||||
static void Finish(IEnumerator routine)
|
||||
{
|
||||
int steps = 0;
|
||||
while (routine.MoveNext())
|
||||
{
|
||||
Assert.That(++steps, Is.LessThan(2000), "Finite authoritative resolution");
|
||||
if (routine.Current is IEnumerator child) Finish(child);
|
||||
}
|
||||
}
|
||||
|
||||
[TestCase("gentoo_emerge_sync", 1, 0, 6, 2, true, false)]
|
||||
[TestCase("gentoo_ebuild", 1, 0, 6, 2, true, false)]
|
||||
[TestCase("gentoo_use_flags", 0, 0, 0, 0, true, false)]
|
||||
[TestCase("gentoo_make_j4", 1, 1, 0, 0, true, false)]
|
||||
[TestCase("gentoo_emerge_world", 2, 1, 6, 2, true, false)]
|
||||
[TestCase("lang_hs_map", 0, 0, 6, 2, false, false)]
|
||||
[TestCase("lang_hs_foldr", 1, 0, 6, 2, false, false)]
|
||||
[TestCase("lang_hs_thunk", 1, 0, 6, 2, false, false)]
|
||||
[TestCase("shop_hs_filter", 1, 0, 6, 2, false, true)]
|
||||
[TestCase("shop_hs_fmap", 0, 0, 6, 2, false, true)]
|
||||
[TestCase("shop_hs_zipwith", 1, 0, 6, 2, false, true)]
|
||||
[TestCase("shop_hs_maybe", 1, 0, 6, 2, false, true)]
|
||||
[TestCase("shop_hs_sequence", 1, 0, 6, 2, false, true)]
|
||||
[TestCase("shop_hs_const", 0, 0, 6, 2, false, true)]
|
||||
[TestCase("shop_hs_scanl", 1, 1, 6, 2, false, true)]
|
||||
[TestCase("shop_hs_foldmap", 2, 1, 6, 2, false, true)]
|
||||
[TestCase("shop_hs_deepseq", 2, 1, 6, 2, false, true)]
|
||||
[TestCase("shop_hs_dollar_bang", 1, 1, 6, 2, false, true)]
|
||||
public void EveryNewDefinitionIsRegisteredAndExecutable(string id, int cost, int rarity, int language, int track, bool exclusive, bool shop)
|
||||
{
|
||||
var card = Card(id).Definition;
|
||||
Assert.That(card.CycleCost, Is.EqualTo(cost));
|
||||
Assert.That((int)card.Rarity, Is.EqualTo(rarity));
|
||||
Assert.That((int)card.Language, Is.EqualTo(language));
|
||||
Assert.That((int)card.ResolutionTrack, Is.EqualTo(track));
|
||||
Assert.That(card.DistroExclusive, Is.EqualTo(exclusive));
|
||||
Assert.That(card.IsRunOnly, Is.EqualTo(shop));
|
||||
Assert.That(card.IsToken, Is.False);
|
||||
Assert.That(CardEffectFactory.CreateEffects(card).All(e => e is not NoOpCardEffect), Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RegistriesContainOnlyRealDefinitionsIncludingTheTwoRepairedPythonCards()
|
||||
{
|
||||
Assert.That(_cards.AllCards, Has.Count.EqualTo(65));
|
||||
Assert.That(_cards.AllCards.All(c => c != null), Is.True);
|
||||
Assert.That(_cards.AllCards.Select(c => c.Id).Distinct().Count(), Is.EqualTo(65));
|
||||
Assert.That(Card("shop_py_list_append").Definition.DisplayName, Is.Not.Empty);
|
||||
Assert.That(Card("shop_py_async_def").Definition.DisplayName, Is.Not.Empty);
|
||||
var distros = Asset<DistroDatabase>("Assets/Data/Distros/DistroDatabase.asset");
|
||||
Assert.That(distros.FindById("gentoo"), Is.SameAs(_gentoo));
|
||||
Assert.That(_gentoo.ExclusiveCards.Count, Is.EqualTo(5));
|
||||
Assert.That((_gentoo.BaseUptime, _gentoo.BaseRam, _gentoo.BaseCyclesPerTurn), Is.EqualTo((55,6,3)));
|
||||
Assert.That((_gentoo.PrimaryLanguage, _gentoo.SecondaryLanguage), Is.EqualTo((Language.Haskell,Language.C)));
|
||||
Assert.That(_gentoo.Passive.Id, Is.EqualTo("gentoo_emerge_world"));
|
||||
Assert.That(_gentoo.AsciiArt.text.Split('\n').Length, Is.GreaterThan(8));
|
||||
}
|
||||
|
||||
[TestCase(1,0,4,85)] [TestCase(2,0,4,95)] [TestCase(3,1,4,100)]
|
||||
[TestCase(4,1,4,100)] [TestCase(5,1,6,100)]
|
||||
public void VersionsInitializeProgressAndReset(int version, int start, int cap, int percent)
|
||||
{
|
||||
var state = _combat.Compilation;
|
||||
state.BeginWave(version);
|
||||
Assert.That((state.Level, state.Maximum, state.DamagePercent), Is.EqualTo((start,cap,percent)));
|
||||
for (int round = 1; round <= 20; round++)
|
||||
{
|
||||
int before = state.Level;
|
||||
state.CompleteRound(round);
|
||||
Assert.That(state.Level, Is.EqualTo(Math.Min(cap,before+1)));
|
||||
Assert.That(state.CompleteRound(round), Is.False);
|
||||
}
|
||||
Assert.That(state.DamagePercent, Is.EqualTo(version == 5 ? 150 : 130));
|
||||
state.BeginWave(version);
|
||||
Assert.That(state.Level, Is.EqualTo(start));
|
||||
Assert.That(state.CompleteRound(1), Is.True);
|
||||
}
|
||||
|
||||
[TestCase(1,0,85)] [TestCase(2,0,95)] [TestCase(1,1,100)]
|
||||
[TestCase(1,2,110)] [TestCase(1,3,120)] [TestCase(1,4,130)]
|
||||
[TestCase(5,4,140)] [TestCase(5,5,150)]
|
||||
public void DirectDamageReadsCurrentCompilation(int version, int completedRounds, int expected)
|
||||
{
|
||||
_combat.Compilation.BeginWave(version);
|
||||
for (int i=1;i<=completedRounds;i++) _combat.Compilation.CompleteRound(i);
|
||||
var ctx = Context(Card("lang_hs_thunk"));
|
||||
var result = _combat.DamagePipeline.DealDamage(DamageRequest.FromCard(ctx, Target.State, 100, Language.Haskell, false, false));
|
||||
Assert.That(result.IncomingAmount, Is.EqualTo(expected));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GarbageCollectionIsTheOnlyRoundProgressionAndIsIdempotent()
|
||||
{
|
||||
Set(_combat, "_turnNumberThisWave", 1);
|
||||
Call(_combat, "GarbageCollect");
|
||||
Assert.That(_combat.Compilation.Level, Is.EqualTo(1));
|
||||
Call(_combat, "GarbageCollect");
|
||||
Assert.That(_combat.Compilation.Level, Is.EqualTo(1));
|
||||
Set(_combat, "_turnNumberThisWave", 2);
|
||||
Call(_combat, "GarbageCollect");
|
||||
Assert.That(_combat.Compilation.Level, Is.EqualTo(2));
|
||||
}
|
||||
|
||||
[TestCase(1,0)] [TestCase(5,1)]
|
||||
public void RealWaveStartClearsPendingSnapshotsAndResetsCompilation(int version, int expected)
|
||||
{
|
||||
Configure(version);
|
||||
Play(Card("lang_hs_map"));
|
||||
for (int i=1;i<=8;i++) _combat.Compilation.CompleteRound(i);
|
||||
Finish((IEnumerator)Call(_combat, "StartWaveSequenced", true));
|
||||
Assert.That(_combat.Compilation.Level, Is.EqualTo(expected));
|
||||
Assert.That(_combat.LazyStack.Count, Is.Zero);
|
||||
Assert.That(_combat.InterpreterQueue.Count, Is.Zero);
|
||||
Assert.That(Player.FlatEffectBonus, Is.Zero);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SnapshotCountsOnlyHaskellAndSurvivesPopsAndCopies()
|
||||
{
|
||||
var stack = new LazyStack();
|
||||
stack.Enqueue(Card("lang_py_print"));
|
||||
var cards = Enumerable.Range(0,6).Select(_ => Card("lang_hs_map")).ToArray();
|
||||
for (int i=0;i<cards.Length;i++)
|
||||
{
|
||||
stack.Enqueue(cards[i]);
|
||||
Assert.That(stack.Entries[0].MultiplierPercent, Is.EqualTo(Math.Min(250,100+i*50)));
|
||||
}
|
||||
int[] expected = {250,250,250,200,150,100,100};
|
||||
foreach (int percent in expected)
|
||||
{
|
||||
Assert.That(stack.TryPopEntry(out var entry), Is.True);
|
||||
Assert.That(entry.MultiplierPercent, Is.EqualTo(percent));
|
||||
}
|
||||
stack.Enqueue(cards[3].CopyForCombat());
|
||||
Assert.That(stack.Entries[0].MultiplierPercent, Is.EqualTo(100));
|
||||
stack.Enqueue(stack.Cards[0]);
|
||||
Assert.That(stack.Count, Is.EqualTo(1), "Same pending instance cannot be pushed twice");
|
||||
}
|
||||
|
||||
[TestCase(false)] [TestCase(true)]
|
||||
public void RealLifoResolutionEventsRidersAndDisposalAreExactlyOnce(bool reducedMotion)
|
||||
{
|
||||
UIPreferences.ReducedMotion = reducedMotion;
|
||||
_combat.Compilation.BeginWave(0);
|
||||
FillDrawPile();
|
||||
string[] ids = {"lang_hs_map","lang_hs_foldr","gentoo_ebuild","lang_hs_thunk"};
|
||||
var cards = ids.Select(Card).ToArray();
|
||||
cards[3].ApplyDrawRider(1);
|
||||
var played = new List<CardInstance>();
|
||||
var resolved = new List<CardInstance>();
|
||||
var resolving = new List<CardInstance>();
|
||||
Action<CardPlayedEvent> onPlay = e => played.Add(e.Card);
|
||||
Action<CardResolvedEvent> onStart = e => resolving.Add(e.Card);
|
||||
Action<CardResolvedEvent> onEnd = e => { resolved.Add(e.Card); _combat.EvaluateLazyStack(); };
|
||||
GameEvents.CardPlayed += onPlay; GameEvents.CardResolving += onStart; GameEvents.CardResolved += onEnd;
|
||||
try
|
||||
{
|
||||
foreach (var card in cards) Play(card);
|
||||
Assert.That(Target.CurrentUptime, Is.EqualTo(10000));
|
||||
Assert.That(Player.Cycles, Is.EqualTo(97));
|
||||
Drain(); Drain();
|
||||
CollectionAssert.AreEqual(cards, played);
|
||||
CollectionAssert.AreEqual(cards.Reverse().ToArray(), resolving);
|
||||
CollectionAssert.AreEqual(resolving, resolved);
|
||||
Assert.That(Target.CurrentUptime, Is.EqualTo(9980)); // 10 + 8 + 2
|
||||
Assert.That(Player.Shield, Is.EqualTo(4)); // 3 * 1.5, nearest-even
|
||||
Assert.That(_combat.HandController.Cards.Count, Is.EqualTo(2)); // draw + rider, not multiplied
|
||||
foreach (var card in cards)
|
||||
{
|
||||
Assert.That(_combat.DeckController.DiscardPile.Count(c => c == card), Is.EqualTo(1));
|
||||
Assert.That(card.TargetSnapshot, Is.Empty);
|
||||
}
|
||||
Assert.That(_combat.LazyStack.Count, Is.Zero);
|
||||
}
|
||||
finally { GameEvents.CardPlayed -= onPlay; GameEvents.CardResolving -= onStart; GameEvents.CardResolved -= onEnd; }
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void QueueBeforeStackAndDeferredDamageUsesResolutionLevel()
|
||||
{
|
||||
Play(Card("lang_hs_thunk")); Play(Card("shop_py_list_append"));
|
||||
for(int i=1;i<=4;i++) _combat.Compilation.CompleteRound(i);
|
||||
var order = new List<string>();
|
||||
Action<CardResolvedEvent> observe = e => order.Add(e.Card.Definition.Id);
|
||||
GameEvents.CardResolved += observe;
|
||||
try
|
||||
{
|
||||
Drain("InterpretQueueSequenced"); Drain();
|
||||
CollectionAssert.AreEqual(new[]{"shop_py_list_append","lang_hs_thunk"},order);
|
||||
Assert.That(Target.CurrentUptime, Is.EqualTo(9990)); // round(4*1.3), twice; not wave-start 85%.
|
||||
}
|
||||
finally { GameEvents.CardResolved -= observe; }
|
||||
}
|
||||
|
||||
[TestCase("gentoo_emerge_sync",0,2,1)]
|
||||
[TestCase("gentoo_ebuild",4,0,0)]
|
||||
[TestCase("gentoo_use_flags",0,4,0)]
|
||||
[TestCase("gentoo_make_j4",8,0,0)]
|
||||
[TestCase("gentoo_emerge_world",3,2,0)]
|
||||
[TestCase("lang_hs_map",2,0,0)]
|
||||
[TestCase("lang_hs_foldr",0,3,1)]
|
||||
[TestCase("lang_hs_thunk",4,0,0)]
|
||||
[TestCase("shop_hs_filter",4,0,0)]
|
||||
[TestCase("shop_hs_fmap",0,2,0)]
|
||||
[TestCase("shop_hs_zipwith",2,0,0)]
|
||||
[TestCase("shop_hs_maybe",0,4,0)]
|
||||
[TestCase("shop_hs_sequence",0,0,2)]
|
||||
[TestCase("shop_hs_const",2,0,0)]
|
||||
[TestCase("shop_hs_scanl",0,4,1)]
|
||||
[TestCase("shop_hs_foldmap",4,0,0)]
|
||||
[TestCase("shop_hs_deepseq",9,0,0)]
|
||||
[TestCase("shop_hs_dollar_bang",5,2,0)]
|
||||
public void EveryCardHasItsExactBaseEffect(string id, int damage, int shield, int draw)
|
||||
{
|
||||
_combat.Compilation.BeginWave(0); FillDrawPile();
|
||||
var card = Card(id); Effect(card);
|
||||
Assert.That(10000 - Target.CurrentUptime, Is.EqualTo(damage));
|
||||
Assert.That(Player.Shield, Is.EqualTo(shield));
|
||||
Assert.That(_combat.HandController.Cards.Count, Is.EqualTo(draw));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ConditionsAreCheckedAtExecutionAndBonusesAreSingleHits()
|
||||
{
|
||||
FillDrawPile();
|
||||
_combat.Compilation.CompleteRound(1); _combat.Compilation.CompleteRound(2);
|
||||
Effect(Card("gentoo_use_flags"));
|
||||
Assert.That(_combat.HandController.Cards.Count, Is.EqualTo(1));
|
||||
_combat.Compilation.CompleteRound(3);
|
||||
int hits=0; Action<DamageDealtEvent> observe=e=>{ if(e.Target==Target.State) hits++; };
|
||||
GameEvents.DamageDealt+=observe;
|
||||
try { Effect(Card("gentoo_make_j4")); Assert.That(10000-Target.CurrentUptime, Is.EqualTo(13)); Assert.That(hits,Is.EqualTo(1)); }
|
||||
finally { GameEvents.DamageDealt-=observe; }
|
||||
_combat.Compilation.BeginWave(0);
|
||||
new StatusEffectController().Apply(Target.State, StatusType.MemoryLeak,1,2);
|
||||
int before=Target.CurrentUptime; Effect(Card("shop_hs_filter"),250);
|
||||
Assert.That(before-Target.CurrentUptime, Is.EqualTo(15));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MaybeHealingDrawAndCyclesNeverReceiveLazyOrCompilationMultipliers()
|
||||
{
|
||||
_combat.Compilation.BeginWave(5);
|
||||
for(int i=1;i<=5;i++) _combat.Compilation.CompleteRound(i);
|
||||
Player.CurrentUptime=40;
|
||||
Effect(Card("shop_hs_maybe"),250);
|
||||
Assert.That(Player.CurrentUptime, Is.EqualTo(43));
|
||||
Assert.That(Player.Shield,Is.Zero);
|
||||
FillDrawPile(); Effect(Card("shop_hs_sequence"),250);
|
||||
Assert.That(_combat.HandController.Cards.Count,Is.EqualTo(2));
|
||||
new NextTurnCycleEffect(1).Execute(Context(Card("shop_hs_sequence"),250));
|
||||
Assert.That(typeof(CombatManager).GetField("_nextTurnCycleBonus",Private).GetValue(_combat),Is.EqualTo(1));
|
||||
Player.CurrentUptime=55; Effect(Card("shop_hs_maybe"),250);
|
||||
Assert.That(Player.Shield,Is.EqualTo(13)); // 4*2.5*1.3
|
||||
}
|
||||
|
||||
[TestCase(1,0,250,8)] [TestCase(1,2,250,11)] [TestCase(5,5,250,15)]
|
||||
public void GentooHaskellDamageBenchmarks(int version,int rounds,int multiplier,int expected)
|
||||
{
|
||||
_combat.Compilation.BeginWave(version);
|
||||
for(int i=1;i<=rounds;i++) _combat.Compilation.CompleteRound(i);
|
||||
Effect(Card("lang_hs_thunk"),multiplier);
|
||||
Assert.That(10000-Target.CurrentUptime,Is.EqualTo(expected));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MagnitudeBeforeMultiplicationCostFloorAndRiderIndependence()
|
||||
{
|
||||
_combat.Compilation.BeginWave(0);
|
||||
var card=Card("lang_hs_thunk");
|
||||
card.ApplyMagnitudeUpgrade(2); card.ApplyCostUpgrade(-1); card.ApplyCostUpgrade(-1);
|
||||
Assert.That(CombatManager.GetCardCost(card),Is.Zero);
|
||||
Effect(card,250);
|
||||
Assert.That(10000-Target.CurrentUptime,Is.EqualTo(15));
|
||||
FillDrawPile();
|
||||
var foldr=Card("lang_hs_foldr"); foldr.ApplyMagnitudeUpgrade(2);
|
||||
Effect(foldr,250);
|
||||
Assert.That(Player.Shield,Is.EqualTo(12)); // nearest-even(5*2.5)
|
||||
Assert.That(_combat.HandController.Cards.Count,Is.EqualTo(3), "Existing +Magnitude draw semantics, not x2.5");
|
||||
}
|
||||
|
||||
[TestCase(1,4,100)] [TestCase(4,3,120)] [TestCase(5,5,130)]
|
||||
public void OnlyExplicitCardShieldGetsCompilation(int version,int rounds,int expectedPercent)
|
||||
{
|
||||
_combat.Compilation.BeginWave(version);
|
||||
for(int i=1;i<=rounds;i++) _combat.Compilation.CompleteRound(i);
|
||||
new ShieldEffect(100).Execute(Context(Card("shop_hs_fmap")));
|
||||
Assert.That(Player.Shield,Is.EqualTo(expectedPercent));
|
||||
_combat.GrantPlayerShield(100,"package");
|
||||
Assert.That(Player.Shield,Is.EqualTo(expectedPercent+100));
|
||||
var status=new StatusEffectController();
|
||||
status.Apply(Player,StatusType.UnattendedUpgrades,4,1);
|
||||
status.Tick(Player,StatusTickTiming.EndOfTurn,Player,_combat.DamagePipeline);
|
||||
Assert.That(Player.Shield,Is.EqualTo(expectedPercent+104));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EnemyRecoilDotAndPreScaledSpillDoNotInheritCardMultipliers()
|
||||
{
|
||||
_combat.Compilation.BeginWave(5); for(int i=1;i<=5;i++) _combat.Compilation.CompleteRound(i);
|
||||
Assert.That(_combat.DamagePipeline.DealDamage(new DamageRequest(null,Player,3,Language.C,true,false)).IncomingAmount,Is.EqualTo(3));
|
||||
Assert.That(_combat.DamagePipeline.DealDamage(new DamageRequest(Target.State,Player,10,Language.C,false,false)).IncomingAmount,Is.EqualTo(10));
|
||||
var status=new StatusEffectController();
|
||||
status.Apply(Target.State,StatusType.MemoryLeak,5,2,Player);
|
||||
status.Tick(Target.State,StatusTickTiming.StartOfTurn,Player,_combat.DamagePipeline);
|
||||
Assert.That(Target.CurrentUptime,Is.EqualTo(9995));
|
||||
Assert.That(_combat.DamagePipeline.DealDamage(new DamageRequest(Player,Target.State,10,Language.C,false,false,false)).IncomingAmount,Is.EqualTo(10));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CritIsAfterCompilationAndClampsSafely()
|
||||
{
|
||||
Player.ForceMaxRolls=false;
|
||||
_combat.Compilation.BeginWave(5); for(int i=1;i<=5;i++) _combat.Compilation.CompleteRound(i);
|
||||
bool found=false;
|
||||
for(int seed=1;seed<100&&!found;seed++)
|
||||
{
|
||||
RandomRoll.Seed(seed);
|
||||
var result=_combat.DamagePipeline.DealDamage(DamageRequest.FromCard(Context(Card("gentoo_make_j4")),Target.State,100,Language.C,false,true));
|
||||
if(result.WasCritical) { Assert.That(result.IncomingAmount,Is.EqualTo(225)); found=true; }
|
||||
}
|
||||
Assert.That(found,Is.True);
|
||||
Assert.That(CardScaling.Scale(int.MaxValue,250,150),Is.EqualTo(int.MaxValue));
|
||||
Assert.That(CardScaling.Scale(3,150),Is.EqualTo(4));
|
||||
Assert.That(CardScaling.Scale(5,150),Is.EqualTo(8));
|
||||
Assert.That(CardScaling.Scale(-1,250),Is.Zero);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HaskellIsIndependentOnUbuntuAndMintRestrictionsRemainIntact()
|
||||
{
|
||||
Configure(1,Asset<DistroDefinition>("Assets/Data/Distros/Ubuntu.asset"));
|
||||
Effect(Card("lang_hs_thunk"),250);
|
||||
Assert.That(10000-Target.CurrentUptime,Is.EqualTo(10));
|
||||
Configure(1,Asset<DistroDefinition>("Assets/Data/Distros/Mint.asset"));
|
||||
int before=Target.CurrentUptime;
|
||||
Effect(Card("lang_hs_thunk"),250); Effect(Card("shop_hs_fmap"),250);
|
||||
Assert.That(before-Target.CurrentUptime,Is.EqualTo(4),"Mint deliberately ignores multiplicative damage buffs");
|
||||
Assert.That(Player.Shield,Is.Zero,"Mint still blocks foreign card buffs");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AoeAndMultiHitApplyOnceToEachGenuineHit()
|
||||
{
|
||||
_combat.Compilation.BeginWave(5); for(int i=1;i<=5;i++) _combat.Compilation.CompleteRound(i);
|
||||
var other=AddEnemy("memory_leak",10000);
|
||||
Effect(Card("gentoo_emerge_world"),250);
|
||||
Assert.That(10000-Target.CurrentUptime,Is.EqualTo(11));
|
||||
Assert.That(10000-other.CurrentUptime,Is.EqualTo(11));
|
||||
Assert.That(Player.Shield,Is.EqualTo(6)); // nearest-even(2*2.5*1.3)
|
||||
int before=Target.CurrentUptime;
|
||||
Effect(Card("shop_js_promise_all"));
|
||||
Assert.That(before-Target.CurrentUptime,Is.EqualTo(45)); // max 10*1.5, three hits
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeadSnapshotRetargetsAndRapidInputCannotReexecute()
|
||||
{
|
||||
_combat.Compilation.BeginWave(0);
|
||||
var card=Card("lang_hs_thunk"); Play(card);
|
||||
Assert.That(_combat.PlayCard(card),Is.False);
|
||||
var other=AddEnemy("memory_leak",10000);
|
||||
var dead=Target; dead.State.IsDefeated=true;
|
||||
((List<EnemyInstance>)_combat.Enemies).Remove(dead);
|
||||
Drain(); Drain();
|
||||
Assert.That(other.CurrentUptime,Is.EqualTo(9996));
|
||||
Assert.That(_combat.DeckController.DiscardPile.Count(c=>c==card),Is.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RootkitResistanceIsAfterBothMultipliers()
|
||||
{
|
||||
((List<EnemyInstance>)_combat.Enemies).Clear();
|
||||
var rootkit=AddEnemy("rootkit",10000); AddEnemy("memory_leak",10000);
|
||||
_combat.Compilation.BeginWave(5); for(int i=1;i<=5;i++) _combat.Compilation.CompleteRound(i);
|
||||
Effect(Card("lang_hs_thunk"),250);
|
||||
Assert.That(10000-rootkit.CurrentUptime,Is.EqualTo(2)); // ceil(15*0.1)
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PendingRevivalDoesNotEndWaveOrConsumeRemainingCardsWithoutResolution()
|
||||
{
|
||||
((List<EnemyInstance>)_combat.Enemies).Clear();
|
||||
// At 1 maximum Uptime the existing ceil(25%) reap threshold is also 1.
|
||||
// Use a healthy 4-Uptime process so the first lethal hit really schedules revival.
|
||||
var zombie=AddEnemy("zombie_process",4);
|
||||
Play(Card("lang_hs_map")); Play(Card("lang_hs_thunk"));
|
||||
Drain();
|
||||
Assert.That(zombie.PendingRevive,Is.True);
|
||||
Assert.That(_combat.AwaitingWaveContinue,Is.False);
|
||||
Assert.That(_combat.LazyStack.Count,Is.Zero);
|
||||
Assert.That(_combat.DeckController.DiscardPile.Count,Is.EqualTo(2));
|
||||
Call(_combat,"RevivePendingEnemies");
|
||||
Assert.That(zombie.HasRevived,Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void WaveCompletionDefeatAndShutdownCleanPendingCardsWithoutFalseResolutions()
|
||||
{
|
||||
var a=Card("lang_hs_map"); var b=Card("lang_hs_thunk");
|
||||
Play(a); Play(b);
|
||||
((List<EnemyInstance>)_combat.Enemies).Clear();
|
||||
Assert.That((bool)Call(_combat,"CheckWin"),Is.True);
|
||||
Assert.That(_combat.LazyStack.Count,Is.Zero);
|
||||
Assert.That(a.TargetSnapshot,Is.Empty);
|
||||
Assert.That(b.TargetSnapshot,Is.Empty);
|
||||
Assert.That(_combat.DeckController.DiscardPile.Count,Is.EqualTo(2));
|
||||
_combat.LazyStack.Enqueue(a);
|
||||
Player.CurrentUptime=0;
|
||||
Player.IsDefeated=true;
|
||||
Call(_combat,"CheckLoss");
|
||||
Assert.That(_combat.LazyStack.Count,Is.Zero);
|
||||
_combat.LazyStack.Enqueue(b); Call(_combat,"OnDisable");
|
||||
Assert.That(_combat.LazyStack.Count,Is.Zero);
|
||||
Assert.That(_combat.Compilation.Active,Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HighLevelDnfAndZramKeepExistingPackageSemantics()
|
||||
{
|
||||
var dnf=new PackageInstance(Asset<PackageDefinition>("Assets/Data/Packages/Dnf.asset"),5);
|
||||
var zram=new PackageInstance(Asset<PackageDefinition>("Assets/Data/Packages/Zram.asset"),5);
|
||||
Configure(5,null,dnf,zram);
|
||||
Assert.That(_run.EffectiveMaxCycles(),Is.EqualTo(9));
|
||||
for(int i=1;i<=5;i++) _combat.Compilation.CompleteRound(i);
|
||||
for(int i=0;i<4;i++) Play(Card("lang_hs_map"));
|
||||
Assert.That(Player.FlatCardDamageBonus,Is.EqualTo(7));
|
||||
Assert.That(Player.FlatEffectBonus,Is.Zero,"DNF does not amplify non-damage effects");
|
||||
Drain();
|
||||
Assert.That(10000-Target.CurrentUptime,Is.EqualTo(95),"DNF is additive before stack/Compilation, not applied twice");
|
||||
}
|
||||
|
||||
[TestCase(0, 2)]
|
||||
[TestCase(5, 7)]
|
||||
public void DnfPreservesNativeTimingStacksOncePerRoundAndResetsAtWaveBoundary(int level, int amount)
|
||||
{
|
||||
// V3 starts at Compilation 1 (100% damage), isolating DNF timing from V1's 85% penalty.
|
||||
Configure(3, null, new PackageInstance(Asset<PackageDefinition>("Assets/Data/Packages/DNF.asset"), level));
|
||||
FillDrawPile();
|
||||
Play(Card("gentoo_make_j4"));
|
||||
Assert.That(10000 - Target.CurrentUptime, Is.EqualTo(8), "The first Native hit resolves before DNF's hook.");
|
||||
Assert.That(Player.FlatCardDamageBonus, Is.EqualTo(amount));
|
||||
Assert.That(Player.FlatEffectBonus, Is.Zero);
|
||||
Play(Card("gentoo_make_j4"));
|
||||
Assert.That(10000 - Target.CurrentUptime, Is.EqualTo(16 + amount));
|
||||
Assert.That(Player.FlatCardDamageBonus, Is.EqualTo(amount), "Only the first play adds a stack.");
|
||||
Finish((IEnumerator)Call(_combat, "AllocateTurnSequenced"));
|
||||
Play(Card("gentoo_make_j4"));
|
||||
Assert.That(Player.FlatCardDamageBonus, Is.EqualTo(amount * 2));
|
||||
Finish((IEnumerator)Call(_combat, "StartWaveSequenced", true));
|
||||
Assert.That(Player.FlatCardDamageBonus, Is.Zero, "DNF stacks last one wave, not the whole run.");
|
||||
}
|
||||
|
||||
[TestCase(0)]
|
||||
[TestCase(5)]
|
||||
public void DnfLeavesMintsExistingGeneralEffectBonusIntact(int level)
|
||||
{
|
||||
var mint = Asset<DistroDefinition>("Assets/Data/Distros/Mint.asset");
|
||||
Configure(2, mint, new PackageInstance(Asset<PackageDefinition>("Assets/Data/Packages/DNF.asset"), level));
|
||||
Play(Card("lang_hs_map"));
|
||||
Assert.That(Player.FlatEffectBonus, Is.EqualTo(2));
|
||||
Assert.That(Player.FlatCardDamageBonus, Is.EqualTo(2 + level));
|
||||
Finish((IEnumerator)Call(_combat, "StartWaveSequenced", true));
|
||||
Assert.That(Player.FlatEffectBonus, Is.EqualTo(2));
|
||||
Assert.That(Player.FlatCardDamageBonus, Is.Zero);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CSpillAndRustOverkillShieldAreNotScaledTwice()
|
||||
{
|
||||
_combat.Compilation.BeginWave(5); for(int i=1;i<=5;i++) _combat.Compilation.CompleteRound(i);
|
||||
var first=Target; first.State.CurrentUptime=5;
|
||||
var other=AddEnemy("memory_leak",10000);
|
||||
Set(_combat,"_enemyExitQueueDraining",true); // Stage exits, as WaveCompletionTests does.
|
||||
Effect(Card("gentoo_make_j4")); // 11*1.5 = 16; 11 excess halves to 5, without reapplying Compilation.
|
||||
Assert.That(other.CurrentUptime,Is.EqualTo(9995));
|
||||
((List<EnemyInstance>)_combat.Enemies).Remove(first);
|
||||
other.State.CurrentUptime=1;
|
||||
Effect(Card("lang_rs_fn_main")); // 6*1.5 =9; overkill Shield8, not round(8*1.3).
|
||||
Assert.That(Player.Shield,Is.EqualTo(8));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InvalidPlayDoesNotPayOrPushAndSourceSnapshotIsImmutable()
|
||||
{
|
||||
var card=Card("lang_hs_thunk"); _combat.HandController.Add(card);
|
||||
Player.Cycles=0;
|
||||
Assert.That(_combat.PlayCard(card),Is.False);
|
||||
Assert.That(_combat.LazyStack.Count,Is.Zero);
|
||||
Player.Cycles=2;
|
||||
Assert.That(_combat.PlayCard(card),Is.False,"Target required");
|
||||
Assert.That(Player.Cycles,Is.EqualTo(2));
|
||||
_combat.SelectEnemy(0); // Completes pending targeting and plays once.
|
||||
Assert.That(_combat.LazyStack.Count,Is.EqualTo(1));
|
||||
var captured=_combat.LazyStack.Entries[0].Targets[0];
|
||||
card.ClearTargetSnapshot();
|
||||
Assert.That(_combat.LazyStack.Entries[0].Targets[0],Is.SameAs(captured));
|
||||
Drain();
|
||||
Assert.That(10000-Target.CurrentUptime,Is.EqualTo(3));
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator CombatReadoutsAndSchedulerFitViewportMatrix()
|
||||
{
|
||||
Configure(5);
|
||||
for(int i=1;i<=5;i++) _combat.Compilation.CompleteRound(i);
|
||||
foreach(string id in new[]{"lang_hs_map","lang_hs_foldr","gentoo_ebuild","lang_hs_thunk"}) Play(Card(id));
|
||||
_combat.HandController.Add(Card("gentoo_make_j4"));
|
||||
var window=ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
var view=_owner.AddComponent<CombatSceneController>();
|
||||
try
|
||||
{
|
||||
window.Show(); var root=window.rootVisualElement;
|
||||
Set(view,"_root",root); Set(view,"_runManager",_run); Set(view,"_combatManager",_combat);
|
||||
Set(view,"_distroAccent",_gentoo.AccentColor);
|
||||
Call(view,"LoadStyles");
|
||||
typeof(CombatSceneController).Assembly.GetType("KernelPanic.UI.TerminalTheme").GetMethod("Attach").Invoke(null,new object[]{root});
|
||||
Call(view,"BuildLayout");
|
||||
foreach(var size in new[]{new Vector2(1920,1080),new Vector2(1366,768),new Vector2(1280,720),new Vector2(1024,768),new Vector2(390,844)})
|
||||
{
|
||||
root.style.width=size.x; root.style.height=size.y;
|
||||
Call(view,"RefreshPlayer"); Call(view,"RefreshTracks"); Call(view,"RefreshEnemies");
|
||||
Call(view,"RefreshHand"); Call(view,"RefreshTurnPanel");
|
||||
for(int frame=0;frame<5;frame++) yield return null;
|
||||
string text=string.Join(" ",root.Query<Label>().ToList().Select(l=>l.text));
|
||||
Assert.That(text,Does.Contain("Compilation"));
|
||||
Assert.That(text,Does.Contain("6/6"));
|
||||
Assert.That(text,Does.Contain("+50%"));
|
||||
var multipliers=root.Query<Label>(className:"execution-multiplier").ToList();
|
||||
CollectionAssert.AreEqual(new[]{"x2.5","x2.0","x1.5","x1.0"},multipliers.Select(l=>l.text));
|
||||
foreach(var label in multipliers)
|
||||
Assert.That(label.worldBound.xMax,Is.LessThanOrEqualTo(root.worldBound.xMax+1),size.ToString());
|
||||
var end=root.Query<Button>().ToList().Single(b=>b.text=="[E] end turn");
|
||||
Assert.That(end.worldBound.yMax,Is.LessThanOrEqualTo(root.worldBound.yMax+1),size.ToString());
|
||||
Assert.That(end.worldBound.xMax,Is.LessThanOrEqualTo(root.worldBound.xMax+1),size.ToString());
|
||||
}
|
||||
}
|
||||
finally { Call(view,"OnDisable"); UnityEngine.Object.DestroyImmediate(view); window.Close(); }
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LethalStackHitEndsCombatBeforeTheNextOperationButDisposesBoth()
|
||||
{
|
||||
_combat.Compilation.BeginWave(0);
|
||||
Target.State.CurrentUptime=1;
|
||||
var pending=Card("lang_hs_map"); var lethal=Card("lang_hs_thunk");
|
||||
Play(pending); Play(lethal);
|
||||
var completed=new List<CardInstance>();
|
||||
Action<CardResolvedEvent> start=e=>Set(_combat,"_enemyExitQueueDraining",true);
|
||||
Action<CardResolvedEvent> end=e=>
|
||||
{
|
||||
completed.Add(e.Card);
|
||||
foreach(var enemy in _combat.Enemies.ToArray())
|
||||
GameEvents.RaiseCombatantDeathVisualCompleted(new CombatantDeathVisualCompletedEvent(enemy.State));
|
||||
Set(_combat,"_enemyExitQueueDraining",false);
|
||||
Finish((IEnumerator)Call(_combat,"DrainEnemyExitQueue"));
|
||||
};
|
||||
GameEvents.CardResolving+=start; GameEvents.CardResolved+=end;
|
||||
try
|
||||
{
|
||||
Drain();
|
||||
CollectionAssert.AreEqual(new[]{lethal},completed);
|
||||
Assert.That(_combat.AwaitingWaveContinue,Is.True);
|
||||
Assert.That(_combat.LazyStack.Count,Is.Zero);
|
||||
Assert.That(_combat.DeckController.DiscardPile.Count(c=>c==pending),Is.EqualTo(1));
|
||||
Assert.That(_combat.DeckController.DiscardPile.Count(c=>c==lethal),Is.EqualTo(1));
|
||||
}
|
||||
finally { GameEvents.CardResolving-=start; GameEvents.CardResolved-=end; }
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DelayedCardCallbackReadsCompilationAndNewBootDropsSnapshots()
|
||||
{
|
||||
_combat.Compilation.BeginWave(1);
|
||||
for(int i=1;i<=4;i++) _combat.Compilation.CompleteRound(i);
|
||||
Call(_combat,"DealToAllEnemies",10,Language.Python,"delayed card");
|
||||
Assert.That(Target.CurrentUptime,Is.EqualTo(9987));
|
||||
var pending=Card("lang_hs_map"); Play(pending);
|
||||
Finish((IEnumerator)Call(_combat,"BootCombatSequenced"));
|
||||
Assert.That(_combat.Compilation.Level,Is.Zero);
|
||||
Assert.That(_combat.LazyStack.Count,Is.Zero);
|
||||
Assert.That(pending.TargetSnapshot,Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PublicBootCancelsStaleEvaluatorGuardsAndPendingEntries()
|
||||
{
|
||||
var pending=Card("lang_hs_map"); Play(pending);
|
||||
Set(_combat,"_interpretingTracks",true);
|
||||
Set(_combat,"_evaluatingLazyStack",true);
|
||||
_combat.StartCombat();
|
||||
Assert.That(_combat.CurrentPhase,Is.EqualTo(TurnPhase.Boot));
|
||||
Assert.That(_combat.LazyStack.Count,Is.Zero);
|
||||
Assert.That(pending.TargetSnapshot,Is.Empty);
|
||||
Assert.That(typeof(CombatManager).GetField("_interpretingTracks",Private).GetValue(_combat),Is.False);
|
||||
Assert.That(typeof(CombatManager).GetField("_evaluatingLazyStack",Private).GetValue(_combat),Is.False);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b821fa56a5034b9bbd3a000000000204
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,319 @@
|
||||
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.Meta;
|
||||
using KernelPanic.Run;
|
||||
using KernelPanic.UI;
|
||||
using NUnit.Framework;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
public class GentooPackageTests
|
||||
{
|
||||
const BindingFlags Private = BindingFlags.NonPublic | BindingFlags.Instance;
|
||||
GameObject owner;
|
||||
CombatManager combat;
|
||||
RunManager run;
|
||||
UnityEngine.Random.State random;
|
||||
bool motion;
|
||||
readonly List<UnityEngine.Object> temporary = new();
|
||||
static T Asset<T>(string path) where T : UnityEngine.Object => AssetDatabase.LoadAssetAtPath<T>(path);
|
||||
static PackageDatabase Database => Asset<PackageDatabase>("Assets/Data/Packages/PackageDatabase.asset");
|
||||
static PackageDefinition Package(string suffix) => Database.FindById("pkg_gentoo_" + suffix);
|
||||
static object Call(object target, string method, params object[] args) => target.GetType().GetMethod(method, Private).Invoke(target, args);
|
||||
static void Set(object target, string field, object value) => target.GetType().GetField(field, Private).SetValue(target, value);
|
||||
CombatantState Player => combat.PlayerState;
|
||||
|
||||
[SetUp]
|
||||
public void Setup()
|
||||
{
|
||||
random = UnityEngine.Random.state;
|
||||
motion = UIPreferences.ReducedMotion;
|
||||
UIPreferences.ReducedMotion = true;
|
||||
owner = new GameObject("Gentoo equipment integration");
|
||||
run = owner.AddComponent<RunManager>();
|
||||
combat = owner.AddComponent<CombatManager>();
|
||||
Call(combat, "OnDisable"); Call(combat, "Awake"); Call(combat, "OnEnable");
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void Cleanup()
|
||||
{
|
||||
Call(combat, "OnDisable");
|
||||
UnityEngine.Object.DestroyImmediate(owner);
|
||||
foreach (var item in temporary) UnityEngine.Object.DestroyImmediate(item);
|
||||
temporary.Clear();
|
||||
UnityEngine.Random.state = random;
|
||||
UIPreferences.ReducedMotion = motion;
|
||||
}
|
||||
|
||||
void Configure(string distro, int version, int level, params string[] packages)
|
||||
{
|
||||
var definition = Asset<DistroDefinition>($"Assets/Data/Distros/{distro}.asset");
|
||||
var config = new RunConfig(definition, Language.C, Language.Haskell, Array.Empty<CardDefinition>(),
|
||||
packages.Select(p => new PackageInstance(Package(p), level)).ToArray(), 17, version);
|
||||
run.StartRun(config);
|
||||
Set(combat, "_runConfig", config);
|
||||
Set(combat, "_runManager", run);
|
||||
BeginWave();
|
||||
}
|
||||
|
||||
static void Finish(IEnumerator routine)
|
||||
{
|
||||
int steps = 0;
|
||||
while (routine.MoveNext())
|
||||
{
|
||||
Assert.That(++steps, Is.LessThan(2000));
|
||||
if (routine.Current is IEnumerator child) Finish(child);
|
||||
}
|
||||
}
|
||||
|
||||
void BeginWave()
|
||||
{
|
||||
Finish((IEnumerator)Call(combat, "StartWaveSequenced", false));
|
||||
Set(combat, "currentPhase", TurnPhase.Execute);
|
||||
Player.ForceMaxRolls = true;
|
||||
}
|
||||
|
||||
void BeginRound()
|
||||
{
|
||||
Finish((IEnumerator)Call(combat, "AllocateTurnSequenced"));
|
||||
Set(combat, "currentPhase", TurnPhase.Execute);
|
||||
}
|
||||
|
||||
CardInstance Card(int cost = 2, ResolutionTrack track = ResolutionTrack.Native, string id = "equipment_test")
|
||||
{
|
||||
var definition = ScriptableObject.CreateInstance<CardDefinition>();
|
||||
temporary.Add(definition);
|
||||
Set(definition, "id", id); Set(definition, "cycleCost", cost);
|
||||
Set(definition, "resolutionTrack", track); Set(definition, "language", Language.C);
|
||||
var card = new CardInstance(definition);
|
||||
Assert.That(combat.HandController.Add(card), Is.True);
|
||||
return card;
|
||||
}
|
||||
|
||||
[TestCase("Gentoo", 1, 0)] [TestCase("Gentoo", 5, 5)]
|
||||
[TestCase("Ubuntu", 1, 0)] [TestCase("Ubuntu", 5, 5)]
|
||||
public void PortageStatsAndShieldAreAppliedOncePerWave(string distro, int version, int level)
|
||||
{
|
||||
Configure(distro, version, level, "portage");
|
||||
int bonus = 4 + 2 * level;
|
||||
Assert.That(Player.MaxUptime, Is.EqualTo(combat.RunConfig.Distro.BaseUptime + bonus));
|
||||
int shield = distro == "Gentoo" ? bonus : 0;
|
||||
Assert.That(Player.Shield, Is.EqualTo(shield));
|
||||
Call(combat, "ApplyPackageWaveStartEffects");
|
||||
Assert.That(Player.Shield, Is.EqualTo(shield));
|
||||
BeginRound(); BeginRound();
|
||||
Assert.That(Player.Shield, Is.EqualTo(shield));
|
||||
BeginWave();
|
||||
Assert.That(Player.Shield, Is.EqualTo(shield));
|
||||
}
|
||||
|
||||
[TestCase("Gentoo", 0)] [TestCase("Gentoo", 5)]
|
||||
[TestCase("Ubuntu", 0)] [TestCase("Ubuntu", 5)]
|
||||
public void CcacheDiscountAndShieldApplyOnlyToFirstAcceptedPlay(string distro, int level)
|
||||
{
|
||||
Configure(distro, 1, level, "ccache"); BeginRound();
|
||||
var first = Card();
|
||||
Assert.That(combat.GetEffectiveCardCost(first), Is.EqualTo(1));
|
||||
Player.Cycles = 0;
|
||||
Assert.That(combat.PlayCard(first), Is.False);
|
||||
Assert.That(Player.Shield, Is.Zero);
|
||||
Assert.That(combat.GetEffectiveCardCost(first), Is.EqualTo(1));
|
||||
Player.Cycles = 10;
|
||||
Assert.That(combat.PlayCard(first), Is.True);
|
||||
Assert.That(Player.Cycles, Is.EqualTo(9));
|
||||
Assert.That(Player.Shield, Is.EqualTo(level));
|
||||
var second = Card();
|
||||
Assert.That(combat.GetEffectiveCardCost(second), Is.EqualTo(2));
|
||||
Assert.That(combat.PlayCard(second), Is.True);
|
||||
Assert.That(Player.Shield, Is.EqualTo(level));
|
||||
Call(combat, "GarbageCollect"); BeginRound();
|
||||
Assert.That(Player.Cycles, Is.EqualTo(Player.MaxCycles + (distro == "Gentoo" ? 1 : 0)));
|
||||
Assert.That(combat.GetEffectiveCardCost(Card()), Is.EqualTo(1));
|
||||
}
|
||||
|
||||
[TestCase(ResolutionTrack.Native)] [TestCase(ResolutionTrack.InterpreterQueue)] [TestCase(ResolutionTrack.LazyStack)]
|
||||
public void CcacheMultiEffectAndDeferredCardsGrantShieldOnce(ResolutionTrack track)
|
||||
{
|
||||
Configure("Gentoo", 5, 5, "ccache"); BeginRound();
|
||||
// Draw and deferred Cycles: several effects must still award Shield only once.
|
||||
var card = Card(0, track, "shop_py_async_def");
|
||||
combat.SelectEnemy(0);
|
||||
Assert.That(combat.PlayCard(card), Is.True);
|
||||
Assert.That(Player.Shield, Is.EqualTo(5));
|
||||
if (track == ResolutionTrack.LazyStack) Finish((IEnumerator)Call(combat, "EvaluateLazyStackSequenced"));
|
||||
else if (track == ResolutionTrack.InterpreterQueue) Finish((IEnumerator)Call(combat, "InterpretQueueSequenced"));
|
||||
Assert.That(Player.Shield, Is.EqualTo(5));
|
||||
Assert.That(combat.GetEffectiveCardCost(Card()), Is.EqualTo(2), "A free first play consumes the discount");
|
||||
}
|
||||
|
||||
[TestCase("Gentoo", 1, 0)] [TestCase("Gentoo", 5, 5)]
|
||||
[TestCase("Ubuntu", 1, 0)] [TestCase("Ubuntu", 5, 5)]
|
||||
public void OpenRCUsesRoundBoundariesAndVersionCap(string distro, int version, int level)
|
||||
{
|
||||
Configure(distro, version, level, "openrc"); BeginRound();
|
||||
int initial = combat.Compilation.Level;
|
||||
Assert.That(Player.Shield, Is.Zero);
|
||||
BeginRound();
|
||||
Assert.That(Player.Shield, Is.EqualTo(2 + level));
|
||||
Assert.That(combat.Compilation.Level, Is.EqualTo(distro == "Gentoo" ? initial + 1 : 0));
|
||||
Call(combat, "ApplyPackageTurnStartEffects");
|
||||
Assert.That(Player.Shield, Is.EqualTo(2 + level));
|
||||
for (int i = 0; i < 10; i++) BeginRound();
|
||||
Assert.That(combat.Compilation.Level, Is.EqualTo(combat.Compilation.Maximum));
|
||||
BeginWave(); BeginRound();
|
||||
Assert.That(Player.Shield, Is.Zero);
|
||||
Assert.That(combat.Compilation.Level, Is.EqualTo(initial));
|
||||
}
|
||||
|
||||
[TestCase(1, 0)] [TestCase(1, 5)] [TestCase(5, 0)] [TestCase(5, 5)]
|
||||
public void AllThreeTrackActualAdvancementIncludingOpenRCAtCap(int version, int level)
|
||||
{
|
||||
Configure("Gentoo", version, level, "portage", "ccache", "openrc"); BeginRound();
|
||||
int expectedLevel = version == 5 ? 1 : 0;
|
||||
int cap = version == 5 ? 6 : 4;
|
||||
Assert.That(Player.Shield, Is.EqualTo(4 + 2 * level));
|
||||
bool previousAdvanced = false;
|
||||
for (int round = 1; round <= 8; round++)
|
||||
{
|
||||
if (round > 1)
|
||||
{
|
||||
BeginRound();
|
||||
Assert.That(Player.Cycles, Is.EqualTo(Player.MaxCycles + (previousAdvanced ? 1 : 0)));
|
||||
Assert.That(Player.Shield, Is.EqualTo(2 + level));
|
||||
}
|
||||
bool openRcAdvanced = round > 1 && expectedLevel < cap;
|
||||
if (openRcAdvanced) expectedLevel++;
|
||||
Assert.That(combat.Compilation.Level, Is.EqualTo(expectedLevel));
|
||||
Player.Cycles = 10;
|
||||
combat.HandController.Clear(); // Round allocation may redraw previous test cards.
|
||||
int before = Player.Shield;
|
||||
Assert.That(combat.PlayCard(Card()), Is.True);
|
||||
Assert.That(Player.Shield, Is.EqualTo(before + level));
|
||||
Assert.That(combat.PlayCard(Card()), Is.True);
|
||||
Assert.That(Player.Shield, Is.EqualTo(before + level));
|
||||
bool naturalAdvanced = expectedLevel < cap;
|
||||
Call(combat, "GarbageCollect");
|
||||
if (naturalAdvanced) expectedLevel++;
|
||||
Assert.That(combat.Compilation.Level, Is.EqualTo(expectedLevel));
|
||||
previousAdvanced = openRcAdvanced || naturalAdvanced;
|
||||
Player.Shield = 0;
|
||||
}
|
||||
BeginWave(); BeginRound();
|
||||
Assert.That(Player.Cycles, Is.EqualTo(Player.MaxCycles));
|
||||
Assert.That(Player.Shield, Is.EqualTo(4 + 2 * level));
|
||||
}
|
||||
|
||||
[TestCase(0)] [TestCase(1)] [TestCase(2)] [TestCase(3)] [TestCase(4)] [TestCase(5)]
|
||||
public void EveryLevelHasIndependentScalingAndAccurateCollectionText(int level)
|
||||
{
|
||||
var format = typeof(CollectionScreenController).GetMethod("FormatPackageEffect", BindingFlags.Static | BindingFlags.NonPublic);
|
||||
foreach (string distro in new[] { "gentoo", "ubuntu" })
|
||||
{
|
||||
string portage = (string)format.Invoke(null, new object[] { Package("portage"), level, distro });
|
||||
Assert.That(portage, Does.Contain($"+{4 + 2 * level} max Uptime"));
|
||||
Assert.That(portage.Contains("Shield"), Is.EqualTo(distro == "gentoo"));
|
||||
string ccache = (string)format.Invoke(null, new object[] { Package("ccache"), level, distro });
|
||||
Assert.That(ccache, Does.Contain("costs 1 less"));
|
||||
if (level > 0) Assert.That(ccache, Does.Contain($"+{level} Shield"));
|
||||
Assert.That(ccache.Contains("Compilation advanced"), Is.EqualTo(distro == "gentoo"));
|
||||
string openrc = (string)format.Invoke(null, new object[] { Package("openrc"), level, distro });
|
||||
Assert.That(openrc, Does.Contain($"+{2 + level} Shield"));
|
||||
Assert.That(openrc.Contains("+1 Compilation"), Is.EqualTo(distro == "gentoo"));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ExistingShieldPackageAndGentooPassiveDoNotDoubleScaleEquipment()
|
||||
{
|
||||
Configure("Gentoo", 5, 5, "portage", "ccache");
|
||||
var packages = combat.RunConfig.EquippedPackages.ToList();
|
||||
packages.Add(new PackageInstance(Database.FindById("pkg_fedora_selinux"), 0));
|
||||
var config = new RunConfig(combat.RunConfig.Distro, Language.C, Language.Haskell, Array.Empty<CardDefinition>(), packages, 17, 5);
|
||||
Set(combat, "_runConfig", config);
|
||||
BeginRound(); Player.Shield = 0;
|
||||
Assert.That(combat.PlayCard(Card(0)), Is.True);
|
||||
Assert.That(Player.Shield, Is.EqualTo(8), "5 equipment Shield + 3 SELinux, not Compilation-scaled card Shield");
|
||||
combat.GrantPlayerShield(1, "second grant");
|
||||
Assert.That(Player.Shield, Is.EqualTo(9));
|
||||
}
|
||||
|
||||
[TestCase(0)] [TestCase(5)]
|
||||
public void AllThreeOffDistroDoNotActivateCompilation(int level)
|
||||
{
|
||||
Configure("Ubuntu", 5, level, "portage", "ccache", "openrc"); BeginRound();
|
||||
Assert.That(Player.Shield, Is.Zero);
|
||||
Assert.That(Player.MaxUptime, Is.EqualTo(combat.RunConfig.Distro.BaseUptime + 4 + 2 * level));
|
||||
Assert.That(combat.PlayCard(Card(1)), Is.True);
|
||||
Assert.That(Player.Shield, Is.EqualTo(level));
|
||||
Call(combat, "GarbageCollect"); BeginRound();
|
||||
Assert.That(Player.Shield, Is.EqualTo(level + 2 + level));
|
||||
Assert.That(Player.Cycles, Is.EqualTo(Player.MaxCycles));
|
||||
Assert.That(combat.Compilation.Active, Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CcacheStacksWithFedoraDiscountWithoutChangingIt()
|
||||
{
|
||||
Configure("Fedora", 1, 5, "ccache"); BeginRound();
|
||||
foreach (var enemy in combat.Enemies) { enemy.State.MaxUptime = 1000; enemy.State.CurrentUptime = 1000; }
|
||||
var card = Card(2, ResolutionTrack.Native, "lang_c_printf");
|
||||
combat.SelectEnemy(0);
|
||||
int cycles = Player.Cycles;
|
||||
Assert.That(combat.GetEffectiveCardCost(card), Is.EqualTo(1));
|
||||
Assert.That(combat.PlayCard(card), Is.True);
|
||||
Assert.That(Player.Cycles, Is.EqualTo(cycles), "ccache and Fedora each reduce cost by 1");
|
||||
Assert.That(Player.Shield, Is.EqualTo(5));
|
||||
}
|
||||
|
||||
[TestCase("portage", 4, PackageSlot.Kernel)]
|
||||
[TestCase("ccache", 4, PackageSlot.Runtime)]
|
||||
[TestCase("openrc", 5, PackageSlot.Daemon)]
|
||||
public void RegisteredPoolsOwnershipUpgradesSaveLoadDuplicatesAndPurge(string suffix, int rarity, PackageSlot slot)
|
||||
{
|
||||
var package = Package(suffix);
|
||||
Assert.That(package, Is.Not.Null);
|
||||
Assert.That(package.Rarity, Is.EqualTo(rarity)); Assert.That(package.Slot, Is.EqualTo(slot));
|
||||
Assert.That(Enumerable.Range(0, Database.CountByRarity(rarity)).Select(i => Database.FindByRarity(rarity, i)), Does.Contain(package));
|
||||
Assert.That(Database.FindById("pkg_ccache").Rarity, Is.EqualTo(3));
|
||||
var owned = new PlayerCollection(); owned.AddPackage(package);
|
||||
var wallet = new SaveData { cacheBalance = 1000, bandwidthBalance = 1000 };
|
||||
var loadout = new PackageLoadout(owned, Database);
|
||||
Assert.That(loadout.TryEquip("gentoo", slot, package.Id, out _), Is.True);
|
||||
for (int i = 1; i <= 5; i++)
|
||||
{
|
||||
var result = PackageUpgrader.TryUpgrade(owned.GetOwnedPackage(package.Id), wallet);
|
||||
Assert.That(result.Success, Is.True); Assert.That(result.NewLevel, Is.EqualTo(i));
|
||||
}
|
||||
Assert.That(wallet.cacheBalance, Is.EqualTo(675)); Assert.That(wallet.bandwidthBalance, Is.EqualTo(350));
|
||||
Assert.That(PackageUpgrader.TryUpgrade(owned.GetOwnedPackage(package.Id), wallet).Success, Is.False);
|
||||
wallet.ownedPackages.Add(new OwnedPackageSaveEntry { id = package.Id, upgradeLevel = 5 });
|
||||
wallet.packageLoadouts.Add(new PackageLoadoutSaveEntry { distroId = "gentoo", slots = new List<PackageLoadoutSlotSaveEntry> { new() { slot = slot, packageId = package.Id } } });
|
||||
var restored = JsonUtility.FromJson<SaveData>(JsonUtility.ToJson(wallet)); restored.EnsureLists();
|
||||
var restoredCollection = new PlayerCollection();
|
||||
foreach (var entry in restored.ownedPackages) restoredCollection.AddPackageSilently(Database.FindById(entry.id), entry.upgradeLevel);
|
||||
var restoredLoadout = new PackageLoadout(restoredCollection, Database);
|
||||
restoredLoadout.Load("gentoo", restored.packageLoadouts[0].slots);
|
||||
Assert.That(restoredLoadout.GetEquippedPackageInstances("gentoo").Single().UpgradeLevel, Is.EqualTo(5));
|
||||
Assert.That(PackageScrapper.Scrap(restoredCollection, restoredLoadout, restored, package.Id).FailureReason, Is.EqualTo(PackageScrapFailureReason.Equipped));
|
||||
restoredLoadout.TryUnequip("gentoo", slot, out _);
|
||||
Assert.That(PackageScrapper.Scrap(restoredCollection, restoredLoadout, restored, package.Id).Success, Is.True);
|
||||
Assert.That(restored.cacheBalance, Is.EqualTo(1000 + PackageTuning.GetCacheForRarity(rarity)));
|
||||
Assert.That(restored.bandwidthBalance, Is.EqualTo(1000));
|
||||
// Exercise the production gacha duplicate path with a deterministic one-package pool.
|
||||
var pool = ScriptableObject.CreateInstance<PackageDatabase>(); temporary.Add(pool);
|
||||
Set(pool, "allPackages", new List<PackageDefinition> { package });
|
||||
object[] args = { pool, owned, wallet, rarity, false, 0 };
|
||||
typeof(GamblingSceneController).GetMethod("GrantRandomPackageByRarity", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, args);
|
||||
Assert.That(args[4], Is.EqualTo(true)); Assert.That(args[5], Is.EqualTo(PackageTuning.GetCacheForRarity(rarity)));
|
||||
var legacy = JsonUtility.FromJson<SaveData>("{\"ownedPackageIds\":[\"pkg_ccache\"]}"); legacy.EnsureLists();
|
||||
Assert.That(legacy.ownedPackages.Single().id, Is.EqualTo("pkg_ccache"));
|
||||
Assert.That(legacy.ownedPackages.Single().upgradeLevel, Is.Zero);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bb260000000000000000000000000004
|
||||
@@ -0,0 +1,166 @@
|
||||
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.Meta;
|
||||
using KernelPanic.Run;
|
||||
using KernelPanic.UI;
|
||||
using NUnit.Framework;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using UnityEngine.TestTools;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
public class GentooProgressionTests
|
||||
{
|
||||
static T Asset<T>(string path) where T:UnityEngine.Object => AssetDatabase.LoadAssetAtPath<T>(path);
|
||||
static DistroDefinition Gentoo => Asset<DistroDefinition>("Assets/Data/Distros/Gentoo.asset");
|
||||
static LanguageDeckDatabase Decks => Asset<LanguageDeckDatabase>("Assets/Data/Cards/Languages/LanguageDeckDatabase.asset");
|
||||
static CardDatabase Cards => Asset<CardDatabase>("Assets/Data/Cards/CardDatabase.asset");
|
||||
|
||||
[Test]
|
||||
public void OwningGentooUnlocksHaskellAndCNotAssembly()
|
||||
{
|
||||
var collection=new PlayerCollection();
|
||||
Assert.That(LanguageUnlock.IsUnlocked(Language.Haskell,collection),Is.False);
|
||||
collection.Add(Gentoo);
|
||||
Assert.That(LanguageUnlock.IsUnlocked(Language.Haskell,collection),Is.True);
|
||||
Assert.That(LanguageUnlock.IsUnlocked(Language.C,collection),Is.True);
|
||||
Assert.That(LanguageUnlock.IsUnlocked(Language.Assembly,collection),Is.False);
|
||||
Assert.That(Decks.FindByLanguage(Language.Haskell).Entries.Sum(e=>e.Count),Is.EqualTo(4));
|
||||
Assert.That(Decks.FindByLanguage(Language.Haskell).Entries.Sum(e=>e.Count*e.Card.CycleCost),Is.EqualTo(2));
|
||||
Assert.That(Decks.FindByLanguage(Language.Haskell).Entries.Single(e=>e.Card.Id=="lang_hs_map").Count,Is.EqualTo(2));
|
||||
}
|
||||
|
||||
[TestCase(0)] [TestCase(1)] [TestCase(2)] [TestCase(3)] [TestCase(4)]
|
||||
public void AnyFourExclusivesProduceTwelveCardDeck(int omitted)
|
||||
{
|
||||
var selected=Gentoo.ExclusiveCards.Where((_,i)=>i!=omitted).ToArray();
|
||||
var loadout=new CardLoadout(new[]{Gentoo});
|
||||
foreach(var card in selected) Assert.That(loadout.TryEquip("gentoo",card.Id,out _),Is.True);
|
||||
Assert.That(loadout.TryEquip("gentoo",Gentoo.ExclusiveCards[omitted].Id,out var reason),Is.False);
|
||||
Assert.That(reason,Is.EqualTo(CardLoadoutFailureReason.Full));
|
||||
RunContext.Set(Gentoo,selected,Language.Haskell,Language.C,5);
|
||||
Assert.That(RunContext.TryCreateRunConfig(Decks,out var config),Is.True);
|
||||
Assert.That(config.StartingDeck.Count,Is.EqualTo(12));
|
||||
Assert.That(config.StartingDeck.Count(c=>c.DistroExclusive),Is.EqualTo(4));
|
||||
Assert.That(config.StartingDeck.Count(c=>c.Id=="lang_hs_map"),Is.EqualTo(2));
|
||||
Assert.That(config.DistroVersion,Is.EqualTo(5));
|
||||
Assert.That(config.StartingDeck.All(c=>!c.IsRunOnly),Is.True);
|
||||
}
|
||||
|
||||
[TestCase(Language.Haskell,Language.Python)] [TestCase(Language.C,Language.Rust)]
|
||||
public void RecommendedLanguagesAreNotRequiredAndRepositoryUsesSelectedLanguages(Language primary,Language secondary)
|
||||
{
|
||||
RunContext.Set(Gentoo,Gentoo.ExclusiveCards.Take(4).ToArray(),primary,secondary,1);
|
||||
Assert.That(RunContext.TryCreateRunConfig(Decks,out var config),Is.True);
|
||||
Assert.That(config.StartingDeck.Count,Is.EqualTo(12));
|
||||
var owner=new GameObject("repository integration");
|
||||
try
|
||||
{
|
||||
var run=owner.AddComponent<RunManager>(); run.StartRun(config);
|
||||
var pool=(List<CardDefinition>)typeof(RunManager).GetMethod("BuildCardOfferPool",BindingFlags.NonPublic|BindingFlags.Instance).Invoke(run,new object[]{Cards,Decks});
|
||||
Assert.That(pool.Count(c=>c.Id.StartsWith("shop_hs_")),Is.EqualTo(primary==Language.Haskell?10:0));
|
||||
Assert.That(pool.All(c=>c.Language==primary||c.Language==secondary),Is.True);
|
||||
}
|
||||
finally { UnityEngine.Object.DestroyImmediate(owner); }
|
||||
}
|
||||
|
||||
sealed class GentooRandom : System.Random
|
||||
{
|
||||
public override double NextDouble()=>0; // Five-star + distro branch, without changing production probabilities.
|
||||
public override int Next(int maxValue)=>Math.Max(0,maxValue-1);
|
||||
}
|
||||
|
||||
static GachaService Service()
|
||||
{
|
||||
var service=new GachaService(new GentooRandom());
|
||||
foreach(var distro in Asset<DistroDatabase>("Assets/Data/Distros/DistroDatabase.asset").AllDistros)
|
||||
service.AddToBannerPool(distro);
|
||||
service.AddCurrency(GachaCurrencyType.StandardPull,100);
|
||||
return service;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void StandardPoolsRatesSelectorAndPaymentRemainCorrect()
|
||||
{
|
||||
var service=Service();
|
||||
CollectionAssert.AreEquivalent(new[]{"arch","gentoo"},service.GetStandardFiveStarCharacterChoices().Select(d=>d.Id));
|
||||
Assert.That(GachaService.GetFiveStarChance(0),Is.EqualTo(.008d));
|
||||
Assert.That(GachaService.GetFiveStarChance(65),Is.EqualTo(.078d).Within(.000001));
|
||||
Assert.That(GachaService.GetFiveStarChance(79),Is.EqualTo(1d));
|
||||
var pull=service.PerformStandardPull(10,null,PullPaymentSource.Commits);
|
||||
Assert.That(pull.Rewards.Count,Is.EqualTo(10));
|
||||
Assert.That(service.Commits,Is.EqualTo(90));
|
||||
Assert.That(pull.Rewards.All(r=>r.Distro==Gentoo&&r.StarRating==5),Is.True);
|
||||
Assert.That(GachaService.IsBeginnerInstallMediaDistro(Gentoo),Is.True);
|
||||
Assert.That(GachaService.IsBeginnerStarterDistro(Gentoo),Is.False);
|
||||
Assert.That(DistroRarity.Stars(Asset<DistroDefinition>("Assets/Data/Distros/Ubuntu.asset")),Is.EqualTo(4));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BeginnerGuaranteedFifthTenPullRemainsFiveStarDistribution()
|
||||
{
|
||||
var service=Service();
|
||||
GachaPullResult last=default;
|
||||
for(int i=0;i<5;i++) last=service.PerformBeginnerPull(10);
|
||||
Assert.That(last.Rewards[9].Distro,Is.SameAs(Gentoo));
|
||||
Assert.That(last.Rewards[9].StarRating,Is.EqualTo(5));
|
||||
Assert.That(last.Rewards[9].Guaranteed,Is.True);
|
||||
Assert.That(service.Commits,Is.EqualTo(60));
|
||||
Assert.That(service.IsBeginnerBannerAvailable,Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AcquisitionDuplicatesVersionsAndSaveCodecPreserveOwnership()
|
||||
{
|
||||
var save=SaveData.CreateDefault(); var collection=new PlayerCollection();
|
||||
var context=new PullResolutionContext(save,collection);
|
||||
var first=PullResolver.Resolve(new[]{Gentoo},context).Outcomes[0];
|
||||
Assert.That(first.Kind,Is.EqualTo(PullOutcomeKind.Granted));
|
||||
CollectionAssert.Contains(first.LanguagesNewlyUnlocked,Language.Haskell);
|
||||
var duplicate=PullResolver.Resolve(new[]{Gentoo},context).Outcomes[0];
|
||||
Assert.That(duplicate.MergesAwarded,Is.EqualTo(50));
|
||||
Assert.That(save.FindOwnedUnit("gentoo").version,Is.EqualTo(1));
|
||||
save.FindOwnedUnit("gentoo").merges=920;
|
||||
int[] costs={50,120,250,500}; string[] versions={"1.1","1.2","2.0","2.1"};
|
||||
for(int i=0;i<4;i++)
|
||||
{
|
||||
var upgrade=VersionUpgrader.TryUpgrade("gentoo",save,collection);
|
||||
Assert.That(upgrade.Success,Is.True);
|
||||
Assert.That(upgrade.Cost,Is.EqualTo(costs[i]));
|
||||
Assert.That(DistroVersionCatalog.GetReleaseLabel("gentoo",i+2),Is.EqualTo(versions[i]));
|
||||
}
|
||||
Assert.That(save.FindOwnedUnit("gentoo").merges,Is.Zero);
|
||||
Assert.That(VersionUpgrader.TryUpgrade("gentoo",save,collection).Success,Is.False);
|
||||
Assert.That(PullResolver.Resolve(new[]{Gentoo},context).Outcomes[0].MergesAwarded,Is.EqualTo(75));
|
||||
var loaded=JsonUtility.FromJson<SaveData>(JsonUtility.ToJson(save)); loaded.EnsureLists();
|
||||
Assert.That(loaded.FindOwnedUnit("gentoo").version,Is.EqualTo(5));
|
||||
Assert.That(loaded.FindOwnedUnit("gentoo").merges,Is.EqualTo(75));
|
||||
var legacy=JsonUtility.FromJson<SaveData>("{\"ownedUnitIds\":[\"arch\"],\"entropyBalance\":12}"); legacy.EnsureLists();
|
||||
Assert.That(legacy.FindOwnedUnit("arch"),Is.Not.Null);
|
||||
Assert.That(legacy.entropyBalance,Is.EqualTo(12));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CollectionAndGachaUseGentooIdentityAndDoNotGrantAgain()
|
||||
{
|
||||
var collection=new PlayerCollection(); collection.Add(Gentoo,5);
|
||||
var root=Asset<VisualTreeAsset>("Assets/UI/MainMenu.uxml").CloneTree();
|
||||
var screen=new CollectionScreenController();
|
||||
screen.Bind(root,null,Decks,Cards,collection);
|
||||
screen.ShowUnits(); screen.ShowUnitDetail(Gentoo,true);
|
||||
Assert.That(string.Join(" ",root.Query<Label>().ToList().Select(l=>l.text)),Does.Contain("Gentoo"));
|
||||
var reward=new CompletedGachaReward(1,5,"Gentoo",GachaRewardType.Distro,PullOutcomeKind.DupeOverflow,75,null,false,false,new GachaRewardDisplayData(Gentoo,null,5,0));
|
||||
var receipt=new VisualElement();
|
||||
using var view=new GachaRevealView(receipt,new CompletedGachaPull("standard","paid",new[]{reward}),()=>{});
|
||||
view.RevealAll();
|
||||
Assert.That(receipt.Q<Label>(className:"reveal-art").text,Is.EqualTo(Gentoo.AsciiArt.text));
|
||||
Assert.That(string.Join(" ",receipt.Query<Label>().ToList().Select(l=>l.text)),Does.Contain("75 Merges"));
|
||||
Assert.That(collection.GetVersion("gentoo"),Is.EqualTo(5));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b821fa56a5034b9bbd3a000000000205
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,122 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using NUnit.Framework;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
public class JunkEligibilityTests
|
||||
{
|
||||
private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
private readonly List<UnityEngine.Object> _temporary = new();
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
foreach (UnityEngine.Object item in _temporary)
|
||||
{
|
||||
UnityEngine.Object.DestroyImmediate(item);
|
||||
}
|
||||
_temporary.Clear();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UbuntuProTrialIsExplicitlyMarkedAsJunk()
|
||||
{
|
||||
CardDefinition definition = AssetDatabase.LoadAssetAtPath<CardDefinition>("Assets/Data/Cards/Ubuntu/UbuntuProTrial.asset");
|
||||
Assert.That(definition, Is.Not.Null);
|
||||
Assert.That(definition.IsJunk, Is.True);
|
||||
Assert.That(CardEligibility.IsJunkForAutoremove(new CardInstance(definition)), Is.True);
|
||||
}
|
||||
|
||||
[TestCase("junk_sorter", "Junk sorter", false)]
|
||||
[TestCase("nop", "NOP optimizer", false)]
|
||||
[TestCase("repair", "Fix broken dependencies", false)]
|
||||
[TestCase("helpful_token", "Helpful token", true)]
|
||||
public void NameAndTokenStatusAloneDoNotMakeCardsJunk(string id, string name, bool isToken)
|
||||
{
|
||||
CardInstance card = Card(id, name, isToken: isToken);
|
||||
Assert.That(CardEligibility.IsJunkForAutoremove(card), Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ExplicitJunkFlagWorksForNonTokenCardsAndSurvivesRename()
|
||||
{
|
||||
CardInstance card = Card("old_package", "Old package", isJunk: true);
|
||||
Assert.That(CardEligibility.IsJunkForAutoremove(card), Is.True);
|
||||
Set(card.Definition, "id", "renamed_package");
|
||||
Set(card.Definition, "displayName", "Renamed package");
|
||||
Assert.That(CardEligibility.IsJunkForAutoremove(card), Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CorruptedCardStopsBeingEligibleAfterRepair()
|
||||
{
|
||||
CardInstance card = Card("ordinary_card", "Ordinary card");
|
||||
card.CorruptForRounds(2, 1);
|
||||
Assert.That(CardEligibility.IsJunkForAutoremove(card), Is.True);
|
||||
card.RepairCorruption();
|
||||
Assert.That(CardEligibility.IsJunkForAutoremove(card), Is.False);
|
||||
Assert.That(CardEligibility.IsJunkForAutoremove(null), Is.False);
|
||||
}
|
||||
|
||||
[TestCase(false)]
|
||||
[TestCase(true)]
|
||||
public void PreviewAndExecutionUseTheSameJunkEligibility(bool isJunk)
|
||||
{
|
||||
var owner = new GameObject("Autoremove eligibility regression");
|
||||
_temporary.Add(owner);
|
||||
CombatManager combat = owner.AddComponent<CombatManager>();
|
||||
var hand = new HandController(5);
|
||||
var source = new CombatantState(100, 5, 3) { ForceMaxRolls = true };
|
||||
var target = new CombatantState(10000, 0, 0);
|
||||
Set(combat, "_handController", hand);
|
||||
Set(combat, "_playerState", source);
|
||||
CardInstance played = Card("fedora_dnf_autoremove", "dnf autoremove");
|
||||
CardInstance candidate = Card("junk_named_token", "Broken NOP token", isJunk, isToken: true);
|
||||
hand.Add(played);
|
||||
hand.Add(candidate);
|
||||
var context = new CombatContext(played, source, new[] { target }, combat, combat.DamagePipeline,
|
||||
new StatusEffectController(), combat.DeckController, hand, Array.Empty<EnemyInstance>());
|
||||
|
||||
Assert.That(combat.HasJunkForPreview(played), Is.EqualTo(isJunk));
|
||||
new DnfAutoremoveEffect(7, 1).Execute(context);
|
||||
|
||||
Assert.That(combat.DeckController.ExhaustPile.Contains(candidate), Is.EqualTo(isJunk));
|
||||
Assert.That(hand.Cards.Contains(candidate), Is.EqualTo(!isJunk));
|
||||
Assert.That(source.Cycles, Is.EqualTo(isJunk ? 4 : 3));
|
||||
Assert.That(target.CurrentUptime < 10000, Is.EqualTo(isJunk));
|
||||
Assert.That(combat.HasJunkForPreview(played), Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AutoremoveCannotExhaustItsOwnCard()
|
||||
{
|
||||
CardInstance played = Card("autoremove_override", "Autoremove override", isJunk: true);
|
||||
CardInstance other = Card("unused_package", "Unused package", isJunk: true);
|
||||
Assert.That(CardEligibility.FindAutoremoveTarget(new[] { played }, played), Is.Null);
|
||||
Assert.That(CardEligibility.FindAutoremoveTarget(new[] { played, other }, played), Is.SameAs(other));
|
||||
Assert.That(CardEligibility.FindAutoremoveTarget(null, played), Is.Null);
|
||||
}
|
||||
|
||||
private CardInstance Card(string id, string name, bool isJunk = false, bool isToken = false)
|
||||
{
|
||||
var definition = ScriptableObject.CreateInstance<CardDefinition>();
|
||||
_temporary.Add(definition);
|
||||
Set(definition, "id", id);
|
||||
Set(definition, "displayName", name);
|
||||
Set(definition, "language", Language.Rust);
|
||||
Set(definition, "isJunk", isJunk);
|
||||
Set(definition, "isToken", isToken);
|
||||
return new CardInstance(definition);
|
||||
}
|
||||
|
||||
private static void Set(object instance, string field, object value)
|
||||
{
|
||||
instance.GetType().GetField(field, Private).SetValue(instance, value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f681b3a459a44e3f93261e7150811ef2
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "KernelPanic.Ui.Tests",
|
||||
"references": [
|
||||
"KernelPanic.Runtime",
|
||||
"UnityEngine.TestRunner",
|
||||
"UnityEditor.TestRunner"
|
||||
],
|
||||
"includePlatforms": ["Editor"],
|
||||
"overrideReferences": true,
|
||||
"precompiledReferences": ["nunit.framework.dll"],
|
||||
"autoReferenced": false,
|
||||
"defineConstraints": ["UNITY_INCLUDE_TESTS"]
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b73ddac91da44a8fb6ba634517d01006
|
||||
@@ -0,0 +1,636 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Meta;
|
||||
using KernelPanic.Run;
|
||||
using KernelPanic.UI;
|
||||
using NUnit.Framework;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
using UnityEngine.TestTools;
|
||||
|
||||
public class MenuPersistenceTests
|
||||
{
|
||||
private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
private GameObject _owner;
|
||||
private MainMenuController _menu;
|
||||
private VisualElement _root;
|
||||
private VisualElement _shell;
|
||||
private string _directory;
|
||||
private SaveService _save;
|
||||
private TerminalFocusTestWindow _window;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_directory = Path.Combine(Path.GetTempPath(), "KernelPanic.MenuTests." + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(_directory);
|
||||
_save = new SaveService(Path.Combine(_directory, "save.json"));
|
||||
_owner = new GameObject("menu persistence regression");
|
||||
_owner.SetActive(false); // Build only the dependencies under test; do not touch a real player save.
|
||||
_menu = _owner.AddComponent<MainMenuController>();
|
||||
_root = new VisualElement();
|
||||
_shell = new VisualElement { name = "ShellRoot" };
|
||||
_root.Add(_shell);
|
||||
Set("_root", _root);
|
||||
Set("_shellRoot", _shell);
|
||||
Call("ComposeMetaServices");
|
||||
Set("_saveService", _save);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
if (_window != null) _window.Close();
|
||||
UnityEngine.Object.DestroyImmediate(_owner);
|
||||
if (Directory.Exists(_directory)) Directory.Delete(_directory, true);
|
||||
}
|
||||
|
||||
[TestCase("{ broken json")]
|
||||
[TestCase("{\"schemaVersion\":2147483647,\"payload\":\"future\"}")]
|
||||
public void UnreadableSaveBlocksProgressionAndCannotBeReplacedByStartupAutosave(string contents)
|
||||
{
|
||||
File.WriteAllText(_save.SavePath, contents);
|
||||
Call("LoadMetaState");
|
||||
Assert.That(_shell.enabledSelf, Is.False);
|
||||
Assert.That(_root.Q<Button>("RetrySaveButton").text, Is.EqualTo("retry loading"));
|
||||
Call("SaveCurrentState");
|
||||
Call("BootSelectedPackage");
|
||||
Call("StartGachaPullCutscene", "standard", 1, 0);
|
||||
Assert.That(File.ReadAllText(_save.SavePath), Is.EqualTo(contents));
|
||||
Assert.That(File.Exists(_save.BackupPath), Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LoadingAfterRecoverySuppressesPartialAutosavesAndRestoresTheMenu()
|
||||
{
|
||||
var data = SaveData.CreateDefault();
|
||||
data.entropyBalance = 321;
|
||||
data.starterChosen = true;
|
||||
data.ownedUnits.Add(new OwnedUnitSaveEntry { id = "gentoo", version = 3 });
|
||||
_save.Save(data);
|
||||
byte[] original = File.ReadAllBytes(_save.SavePath);
|
||||
File.WriteAllText(_save.SavePath, "{ truncated");
|
||||
Call("LoadMetaState");
|
||||
File.WriteAllBytes(_save.SavePath, original);
|
||||
Set("distroDatabase", AssetDatabase.LoadAssetAtPath<DistroDatabase>("Assets/Data/Distros/DistroDatabase.asset"));
|
||||
var collection = (PlayerCollection)Get("_playerCollection");
|
||||
var changed = (Action)Delegate.CreateDelegate(typeof(Action), _menu, typeof(MainMenuController).GetMethod("HandleMetaStateChanged", Private));
|
||||
collection.Changed += changed; // Retry occurs after the normal menu has subscribed.
|
||||
try { Call("LoadMetaState"); }
|
||||
finally { collection.Changed -= changed; }
|
||||
Assert.That(_shell.enabledSelf, Is.True);
|
||||
Assert.That(_root.Q("SaveRecoveryOverlay"), Is.Null);
|
||||
var restored = _save.Load();
|
||||
Assert.That(restored.entropyBalance, Is.EqualTo(321));
|
||||
Assert.That(restored.FindOwnedUnit("gentoo").version, Is.EqualTo(3));
|
||||
Assert.That(File.ReadAllBytes(_save.BackupPath), Is.EqualTo(original), "Only the complete hydrated snapshot is saved.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FailedWriteRetainsInMemoryProgressUntilSavingCanBeRetried()
|
||||
{
|
||||
_save.Save(SaveData.CreateDefault());
|
||||
Call("LoadMetaState");
|
||||
((EntropyWallet)Get("_wallet")).SetBalance(777);
|
||||
using (var locked = new FileStream(_save.SavePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
|
||||
{
|
||||
Call("SaveCurrentState");
|
||||
Assert.That(_shell.enabledSelf, Is.False);
|
||||
Assert.That(_root.Q<Button>("RetrySaveButton").text, Is.EqualTo("retry saving"));
|
||||
Assert.That(((SaveData)Get("_saveData")).entropyBalance, Is.EqualTo(777));
|
||||
}
|
||||
Call("SaveCurrentState");
|
||||
Assert.That(_shell.enabledSelf, Is.True);
|
||||
Assert.That(_root.Q("SaveRecoveryOverlay"), Is.Null);
|
||||
Assert.That(_save.Load().entropyBalance, Is.EqualTo(777));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SeedValidationGatesReadyLoadoutsAndAcceptsTheFullIntegerRange()
|
||||
{
|
||||
var languages = (List<Language>)Get("_selectedRunLanguages");
|
||||
languages.Add(Language.C);
|
||||
languages.Add(Language.Haskell);
|
||||
var cards = Enumerable.Range(0, CardLoadout.MaxEquippedCards).Select(index => index.ToString()).ToArray();
|
||||
foreach (string invalid in new[] { "abc", "2147483648", "-2147483649", "1.5" })
|
||||
{
|
||||
Set("_runSeedText", invalid);
|
||||
Assert.That(Call("CanBootRun", (object)cards), Is.False, invalid);
|
||||
}
|
||||
foreach (string valid in new[] { "", "0", "-2147483648", "2147483647" })
|
||||
{
|
||||
Set("_runSeedText", valid);
|
||||
Assert.That(Call("CanBootRun", (object)cards), Is.True, valid);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DistroDraftsSurviveSwitchesCardChangesMenuNavigationAndReload()
|
||||
{
|
||||
var database = ConfigureBuildMenu();
|
||||
// Distro selection scrolls its active row into view, which requires an attached panel.
|
||||
_window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
_window.Show();
|
||||
_window.rootVisualElement.Add(_root);
|
||||
var ubuntu = database.FindById("ubuntu");
|
||||
var gentoo = database.FindById("gentoo");
|
||||
var data = SaveData.CreateDefault();
|
||||
data.starterChosen = true;
|
||||
data.ownedUnits.Add(new OwnedUnitSaveEntry { id = ubuntu.Id, version = 1 });
|
||||
data.ownedUnits.Add(new OwnedUnitSaveEntry { id = gentoo.Id, version = 1 });
|
||||
_save.Save(data);
|
||||
Call("LoadMetaState");
|
||||
Call("RefreshRunSetup");
|
||||
foreach (var card in Equipable(ubuntu)) Call("ToggleCardInSelectedLoadout", ubuntu, card);
|
||||
Call("ToggleRunLanguage", Language.Python);
|
||||
Call("ToggleRunLanguage", Language.JavaScript);
|
||||
Call("SelectPackage", 1);
|
||||
foreach (var card in Equipable(gentoo)) Call("ToggleCardInSelectedLoadout", gentoo, card);
|
||||
Call("ToggleRunLanguage", Language.C);
|
||||
Call("ToggleRunLanguage", Language.Haskell);
|
||||
Call("SelectPackage", 0);
|
||||
Assert.That((List<Language>)Get("_selectedRunLanguages"), Is.EqualTo(new[] { Language.Python, Language.JavaScript }));
|
||||
Call("ToggleCardInSelectedLoadout", ubuntu, Equipable(ubuntu)[0]);
|
||||
Assert.That((List<Language>)Get("_selectedRunLanguages"), Has.Count.EqualTo(2), "Replacing a card must not clear languages.");
|
||||
Call("ShowMainMenu");
|
||||
Call("RefreshRunSetup");
|
||||
Assert.That(((CardLoadout)Get("_cardLoadout")).GetEquippedCardIds(ubuntu.Id), Has.Count.EqualTo(3));
|
||||
Assert.That((List<Language>)Get("_selectedRunLanguages"), Has.Count.EqualTo(2));
|
||||
|
||||
Call("ComposeMetaServices");
|
||||
Set("_saveService", _save);
|
||||
Call("LoadMetaState");
|
||||
Assert.That((List<Language>)Get("_selectedRunLanguages"), Is.EqualTo(new[] { Language.Python, Language.JavaScript }));
|
||||
Assert.That(((CardLoadout)Get("_cardLoadout")).GetEquippedCardIds(ubuntu.Id), Has.Count.EqualTo(3));
|
||||
Call("SelectPackage", 1);
|
||||
Assert.That((List<Language>)Get("_selectedRunLanguages"), Is.EqualTo(new[] { Language.C, Language.Haskell }));
|
||||
Assert.That(((CardLoadout)Get("_cardLoadout")).GetEquippedCardIds(gentoo.Id), Has.Count.EqualTo(4));
|
||||
Assert.That(_save.Load().lastSetupDistroId, Is.EqualTo("gentoo"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LegacyLastCardsBecomeADraftWithoutInventingLanguagesOrASeed()
|
||||
{
|
||||
var ubuntu = ConfigureBuildMenu().FindById("ubuntu");
|
||||
var data = SaveData.CreateDefault();
|
||||
data.ownedUnits.Add(new OwnedUnitSaveEntry { id = ubuntu.Id, version = 1 });
|
||||
data.lastRunLoadout.distroId = ubuntu.Id;
|
||||
data.lastRunLoadout.cardIds.AddRange(Equipable(ubuntu).Select(card => card.Id));
|
||||
_save.Save(data);
|
||||
Call("LoadMetaState");
|
||||
Assert.That(((CardLoadout)Get("_cardLoadout")).GetEquippedCardIds(ubuntu.Id), Has.Count.EqualTo(4));
|
||||
Assert.That((List<Language>)Get("_selectedRunLanguages"), Is.Empty);
|
||||
Assert.That(_save.Load().lastRunLoadout.hasRunSeed, Is.False);
|
||||
Assert.That(_root.Q<Button>("RetrySameSeedButton").enabledSelf, Is.False);
|
||||
Assert.That(_root.Q<Button>("RetryNewSeedButton").enabledSelf, Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LoadingDraftsDiscardsInvalidCardsLockedLanguagesAndUnknownDistros()
|
||||
{
|
||||
var ubuntu = ConfigureBuildMenu().FindById("ubuntu");
|
||||
var data = SaveData.CreateDefault();
|
||||
data.ownedUnits.Add(new OwnedUnitSaveEntry { id = ubuntu.Id, version = 1 });
|
||||
data.runBuildDrafts.Add(new RunBuildDraftSaveEntry
|
||||
{
|
||||
distroId = ubuntu.Id,
|
||||
cardIds = new List<string> { Equipable(ubuntu)[0].Id, "missing", Equipable(ubuntu)[0].Id },
|
||||
languages = new List<Language> { (Language)999, Language.C, Language.Python, Language.Python, Language.JavaScript }
|
||||
});
|
||||
data.runBuildDrafts.Add(new RunBuildDraftSaveEntry { distroId = "not-owned" });
|
||||
_save.Save(data);
|
||||
Call("LoadMetaState");
|
||||
var saved = _save.Load();
|
||||
Assert.That(saved.runBuildDrafts, Has.Count.EqualTo(1));
|
||||
Assert.That(saved.runBuildDrafts[0].cardIds, Is.EqualTo(new[] { Equipable(ubuntu)[0].Id }));
|
||||
Assert.That(saved.runBuildDrafts[0].languages, Is.EqualTo(new[] { Language.Python, Language.JavaScript }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LastRunSnapshotRetainsItsVersionPackageLevelsAndSeedAfterUpgrades()
|
||||
{
|
||||
var ubuntu = ConfigureBuildMenu().FindById("ubuntu");
|
||||
var data = SaveData.CreateDefault();
|
||||
data.ownedUnits.Add(new OwnedUnitSaveEntry { id = ubuntu.Id, version = 2 });
|
||||
data.ownedPackages.Add(new OwnedPackageSaveEntry { id = "pkg_fedora_dnf", upgradeLevel = 1 });
|
||||
data.packageLoadouts.Add(new PackageLoadoutSaveEntry
|
||||
{
|
||||
distroId = ubuntu.Id,
|
||||
slots = new List<PackageLoadoutSlotSaveEntry> { new() { slot = PackageSlot.Runtime, packageId = "pkg_fedora_dnf" } }
|
||||
});
|
||||
_save.Save(data);
|
||||
Call("LoadMetaState");
|
||||
var languages = (List<Language>)Get("_selectedRunLanguages");
|
||||
languages.Add(Language.Python);
|
||||
languages.Add(Language.JavaScript);
|
||||
var inMemory = (SaveData)Get("_saveData");
|
||||
inMemory.lastRunLoadout.runSeed = -12345;
|
||||
inMemory.lastRunLoadout.hasRunSeed = true;
|
||||
Call("SaveLastRunLoadout", ubuntu, Equipable(ubuntu).Select(card => card.Id).ToArray());
|
||||
var collection = (PlayerCollection)Get("_playerCollection");
|
||||
collection.SetVersionSilently(ubuntu.Id, 5);
|
||||
collection.GetOwnedPackage("pkg_fedora_dnf").SetUpgradeLevel(5);
|
||||
Call("SaveCurrentState");
|
||||
var saved = _save.Load();
|
||||
Assert.That(saved.lastRunLoadout.distroVersion, Is.EqualTo(2));
|
||||
Assert.That(saved.lastRunLoadout.packages[0].upgradeLevel, Is.EqualTo(1));
|
||||
Assert.That(saved.lastRunLoadout.runSeed, Is.EqualTo(-12345));
|
||||
object[] resolved = { null, null, null, null };
|
||||
Assert.That(Call("TryResolveLastRunBuild", resolved), Is.True);
|
||||
Assert.That(((List<PackageInstance>)resolved[2])[0].UpgradeLevel, Is.EqualTo(1));
|
||||
Assert.That((List<CardDefinition>)resolved[1], Has.Count.EqualTo(4));
|
||||
Call("RefreshRunActions");
|
||||
Assert.That(_root.Q<Button>("RetrySameSeedButton").enabledSelf, Is.True);
|
||||
Assert.That(_root.Q<Button>("RetryNewSeedButton").enabledSelf, Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RetryDoesNotSilentlyDropAnUnavailablePackage()
|
||||
{
|
||||
var ubuntu = ConfigureBuildMenu().FindById("ubuntu");
|
||||
var data = SaveData.CreateDefault();
|
||||
data.ownedUnits.Add(new OwnedUnitSaveEntry { id = ubuntu.Id, version = 1 });
|
||||
data.lastRunLoadout.distroId = ubuntu.Id;
|
||||
data.lastRunLoadout.cardIds.AddRange(Equipable(ubuntu).Select(card => card.Id));
|
||||
data.lastRunLoadout.languages.AddRange(new[] { Language.Python, Language.JavaScript });
|
||||
data.lastRunLoadout.packages.Add(new RunBuildPackageSaveEntry { packageId = "pkg_fedora_dnf", slot = PackageSlot.Runtime });
|
||||
data.lastRunLoadout.hasRunSeed = true;
|
||||
_save.Save(data);
|
||||
Call("LoadMetaState");
|
||||
object[] resolved = { null, null, null, null };
|
||||
Assert.That(Call("TryResolveLastRunBuild", resolved), Is.False);
|
||||
Assert.That(_root.Q<Button>("RetrySameSeedButton").enabledSelf, Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InvalidCheckpointShowsRecoveryWithoutChangingTheSaveOrStartingALaunch()
|
||||
{
|
||||
ConfigureBuildMenu();
|
||||
var data = SaveData.CreateDefault();
|
||||
data.activeRun = new RunCheckpoint { version = 999 };
|
||||
_save.Save(data);
|
||||
Call("LoadMetaState");
|
||||
byte[] original = File.ReadAllBytes(_save.SavePath);
|
||||
Assert.DoesNotThrow(() => Call("ResumeSavedRun"));
|
||||
Assert.That(_root.Q("CheckpointRecoveryDialog"), Is.Not.Null);
|
||||
Assert.That((bool)Get("_runLaunchPending"), Is.False);
|
||||
Assert.That(File.ReadAllBytes(_save.SavePath), Is.EqualTo(original));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RunArchiveOwnsAllThreePastRunActionsWhileResumeStaysOnHome()
|
||||
{
|
||||
var ubuntu = ConfigureBuildMenu().FindById("ubuntu");
|
||||
var data = SaveData.CreateDefault();
|
||||
data.starterChosen = true;
|
||||
data.ownedUnits.Add(new OwnedUnitSaveEntry { id = ubuntu.Id, version = 1 });
|
||||
data.lastRunLoadout.distroId = ubuntu.Id;
|
||||
data.lastRunLoadout.cardIds.AddRange(Equipable(ubuntu).Select(card => card.Id));
|
||||
data.lastRunLoadout.languages.AddRange(new[] { Language.Python, Language.JavaScript });
|
||||
data.lastRunLoadout.hasRunSeed = true;
|
||||
data.activeRun = new RunCheckpoint { wave = 3 };
|
||||
_save.Save(data);
|
||||
Call("LoadMetaState");
|
||||
Call("RefreshRunActions"); // Repeated refreshes must not duplicate relocated controls.
|
||||
Call("RefreshRunActions");
|
||||
|
||||
var home = _root.Q("MainMenuPanel");
|
||||
var archive = _root.Q("RunArchiveActions");
|
||||
foreach (string id in new[] { "RetrySameSeedButton", "RetryNewSeedButton", "RecentRunsButton" })
|
||||
{
|
||||
Assert.That(home.Q<Button>(id), Is.Null, id);
|
||||
Assert.That(archive.Q<Button>(id), Is.Not.Null, id);
|
||||
Assert.That(archive.Q<Button>(id).enabledSelf, Is.True, id);
|
||||
Assert.That(_root.Query<Button>(id).ToList(), Has.Count.EqualTo(1), id);
|
||||
}
|
||||
Assert.That(home.Q<Button>("ResumeSavedRunButton"), Is.Not.Null);
|
||||
Assert.That(archive.Q<Button>("ResumeSavedRunButton"), Is.Null);
|
||||
Assert.That(_root.Query<Button>("ResumeSavedRunButton").ToList(), Has.Count.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EmptyRunArchiveKeepsHistoryAvailableAndDisablesBothRetries()
|
||||
{
|
||||
ConfigureBuildMenu();
|
||||
Set("_saveData", SaveData.CreateDefault());
|
||||
Call("RefreshRunActions");
|
||||
var archive = _root.Q("RunArchiveActions");
|
||||
Assert.That(archive.Q<Button>("RetrySameSeedButton"), Is.Not.Null);
|
||||
Assert.That(archive.Q<Button>("RetryNewSeedButton"), Is.Not.Null);
|
||||
Assert.That(archive.Q<Button>("RetrySameSeedButton").enabledSelf, Is.False);
|
||||
Assert.That(archive.Q<Button>("RetryNewSeedButton").enabledSelf, Is.False);
|
||||
Assert.That(archive.Q<Button>("RecentRunsButton").enabledSelf, Is.True);
|
||||
Assert.That(archive.Q<Label>("LastRunBuildSummary").text, Does.Contain("No previous build saved"));
|
||||
Assert.That(_root.Q("MainMenuPanel").Q<Button>("RecentRunsButton"), Is.Null);
|
||||
Assert.That(_root.Q<Button>("ResumeSavedRunButton"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RunArchiveOpensItsOwnScreenAndEscapeReturnsToTheCommandMenu()
|
||||
{
|
||||
ConfigureArchiveNavigation();
|
||||
Call("ShowRunArchive");
|
||||
Assert.That(Get("_activeScreen").ToString(), Is.EqualTo("RunArchive"));
|
||||
Assert.That(_root.Q("RunArchivePanel").ClassListContains("hidden"), Is.False);
|
||||
Assert.That(_root.Q("MainMenuPanel").ClassListContains("hidden"), Is.True);
|
||||
Assert.That(_root.Q<TextField>("CommandInput").enabledSelf, Is.False);
|
||||
Assert.That(_root.Q("RunArchivePanel").Q<Button>(className: "screen-back"), Is.Not.Null);
|
||||
|
||||
SendMenuKey(KeyCode.Escape);
|
||||
Assert.That(Get("_activeScreen").ToString(), Is.EqualTo("Main"));
|
||||
Assert.That(_root.Q("RunArchivePanel").ClassListContains("hidden"), Is.True);
|
||||
Assert.That(_root.Q("MainMenuPanel").ClassListContains("hidden"), Is.False);
|
||||
Assert.That(_root.Q<TextField>("CommandInput").enabledSelf, Is.True);
|
||||
}
|
||||
|
||||
[TestCase(KeyCode.UpArrow)]
|
||||
[TestCase(KeyCode.DownArrow)]
|
||||
[TestCase(KeyCode.Alpha1)]
|
||||
[TestCase(KeyCode.Alpha5)]
|
||||
[TestCase(KeyCode.Alpha6)]
|
||||
[TestCase(KeyCode.Return)]
|
||||
[TestCase(KeyCode.Space)]
|
||||
[TestCase(KeyCode.F2)]
|
||||
[TestCase(KeyCode.Slash)]
|
||||
[TestCase(KeyCode.Tab)]
|
||||
public void RunArchiveDoesNotRouteNativeKeysToHomeCommands(KeyCode key)
|
||||
{
|
||||
ConfigureArchiveNavigation();
|
||||
Set("_selectedCommandIndex", 4);
|
||||
Call("ShowRunArchive");
|
||||
using var evt = KeyDownEvent.GetPooled('\0', key, EventModifiers.None);
|
||||
evt.target = _root.Q("RunArchiveActions");
|
||||
Assert.DoesNotThrow(() => Call("HandleKeyDown", evt));
|
||||
Assert.That(Get("_activeScreen").ToString(), Is.EqualTo("RunArchive"));
|
||||
Assert.That((int)Get("_selectedCommandIndex"), Is.EqualTo(4));
|
||||
Assert.That(evt.isPropagationStopped, Is.False, "Archive controls retain native keyboard handling.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ClosingRecentRunHistoryReturnsToTheArchiveInsteadOfHome()
|
||||
{
|
||||
ConfigureArchiveNavigation();
|
||||
Call("ShowRunArchive");
|
||||
Call("OpenRunHistory");
|
||||
Assert.That(Get("_runHistoryOverlay"), Is.Not.Null);
|
||||
SendMenuKey(KeyCode.Escape);
|
||||
Assert.That(Get("_runHistoryOverlay"), Is.Null);
|
||||
Assert.That(Get("_activeScreen").ToString(), Is.EqualTo("RunArchive"));
|
||||
Assert.That(_root.Q("RunArchivePanel").ClassListContains("hidden"), Is.False);
|
||||
Assert.That(_root.Q("MainMenuPanel").ClassListContains("hidden"), Is.True);
|
||||
}
|
||||
|
||||
private void ConfigureArchiveNavigation()
|
||||
{
|
||||
ConfigureBuildMenu();
|
||||
Set("_saveData", SaveData.CreateDefault());
|
||||
var intro = _root.Q("BootIntroPanel");
|
||||
intro.AddToClassList("hidden");
|
||||
Set("_bootIntroPanel", intro);
|
||||
Call("BindCommandEntries");
|
||||
Call("BindScreenFrames");
|
||||
var commandLine = typeof(MainMenuController).Assembly.GetType("KernelPanic.UI.TerminalCommandLine");
|
||||
Set("_commandLine", Activator.CreateInstance(commandLine, _root, (Action<int>)(_ => { }), (Func<bool>)(() => true)));
|
||||
}
|
||||
|
||||
private void SendMenuKey(KeyCode key)
|
||||
{
|
||||
using var evt = KeyDownEvent.GetPooled('\0', key, EventModifiers.None);
|
||||
evt.target = _root;
|
||||
Call("HandleKeyDown", evt);
|
||||
}
|
||||
|
||||
private DistroDatabase ConfigureBuildMenu()
|
||||
{
|
||||
var tree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/MainMenu.uxml");
|
||||
_root = tree.CloneTree();
|
||||
_shell = _root.Q("ShellRoot");
|
||||
Set("_root", _root);
|
||||
Set("_shellRoot", _shell);
|
||||
foreach (string name in new[] { "MainMenuPanel", "CollectionPanel", "RunSetupPanel", "GachaPanel", "SettingsPanel", "RunArchivePanel", "EventBanner", "MotdBlock", "RunSetupDetail" })
|
||||
Set("_" + char.ToLowerInvariant(name[0]) + name.Substring(1), _root.Q(name));
|
||||
Set("_runSetupList", _root.Q<ScrollView>("RunSetupList"));
|
||||
var database = AssetDatabase.LoadAssetAtPath<DistroDatabase>("Assets/Data/Distros/DistroDatabase.asset");
|
||||
Set("distroDatabase", database);
|
||||
Set("packageDatabase", AssetDatabase.LoadAssetAtPath<PackageDatabase>("Assets/Data/Packages/PackageDatabase.asset"));
|
||||
Call("ComposeMetaServices");
|
||||
Set("_saveService", _save);
|
||||
return database;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DailyQuestClaimCommitsBothCurrenciesAndRetryCannotPayTwice()
|
||||
{
|
||||
var data = SaveData.CreateDefault();
|
||||
data.dailyQuests.refreshAtUtcTicks = DateTime.UtcNow.AddDays(1).Ticks;
|
||||
DailyQuests.Record(data.dailyQuests, DailyQuestKind.Waves, 3, DateTime.UtcNow);
|
||||
_save.Save(data);
|
||||
Call("LoadMetaState");
|
||||
long period = ((SaveData)Get("_saveData")).dailyQuests.refreshAtUtcTicks;
|
||||
var overlay = DailyQuestView.BuildOverlay(((SaveData)Get("_saveData")).dailyQuests, DateTime.UtcNow,
|
||||
(kind, deadline) => Call("ClaimDailyQuest", kind, deadline), () => { });
|
||||
_root.Add(overlay);
|
||||
Set("_dailyQuestOverlay", overlay);
|
||||
using (var locked = new FileStream(_save.SavePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
|
||||
{
|
||||
Call("ClaimDailyQuest", DailyQuestKind.Waves, period);
|
||||
Assert.That(_shell.enabledSelf, Is.False);
|
||||
Assert.That(overlay.Q("DailyQuestFeedback").style.display.value, Is.EqualTo(DisplayStyle.None),
|
||||
"A failed save must not announce a successful deposit.");
|
||||
Call("ClaimDailyQuest", DailyQuestKind.Waves, period);
|
||||
}
|
||||
Assert.That(_save.Load().entropyBalance, Is.Zero, "A failed write cannot partially commit currency.");
|
||||
Call("SaveCurrentState");
|
||||
Call("ClaimDailyQuest", DailyQuestKind.Waves, period);
|
||||
var saved = _save.Load();
|
||||
Assert.That(saved.entropyBalance, Is.EqualTo(DailyQuests.Reward(DailyQuestKind.Waves).Entropy));
|
||||
Assert.That(saved.bandwidthBalance, Is.EqualTo(DailyQuests.Reward(DailyQuestKind.Waves).Bandwidth));
|
||||
Assert.That(DailyQuests.Claimed(saved.dailyQuests, DailyQuestKind.Waves), Is.True);
|
||||
Assert.That(((EntropyWallet)Get("_wallet")).Balance, Is.EqualTo(saved.entropyBalance));
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator DailyQuestWidgetSupportsMouseKeyboardAliasClaimsAndLiveReset()
|
||||
{
|
||||
_root.focusable = true;
|
||||
_window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
_window.position = new Rect(20, 20, 640, 720);
|
||||
_window.Show();
|
||||
_window.rootVisualElement.Add(_root);
|
||||
_root.style.width = 640;
|
||||
_root.style.height = 720;
|
||||
_root.styleSheets.Add(AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/UI/MainMenu.uss"));
|
||||
typeof(MainMenuController).Assembly.GetType("KernelPanic.UI.TerminalTheme")
|
||||
.GetMethod("Attach").Invoke(null, new object[] { _root });
|
||||
_shell.Add(new VisualElement { name = "DailyQuestsHost" });
|
||||
var input = new TextField { name = "CommandInput" };
|
||||
_shell.Add(input);
|
||||
_shell.Add(new Label { name = "CommandOutput" });
|
||||
var commandType = typeof(MainMenuController).Assembly.GetType("KernelPanic.UI.TerminalCommandLine");
|
||||
var line = Activator.CreateInstance(commandType, _root, (Action<int>)(index => Call("ActivateCommand", index)),
|
||||
(Func<bool>)(() => Get("_dailyQuestOverlay") == null));
|
||||
Set("_commandLine", line);
|
||||
var data = SaveData.CreateDefault();
|
||||
data.dailyQuests.refreshAtUtcTicks = DateTime.UtcNow.AddHours(12).Ticks;
|
||||
DailyQuests.Record(data.dailyQuests, DailyQuestKind.Waves, 3, DateTime.UtcNow);
|
||||
DailyQuests.Record(data.dailyQuests, DailyQuestKind.Damage, 200, DateTime.UtcNow);
|
||||
_save.Save(data);
|
||||
Call("LoadMetaState");
|
||||
for (int frame = 0; frame < 4; frame++) yield return null;
|
||||
var widget = _root.Q<Button>("DailyQuestWidget");
|
||||
Assert.That(_root.Q<Label>("DailyQuestCompleted").text, Is.EqualTo("2/3 completed"));
|
||||
Assert.That(_root.Q<Label>("DailyQuestRewardReady").text, Is.EqualTo("2 rewards ready"));
|
||||
Assert.That(_root.Q<Label>("DailyQuestInspect").text, Is.EqualTo("> claim available rewards"));
|
||||
var position = widget.worldBound.center;
|
||||
using (var down = PointerDownEvent.GetPooled(new Event { type = EventType.MouseDown, button = 0, mousePosition = position }))
|
||||
{ down.target = widget; widget.SendEvent(down); }
|
||||
using (var up = PointerUpEvent.GetPooled(new Event { type = EventType.MouseUp, button = 0, mousePosition = position }))
|
||||
{ up.target = widget; widget.SendEvent(up); }
|
||||
Assert.That(_root.Q("DailyQuestOverlay"), Is.Not.Null, "Mouse opens details.");
|
||||
Assert.That(_shell.enabledSelf, Is.False, "The menu cannot receive input behind the modal.");
|
||||
for (int frame = 0; frame < 3; frame++) yield return null;
|
||||
var claim = _root.Q<Button>("ClaimDailyQuestWaves");
|
||||
Assert.That(claim.text, Is.EqualTo("> CLAIM REWARD"));
|
||||
Assert.That(_root.Q<Button>("ClaimDailyQuestCards").text, Is.EqualTo("[ in progress ]"));
|
||||
Assert.That(_root.Q<Button>("ClaimDailyQuestCards").enabledSelf, Is.False);
|
||||
Assert.That(_root.Q<Label>("DailyQuestDetailSummary").text, Is.EqualTo("3 tasks / 2 completed"));
|
||||
Assert.That(_root.Q("DailyQuestFeedback").style.display.value, Is.EqualTo(DisplayStyle.None));
|
||||
claim.Focus();
|
||||
using (var tab = NavigationMoveEvent.GetPooled(NavigationMoveEvent.Direction.Next))
|
||||
{ tab.target = claim; claim.SendEvent(tab); }
|
||||
Assert.That(_root.focusController.focusedElement, Is.SameAs(_root.Q<Button>("ClaimDailyQuestDamage")));
|
||||
using (var tab = NavigationMoveEvent.GetPooled(NavigationMoveEvent.Direction.Previous))
|
||||
{ tab.target = _root.Q<Button>("ClaimDailyQuestDamage"); _root.Q<Button>("ClaimDailyQuestDamage").SendEvent(tab); }
|
||||
Assert.That(_root.focusController.focusedElement, Is.SameAs(claim));
|
||||
using (var submit = NavigationSubmitEvent.GetPooled())
|
||||
{ submit.target = claim; claim.SendEvent(submit); }
|
||||
Assert.That(_save.Load().bandwidthBalance, Is.EqualTo(DailyQuests.Reward(DailyQuestKind.Waves).Bandwidth));
|
||||
Assert.That(_save.Load().entropyBalance, Is.EqualTo(DailyQuests.Reward(DailyQuestKind.Waves).Entropy));
|
||||
Assert.That(_root.Q<Button>("ClaimDailyQuestWaves").enabledSelf, Is.False);
|
||||
Assert.That(_root.Q<Button>("ClaimDailyQuestWaves").text, Is.EqualTo("[ CLAIMED ]"));
|
||||
Assert.That(_root.Q<Label>("DailyQuestRewardReady").text, Is.EqualTo("1 reward ready"), "Another reward is still ready.");
|
||||
Assert.That(_root.Q<Label>("DailyQuestClaimed").text, Is.EqualTo("1 claimed"));
|
||||
var reward = DailyQuests.Reward(DailyQuestKind.Waves);
|
||||
Assert.That(_root.Q<Label>("DailyQuestFeedback").text,
|
||||
Is.EqualTo($"[ OK ] Daily task completed.\n[ OK ] +{reward.Bandwidth} Bandwidth, +{reward.Entropy} Entropy deposited."));
|
||||
Assert.That(_root.Q("DailyQuestFeedback").style.display.value, Is.EqualTo(DisplayStyle.Flex));
|
||||
Assert.That(_root.focusController.focusedElement, Is.SameAs(_root.Q<Button>("CloseDailyQuests")),
|
||||
"Repeated Enter must not automatically activate the next reward.");
|
||||
for (int repeat = 0; repeat < 3; repeat++)
|
||||
Call("ClaimDailyQuest", DailyQuestKind.Waves, ((SaveData)Get("_saveData")).dailyQuests.refreshAtUtcTicks);
|
||||
Assert.That(_save.Load().bandwidthBalance, Is.EqualTo(reward.Bandwidth));
|
||||
Assert.That(_save.Load().entropyBalance, Is.EqualTo(reward.Entropy));
|
||||
using (var escape = KeyDownEvent.GetPooled(new Event { type = EventType.KeyDown, keyCode = KeyCode.Escape }))
|
||||
{ var close = _root.Q<Button>("CloseDailyQuests"); escape.target = close; close.SendEvent(escape); }
|
||||
Assert.That(_root.Q("DailyQuestOverlay"), Is.Null);
|
||||
Assert.That(_root.focusController.focusedElement, Is.SameAs(_root), "Mouse-opened details must not leave the widget focused after closing.");
|
||||
widget = _root.Q<Button>("DailyQuestWidget");
|
||||
widget.Focus();
|
||||
using (var enter = KeyDownEvent.GetPooled(new Event { type = EventType.KeyDown, keyCode = KeyCode.Return }))
|
||||
{ enter.target = widget; widget.SendEvent(enter); }
|
||||
Assert.That(_root.Q("DailyQuestOverlay"), Is.Not.Null, "Enter opens the focused widget.");
|
||||
Call("CloseDailyQuestDetails");
|
||||
Assert.That(_root.focusController.focusedElement, Is.SameAs(widget), "Keyboard-opened details restore keyboard focus.");
|
||||
var previous = new Button { name = "PreviousQuestFocus" };
|
||||
_shell.Add(previous);
|
||||
previous.Focus();
|
||||
Call("OpenDailyQuestDetails");
|
||||
using (var submit = NavigationSubmitEvent.GetPooled())
|
||||
{ var close = _root.Q<Button>("CloseDailyQuests"); submit.target = close; close.SendEvent(submit); }
|
||||
Assert.That(_root.focusController.focusedElement, Is.SameAs(previous), "Close restores arbitrary previous focus.");
|
||||
input.value = "cat /etc/cron.daily/quests";
|
||||
commandType.GetMethod("Submit", Private).Invoke(line, null);
|
||||
Assert.That(_root.Q("DailyQuestOverlay"), Is.Not.Null, "The existing prompt routes the alias.");
|
||||
var current = (SaveData)Get("_saveData");
|
||||
current.dailyQuests.refreshAtUtcTicks = DateTime.UtcNow.AddMinutes(5).AddSeconds(-1).Ticks;
|
||||
Call("TickDailyQuests");
|
||||
Assert.That(_root.Q<Label>("DailyQuestCountdown").text.Replace("refresh in ", "reset "), Is.EqualTo(_root.Q<Label>("DailyQuestDetailCountdown").text));
|
||||
Assert.That(_root.Q<Label>("DailyQuestCountdown").text, Does.StartWith("refresh in 00:04:"));
|
||||
current.dailyQuests.refreshAtUtcTicks = DateTime.UtcNow.AddSeconds(-1).Ticks;
|
||||
Call("TickDailyQuests");
|
||||
Assert.That(_root.Q<Label>("DailyQuestCompleted").text, Is.EqualTo("0/3 completed"));
|
||||
Assert.That(_root.Q("DailyQuestRewardReady").style.display.value, Is.EqualTo(DisplayStyle.None));
|
||||
Assert.That(_root.Q("DailyQuestOverlay"), Is.Not.Null, "Rollover refreshes the open details.");
|
||||
Assert.That(_root.Q<Label>("DailyQuestDetailSummary").text, Is.EqualTo("3 tasks / 0 completed"));
|
||||
Assert.That(_root.Q("DailyQuestFeedback").style.display.value, Is.EqualTo(DisplayStyle.None));
|
||||
Assert.That(_save.Load().bandwidthBalance, Is.EqualTo(DailyQuests.Reward(DailyQuestKind.Waves).Bandwidth));
|
||||
Call("CloseDailyQuestDetails");
|
||||
Assert.That(input.Contains(_root.focusController.focusedElement as VisualElement) || _root.focusController.focusedElement == input, Is.True);
|
||||
Assert.That(_shell.enabledSelf, Is.True);
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator LeavingQuestWidgetKeepsCommandSelectionAndEnterTargetInSync()
|
||||
{
|
||||
_window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
_window.Show();
|
||||
_window.rootVisualElement.Add(_root);
|
||||
_root.focusable = true;
|
||||
var boot = new VisualElement();
|
||||
boot.AddToClassList("hidden");
|
||||
Set("_bootIntroPanel", boot);
|
||||
_shell.Add(new TextField { name = "CommandInput" });
|
||||
_shell.Add(new Label { name = "CommandOutput" });
|
||||
var commandType = typeof(MainMenuController).Assembly.GetType("KernelPanic.UI.TerminalCommandLine");
|
||||
Set("_commandLine", Activator.CreateInstance(commandType, _root, (Action<int>)(_ => { }), (Func<bool>)(() => true)));
|
||||
int activated = -1, opened = 0;
|
||||
var entries = (IList)Get("_commandEntries");
|
||||
var entryType = typeof(MainMenuController).GetNestedType("CommandMenuEntry", BindingFlags.NonPublic);
|
||||
var rows = new VisualElement[2];
|
||||
for (int i = 0; i < rows.Length; i++)
|
||||
{
|
||||
int index = i;
|
||||
rows[i] = new VisualElement { name = "TestCommand" + i };
|
||||
var cursor = new Label();
|
||||
cursor.AddToClassList("command-cursor");
|
||||
rows[i].Add(cursor);
|
||||
_shell.Add(rows[i]);
|
||||
entries.Add(Activator.CreateInstance(entryType, rows[i], (Action)(() => activated = index)));
|
||||
}
|
||||
Call("RegisterCommandEntryCallbacks");
|
||||
_root.RegisterCallback<KeyDownEvent>(evt => Call("HandleKeyDown", evt));
|
||||
var widget = DailyQuestView.BuildWidget(new DailyQuestState(), DateTime.UtcNow, () => opened++);
|
||||
_shell.Add(widget);
|
||||
yield return null;
|
||||
void Key(KeyCode key)
|
||||
{
|
||||
using var evt = KeyDownEvent.GetPooled('\0', key, EventModifiers.None);
|
||||
var focused = _root.focusController.focusedElement as VisualElement ?? _root;
|
||||
evt.target = focused;
|
||||
focused.SendEvent(evt);
|
||||
}
|
||||
widget.Focus();
|
||||
Key(KeyCode.DownArrow);
|
||||
Assert.That(_root.focusController.focusedElement, Is.SameAs(rows[1]));
|
||||
Key(KeyCode.Return);
|
||||
Assert.That(activated, Is.EqualTo(1));
|
||||
widget.Focus();
|
||||
Key(KeyCode.UpArrow);
|
||||
Assert.That(_root.focusController.focusedElement, Is.SameAs(rows[0]));
|
||||
Key(KeyCode.Return);
|
||||
Assert.That(activated, Is.Zero);
|
||||
widget.Focus();
|
||||
using (var hover = PointerEnterEvent.GetPooled())
|
||||
{ hover.target = rows[1]; rows[1].SendEvent(hover); }
|
||||
Assert.That(_root.focusController.focusedElement, Is.Not.SameAs(widget));
|
||||
Key(KeyCode.Return);
|
||||
Assert.That(activated, Is.EqualTo(1));
|
||||
Assert.That(opened, Is.Zero, "Enter after selecting a menu command must not reopen quests.");
|
||||
widget.Focus();
|
||||
Key(KeyCode.Escape);
|
||||
Assert.That(_root.focusController.focusedElement, Is.Not.SameAs(widget), "Escape releases the widget's keyboard selection.");
|
||||
}
|
||||
|
||||
private static CardDefinition[] Equipable(DistroDefinition distro) => distro.ExclusiveCards.Where(card => card != null && !card.IsToken && !card.IsRunOnly).Take(4).ToArray();
|
||||
|
||||
private object Call(string method, params object[] args) => typeof(MainMenuController).GetMethod(method, Private).Invoke(_menu, args);
|
||||
private object Get(string field) => typeof(MainMenuController).GetField(field, Private).GetValue(_menu);
|
||||
private void Set(string field, object value) => typeof(MainMenuController).GetField(field, Private).SetValue(_menu, value);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f851bb149f8f481cbd73878ee00e110b
|
||||
@@ -0,0 +1,254 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Run;
|
||||
using KernelPanic.UI;
|
||||
using NUnit.Framework;
|
||||
using UnityEngine;
|
||||
|
||||
public class OrphanSpawnTests
|
||||
{
|
||||
private const BindingFlags Private = BindingFlags.NonPublic | BindingFlags.Instance;
|
||||
private static readonly FieldInfo CombatRandom = typeof(RandomRoll).GetField("_random", BindingFlags.NonPublic | BindingFlags.Static);
|
||||
private GameObject _owner;
|
||||
private CombatManager _combat;
|
||||
private RunManager _run;
|
||||
private object _random;
|
||||
private UnityEngine.Random.State _unityRandom;
|
||||
private bool _reducedMotion;
|
||||
private int _spawnEvents;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_random = CombatRandom.GetValue(null);
|
||||
_unityRandom = UnityEngine.Random.state;
|
||||
_reducedMotion = UIPreferences.ReducedMotion;
|
||||
UIPreferences.ReducedMotion = true;
|
||||
RandomRoll.Seed(0);
|
||||
_owner = new GameObject("Orphan spawn regression");
|
||||
_run = _owner.AddComponent<RunManager>();
|
||||
_combat = _owner.AddComponent<CombatManager>();
|
||||
Call(_run, "OnDisable");
|
||||
Call(_run, "OnEnable");
|
||||
Call(_combat, "OnDisable");
|
||||
Call(_combat, "OnEnable");
|
||||
_run.StartRun(null);
|
||||
Set(_combat, "_runManager", _run);
|
||||
Set(_combat, "_playerState", new CombatantState(100, 5, 3));
|
||||
Set(_combat, "currentPhase", TurnPhase.Execute);
|
||||
_spawnEvents = 0;
|
||||
GameEvents.DeathSpawnedEnemy += OnDeathSpawn;
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
GameEvents.DeathSpawnedEnemy -= OnDeathSpawn;
|
||||
if (_combat != null) Call(_combat, "OnDisable");
|
||||
if (_run != null) Call(_run, "OnDisable");
|
||||
if (_owner != null) UnityEngine.Object.DestroyImmediate(_owner);
|
||||
UIPreferences.ReducedMotion = _reducedMotion;
|
||||
UnityEngine.Random.state = _unityRandom;
|
||||
CombatRandom.SetValue(null, _random);
|
||||
}
|
||||
|
||||
[TestCase("fork_bomb", 1, true)]
|
||||
[TestCase("fork_bomb", 25, true)]
|
||||
[TestCase("fork_bomb", 26, false)]
|
||||
[TestCase("fork_bomb", 100, false)]
|
||||
[TestCase("zombie_process", 1, true)]
|
||||
[TestCase("zombie_process", 25, true)]
|
||||
[TestCase("zombie_process", 26, false)]
|
||||
[TestCase("zombie_process", 100, false)]
|
||||
public void PermanentDeathUsesTwentyFivePercentBoundaryAndSpawnsOnlyAfterExit(string archetype, int roll, bool expectedSpawn)
|
||||
{
|
||||
AddEnemy("memory_leak"); // Keep the encounter open while inspecting the death-spawn path.
|
||||
var source = AddEnemy(archetype);
|
||||
if (archetype == "zombie_process")
|
||||
{
|
||||
LethalHit(source);
|
||||
Assert.That(source.PendingRevive, Is.True);
|
||||
Call(_combat, "RevivePendingEnemies");
|
||||
}
|
||||
RandomRoll.Seed(SeedForFirstRoll(roll));
|
||||
KillAndQueue(source);
|
||||
Assert.That(_combat.Enemies.Count, Is.EqualTo(2));
|
||||
Assert.That(_spawnEvents, Is.Zero, "Death-spawn visuals must follow the source's completed exit.");
|
||||
FinishExit(source);
|
||||
Assert.That(_combat.Enemies.Count, Is.EqualTo(expectedSpawn ? 2 : 1));
|
||||
Assert.That(_spawnEvents, Is.EqualTo(expectedSpawn ? 1 : 0));
|
||||
Assert.That(_run.Bits, Is.EqualTo(CombatTuning.BitsPerKill));
|
||||
if (expectedSpawn)
|
||||
{
|
||||
var orphan = _combat.Enemies[1];
|
||||
Assert.That(orphan.ArchetypeId, Is.EqualTo("orphan_process"));
|
||||
Assert.That(orphan.SpawnedFromDeath, Is.True);
|
||||
Assert.That(orphan.DeathSpawnIntentRevealed, Is.True);
|
||||
Assert.That(orphan.CurrentUptime, Is.InRange(2, 4));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ActualSpawnSequenceIsSeededOccasionalAndIndependentOfForceMaxRolls()
|
||||
{
|
||||
const int count = 512;
|
||||
int[] ordinary = SampleActualSpawns(628207484, count, false);
|
||||
int[] mint = SampleActualSpawns(628207484, count, true);
|
||||
Assert.That(mint, Is.EqualTo(ordinary), "Player/enemy maximum-roll passives cannot change world spawn rolls or their RNG consumption.");
|
||||
int spawned = 0;
|
||||
foreach (int uptime in ordinary) if (uptime > 0) spawned++;
|
||||
Assert.That(spawned, Is.InRange(80, 180), "The deterministic sample must remain occasional, consistent with 25%, and far below guaranteed spawning.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PendingRevivalDoesNotRollOrPayAndZombieRevivesOnlyOnce()
|
||||
{
|
||||
AddEnemy("memory_leak");
|
||||
var zombie = AddEnemy("zombie_process");
|
||||
RandomRoll.Seed(17);
|
||||
int expectedNext = new System.Random(17).Next(1, 1000001);
|
||||
LethalHit(zombie);
|
||||
_combat.QueueDefeatedCombatantForRemoval(zombie.State);
|
||||
Assert.That(zombie.PendingRevive, Is.True);
|
||||
Assert.That(_run.Bits, Is.Zero);
|
||||
Assert.That(_spawnEvents, Is.Zero);
|
||||
Assert.That(RandomRoll.RollRange(1, 1000000, RollContext.None), Is.EqualTo(expectedNext), "Revival must not consume an orphan roll.");
|
||||
|
||||
Call(_combat, "RevivePendingEnemies");
|
||||
Assert.That(zombie.HasRevived, Is.True);
|
||||
Assert.That(zombie.CurrentUptime, Is.EqualTo(5));
|
||||
RandomRoll.Seed(SeedForFirstRoll(26));
|
||||
KillAndQueue(zombie);
|
||||
Assert.That(zombie.PendingRevive, Is.False);
|
||||
Assert.That(zombie.Reaped, Is.True);
|
||||
FinishExit(zombie);
|
||||
Call(_combat, "RevivePendingEnemies");
|
||||
Assert.That(zombie.CurrentUptime, Is.Zero);
|
||||
Assert.That(_combat.Enemies.Count, Is.EqualTo(1));
|
||||
Assert.That(_run.Bits, Is.EqualTo(CombatTuning.BitsPerKill));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DuplicateQueueRequestsDoNotRerollOrPayAgain()
|
||||
{
|
||||
AddEnemy("memory_leak");
|
||||
var fork = AddEnemy("fork_bomb");
|
||||
int seed = SeedForFirstRoll(25);
|
||||
var expected = new System.Random(seed);
|
||||
expected.Next(1, 101);
|
||||
int expectedNext = expected.Next(1, 1000001);
|
||||
RandomRoll.Seed(seed);
|
||||
KillAndQueue(fork);
|
||||
_combat.QueueDefeatedCombatantForRemoval(fork.State);
|
||||
_combat.QueueDefeatedCombatantForRemoval(fork.State);
|
||||
Assert.That(_run.Bits, Is.EqualTo(CombatTuning.BitsPerKill));
|
||||
Assert.That(RandomRoll.RollRange(1, 1000000, RollContext.None), Is.EqualTo(expectedNext));
|
||||
FinishExit(fork);
|
||||
Assert.That(_spawnEvents, Is.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ForkBombStillSplitsAfterActingUpToItsExistingCap()
|
||||
{
|
||||
var fork = AddEnemy("fork_bomb");
|
||||
for (int i = 1; i <= EnemyArchetypeCatalog.ForkBombTotalCap + 1; i++)
|
||||
{
|
||||
Call(_combat, "ResolvePassiveEnemyAfterAction", fork);
|
||||
Assert.That(_combat.Enemies.Count, Is.EqualTo(Mathf.Min(i + 1, EnemyArchetypeCatalog.ForkBombTotalCap)));
|
||||
}
|
||||
Assert.That(_spawnEvents, Is.Zero);
|
||||
foreach (var enemy in _combat.Enemies)
|
||||
{
|
||||
Assert.That(enemy.ArchetypeId, Is.EqualTo("fork_bomb"));
|
||||
if (enemy != fork) Assert.That(enemy.MaxUptime, Is.EqualTo(5));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OrphanDeathNeverRecursesOrConsumesASpawnRoll()
|
||||
{
|
||||
var orphan = AddEnemy("orphan_process");
|
||||
RandomRoll.Seed(1);
|
||||
int expectedNext = new System.Random(1).Next(1, 1000001);
|
||||
KillAndQueue(orphan);
|
||||
Assert.That(RandomRoll.RollRange(1, 1000000, RollContext.None), Is.EqualTo(expectedNext));
|
||||
FinishExit(orphan);
|
||||
Assert.That(_combat.Enemies, Is.Empty);
|
||||
Assert.That(_spawnEvents, Is.Zero);
|
||||
Assert.That(_combat.AwaitingWaveContinue, Is.True);
|
||||
Assert.That(_run.Bits, Is.EqualTo(CombatTuning.BitsPerKill));
|
||||
}
|
||||
|
||||
private int[] SampleActualSpawns(int seed, int count, bool forceMax)
|
||||
{
|
||||
var enemies = (List<EnemyInstance>)_combat.Enemies;
|
||||
enemies.Clear();
|
||||
AddEnemy("memory_leak");
|
||||
_combat.PlayerState.ForceMaxRolls = forceMax;
|
||||
RandomRoll.Seed(seed);
|
||||
var outcomes = new int[count];
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
var fork = AddEnemy("fork_bomb");
|
||||
fork.State.ForceMaxRolls = forceMax;
|
||||
KillAndQueue(fork);
|
||||
FinishExit(fork);
|
||||
if (enemies.Count == 2)
|
||||
{
|
||||
Assert.That(enemies[1].ArchetypeId, Is.EqualTo("orphan_process"));
|
||||
outcomes[i] = enemies[1].CurrentUptime;
|
||||
enemies.RemoveAt(1);
|
||||
}
|
||||
Assert.That(enemies.Count, Is.EqualTo(1));
|
||||
}
|
||||
return outcomes;
|
||||
}
|
||||
|
||||
private static int SeedForFirstRoll(int desired)
|
||||
{
|
||||
for (int seed = 0; seed < 10000; seed++)
|
||||
if (new System.Random(seed).Next(1, 101) == desired) return seed;
|
||||
throw new InvalidOperationException("No deterministic seed found for test boundary.");
|
||||
}
|
||||
|
||||
private EnemyInstance AddEnemy(string id)
|
||||
{
|
||||
var enemy = new EnemyInstance(EnemyArchetypeCatalog.Get(id), 10);
|
||||
((List<EnemyInstance>)_combat.Enemies).Add(enemy);
|
||||
return enemy;
|
||||
}
|
||||
|
||||
private void OnDeathSpawn(DeathSpawnedEnemyEvent _) => _spawnEvents++;
|
||||
private void LethalHit(EnemyInstance enemy) => _combat.DamagePipeline.DealDamage(
|
||||
new DamageRequest(null, enemy.State, enemy.MaxUptime, Language.Python, false, false));
|
||||
private void KillAndQueue(EnemyInstance enemy)
|
||||
{
|
||||
Set(_combat, "_enemyExitQueueDraining", true);
|
||||
LethalHit(enemy);
|
||||
_combat.QueueDefeatedCombatantForRemoval(enemy.State);
|
||||
}
|
||||
|
||||
private void FinishExit(EnemyInstance source)
|
||||
{
|
||||
GameEvents.RaiseCombatantDeathVisualCompleted(new CombatantDeathVisualCompletedEvent(source.State));
|
||||
Set(_combat, "_enemyExitQueueDraining", false);
|
||||
FinishRoutine((IEnumerator)Call(_combat, "DrainEnemyExitQueue"));
|
||||
}
|
||||
|
||||
private static void FinishRoutine(IEnumerator routine)
|
||||
{
|
||||
int steps = 0;
|
||||
while (routine.MoveNext())
|
||||
{
|
||||
Assert.That(++steps, Is.LessThan(100));
|
||||
if (routine.Current is IEnumerator nested) FinishRoutine(nested);
|
||||
}
|
||||
}
|
||||
|
||||
private static object Call(object owner, string method, params object[] args) => owner.GetType().GetMethod(method, Private).Invoke(owner, args);
|
||||
private static void Set(object owner, string field, object value) => owner.GetType().GetField(field, Private).SetValue(owner, value);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f12b205a14d84e969b2a7c1bf6079321
|
||||
@@ -0,0 +1,260 @@
|
||||
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.Meta;
|
||||
using KernelPanic.Run;
|
||||
using KernelPanic.UI;
|
||||
using NUnit.Framework;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
public class PackageReadinessTests
|
||||
{
|
||||
private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
private readonly List<UnityEngine.Object> _temporary = new();
|
||||
private readonly List<PackageActivation> _activations = new();
|
||||
private GameObject _owner;
|
||||
private CombatManager _combat;
|
||||
private RunManager _run;
|
||||
private UnityEngine.Random.State _random;
|
||||
private bool _motion;
|
||||
private CombatantState Player => _combat.PlayerState;
|
||||
private static PackageDatabase Packages => AssetDatabase.LoadAssetAtPath<PackageDatabase>("Assets/Data/Packages/PackageDatabase.asset");
|
||||
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()
|
||||
{
|
||||
_random = UnityEngine.Random.state;
|
||||
_motion = UIPreferences.ReducedMotion;
|
||||
UIPreferences.ReducedMotion = true;
|
||||
_owner = new GameObject("Package readiness integration");
|
||||
_run = _owner.AddComponent<RunManager>();
|
||||
_combat = _owner.AddComponent<CombatManager>();
|
||||
Call(_combat, "OnDisable"); Call(_combat, "Awake"); Call(_combat, "OnEnable");
|
||||
_combat.PackageActivated += _activations.Add;
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
_combat.PackageActivated -= _activations.Add;
|
||||
Call(_combat, "OnDisable");
|
||||
UnityEngine.Object.DestroyImmediate(_owner);
|
||||
foreach (var item in _temporary) UnityEngine.Object.DestroyImmediate(item);
|
||||
_temporary.Clear();
|
||||
_activations.Clear();
|
||||
UnityEngine.Random.state = _random;
|
||||
UIPreferences.ReducedMotion = _motion;
|
||||
}
|
||||
|
||||
private void Configure(string distro, int version, int level, params string[] ids)
|
||||
{
|
||||
var definition = AssetDatabase.LoadAssetAtPath<DistroDefinition>($"Assets/Data/Distros/{distro}.asset");
|
||||
var config = new RunConfig(definition, Language.C, Language.Haskell, Array.Empty<CardDefinition>(),
|
||||
ids.Select(id => new PackageInstance(Packages.FindById(id), level)).ToArray(), 17, version);
|
||||
_run.StartRun(config);
|
||||
Set(_combat, "_runConfig", config);
|
||||
Set(_combat, "_runManager", _run);
|
||||
BeginWave();
|
||||
BeginRound();
|
||||
}
|
||||
|
||||
private static void Finish(IEnumerator routine)
|
||||
{
|
||||
int steps = 0;
|
||||
while (routine.MoveNext())
|
||||
{
|
||||
Assert.That(++steps, Is.LessThan(2000));
|
||||
if (routine.Current is IEnumerator child) Finish(child);
|
||||
}
|
||||
}
|
||||
|
||||
private void BeginWave()
|
||||
{
|
||||
Finish((IEnumerator)Call(_combat, "StartWaveSequenced", false));
|
||||
Set(_combat, "currentPhase", TurnPhase.Execute);
|
||||
Player.ForceMaxRolls = true;
|
||||
}
|
||||
|
||||
private void BeginRound()
|
||||
{
|
||||
Finish((IEnumerator)Call(_combat, "AllocateTurnSequenced"));
|
||||
Set(_combat, "currentPhase", TurnPhase.Execute);
|
||||
}
|
||||
|
||||
private CardInstance Card(int cost = 2, ResolutionTrack track = ResolutionTrack.Native,
|
||||
string id = "package_readiness_test", Language language = Language.C)
|
||||
{
|
||||
var definition = ScriptableObject.CreateInstance<CardDefinition>();
|
||||
_temporary.Add(definition);
|
||||
Set(definition, "id", id); Set(definition, "cycleCost", cost);
|
||||
Set(definition, "resolutionTrack", track); Set(definition, "language", language);
|
||||
var card = new CardInstance(definition);
|
||||
Assert.That(_combat.HandController.Add(card), Is.True);
|
||||
return card;
|
||||
}
|
||||
|
||||
private PackageCombatReadout Readout(string suffix) => _combat.GetPackageReadouts().Single(row => row.Definition.Id == "pkg_gentoo_" + suffix);
|
||||
private int Activations(string suffix, string fragment = null) => _activations.Count(item =>
|
||||
item.PackageId == "pkg_gentoo_" + suffix && (fragment == null || item.Message.Contains(fragment)));
|
||||
|
||||
[TestCase("Gentoo", 1, 0)] [TestCase("Gentoo", 1, 5)]
|
||||
[TestCase("Gentoo", 5, 0)] [TestCase("Gentoo", 5, 5)]
|
||||
[TestCase("Ubuntu", 1, 0)] [TestCase("Ubuntu", 5, 5)]
|
||||
public void EquipmentReadoutsAndCostQueriesAreAccurateAndDoNotMutateCombat(string distro, int version, int level)
|
||||
{
|
||||
Configure(distro, version, level, "pkg_gentoo_portage", "pkg_gentoo_ccache", "pkg_gentoo_openrc");
|
||||
var card = Card();
|
||||
var random = UnityEngine.Random.state;
|
||||
int shield = Player.Shield, cycles = Player.Cycles, uptime = Player.CurrentUptime;
|
||||
int compilation = _combat.Compilation.Level, lastAdvanced = _combat.Compilation.LastAdvancedRound;
|
||||
int events = _activations.Count;
|
||||
var hand = _combat.HandController.Cards.ToArray();
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
Assert.That(_combat.GetPackageReadouts(), Has.Count.EqualTo(3));
|
||||
Assert.That(Readout("ccache").State, Is.EqualTo("ready"));
|
||||
Assert.That(Readout("portage").Details, Does.Contain($"+{4 + level * 2} maximum Uptime"));
|
||||
Assert.That(Readout("portage").Details.Contains("Shield"), Is.EqualTo(distro == "Gentoo"));
|
||||
Assert.That(Readout("openrc").Details, Does.Contain($"+{2 + level} Shield"));
|
||||
Assert.That(Readout("openrc").Details.Contains("Compilation"), Is.EqualTo(distro == "Gentoo"));
|
||||
Assert.That(_combat.GetDisplayedPlayCost(card), Is.EqualTo(1));
|
||||
Assert.That(_combat.GetCardCostBreakdown(card), Does.Contain("Cycles: 1 (base 2)").And.Contain("ccache: -1"));
|
||||
Assert.That(_combat.PreviewCardPlayShield(card), Is.EqualTo(level));
|
||||
}
|
||||
|
||||
Assert.That(UnityEngine.Random.state, Is.EqualTo(random));
|
||||
Assert.That(Player.Shield, Is.EqualTo(shield));
|
||||
Assert.That(Player.Cycles, Is.EqualTo(cycles));
|
||||
Assert.That(Player.CurrentUptime, Is.EqualTo(uptime));
|
||||
Assert.That(_combat.Compilation.Level, Is.EqualTo(compilation));
|
||||
Assert.That(_combat.Compilation.LastAdvancedRound, Is.EqualTo(lastAdvanced));
|
||||
Assert.That(_combat.CardsPlayedThisRound, Is.Zero);
|
||||
Assert.That(_combat.HandController.Cards, Is.EqualTo(hand));
|
||||
Assert.That(_activations.Count, Is.EqualTo(events));
|
||||
Assert.That(Activations("portage"), Is.EqualTo(distro == "Gentoo" ? 1 : 0));
|
||||
Assert.That(card.QueuePlayCount, Is.Zero);
|
||||
Assert.That(card.MagnitudeBonus, Is.Zero);
|
||||
}
|
||||
|
||||
[TestCase("Gentoo", 0)] [TestCase("Gentoo", 5)]
|
||||
[TestCase("Ubuntu", 0)] [TestCase("Ubuntu", 5)]
|
||||
public void FailedPlayPreservesReadinessAndOnlyTheFirstAcceptedPlayActivates(string distro, int level)
|
||||
{
|
||||
Configure(distro, 1, level, "pkg_gentoo_ccache");
|
||||
var card = Card();
|
||||
var before = Readout("ccache");
|
||||
Player.Cycles = 0;
|
||||
Assert.That(_combat.PlayCard(card), Is.False);
|
||||
Assert.That(Readout("ccache").State, Is.EqualTo("ready"));
|
||||
Assert.That(_combat.PreviewCardPlayShield(card), Is.EqualTo(level));
|
||||
Assert.That(Activations("ccache"), Is.Zero);
|
||||
|
||||
Player.Cycles = 10;
|
||||
Assert.That(_combat.PlayCard(card), Is.True);
|
||||
Assert.That(Readout("ccache").State, Is.EqualTo("used"));
|
||||
Assert.That(before.State, Is.EqualTo("ready"), "Published readouts are immutable snapshots.");
|
||||
Assert.That(Player.Shield, Is.EqualTo(level));
|
||||
Assert.That(Activations("ccache"), Is.EqualTo(1));
|
||||
var second = Card();
|
||||
Assert.That(_combat.PreviewCardPlayShield(second), Is.Zero);
|
||||
Assert.That(_combat.GetCardCostBreakdown(second), Does.Contain("Cycles: 2 (base 2)").And.Not.Contain("ccache: -1"));
|
||||
Assert.That(_combat.PlayCard(second), Is.True);
|
||||
Assert.That(Player.Shield, Is.EqualTo(level));
|
||||
Assert.That(Activations("ccache"), Is.EqualTo(1));
|
||||
|
||||
BeginRound();
|
||||
Assert.That(Readout("ccache").State, Is.EqualTo("ready"));
|
||||
Assert.That(_combat.PreviewCardPlayShield(Card()), Is.EqualTo(level));
|
||||
BeginWave(); BeginRound();
|
||||
Assert.That(Readout("ccache").State, Is.EqualTo("ready"));
|
||||
Assert.That(_combat.GetDisplayedPlayCost(Card()), Is.EqualTo(1));
|
||||
}
|
||||
|
||||
[TestCase(ResolutionTrack.Native)]
|
||||
[TestCase(ResolutionTrack.InterpreterQueue)]
|
||||
[TestCase(ResolutionTrack.LazyStack)]
|
||||
public void MultiEffectCardProducesOneActivationIncludingFreeAndDeferredPlay(ResolutionTrack track)
|
||||
{
|
||||
Configure("Gentoo", 5, 5, "pkg_gentoo_ccache");
|
||||
var card = Card(0, track, "shop_py_async_def", Language.Python);
|
||||
Assert.That(_combat.PreviewCardPlayShield(card), Is.EqualTo(5));
|
||||
Assert.That(_combat.PlayCard(card), Is.True);
|
||||
Assert.That(Activations("ccache"), Is.EqualTo(1));
|
||||
Assert.That(Player.Shield, Is.EqualTo(5));
|
||||
if (track == ResolutionTrack.InterpreterQueue) Finish((IEnumerator)Call(_combat, "InterpretQueueSequenced"));
|
||||
if (track == ResolutionTrack.LazyStack) Finish((IEnumerator)Call(_combat, "EvaluateLazyStackSequenced"));
|
||||
Assert.That(Activations("ccache"), Is.EqualTo(1));
|
||||
Assert.That(Player.Shield, Is.EqualTo(5));
|
||||
Assert.That(Readout("ccache").State, Is.EqualTo("used"));
|
||||
}
|
||||
|
||||
[TestCase(1, 0)] [TestCase(1, 5)] [TestCase(5, 0)] [TestCase(5, 5)]
|
||||
public void PendingCycleAndCompilationCapFollowRoundStateAndWaveReset(int version, int level)
|
||||
{
|
||||
Configure("Gentoo", version, level, "pkg_gentoo_portage", "pkg_gentoo_ccache", "pkg_gentoo_openrc");
|
||||
int initial = _combat.Compilation.Level;
|
||||
Assert.That(Readout("ccache").Details, Does.Not.Contain("Next round: +1 Cycle"));
|
||||
Call(_combat, "GarbageCollect");
|
||||
Assert.That(Readout("ccache").Details, Does.Contain("Next round: +1 Cycle"));
|
||||
int before = _activations.Count;
|
||||
BeginRound();
|
||||
Assert.That(Player.Cycles, Is.EqualTo(Player.MaxCycles + 1));
|
||||
Assert.That(Activations("ccache", "Cycle from Compilation"), Is.EqualTo(1));
|
||||
Assert.That(Activations("openrc", "Shield"), Is.EqualTo(1));
|
||||
Assert.That(Activations("openrc", "Compilation ("), Is.EqualTo(1));
|
||||
Assert.That(_activations.Count - before, Is.EqualTo(3));
|
||||
Assert.That(_combat.Compilation.Level, Is.EqualTo(initial + 2));
|
||||
Assert.That(Player.Shield, Is.EqualTo(4 + 2 * level + 2 + level));
|
||||
int shield = Player.Shield, cycle = Player.Cycles;
|
||||
Call(_combat, "ApplyPackageTurnStartEffects");
|
||||
Call(_combat, "ApplyPackageWaveStartEffects");
|
||||
Assert.That(Player.Shield, Is.EqualTo(shield));
|
||||
Assert.That(Player.Cycles, Is.EqualTo(cycle));
|
||||
Assert.That(_activations.Count - before, Is.EqualTo(3));
|
||||
|
||||
// OpenRC alone eventually reaches the real version cap. No fabricated rounds or animations.
|
||||
for (int i = 0; i < 10; i++) BeginRound();
|
||||
Assert.That(_combat.Compilation.Level, Is.EqualTo(_combat.Compilation.Maximum));
|
||||
Assert.That(Readout("openrc").Details, Does.Contain("Compilation capped"));
|
||||
Assert.That(Readout("ccache").Details, Does.Not.Contain("Next round: +1 Cycle"));
|
||||
Assert.That(Player.Cycles, Is.EqualTo(Player.MaxCycles));
|
||||
int compilationEvents = Activations("openrc", "Compilation (");
|
||||
int cycleEvents = Activations("ccache", "Cycle from Compilation");
|
||||
Call(_combat, "GarbageCollect"); BeginRound();
|
||||
Assert.That(Activations("openrc", "Compilation ("), Is.EqualTo(compilationEvents));
|
||||
Assert.That(Activations("ccache", "Cycle from Compilation"), Is.EqualTo(cycleEvents));
|
||||
|
||||
BeginWave(); BeginRound();
|
||||
Assert.That(_combat.Compilation.Level, Is.EqualTo(initial));
|
||||
Assert.That(Player.Shield, Is.EqualTo(4 + level * 2));
|
||||
Assert.That(Player.Cycles, Is.EqualTo(Player.MaxCycles));
|
||||
Assert.That(Readout("ccache").State, Is.EqualTo("ready"));
|
||||
Assert.That(Readout("openrc").Details, Does.Not.Contain("Compilation capped"));
|
||||
Assert.That(Activations("portage"), Is.EqualTo(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CostBreakdownIncludesExistingJavaAndFedoraModifiersWithoutConsumingThem()
|
||||
{
|
||||
Configure("Fedora", 3, 5, "pkg_gentoo_ccache");
|
||||
var card = Card(5, ResolutionTrack.Native, "lang_java_public_static_main", Language.Java);
|
||||
card.ApplyCostUpgrade(-1);
|
||||
card.TemporaryCostDelta = -1;
|
||||
Set(_combat, "_javaCardsPlayedThisCombat", 1);
|
||||
string explanation = _combat.GetCardCostBreakdown(card);
|
||||
Assert.That(explanation, Does.Contain("upgrades: -1").And.Contain("temporary: -1")
|
||||
.And.Contain("Java warmup: -1").And.Contain("ccache: -1").And.Contain("Bleeding Edge: -1"));
|
||||
Assert.That(_combat.GetDisplayedPlayCost(card), Is.Zero);
|
||||
Assert.That(_combat.CardsPlayedThisRound, Is.Zero);
|
||||
Assert.That(Activations("ccache"), Is.Zero);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 64c67631f8c94fbf96527bc0d79588cf
|
||||
@@ -0,0 +1,191 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Meta;
|
||||
using KernelPanic.Run;
|
||||
using NUnit.Framework;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
public class PileCostDetailsTests
|
||||
{
|
||||
private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
private readonly List<UnityEngine.Object> _temporary = new();
|
||||
private GameObject _owner;
|
||||
private CombatManager _combat;
|
||||
|
||||
private static void Set(object target, string field, object value) =>
|
||||
target.GetType().GetField(field, Private).SetValue(target, value);
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_owner = new GameObject("Pile cost details tests");
|
||||
_combat = _owner.AddComponent<CombatManager>();
|
||||
Configure("Gentoo");
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
UnityEngine.Object.DestroyImmediate(_owner);
|
||||
foreach (var item in _temporary) UnityEngine.Object.DestroyImmediate(item);
|
||||
_temporary.Clear();
|
||||
}
|
||||
|
||||
private void Configure(string distro, params string[] packageIds)
|
||||
{
|
||||
var definition = AssetDatabase.LoadAssetAtPath<DistroDefinition>($"Assets/Data/Distros/{distro}.asset");
|
||||
var packages = AssetDatabase.LoadAssetAtPath<PackageDatabase>("Assets/Data/Packages/PackageDatabase.asset");
|
||||
var config = new RunConfig(definition, Language.C, Language.Java, Array.Empty<CardDefinition>(),
|
||||
packageIds.Select(id => new PackageInstance(packages.FindById(id), 0)).ToArray(), 19, 3);
|
||||
Set(_combat, "_runConfig", config);
|
||||
Set(_combat, "_playerState", new CombatantState(60, 10, 3));
|
||||
Set(_combat, "_handController", new HandController(10));
|
||||
}
|
||||
|
||||
private CardInstance Card(int cost = 3, string id = "pile_cost_test", Language language = Language.C,
|
||||
bool token = false, bool junk = false)
|
||||
{
|
||||
var definition = ScriptableObject.CreateInstance<CardDefinition>();
|
||||
_temporary.Add(definition);
|
||||
Set(definition, "id", id);
|
||||
Set(definition, "cycleCost", cost);
|
||||
Set(definition, "language", language);
|
||||
Set(definition, "resolutionTrack", ResolutionTrack.Native);
|
||||
Set(definition, "isToken", token);
|
||||
Set(definition, "isJunk", junk);
|
||||
return new CardInstance(definition);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MissingCardsHaveNoMisleadingZeroCostEstimate()
|
||||
{
|
||||
Assert.That(_combat.GetPileCostDetails(null), Is.Empty);
|
||||
Assert.That(_combat.GetPileCostDetails(new CardInstance(null)), Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void StoredCostIncludesPermanentAndTemporaryCardAdjustments()
|
||||
{
|
||||
var card = Card(6);
|
||||
card.ApplyCostUpgrade(-1);
|
||||
card.TemporaryCostDelta = -1;
|
||||
|
||||
string details = _combat.GetPileCostDetails(card);
|
||||
|
||||
Assert.That(details, Does.Contain("Current estimate: 4 Cycles (stored 4, base 6)")
|
||||
.And.Contain("upgrades: -1").And.Contain("temporary: -1"));
|
||||
Assert.That(details, Does.Contain("current hand and ready discounts")
|
||||
.And.Contain("Drawing or playing cards can change it"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CostsRemainClampedToZeroInPileDetails()
|
||||
{
|
||||
var card = Card(1);
|
||||
card.TemporaryCostDelta = -5;
|
||||
Assert.That(_combat.GetPileCostDetails(card), Does.Contain("Current estimate: 0 Cycles (stored 0, base 1)"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CurrentEstimateExplainsJavaPackageAndFedoraDiscountsWithoutConsumingThem()
|
||||
{
|
||||
Configure("Fedora", "pkg_gentoo_ccache");
|
||||
var card = Card(5, "lang_java_public_static_main", Language.Java);
|
||||
card.ApplyCostUpgrade(-1);
|
||||
card.TemporaryCostDelta = -1;
|
||||
Set(_combat, "_javaCardsPlayedThisCombat", 1);
|
||||
int seed = RandomRoll.CurrentSeed, draws = RandomRoll.DrawCount;
|
||||
var random = UnityEngine.Random.state;
|
||||
int cycles = _combat.PlayerState.Cycles, shield = _combat.PlayerState.Shield;
|
||||
int events = 0;
|
||||
_combat.PackageActivated += _ => events++;
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
string details = _combat.GetPileCostDetails(card);
|
||||
Assert.That(details, Does.Contain("Current estimate: 0 Cycles (stored 3, base 5)")
|
||||
.And.Contain("upgrades: -1").And.Contain("temporary: -1")
|
||||
.And.Contain("Java warmup: -1").And.Contain("ccache: -1").And.Contain("Bleeding Edge: -1"));
|
||||
}
|
||||
|
||||
Assert.That(RandomRoll.CurrentSeed, Is.EqualTo(seed));
|
||||
Assert.That(RandomRoll.DrawCount, Is.EqualTo(draws));
|
||||
Assert.That(UnityEngine.Random.state, Is.EqualTo(random));
|
||||
Assert.That(_combat.PlayerState.Cycles, Is.EqualTo(cycles));
|
||||
Assert.That(_combat.PlayerState.Shield, Is.EqualTo(shield));
|
||||
Assert.That(_combat.CardsPlayedThisRound, Is.Zero);
|
||||
Assert.That(_combat.HandController.Cards, Is.Empty, "A pile cost query must not stage the card in hand.");
|
||||
Assert.That(card.QueuePlayCount, Is.Zero);
|
||||
Assert.That(card.TemporaryCostDelta, Is.EqualTo(-1));
|
||||
Assert.That(card.PermanentCostDelta, Is.EqualTo(-1));
|
||||
Assert.That(events, Is.Zero);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CurrentEstimateChangesWhenFirstCardDiscountIsNoLongerReady()
|
||||
{
|
||||
Configure("Gentoo", "pkg_gentoo_ccache");
|
||||
var card = Card(3);
|
||||
Assert.That(_combat.GetPileCostDetails(card), Does.Contain("Current estimate: 2 Cycles (stored 3")
|
||||
.And.Contain("ccache: -1"));
|
||||
|
||||
Set(_combat, "_cardsPlayedThisTurn", 1);
|
||||
|
||||
Assert.That(_combat.GetPileCostDetails(card), Does.Contain("Current estimate: 3 Cycles (stored 3")
|
||||
.And.Not.Contain("ccache: -1"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AutoremoveEstimateUsesCurrentHandWithoutInventingFutureJunk()
|
||||
{
|
||||
Configure("Fedora");
|
||||
var card = Card(3, "fedora_dnf_autoremove", Language.Rust);
|
||||
Assert.That(_combat.GetPileCostDetails(card), Does.Contain("Current estimate: 3 Cycles")
|
||||
.And.Not.Contain("Bleeding Edge"));
|
||||
|
||||
var junk = Card(0, "junk", token: true, junk: true);
|
||||
_combat.HandController.Add(junk);
|
||||
Assert.That(_combat.GetPileCostDetails(card), Does.Contain("Current estimate: 2 Cycles")
|
||||
.And.Contain("Bleeding Edge: -1").And.Contain("current hand"));
|
||||
Assert.That(_combat.HandController.Cards, Is.EqualTo(new[] { junk }));
|
||||
|
||||
_combat.HandController.Remove(junk);
|
||||
Assert.That(_combat.GetPileCostDetails(card), Does.Contain("Current estimate: 3 Cycles"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ConsultWikiEstimateReflectsCurrentBrokenHandWithoutRepairingIt()
|
||||
{
|
||||
Configure("Fedora");
|
||||
var card = Card(3, "arch_consult_wiki");
|
||||
Assert.That(_combat.GetPileCostDetails(card), Does.Contain("Current estimate: 2 Cycles"));
|
||||
var broken = Card();
|
||||
broken.IsBroken = true;
|
||||
_combat.HandController.Add(broken);
|
||||
|
||||
Assert.That(_combat.GetPileCostDetails(card), Does.Contain("Current estimate: 3 Cycles")
|
||||
.And.Not.Contain("Bleeding Edge"));
|
||||
Assert.That(broken.IsBroken, Is.True);
|
||||
Assert.That(_combat.HandController.Cards, Is.EqualTo(new[] { broken }));
|
||||
}
|
||||
|
||||
[TestCase(true, false, false, "Unplayable token")]
|
||||
[TestCase(false, true, false, "Corrupted: cannot play")]
|
||||
[TestCase(false, false, true, "Locked: unlocking costs 1 extra Cycle in hand")]
|
||||
public void RestrictionsAreSeparateFromQuotedCycleCost(bool token, bool broken, bool locked, string expected)
|
||||
{
|
||||
var card = Card(0, token: token);
|
||||
card.IsBroken = broken;
|
||||
card.IsLocked = locked;
|
||||
string details = _combat.GetPileCostDetails(card);
|
||||
Assert.That(details, Does.Contain("Current estimate: 0 Cycles").And.Contain(expected));
|
||||
Assert.That(card.IsBroken, Is.EqualTo(broken));
|
||||
Assert.That(card.IsLocked, Is.EqualTo(locked));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c5edc08545bb4fbd82917fd384dd49ea
|
||||
@@ -0,0 +1,321 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Reflection;
|
||||
using KernelPanic.UI;
|
||||
using NUnit.Framework;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using UnityEngine.TestTools;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
public class ReadabilityTests
|
||||
{
|
||||
private string _testKey;
|
||||
private bool _motion;
|
||||
private UITextSize _size;
|
||||
private UILayoutDensity _density;
|
||||
private int _soundVolume;
|
||||
private const BindingFlags InternalStatic = BindingFlags.NonPublic | BindingFlags.Static;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_testKey = "KernelPanic.UI.Tests." + Guid.NewGuid().ToString("N");
|
||||
_motion = UIPreferences.ReducedMotion;
|
||||
_size = UIPreferences.TextSize;
|
||||
_density = UIPreferences.Density;
|
||||
_soundVolume = UIPreferences.SoundVolume;
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
UIPreferences.ReducedMotion = _motion;
|
||||
UIPreferences.TextSize = _size;
|
||||
UIPreferences.Density = _density;
|
||||
UIPreferences.SoundVolume = _soundVolume;
|
||||
PlayerPrefs.DeleteKey(_testKey);
|
||||
}
|
||||
|
||||
[TestCase(false, UITextSize.Standard, UILayoutDensity.Compact)]
|
||||
[TestCase(true, UITextSize.Large, UILayoutDensity.Compact)]
|
||||
[TestCase(false, UITextSize.Standard, UILayoutDensity.Comfortable)]
|
||||
[TestCase(true, UITextSize.Large, UILayoutDensity.Comfortable)]
|
||||
public void PreferencesRoundTripWithoutChangingTheProgressionSaveOrPersistingTemporaryOverrides(
|
||||
bool motion, UITextSize size, UILayoutDensity density)
|
||||
{
|
||||
string productionKey = (string)typeof(UIPreferences).GetField("StorageKey", InternalStatic).GetRawConstantValue();
|
||||
string productionBefore = PlayerPrefs.GetString(productionKey, "<absent>");
|
||||
UIPreferences.ReducedMotion = motion;
|
||||
UIPreferences.TextSize = size;
|
||||
UIPreferences.Density = density;
|
||||
InvokeStore("SaveToKey");
|
||||
string stored = PlayerPrefs.GetString(_testKey);
|
||||
|
||||
UIPreferences.ReducedMotion = !motion;
|
||||
UIPreferences.TextSize = size == UITextSize.Standard ? UITextSize.Large : UITextSize.Standard;
|
||||
UIPreferences.Density = density == UILayoutDensity.Compact ? UILayoutDensity.Comfortable : UILayoutDensity.Compact;
|
||||
Assert.That(PlayerPrefs.GetString(_testKey), Is.EqualTo(stored), "Transient overrides must not write preferences.");
|
||||
InvokeStore("LoadFromKey");
|
||||
|
||||
Assert.That(UIPreferences.ReducedMotion, Is.EqualTo(motion));
|
||||
Assert.That(UIPreferences.TextSize, Is.EqualTo(size));
|
||||
Assert.That(UIPreferences.Density, Is.EqualTo(density));
|
||||
Assert.That(PlayerPrefs.GetString(productionKey, "<absent>"), Is.EqualTo(productionBefore), "Fixtures never save to the player's preference key.");
|
||||
}
|
||||
|
||||
[TestCase(null)]
|
||||
[TestCase("not-json")]
|
||||
[TestCase("{\"version\":99,\"reducedMotion\":true,\"textSize\":1,\"density\":1}")]
|
||||
[TestCase("{\"version\":1,\"textSize\":38,\"density\":-7}")]
|
||||
public void ExistingPlayersAndUnknownPreferenceValuesUseReadableDefaults(string json)
|
||||
{
|
||||
if (json != null) PlayerPrefs.SetString(_testKey, json);
|
||||
UIPreferences.ReducedMotion = true;
|
||||
UIPreferences.TextSize = UITextSize.Large;
|
||||
UIPreferences.Density = UILayoutDensity.Comfortable;
|
||||
InvokeStore("LoadFromKey");
|
||||
Assert.That(UIPreferences.ReducedMotion, Is.False);
|
||||
Assert.That(UIPreferences.TextSize, Is.EqualTo(UITextSize.Standard));
|
||||
Assert.That(UIPreferences.Density, Is.EqualTo(UILayoutDensity.Compact));
|
||||
Assert.That(PlayerPrefs.GetString(_testKey, "<absent>"), Is.EqualTo(json ?? "<absent>"), "Loading must not rewrite old or unknown preferences.");
|
||||
}
|
||||
|
||||
[TestCase(0)]
|
||||
[TestCase(25)]
|
||||
[TestCase(100)]
|
||||
public void SoundVolumeRoundTripsAndMuteIsPreserved(int volume)
|
||||
{
|
||||
UIPreferences.SoundVolume = volume;
|
||||
InvokeStore("SaveToKey");
|
||||
UIPreferences.SoundVolume = 75;
|
||||
InvokeStore("LoadFromKey");
|
||||
Assert.That(UIPreferences.SoundVolume, Is.EqualTo(volume));
|
||||
UIPreferences.SoundVolume = -1;
|
||||
Assert.That(UIPreferences.SoundVolume, Is.Zero);
|
||||
UIPreferences.SoundVolume = 999;
|
||||
Assert.That(UIPreferences.SoundVolume, Is.EqualTo(100));
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator PreferencesUpdateEveryAttachedRootAndDetachSubscriptionsAreReleased()
|
||||
{
|
||||
RequireGraphics();
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
try
|
||||
{
|
||||
window.Show();
|
||||
var first = new VisualElement();
|
||||
var second = new VisualElement();
|
||||
window.rootVisualElement.Add(first);
|
||||
window.rootVisualElement.Add(second);
|
||||
UIPreferences.ReducedMotion = false;
|
||||
UIPreferences.TextSize = UITextSize.Standard;
|
||||
UIPreferences.Density = UILayoutDensity.Compact;
|
||||
Attach(first);
|
||||
Attach(second);
|
||||
Attach(first); // Repeated screen binding must not add duplicate subscriptions or sheets.
|
||||
UIPreferences.ReducedMotion = true;
|
||||
UIPreferences.TextSize = UITextSize.Large;
|
||||
UIPreferences.Density = UILayoutDensity.Comfortable;
|
||||
yield return null;
|
||||
foreach (var root in new[] { first, second })
|
||||
{
|
||||
Assert.That(root.ClassListContains("reduced-motion"), Is.True);
|
||||
Assert.That(root.ClassListContains("text-large"), Is.True);
|
||||
Assert.That(root.ClassListContains("density-comfortable"), Is.True);
|
||||
Assert.That(root.styleSheets.count, Is.EqualTo(2));
|
||||
}
|
||||
second.RemoveFromHierarchy();
|
||||
UIPreferences.ReducedMotion = false;
|
||||
UIPreferences.TextSize = UITextSize.Standard;
|
||||
UIPreferences.Density = UILayoutDensity.Compact;
|
||||
Assert.That(first.ClassListContains("text-large"), Is.False);
|
||||
Assert.That(second.ClassListContains("text-large"), Is.True, "A detached screen must not remain subscribed.");
|
||||
window.rootVisualElement.Add(second);
|
||||
Assert.That(second.ClassListContains("text-large"), Is.False, "Reattached screens immediately receive current preferences.");
|
||||
Assert.That(second.ClassListContains("density-comfortable"), Is.False);
|
||||
Assert.That(second.ClassListContains("reduced-motion"), Is.False);
|
||||
}
|
||||
finally { window.Close(); }
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator SettingsRemainReadableAndKeyboardReachableAtEveryTextAndSpacingPreset()
|
||||
{
|
||||
RequireGraphics();
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
try
|
||||
{
|
||||
window.minSize = new Vector2(100, 100);
|
||||
window.Show();
|
||||
var root = window.rootVisualElement;
|
||||
root.styleSheets.Add(AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/UI/MainMenu.uss"));
|
||||
Attach(root);
|
||||
var template = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/SettingsScreen.uxml").CloneTree();
|
||||
var settings = template.Q("SettingsPanel");
|
||||
settings.RemoveFromClassList("hidden");
|
||||
root.Add(settings);
|
||||
var scroll = settings.Q<ScrollView>();
|
||||
foreach (var viewport in new[] { new Vector2(960, 600), new Vector2(390, 600) })
|
||||
foreach (UITextSize size in Enum.GetValues(typeof(UITextSize)))
|
||||
foreach (UILayoutDensity density in Enum.GetValues(typeof(UILayoutDensity)))
|
||||
{
|
||||
window.position = new Rect(24, 24, viewport.x, viewport.y);
|
||||
root.style.width = viewport.x;
|
||||
root.style.height = viewport.y;
|
||||
UIPreferences.TextSize = size;
|
||||
UIPreferences.Density = density;
|
||||
for (int frame = 0; frame < 5; frame++) yield return null;
|
||||
string context = $"{viewport}, {size}, {density}";
|
||||
foreach (var label in settings.Query<Label>().ToList())
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(label.text)) continue;
|
||||
Assert.That(label.worldBound.xMin, Is.GreaterThanOrEqualTo(scroll.contentViewport.worldBound.xMin - 1), context + ": " + label.text);
|
||||
Assert.That(label.worldBound.xMax, Is.LessThanOrEqualTo(scroll.contentViewport.worldBound.xMax + 1), context + ": " + label.text);
|
||||
float measured = label.MeasureTextSize(label.text, label.contentRect.width,
|
||||
VisualElement.MeasureMode.Exactly, 0, VisualElement.MeasureMode.Undefined).y;
|
||||
Assert.That(label.contentRect.height, Is.GreaterThanOrEqualTo(measured - 1), context + ": clipped " + label.text);
|
||||
}
|
||||
Assert.That(settings.Q<Label>(className: "settings-description").resolvedStyle.fontSize,
|
||||
Is.EqualTo(size == UITextSize.Large ? 17 : 15), context);
|
||||
foreach (var control in new VisualElement[] { settings.Q<Toggle>("ReducedMotionToggle"), settings.Q<Button>("TextSizeButton"), settings.Q<Button>("DensityButton"), settings.Q<Button>("SoundVolumeButton") })
|
||||
{
|
||||
Assert.That(control.focusable, Is.True, context);
|
||||
control.Focus();
|
||||
yield return null;
|
||||
Assert.That(root.focusController.focusedElement, Is.SameAs(control), context);
|
||||
Assert.That(control.worldBound.xMax, Is.LessThanOrEqualTo(scroll.contentViewport.worldBound.xMax + 1), context);
|
||||
}
|
||||
}
|
||||
LogAssert.NoUnexpectedReceived();
|
||||
}
|
||||
finally { window.Close(); }
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator RunArchiveActionsWrapInsideNarrowScreensAtBothTextSizes()
|
||||
{
|
||||
RequireGraphics();
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
var owner = new GameObject("run archive layout fixture");
|
||||
owner.SetActive(false);
|
||||
try
|
||||
{
|
||||
var controller = owner.AddComponent<MainMenuController>();
|
||||
const BindingFlags privateInstance = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
window.minSize = new Vector2(100, 100);
|
||||
window.Show();
|
||||
var root = window.rootVisualElement;
|
||||
root.styleSheets.Add(AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/UI/MainMenu.uss"));
|
||||
Attach(root);
|
||||
var menu = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/MainMenu.uxml").CloneTree();
|
||||
var archive = menu.Q("RunArchivePanel");
|
||||
archive.RemoveFromClassList("hidden");
|
||||
root.Add(archive);
|
||||
new ScreenFrameController().Bind(archive, "$ history --runs", "[esc] back [tab/enter] actions", () => { });
|
||||
typeof(MainMenuController).GetField("_runArchivePanel", privateInstance).SetValue(controller, archive);
|
||||
typeof(MainMenuController).GetMethod("RefreshRunActions", privateInstance).Invoke(controller, null);
|
||||
var scroll = archive.Q<ScrollView>();
|
||||
var actions = archive.Q("RunArchiveActions");
|
||||
foreach (var viewport in new[] { new Vector2(960, 600), new Vector2(390, 600) })
|
||||
foreach (UITextSize size in Enum.GetValues(typeof(UITextSize)))
|
||||
{
|
||||
window.position = new Rect(24, 24, viewport.x, viewport.y);
|
||||
root.style.width = viewport.x;
|
||||
root.style.height = viewport.y;
|
||||
UIPreferences.TextSize = size;
|
||||
UIPreferences.Density = UILayoutDensity.Comfortable;
|
||||
for (int frame = 0; frame < 5; frame++) yield return null;
|
||||
string context = $"{viewport}, {size}";
|
||||
foreach (var element in actions.Query<TextElement>().ToList())
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(element.text)) continue;
|
||||
Assert.That(element.worldBound.xMin, Is.GreaterThanOrEqualTo(scroll.contentViewport.worldBound.xMin - 1), context + ": " + element.text);
|
||||
Assert.That(element.worldBound.xMax, Is.LessThanOrEqualTo(scroll.contentViewport.worldBound.xMax + 1), context + ": " + element.text);
|
||||
float measured = element.MeasureTextSize(element.text, element.contentRect.width,
|
||||
VisualElement.MeasureMode.Exactly, 0, VisualElement.MeasureMode.Undefined).y;
|
||||
Assert.That(element.contentRect.height, Is.GreaterThanOrEqualTo(measured - 1), context + ": clipped " + element.text);
|
||||
}
|
||||
var history = actions.Q<Button>("RecentRunsButton");
|
||||
history.Focus();
|
||||
yield return null;
|
||||
Assert.That(root.focusController.focusedElement, Is.SameAs(history), context);
|
||||
Assert.That(archive.Q<Button>(className: "screen-back").worldBound.yMax,
|
||||
Is.LessThanOrEqualTo(root.worldBound.yMax + 1), context);
|
||||
}
|
||||
LogAssert.NoUnexpectedReceived();
|
||||
}
|
||||
finally
|
||||
{
|
||||
window.Close();
|
||||
UnityEngine.Object.DestroyImmediate(owner);
|
||||
}
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator LongRuntimeHintsStayOnscreenScrollWithoutTakingFocusAndRefreshRetainedOwners()
|
||||
{
|
||||
RequireGraphics();
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
try
|
||||
{
|
||||
window.minSize = new Vector2(100, 100);
|
||||
window.position = new Rect(24, 24, 390, 300);
|
||||
window.Show();
|
||||
var root = window.rootVisualElement;
|
||||
root.style.width = 390;
|
||||
root.style.height = 300;
|
||||
UIPreferences.TextSize = UITextSize.Large;
|
||||
Attach(root);
|
||||
var owner = new Button { text = "Inspect live card" };
|
||||
var lines = new string[24];
|
||||
for (int i = 0; i < lines.Length; i++) lines[i] = "Compilation and equipment modify this card.";
|
||||
owner.tooltip = string.Join("\n", lines);
|
||||
root.Add(owner);
|
||||
owner.Focus();
|
||||
double waitUntil = EditorApplication.timeSinceStartup + 0.7;
|
||||
while (EditorApplication.timeSinceStartup < waitUntil) yield return null;
|
||||
var hint = root.Q<ScrollView>(className: "runtime-hint");
|
||||
Assert.That(hint, Is.Not.Null);
|
||||
Assert.That(hint.resolvedStyle.display, Is.EqualTo(DisplayStyle.Flex));
|
||||
Assert.That(hint.worldBound.xMin, Is.GreaterThanOrEqualTo(root.worldBound.xMin));
|
||||
Assert.That(hint.worldBound.xMax, Is.LessThanOrEqualTo(root.worldBound.xMax));
|
||||
Assert.That(hint.worldBound.yMin, Is.GreaterThanOrEqualTo(root.worldBound.yMin));
|
||||
Assert.That(hint.worldBound.yMax, Is.LessThanOrEqualTo(root.worldBound.yMax));
|
||||
Assert.That(hint.verticalScroller.highValue, Is.GreaterThan(0));
|
||||
Assert.That(hint.focusable, Is.False);
|
||||
Assert.That(hint.verticalScroller.slider.focusable, Is.False);
|
||||
using (var pageDown = KeyDownEvent.GetPooled('\0', KeyCode.PageDown, EventModifiers.None)) owner.SendEvent(pageDown);
|
||||
yield return null;
|
||||
Assert.That(hint.scrollOffset.y, Is.GreaterThan(0));
|
||||
Assert.That(root.focusController.focusedElement, Is.SameAs(owner));
|
||||
|
||||
owner.tooltip = "Updated preview: 24 damage; 7 Shield; cost 1 Cycle.";
|
||||
waitUntil = EditorApplication.timeSinceStartup + 0.3;
|
||||
while (EditorApplication.timeSinceStartup < waitUntil) yield return null;
|
||||
Assert.That(hint.Q<Label>("RuntimeHintText").text, Is.EqualTo(owner.tooltip));
|
||||
Assert.That(hint.resolvedStyle.display, Is.EqualTo(DisplayStyle.Flex));
|
||||
|
||||
root.Clear();
|
||||
var replacement = new Button { text = "Inspect another card", tooltip = "Current package readiness" };
|
||||
root.Add(replacement);
|
||||
replacement.Focus();
|
||||
waitUntil = EditorApplication.timeSinceStartup + 0.7;
|
||||
while (EditorApplication.timeSinceStartup < waitUntil) yield return null;
|
||||
Assert.That(root.Q<ScrollView>(className: "runtime-hint"), Is.SameAs(hint));
|
||||
Assert.That(hint.Q<Label>("RuntimeHintText").text, Is.EqualTo(replacement.tooltip));
|
||||
LogAssert.NoUnexpectedReceived();
|
||||
}
|
||||
finally { window.Close(); }
|
||||
}
|
||||
|
||||
private void InvokeStore(string method) => typeof(UIPreferences).GetMethod(method, InternalStatic).Invoke(null, new object[] { _testKey });
|
||||
private static void Attach(VisualElement root) => typeof(MainMenuController).Assembly.GetType("KernelPanic.UI.TerminalTheme")
|
||||
.GetMethod("Attach").Invoke(null, new object[] { root });
|
||||
private static void RequireGraphics()
|
||||
{
|
||||
if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Null)
|
||||
Assert.Ignore("Readability layout verification needs a graphical editor panel.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2758da1699394b94bba3a442d68d1ee3
|
||||
@@ -0,0 +1,159 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Meta;
|
||||
using KernelPanic.Run;
|
||||
using KernelPanic.UI;
|
||||
using NUnit.Framework;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
public class RewardSettlementTests
|
||||
{
|
||||
private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
private string _directory;
|
||||
private GameObject _owner;
|
||||
private RunManager _run;
|
||||
private CombatSceneController _controller;
|
||||
private SaveService _save;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_directory = Path.Combine(Path.GetTempPath(), "KernelPanic-RewardTests-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(_directory);
|
||||
_save = new SaveService(Path.Combine(_directory, "progression.json"));
|
||||
_owner = new GameObject("reward persistence regression");
|
||||
_owner.SetActive(false);
|
||||
_controller = _owner.AddComponent<CombatSceneController>();
|
||||
_run = _owner.GetComponent<RunManager>();
|
||||
Set(_controller, "_runManager", _run);
|
||||
Set(_controller, "_combatManager", _owner.GetComponent<CombatManager>());
|
||||
Set(_controller, "_saveService", _save);
|
||||
DistroDefinition distro = AssetDatabase.LoadAssetAtPath<DistroDefinition>("Assets/Data/Distros/Gentoo.asset");
|
||||
_run.StartRun(new RunConfig(distro, Language.Haskell, Language.C, Array.Empty<CardDefinition>(), 314));
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
// Destruction must never cause an additional settlement or touch the default save.
|
||||
if (_controller != null) Set(_controller, "_saveService", null);
|
||||
if (_owner != null) UnityEngine.Object.DestroyImmediate(_owner);
|
||||
if (Directory.Exists(_directory)) Directory.Delete(_directory, true);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FailedWriteKeepsRewardsPendingAndRetryPersistsThemExactlyOnce()
|
||||
{
|
||||
SaveData initial = SaveData.CreateDefault();
|
||||
initial.entropyBalance = 9;
|
||||
initial.bandwidthBalance = 20;
|
||||
_save.Save(initial);
|
||||
Directory.CreateDirectory(_save.BackupPath);
|
||||
Set(_run, "_accruedBandwidth", 7);
|
||||
Set(_run, "_accruedEntropy", 3);
|
||||
Set(_run, "currentWaveNumber", 4);
|
||||
|
||||
Settle();
|
||||
Assert.That(_run.RewardsSettled, Is.False);
|
||||
Assert.That(Get<string>(_controller, "_saveError"), Is.Not.Null.And.Not.Empty);
|
||||
Assert.That(_save.Load().bandwidthBalance, Is.EqualTo(20));
|
||||
Assert.That(_save.Load().entropyBalance, Is.EqualTo(9));
|
||||
|
||||
Directory.Delete(_save.BackupPath);
|
||||
Settle();
|
||||
Assert.That(_run.RewardsSettled, Is.True);
|
||||
Assert.That(Get<string>(_controller, "_saveError"), Is.Null);
|
||||
SaveData settled = _save.Load();
|
||||
Assert.That(settled.bandwidthBalance, Is.EqualTo(27));
|
||||
Assert.That(settled.entropyBalance, Is.EqualTo(12));
|
||||
Assert.That(settled.GetBestWave("gentoo"), Is.EqualTo(4));
|
||||
string once = File.ReadAllText(_save.SavePath);
|
||||
|
||||
Settle();
|
||||
Assert.That(File.ReadAllText(_save.SavePath), Is.EqualTo(once));
|
||||
Assert.That(_save.Load().bandwidthBalance, Is.EqualTo(27));
|
||||
Assert.That(_save.Load().entropyBalance, Is.EqualTo(12));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RunWithNoCurrencyRewardStillPersistsDistroAndBestWave()
|
||||
{
|
||||
Assert.That(_run.AccruedBandwidth, Is.Zero);
|
||||
Assert.That(_run.AccruedEntropy, Is.Zero);
|
||||
|
||||
Settle();
|
||||
|
||||
Assert.That(_run.RewardsSettled, Is.True);
|
||||
SaveData settled = _save.Load();
|
||||
Assert.That(settled.lastRunDistroId, Is.EqualTo("gentoo"));
|
||||
Assert.That(settled.lastRunLoadout.distroId, Is.EqualTo("gentoo"));
|
||||
Assert.That(settled.GetBestWave("gentoo"), Is.EqualTo(1));
|
||||
Assert.That(settled.bandwidthBalance, Is.Zero);
|
||||
Assert.That(settled.entropyBalance, Is.Zero);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ReadFailureAfterSettlementDoesNotTrapTheRunReportAndRecoveryClearsTheWarning()
|
||||
{
|
||||
Set(_run, "_accruedBandwidth", 7);
|
||||
Settle();
|
||||
Assert.That(_run.RewardsSettled, Is.True);
|
||||
string committed = File.ReadAllText(_save.SavePath);
|
||||
foreach (string field in new[] { "_waveLabel", "_phaseLabel", "_bitsLabel", "_entropyLabel", "_bandwidthLabel", "_rootCreditsLabel", "_seedLabel" })
|
||||
Set(_controller, field, new Label());
|
||||
|
||||
using (var locked = new FileStream(_save.SavePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
|
||||
{
|
||||
RefreshStatus();
|
||||
Assert.That(Get<string>(_controller, "_saveError"), Is.Not.Null.And.Not.Empty);
|
||||
var report = (VisualElement)typeof(CombatSceneController).GetMethod("BuildRunEndOverlay", Private).Invoke(_controller, null);
|
||||
Assert.That(report.Q<Button>(className: "death-return-action").enabledSelf, Is.True,
|
||||
"A later read failure cannot prevent leaving a run whose rewards are already saved.");
|
||||
}
|
||||
|
||||
RefreshStatus();
|
||||
Assert.That(Get<string>(_controller, "_saveError"), Is.Null);
|
||||
Assert.That(_run.RewardsSettled, Is.True);
|
||||
Assert.That(File.ReadAllText(_save.SavePath), Is.EqualTo(committed), "Status refresh must not settle rewards again.");
|
||||
Assert.That(_save.Load().bandwidthBalance, Is.EqualTo(7));
|
||||
}
|
||||
|
||||
private void Settle() => typeof(CombatSceneController).GetMethod("SettleRunRewardsIfNeeded", Private).Invoke(_controller, null);
|
||||
|
||||
[Test]
|
||||
public void CampaignVictorySaveFailureCanRetryWithoutDuplicateRewardsOrHistory()
|
||||
{
|
||||
_save.Save(SaveData.CreateDefault());
|
||||
Set(_run, "_accruedBandwidth", 100);
|
||||
Set(_run, "_accruedEntropy", 3);
|
||||
Set(_run, "currentWaveNumber", 6);
|
||||
Set(_run, "_wavesCleared", 5);
|
||||
var combat = _owner.GetComponent<CombatManager>();
|
||||
Set(combat, "_runManager", _run);
|
||||
Set(combat, "_awaitingWaveContinue", true);
|
||||
Assert.That(combat.CompleteCampaign(), Is.True);
|
||||
Directory.CreateDirectory(_save.BackupPath);
|
||||
Settle();
|
||||
Assert.That(_run.RewardsSettled, Is.False);
|
||||
Assert.That(_save.Load().recentRuns, Is.Empty);
|
||||
Directory.Delete(_save.BackupPath);
|
||||
Settle(); Settle();
|
||||
var saved = _save.Load();
|
||||
Assert.That(saved.bandwidthBalance, Is.EqualTo(100));
|
||||
Assert.That(saved.entropyBalance, Is.EqualTo(3));
|
||||
Assert.That(saved.GetBestWave("gentoo"), Is.EqualTo(5));
|
||||
Assert.That(saved.recentRuns.Count, Is.EqualTo(1));
|
||||
Assert.That(saved.recentRuns[0].victory, Is.True);
|
||||
Assert.That(saved.recentRuns[0].waveReached, Is.EqualTo(5));
|
||||
Assert.That(saved.recentRuns[0].cause, Does.Contain("campaign complete"));
|
||||
}
|
||||
private void RefreshStatus() => typeof(CombatSceneController).GetMethod("RefreshStatus", Private).Invoke(_controller, null);
|
||||
private static void Set(object instance, string field, object value) => instance.GetType().GetField(field, Private).SetValue(instance, value);
|
||||
private static T Get<T>(object instance, string field) => (T)instance.GetType().GetField(field, Private).GetValue(instance);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 09a24725ce714034a176ea5c30f0d056
|
||||
@@ -0,0 +1,271 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Meta;
|
||||
using KernelPanic.Run;
|
||||
using KernelPanic.UI;
|
||||
using NUnit.Framework;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using UnityEngine.TestTools;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
public class RunArchiveBuildTests
|
||||
{
|
||||
private DistroDatabase _distros;
|
||||
private CardDatabase _cards;
|
||||
private PackageDatabase _packages;
|
||||
private LanguageDeckDatabase _languages;
|
||||
private PlayerCollection _collection;
|
||||
private DistroDefinition _distro;
|
||||
private PackageDefinition _package;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_distros = AssetDatabase.LoadAssetAtPath<DistroDatabase>("Assets/Data/Distros/DistroDatabase.asset");
|
||||
_cards = AssetDatabase.LoadAssetAtPath<CardDatabase>("Assets/Data/Cards/CardDatabase.asset");
|
||||
_packages = AssetDatabase.LoadAssetAtPath<PackageDatabase>("Assets/Data/Packages/PackageDatabase.asset");
|
||||
_languages = AssetDatabase.LoadAssetAtPath<LanguageDeckDatabase>("Assets/Data/Cards/Languages/LanguageDeckDatabase.asset");
|
||||
_distro = _distros.FindById("gentoo");
|
||||
_package = _packages.FindById("pkg_fedora_dnf");
|
||||
_collection = new PlayerCollection();
|
||||
_collection.AddSilently(_distro, 5);
|
||||
_collection.AddPackageSilently(_package, 5);
|
||||
}
|
||||
|
||||
private RunHistoryEntry Entry()
|
||||
{
|
||||
var deck = _distro.ExclusiveCards.Where(card => card != null && !card.IsToken && !card.IsRunOnly).Take(4).ToList();
|
||||
foreach (var language in new[] { Language.Haskell, Language.C })
|
||||
foreach (var item in _languages.FindByLanguage(language).Entries)
|
||||
for (int i = 0; i < item.Count; i++) deck.Add(item.Card);
|
||||
var config = new RunConfig(_distro, Language.Haskell, Language.C, deck,
|
||||
new[] { new PackageInstance(_package, 1) }, int.MinValue, 2);
|
||||
return new RunHistoryEntry { runId = "archive-test", distroId = _distro.Id, distroName = _distro.DisplayName,
|
||||
distroVersion = 2, languages = "Haskell + C", seed = int.MinValue, build = RunHistory.CaptureBuild(config) };
|
||||
}
|
||||
|
||||
private bool Resolve(RunHistoryEntry entry, out ResolvedHistoryBuild build, out string reason)
|
||||
=> RunHistory.TryResolveBuild(entry, _collection, _distros, _cards, _packages, _languages, out build, out reason);
|
||||
|
||||
[Test]
|
||||
public void SnapshotPreservesCompleteOriginalDeckAndIndependentPackageLevels()
|
||||
{
|
||||
var entry = Entry();
|
||||
Assert.That(entry.build.exclusiveCardIds, Has.Count.EqualTo(4));
|
||||
Assert.That(entry.build.startingDeckCardIds.Count, Is.GreaterThan(4));
|
||||
Assert.That(entry.build.languages, Is.EqualTo(new[] { Language.Haskell, Language.C }));
|
||||
Assert.That(entry.build.packages.Single().upgradeLevel, Is.EqualTo(1));
|
||||
Assert.That(entry.build.packages.Single().slot, Is.EqualTo(_package.Slot));
|
||||
Assert.That(entry.build.seed, Is.EqualTo(int.MinValue));
|
||||
Assert.That(entry.build.distroVersion, Is.EqualTo(2));
|
||||
_collection.GetOwnedPackage(_package.Id).SetUpgradeLevel(3);
|
||||
Assert.That(entry.build.packages.Single().upgradeLevel, Is.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SaveRoundTripKeepsBuildSnapshotAndDoesNotInventOneForOldEntries()
|
||||
{
|
||||
string directory = Path.Combine(Path.GetTempPath(), "KernelPanic.Archive." + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(directory);
|
||||
try
|
||||
{
|
||||
var service = new SaveService(Path.Combine(directory, "save.json"));
|
||||
var data = SaveData.CreateDefault();
|
||||
data.recentRuns.Add(Entry());
|
||||
data.recentRuns.Add(new RunHistoryEntry { runId = "old-run", distroId = "gentoo", seed = 0 });
|
||||
service.Save(data);
|
||||
var saved = service.Load();
|
||||
Assert.That(RunHistory.HasBuildSnapshot(saved.recentRuns[0]), Is.True);
|
||||
Assert.That(saved.recentRuns[0].build.startingDeckCardIds, Is.EqualTo(data.recentRuns[0].build.startingDeckCardIds));
|
||||
Assert.That(saved.recentRuns[0].build.packages[0].upgradeLevel, Is.EqualTo(1));
|
||||
Assert.That(RunHistory.HasBuildSnapshot(saved.recentRuns[1]), Is.False);
|
||||
Assert.That(saved.recentRuns[1].seed, Is.Zero);
|
||||
}
|
||||
finally { Directory.Delete(directory, true); }
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LoadResolutionUsesCurrentOwnershipAndClearlyReportsVersionDifferences()
|
||||
{
|
||||
var entry = Entry();
|
||||
string original = JsonUtility.ToJson(entry);
|
||||
Assert.That(Resolve(entry, out var resolved, out string reason), Is.True, reason);
|
||||
Assert.That(resolved.Notice, Does.Contain("archived V2 -> owned V5"));
|
||||
Assert.That(resolved.Notice, Does.Contain("archived +1 -> owned +5"));
|
||||
Assert.That(resolved.CardIds, Is.EqualTo(entry.build.exclusiveCardIds));
|
||||
Assert.That(resolved.Languages, Is.EqualTo(entry.build.languages));
|
||||
Assert.That(resolved.Seed, Is.EqualTo(int.MinValue));
|
||||
Assert.That(resolved.PackageSlots.Single().packageId, Is.EqualTo(_package.Id));
|
||||
Assert.That(JsonUtility.ToJson(entry), Is.EqualTo(original), "Inspecting/loading must not rewrite history.");
|
||||
}
|
||||
|
||||
[TestCase("legacy")]
|
||||
[TestCase("future")]
|
||||
[TestCase("distro")]
|
||||
[TestCase("exclusive")]
|
||||
[TestCase("duplicate card")]
|
||||
[TestCase("language")]
|
||||
[TestCase("deck")]
|
||||
[TestCase("package")]
|
||||
[TestCase("slot")]
|
||||
public void MissingOrMalformedBuildDataCannotLoadAPartialOrInventedBuild(string missing)
|
||||
{
|
||||
var entry = Entry();
|
||||
switch (missing)
|
||||
{
|
||||
case "legacy": entry.build = null; break;
|
||||
case "future": entry.build.schemaVersion = 7; break;
|
||||
case "distro": entry.build.distroId = "missing-distro"; break;
|
||||
case "exclusive": entry.build.exclusiveCardIds[0] = "missing-card"; break;
|
||||
case "duplicate card": entry.build.exclusiveCardIds[0] = entry.build.exclusiveCardIds[1]; break;
|
||||
case "language": entry.build.languages[0] = Language.TypeScript; break;
|
||||
case "deck": entry.build.startingDeckCardIds.Add("missing-card"); break;
|
||||
case "package": entry.build.packages[0].packageId = "missing-package"; break;
|
||||
case "slot": entry.build.packages[0].slot = (PackageSlot)99; break;
|
||||
}
|
||||
Assert.That(Resolve(entry, out var resolved, out string reason), Is.False);
|
||||
Assert.That(resolved, Is.Null);
|
||||
Assert.That(reason, Is.Not.Null.And.Not.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UnownedDistroOrPackageDoesNotLoadEvenIfContentExists()
|
||||
{
|
||||
var entry = Entry();
|
||||
_collection = new PlayerCollection();
|
||||
Assert.That(Resolve(entry, out _, out string reason), Is.False);
|
||||
Assert.That(reason, Does.Contain("not currently owned"));
|
||||
_collection.AddSilently(_distro, 1);
|
||||
Assert.That(Resolve(entry, out _, out reason), Is.False);
|
||||
Assert.That(reason, Does.Contain("not owned"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LegacyViewExplainsMissingSnapshotAndRetainsSeedCopy()
|
||||
{
|
||||
var entry = new RunHistoryEntry { runId = "old-run", seed = 0 };
|
||||
var view = RunHistoryView.Build(new[] { entry }, () => { });
|
||||
Assert.That(view.Query<Label>().ToList().Any(label => label.text.Contains("Build snapshot unavailable")), Is.True);
|
||||
Assert.That(view.Q<Button>("LoadArchivedBuild_0").enabledSelf, Is.False);
|
||||
Assert.That(view.Q<Button>("CopyRunSeed_0").enabledSelf, Is.True);
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator OriginalBuildFoldoutLabelsWrapAtNarrowAndDesktopWidths()
|
||||
{
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
var previousText = UIPreferences.TextSize;
|
||||
try
|
||||
{
|
||||
window.Show();
|
||||
var root = window.rootVisualElement;
|
||||
root.styleSheets.Add(AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/UI/MainMenu.uss"));
|
||||
typeof(MainMenuController).Assembly.GetType("KernelPanic.UI.TerminalTheme")
|
||||
.GetMethod("Attach").Invoke(null, new object[] { root });
|
||||
foreach (float width in new[] { 312f, 1093f })
|
||||
foreach (var textSize in new[] { UITextSize.Standard, UITextSize.Large })
|
||||
{
|
||||
root.Clear();
|
||||
root.style.width = width;
|
||||
root.style.height = 675;
|
||||
UIPreferences.TextSize = textSize;
|
||||
var view = RunHistoryView.Build(new[] { Entry() }, () => { }, _cards, _packages, _ => { }, _ => null);
|
||||
root.Add(view);
|
||||
view.Query<Foldout>().ForEach(foldout => foldout.value = true);
|
||||
for (int frame = 0; frame < 6; frame++) yield return null;
|
||||
foreach (var label in view.Query<Label>(className: "unity-foldout__text").ToList())
|
||||
{
|
||||
var measured = label.MeasureTextSize(label.text, label.contentRect.width,
|
||||
VisualElement.MeasureMode.AtMost, 0, VisualElement.MeasureMode.Undefined);
|
||||
Assert.That(measured.y, Is.LessThanOrEqualTo(label.contentRect.height + 1),
|
||||
$"{width}, {textSize}: {label.text}");
|
||||
Assert.That(label.worldBound.xMax, Is.LessThanOrEqualTo(view.worldBound.xMax + 1));
|
||||
}
|
||||
var close = view.Q<Button>("CloseRunHistory");
|
||||
Assert.That(close.worldBound.yMax, Is.LessThanOrEqualTo(root.worldBound.yMax + 1));
|
||||
}
|
||||
}
|
||||
finally { UIPreferences.TextSize = previousText; window.Close(); }
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BuildViewShowsReadableCardPackageNamesAndUnavailableReason()
|
||||
{
|
||||
var entry = Entry();
|
||||
var view = RunHistoryView.Build(new[] { entry }, () => { }, _cards, _packages, _ => { }, _ => "Package ownership changed.");
|
||||
string labels = string.Join("\n", view.Query<Label>().ToList().Select(label => label.text));
|
||||
Assert.That(labels, Does.Contain(_cards.FindById(entry.build.exclusiveCardIds[0]).DisplayName));
|
||||
Assert.That(labels, Does.Contain(_package.DisplayName + " +1"));
|
||||
Assert.That(labels, Does.Contain("Original distro: " + _distro.DisplayName + " V2"));
|
||||
Assert.That(labels, Does.Contain("Package ownership changed."));
|
||||
Assert.That(view.Q<Button>("LoadArchivedBuild_0").enabledSelf, Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LoadingArchiveBuildChangesSetupOnlyAndPreservesCheckpointAndRetry()
|
||||
{
|
||||
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
string directory = Path.Combine(Path.GetTempPath(), "KernelPanic.ArchiveMenu." + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(directory);
|
||||
var owner = new GameObject("archive setup regression");
|
||||
owner.SetActive(false);
|
||||
var menu = owner.AddComponent<MainMenuController>();
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
try
|
||||
{
|
||||
void Set(string field, object value) => typeof(MainMenuController).GetField(field, flags).SetValue(menu, value);
|
||||
object Get(string field) => typeof(MainMenuController).GetField(field, flags).GetValue(menu);
|
||||
object Call(string method, params object[] args) => typeof(MainMenuController).GetMethod(method, flags).Invoke(menu, args);
|
||||
var root = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/MainMenu.uxml").CloneTree();
|
||||
window.Show();
|
||||
window.rootVisualElement.Add(root);
|
||||
Set("_root", root);
|
||||
Set("_shellRoot", root.Q("ShellRoot"));
|
||||
foreach (string name in new[] { "MainMenuPanel", "CollectionPanel", "RunSetupPanel", "GachaPanel", "SettingsPanel", "RunArchivePanel", "EventBanner", "MotdBlock", "RunSetupDetail" })
|
||||
Set("_" + char.ToLowerInvariant(name[0]) + name.Substring(1), root.Q(name));
|
||||
Set("_runSetupList", root.Q<ScrollView>("RunSetupList"));
|
||||
Set("distroDatabase", _distros); Set("cardDatabase", _cards);
|
||||
Set("packageDatabase", _packages); Set("languageDeckDatabase", _languages);
|
||||
Call("ComposeMetaServices");
|
||||
var service = new SaveService(Path.Combine(directory, "save.json"));
|
||||
Set("_saveService", service);
|
||||
var collection = (PlayerCollection)Get("_playerCollection");
|
||||
collection.AddSilently(_distro, 5);
|
||||
collection.AddPackageSilently(_package, 5);
|
||||
var data = SaveData.CreateDefault();
|
||||
data.lastRunLoadout.distroId = "do-not-change-retry";
|
||||
data.activeRun = new RunCheckpoint { runId = "keep-checkpoint", distroId = "gentoo", wave = 4 };
|
||||
Set("_saveData", data);
|
||||
string checkpoint = JsonUtility.ToJson(data.activeRun);
|
||||
string retry = JsonUtility.ToJson(data.lastRunLoadout);
|
||||
bool hadPendingRun = RunContext.HasPendingRun;
|
||||
var entry = Entry();
|
||||
Call("LoadArchivedBuildIntoSetup", entry);
|
||||
Assert.That(Get("_activeScreen").ToString(), Is.EqualTo("RunSetup"));
|
||||
Assert.That(Get("_runLaunchPending"), Is.False);
|
||||
Assert.That(RunContext.HasPendingRun, Is.EqualTo(hadPendingRun));
|
||||
Assert.That(Get("_runSeedText"), Is.EqualTo(int.MinValue.ToString(System.Globalization.CultureInfo.InvariantCulture)));
|
||||
Assert.That(((CardLoadout)Get("_cardLoadout")).GetEquippedCardIds(_distro.Id), Is.EqualTo(entry.build.exclusiveCardIds));
|
||||
Assert.That(((PackageLoadout)Get("_packageLoadout")).GetEquippedPackageInstances(_distro.Id).Single().UpgradeLevel, Is.EqualTo(5));
|
||||
Assert.That((List<Language>)Get("_selectedRunLanguages"), Is.EqualTo(entry.build.languages));
|
||||
Assert.That(root.Q<Label>("RunSetupNotice").text, Does.Contain("archived V2 -> owned V5"));
|
||||
var saved = service.Load();
|
||||
Assert.That(JsonUtility.ToJson(saved.activeRun), Is.EqualTo(checkpoint));
|
||||
Assert.That(JsonUtility.ToJson(saved.lastRunLoadout), Is.EqualTo(retry));
|
||||
Assert.That(saved.runBuildDrafts.Single(draft => draft.distroId == _distro.Id).cardIds, Is.EqualTo(entry.build.exclusiveCardIds));
|
||||
}
|
||||
finally
|
||||
{
|
||||
window.Close();
|
||||
UnityEngine.Object.DestroyImmediate(owner);
|
||||
Directory.Delete(directory, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8f5db2edbf65426f8266470b7207855b
|
||||
@@ -0,0 +1,361 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Meta;
|
||||
using KernelPanic.Run;
|
||||
using NUnit.Framework;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
public class RunCheckpointTests
|
||||
{
|
||||
private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
private const BindingFlags Static = BindingFlags.Static | BindingFlags.NonPublic;
|
||||
private GameObject _owner;
|
||||
private RunManager _run;
|
||||
private CombatManager _combat;
|
||||
private DistroDatabase _distros;
|
||||
private CardDatabase _cards;
|
||||
private LanguageDeckDatabase _languages;
|
||||
private PackageDatabase _packages;
|
||||
private SaveService _saves;
|
||||
private string _directory;
|
||||
private object _oldRandom, _oldSeed, _oldDraws, _oldPendingRun, _oldPendingResume, _oldLastSeed;
|
||||
private UnityEngine.Random.State _oldUnityRandom;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_oldRandom = StaticField(typeof(RandomRoll), "_random").GetValue(null);
|
||||
_oldSeed = StaticField(typeof(RandomRoll), "<CurrentSeed>k__BackingField").GetValue(null);
|
||||
_oldDraws = StaticField(typeof(RandomRoll), "<DrawCount>k__BackingField").GetValue(null);
|
||||
_oldUnityRandom = UnityEngine.Random.state;
|
||||
_oldPendingRun = StaticField(typeof(RunContext), "_pendingRun").GetValue(null);
|
||||
_oldPendingResume = StaticField(typeof(RunContext), "_pendingResume").GetValue(null);
|
||||
_oldLastSeed = StaticField(typeof(RunContext), "<LastRunSeed>k__BackingField").GetValue(null);
|
||||
_directory = Path.Combine(Path.GetTempPath(), "KernelPanic.CheckpointTests." + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(_directory);
|
||||
_saves = new SaveService(Path.Combine(_directory, "progress.json"));
|
||||
_distros = AssetDatabase.LoadAssetAtPath<DistroDatabase>("Assets/Data/Distros/DistroDatabase.asset");
|
||||
_cards = AssetDatabase.LoadAssetAtPath<CardDatabase>("Assets/Data/Cards/CardDatabase.asset");
|
||||
_languages = AssetDatabase.LoadAssetAtPath<LanguageDeckDatabase>("Assets/Data/Cards/Languages/LanguageDeckDatabase.asset");
|
||||
_packages = AssetDatabase.LoadAssetAtPath<PackageDatabase>("Assets/Data/Packages/PackageDatabase.asset");
|
||||
_owner = new GameObject("isolated repository checkpoint test");
|
||||
_owner.SetActive(false);
|
||||
_run = _owner.AddComponent<RunManager>();
|
||||
_combat = _owner.AddComponent<CombatManager>();
|
||||
var distro = _distros.FindById("ubuntu");
|
||||
var starting = distro.ExclusiveCards.Where(card => card != null && !card.IsToken && !card.IsRunOnly).Take(4).ToArray();
|
||||
var config = new RunConfig(distro, Language.Python, Language.JavaScript, starting,
|
||||
new[] { new PackageInstance(_packages.FindById("pkg_fedora_dnf"), 3) }, -7712, 2);
|
||||
_run.StartRun(config); // No bound CombatManager: do not start Play-mode coroutines.
|
||||
Set(_combat, "_runManager", _run);
|
||||
Set(_combat, "_runConfig", config);
|
||||
Set(_combat, "_playerState", new CombatantState(_run.EffectiveMaxUptime(), _run.EffectiveRam(), _run.EffectiveMaxCycles())
|
||||
{ CurrentUptime = 21, Shield = 7, Cycles = 2 });
|
||||
Set(_combat, "_awaitingWaveContinue", true);
|
||||
Set(_run, "currentWaveNumber", 3);
|
||||
Set(_run, "_wavesCleared", 2);
|
||||
Set(_run, "_accruedBandwidth", 9);
|
||||
Set(_run, "_accruedEntropy", 2);
|
||||
_run.AddBits(1000);
|
||||
_run.GenerateRepositoryOffers(_cards, _languages);
|
||||
RandomRoll.Seed(config.RunSeed);
|
||||
for (int i = 0; i < 13; i++) RandomRoll.RollRange(0, 100, RollContext.None);
|
||||
var progress = SaveData.CreateDefault();
|
||||
progress.entropyBalance = 123;
|
||||
progress.bandwidthBalance = 456;
|
||||
progress.ownedUnits.Add(new OwnedUnitSaveEntry { id = distro.Id, version = 2 });
|
||||
_saves.Save(progress);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
if (_owner != null) UnityEngine.Object.DestroyImmediate(_owner);
|
||||
StaticField(typeof(RandomRoll), "_random").SetValue(null, _oldRandom);
|
||||
StaticField(typeof(RandomRoll), "<CurrentSeed>k__BackingField").SetValue(null, _oldSeed);
|
||||
StaticField(typeof(RandomRoll), "<DrawCount>k__BackingField").SetValue(null, _oldDraws);
|
||||
UnityEngine.Random.state = _oldUnityRandom;
|
||||
StaticField(typeof(RunContext), "_pendingRun").SetValue(null, _oldPendingRun);
|
||||
StaticField(typeof(RunContext), "_pendingResume").SetValue(null, _oldPendingResume);
|
||||
StaticField(typeof(RunContext), "<LastRunSeed>k__BackingField").SetValue(null, _oldLastSeed);
|
||||
if (Directory.Exists(_directory)) Directory.Delete(_directory, true);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SaveRoundTripPreservesUpgradesOffersTargetIdentityAndProgression()
|
||||
{
|
||||
CardInstance target = _run.RunDeck[0];
|
||||
target.ApplyMagnitudeUpgrade(4);
|
||||
target.ApplyDrawRider(1);
|
||||
target.ApplyCostUpgrade(-1);
|
||||
var offers = (List<RepositoryOffer>)Get(_run, "_repositoryOffers");
|
||||
offers.Clear();
|
||||
offers.Add(RepositoryOffer.CardUpgrade(target, CardUpgradeKind.MagnitudeUp, 3));
|
||||
var sold = RepositoryOffer.StatUpgrade(RunStatUpgradeKind.MaxCycles, 4);
|
||||
sold.MarkSold();
|
||||
offers.Add(sold);
|
||||
offers.Add(RepositoryOffer.NewCard(_run.RunDeck[1].Definition, 5));
|
||||
|
||||
RunCheckpointService.SaveAndSuspend(_saves, _run, _combat);
|
||||
Assert.That(_run.IsSuspended, Is.True);
|
||||
Assert.That(_run.RewardsSettled, Is.False, "Suspending banks no rewards.");
|
||||
SaveData saved = _saves.Load();
|
||||
Assert.That(saved.entropyBalance, Is.EqualTo(123));
|
||||
Assert.That(saved.bandwidthBalance, Is.EqualTo(456));
|
||||
Assert.That(saved.ownedUnits.Single().version, Is.EqualTo(2));
|
||||
var restored = Prepare();
|
||||
Assert.That(restored.Config.RunSeed, Is.EqualTo(-7712));
|
||||
Assert.That(restored.Config.DistroVersion, Is.EqualTo(2));
|
||||
Assert.That(restored.Config.EquippedPackages.Single().UpgradeLevel, Is.EqualTo(3));
|
||||
Assert.That(restored.Deck[0].InstanceId, Is.EqualTo(target.InstanceId));
|
||||
Assert.That(restored.Deck[0].MagnitudeBonus, Is.EqualTo(target.MagnitudeBonus));
|
||||
Assert.That(restored.Deck[0].DrawRider, Is.EqualTo(target.DrawRider));
|
||||
Assert.That(restored.Deck[0].PermanentCostDelta, Is.EqualTo(target.PermanentCostDelta));
|
||||
Assert.That(restored.Deck[0].UpgradeLevel, Is.EqualTo(target.UpgradeLevel));
|
||||
Assert.That(restored.Offers[0].TargetCard, Is.SameAs(restored.Deck[0]));
|
||||
Assert.That(restored.Offers[1].Sold, Is.True);
|
||||
Assert.That(restored.Snapshot.combat.uptime, Is.EqualTo(21));
|
||||
Assert.That(restored.Snapshot.combat.shield, Is.EqualTo(7));
|
||||
_run.RestoreCheckpoint(restored);
|
||||
Assert.That(_run.RunId, Is.EqualTo(saved.activeRun.runId));
|
||||
Assert.That(_run.CurrentWaveNumber, Is.EqualTo(3));
|
||||
Assert.That(_run.WavesCleared, Is.EqualTo(2));
|
||||
Assert.That(_run.Bits, Is.EqualTo(1000));
|
||||
Assert.That(_run.AccruedBandwidth, Is.EqualTo(9));
|
||||
Assert.That(_run.RepositoryVisitActive, Is.True);
|
||||
Assert.That(_run.IsSuspended, Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RewardChoiceSurvivesSuspendResumeAndCannotPayAgainAfterSecondResume()
|
||||
{
|
||||
_run.Journey.pendingRewardWave = 2;
|
||||
RunCheckpointService.SaveAndSuspend(_saves, _run, _combat);
|
||||
var resume = Prepare();
|
||||
_run.RestoreCheckpoint(resume);
|
||||
Assert.That(_run.BuildRewardPending, Is.True);
|
||||
Assert.That(_run.Journey.encounterRevision, Is.EqualTo(1));
|
||||
int bits = _run.Bits;
|
||||
Assert.That(_run.ClaimBuildReward(null, CardUpgradeKind.MagnitudeUp, true), Is.True);
|
||||
RunCheckpointService.SaveAndSuspend(_saves, _run, _combat);
|
||||
_run.RestoreCheckpoint(Prepare());
|
||||
Assert.That(_run.BuildRewardPending, Is.False);
|
||||
Assert.That(_run.ClaimBuildReward(null, CardUpgradeKind.MagnitudeUp, true), Is.False);
|
||||
Assert.That(_run.Bits, Is.EqualTo(bits + RunManager.BuildRewardBits));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RestoredRandomCursorsContinueTheSameShopAndCombatSequences()
|
||||
{
|
||||
RunCheckpointService.SaveAndSuspend(_saves, _run, _combat);
|
||||
var resume = Prepare();
|
||||
_run.RestoreCheckpoint(resume);
|
||||
int[] expectedCombat = Enumerable.Range(0, 40).Select(_ => RandomRoll.RollRange(-7, 81, RollContext.None)).ToArray();
|
||||
var expectedShops = new List<string>();
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
Assert.That(_run.RerollRepositoryOffers(_cards, _languages), Is.True);
|
||||
expectedShops.Add(ShopSignature(_run));
|
||||
}
|
||||
_run.RestoreCheckpoint(resume);
|
||||
_combat.RestoreBoundaryState(resume.Config, resume.Snapshot.combat);
|
||||
Assert.That(Enumerable.Range(0, 40).Select(_ => RandomRoll.RollRange(-7, 81, RollContext.None)), Is.EqualTo(expectedCombat));
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
Assert.That(_run.RerollRepositoryOffers(_cards, _languages), Is.True);
|
||||
Assert.That(ShopSignature(_run), Is.EqualTo(expectedShops[i]));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CombatBoundaryRestoreRetainsCarriedFlagsAndDelayedEffects()
|
||||
{
|
||||
Set(_combat, "_ubuntuEmptyHandRefillUsed", true);
|
||||
Set(_combat, "_fedoraCrashChance", 27.5f);
|
||||
Set(_combat, "_packageInterpreterQueueShieldTriggeredThisWave", true);
|
||||
Set(_combat, "_packageNativeDamageTriggeredThisWave", true);
|
||||
Set(_combat, "_javaCardsPlayedThisCombat", 6);
|
||||
Set(_combat, "_rawhideBonusCharges", 2);
|
||||
Set(_combat, "_queuedRepeatCharges", 4);
|
||||
Set(_combat, "_nextTurnCycleBonus", 3);
|
||||
_combat.ScheduleUpdateManagerRepeat(17);
|
||||
_combat.ScheduleTimeshiftRestore(31);
|
||||
RunCheckpointService.SaveAndSuspend(_saves, _run, _combat);
|
||||
var resume = Prepare();
|
||||
_run.RestoreCheckpoint(resume);
|
||||
_combat.RestoreBoundaryState(resume.Config, resume.Snapshot.combat);
|
||||
Assert.That(JsonUtility.ToJson(_combat.CaptureBoundaryState()), Is.EqualTo(JsonUtility.ToJson(resume.Snapshot.combat)));
|
||||
Assert.That(_combat.AwaitingWaveContinue, Is.True);
|
||||
Assert.That(_combat.RunLost, Is.False);
|
||||
Assert.That(_combat.PlayerState.CurrentUptime, Is.EqualTo(21));
|
||||
Assert.That(_combat.PlayerState.Shield, Is.EqualTo(7));
|
||||
Assert.That(_combat.PlayerState.Cycles, Is.EqualTo(2));
|
||||
Assert.That(_combat.RunConfig.RunSeed, Is.EqualTo(-7712));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FailedCheckpointWriteKeepsRunActiveAndExistingSaveUnchanged()
|
||||
{
|
||||
byte[] before = File.ReadAllBytes(_saves.SavePath);
|
||||
Directory.CreateDirectory(_saves.BackupPath);
|
||||
Exception failure = Assert.Catch(() => RunCheckpointService.SaveAndSuspend(_saves, _run, _combat));
|
||||
Assert.That(failure, Is.InstanceOf<IOException>().Or.InstanceOf<UnauthorizedAccessException>());
|
||||
Assert.That(_run.IsSuspended, Is.False);
|
||||
Assert.That(_run.IsRunActive, Is.True);
|
||||
Assert.That(_run.RewardsSettled, Is.False);
|
||||
Assert.That(File.ReadAllBytes(_saves.SavePath), Is.EqualTo(before));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ConsumingCheckpointIsSingleUseAndDoesNotGrantCurrency()
|
||||
{
|
||||
RunCheckpointService.SaveAndSuspend(_saves, _run, _combat);
|
||||
var resume = Prepare();
|
||||
RunCheckpointService.Consume(_saves, resume);
|
||||
byte[] claimed = File.ReadAllBytes(_saves.SavePath);
|
||||
var data = _saves.Load();
|
||||
Assert.That(data.activeRun, Is.Null);
|
||||
Assert.That(data.entropyBalance, Is.EqualTo(123));
|
||||
Assert.That(data.bandwidthBalance, Is.EqualTo(456));
|
||||
Assert.Throws<InvalidDataException>(() => RunCheckpointService.Consume(_saves, resume));
|
||||
Assert.That(File.ReadAllBytes(_saves.SavePath), Is.EqualTo(claimed));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void StaleResumeCannotConsumeANewerCheckpoint()
|
||||
{
|
||||
RunCheckpointService.SaveAndSuspend(_saves, _run, _combat);
|
||||
var old = Prepare();
|
||||
var data = _saves.Load();
|
||||
data.activeRun.savedUtc = DateTime.UtcNow.AddDays(1).ToString("O");
|
||||
_saves.Save(data);
|
||||
byte[] newer = File.ReadAllBytes(_saves.SavePath);
|
||||
Assert.Throws<InvalidDataException>(() => RunCheckpointService.Consume(_saves, old));
|
||||
Assert.That(File.ReadAllBytes(_saves.SavePath), Is.EqualTo(newer));
|
||||
}
|
||||
|
||||
[TestCase("card")]
|
||||
[TestCase("distro")]
|
||||
[TestCase("duplicate-card")]
|
||||
[TestCase("negative-balance")]
|
||||
[TestCase("future-version")]
|
||||
[TestCase("random-cursor")]
|
||||
public void MalformedOrMissingContentLeavesCheckpointUntouched(string damage)
|
||||
{
|
||||
RunCheckpointService.SaveAndSuspend(_saves, _run, _combat);
|
||||
SaveData data = _saves.Load();
|
||||
switch (damage)
|
||||
{
|
||||
case "card": data.activeRun.deck[0].cardId = "removed-card"; break;
|
||||
case "distro": data.activeRun.distroId = "removed-distro"; break;
|
||||
case "duplicate-card": data.activeRun.deck[1].instanceId = data.activeRun.deck[0].instanceId; break;
|
||||
case "negative-balance": data.activeRun.bits = -1; break;
|
||||
case "future-version": data.activeRun.version = 999; break;
|
||||
case "random-cursor": data.activeRun.combat.randomDraws = -1; break;
|
||||
}
|
||||
_saves.Save(data);
|
||||
byte[] original = File.ReadAllBytes(_saves.SavePath);
|
||||
Assert.Throws<InvalidDataException>(() => Prepare());
|
||||
Assert.That(File.ReadAllBytes(_saves.SavePath), Is.EqualTo(original));
|
||||
}
|
||||
|
||||
[TestCase("combat-running")]
|
||||
[TestCase("not-in-repository")]
|
||||
[TestCase("lost")]
|
||||
[TestCase("already-settled")]
|
||||
public void OnlyAnUnsettledLivingRepositoryBoundaryCanBeSaved(string state)
|
||||
{
|
||||
switch (state)
|
||||
{
|
||||
case "combat-running": Set(_combat, "_awaitingWaveContinue", false); break;
|
||||
case "not-in-repository": Set(_run, "_repositoryVisitActive", false); break;
|
||||
case "lost": Set(_combat, "_runLost", true); break;
|
||||
case "already-settled": _run.MarkRunRewardsSettled(); break;
|
||||
}
|
||||
byte[] before = File.ReadAllBytes(_saves.SavePath);
|
||||
Assert.Throws<InvalidDataException>(() => RunCheckpointService.SaveAndSuspend(_saves, _run, _combat));
|
||||
Assert.That(_run.IsSuspended, Is.False);
|
||||
Assert.That(File.ReadAllBytes(_saves.SavePath), Is.EqualTo(before));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ResumeSceneHandoffIsConsumedOnce()
|
||||
{
|
||||
RunCheckpointService.SaveAndSuspend(_saves, _run, _combat);
|
||||
var resume = Prepare();
|
||||
RunContext.SetResume(resume);
|
||||
Assert.That(RunContext.HasPendingRun, Is.True);
|
||||
Assert.That(RunContext.TryTakeResume(out var handoff), Is.True);
|
||||
Assert.That(handoff, Is.SameAs(resume));
|
||||
Assert.That(RunContext.TryTakeResume(out _), Is.False);
|
||||
Assert.That(RunContext.HasPendingRun, Is.False);
|
||||
}
|
||||
|
||||
private ResolvedRunCheckpoint Prepare() => RunCheckpointService.PrepareResume(_saves, _distros, _cards, _languages, _packages);
|
||||
|
||||
[Test]
|
||||
public void CheckpointPreservesRouteChoiceWithoutGrantingRepairOrChallengeTwice()
|
||||
{
|
||||
Assert.That(_run.SelectRoute(WaveRoute.Challenge), Is.True);
|
||||
RunCheckpointService.SaveAndSuspend(_saves, _run, _combat);
|
||||
var restored = Prepare();
|
||||
Assert.That(restored.Snapshot.version, Is.EqualTo(3));
|
||||
_run.RestoreCheckpoint(restored);
|
||||
_combat.RestoreBoundaryState(restored.Config, restored.Snapshot.combat);
|
||||
Assert.That(_run.Journey.campaign, Is.True);
|
||||
Assert.That(_run.Journey.selectedRoute, Is.EqualTo(WaveRoute.Challenge));
|
||||
Assert.That(_combat.PlayerState.CurrentUptime, Is.EqualTo(21));
|
||||
_run.PrepareNextEncounter(_combat.PlayerState);
|
||||
Assert.That(_run.Journey.activeRoute, Is.EqualTo(WaveRoute.Challenge));
|
||||
Assert.That(_run.Bits, Is.EqualTo(1000));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LegacyCheckpointKeepsEndlessRules()
|
||||
{
|
||||
var snapshot = _run.CaptureCheckpoint(_combat);
|
||||
snapshot.version = 1; snapshot.journey = null;
|
||||
var restored = snapshot.Resolve(_distros, _cards, _languages, _packages);
|
||||
_run.RestoreCheckpoint(restored);
|
||||
Assert.That(_run.Journey.campaign, Is.False);
|
||||
Assert.That(_run.CampaignChoicePending, Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BossMilestoneSurvivesSaveAndResumeWithoutStartingEndless()
|
||||
{
|
||||
Set(_run, "currentWaveNumber", 6);
|
||||
Set(_run, "_wavesCleared", 5);
|
||||
RunCheckpointService.SaveAndSuspend(_saves, _run, _combat);
|
||||
var restored = Prepare();
|
||||
_run.RestoreCheckpoint(restored);
|
||||
_combat.RestoreBoundaryState(restored.Config, restored.Snapshot.combat);
|
||||
Assert.That(_run.CampaignChoicePending, Is.True);
|
||||
Assert.That(_run.Journey.endless, Is.False);
|
||||
Assert.That(_run.EnterEndless(), Is.True);
|
||||
RunCheckpointService.SaveAndSuspend(_saves, _run, _combat);
|
||||
_run.RestoreCheckpoint(Prepare());
|
||||
Assert.That(_run.Journey.endless, Is.True);
|
||||
Assert.That(_run.CampaignChoicePending, Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InvalidSavedRouteCannotBeResumed()
|
||||
{
|
||||
var snapshot = _run.CaptureCheckpoint(_combat);
|
||||
snapshot.journey.selectedRoute = (WaveRoute)999;
|
||||
Assert.Throws<InvalidDataException>(() => snapshot.Resolve(_distros, _cards, _languages, _packages));
|
||||
}
|
||||
private static string ShopSignature(RunManager run) => string.Join(";", run.RepositoryOffers.Select(offer =>
|
||||
$"{offer.Kind}:{offer.CardDefinition?.Id}:{offer.TargetCard?.InstanceId}:{offer.CardUpgradeKind}:{offer.StatUpgradeKind}:{offer.Price}:{offer.Sold}"));
|
||||
private static FieldInfo StaticField(Type type, string field) => type.GetField(field, Static);
|
||||
private static void Set(object instance, string field, object value) => instance.GetType().GetField(field, Private).SetValue(instance, value);
|
||||
private static object Get(object instance, string field) => instance.GetType().GetField(field, Private).GetValue(instance);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2434778c73064fb48bde80c3d1c125f6
|
||||
@@ -0,0 +1,317 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Meta;
|
||||
using KernelPanic.UI;
|
||||
using NUnit.Framework;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
public class RunInsightTests
|
||||
{
|
||||
private CardDatabase Cards => AssetDatabase.LoadAssetAtPath<CardDatabase>("Assets/Data/Cards/CardDatabase.asset");
|
||||
|
||||
[Test]
|
||||
public void VictoryRecapRetainsTheCompletedRoundAfterWaveAdvance()
|
||||
{
|
||||
var player = new CombatantState(50, 6, 3);
|
||||
using var telemetry = new CombatRunTelemetry(() => player, _ => "boss");
|
||||
telemetry.BeginRound(); telemetry.BeginRound(); telemetry.BeginRound();
|
||||
GameEvents.RaiseWaveAdvanced(new WaveAdvancedEvent(6));
|
||||
var report = new RunHistoryEntry();
|
||||
telemetry.FillReport(report);
|
||||
Assert.That(report.finalRound, Is.EqualTo(3));
|
||||
telemetry.BeginRound();
|
||||
telemetry.FillReport(report);
|
||||
Assert.That(report.finalRound, Is.EqualTo(1), "An endless wave starts its own round count.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PileInventorySortsCopyWithoutChangingDeckOrRandomState()
|
||||
{
|
||||
var cards = Cards.AllCards.Where(card => card != null).Take(12).Select(card => new CardInstance(card)).ToArray();
|
||||
var deck = new DeckController();
|
||||
deck.Initialize(cards);
|
||||
var original = deck.DrawPile.ToArray();
|
||||
var random = UnityEngine.Random.state;
|
||||
var inventory = CardPileView.FilterAndSort(deck.DrawPile, null);
|
||||
CollectionAssert.AreEqual(original, deck.DrawPile);
|
||||
CollectionAssert.AreEquivalent(original, inventory);
|
||||
CollectionAssert.AreEqual(inventory.Select(card => card.Definition.DisplayName).OrderBy(name => name, StringComparer.OrdinalIgnoreCase),
|
||||
inventory.Select(card => card.Definition.DisplayName));
|
||||
Assert.That(UnityEngine.Random.state, Is.EqualTo(random));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PileInventorySortsUpgradeVariantsAndSearchesPatchAndLanguage()
|
||||
{
|
||||
var definition = Cards.AllCards.First(card => card != null && card.CycleCost > 0);
|
||||
var plain = new CardInstance(definition);
|
||||
var patched = new CardInstance(definition);
|
||||
patched.ApplyMagnitudeUpgrade(3);
|
||||
var cards = new[] { patched, plain };
|
||||
CollectionAssert.AreEqual(new[] { plain, patched }, CardPileView.FilterAndSort(cards, ""));
|
||||
CollectionAssert.AreEqual(new[] { patched }, CardPileView.FilterAndSort(cards, "upgraded"));
|
||||
Assert.That(CardPileView.FilterAndSort(cards, definition.Language.ToString()).Count, Is.EqualTo(2));
|
||||
Assert.That(CardPileView.FilterAndSort(cards, "DOES-NOT-EXIST"), Is.Empty);
|
||||
}
|
||||
|
||||
[TestCase("draw")]
|
||||
[TestCase("discard")]
|
||||
[TestCase("exhaust")]
|
||||
public void PileViewShowsFullRulesAndUpgradesWithoutPlayableButtons(string pile)
|
||||
{
|
||||
var card = new CardInstance(Cards.AllCards.First(definition => definition != null));
|
||||
card.ApplyMagnitudeUpgrade(2);
|
||||
card.ApplyDrawRider(1);
|
||||
var view = CardPileView.Build(pile, new[] { card }, () => { });
|
||||
Assert.That(view.Query<Button>().ToList().Select(button => button.name),
|
||||
Is.EquivalentTo(new[] { "ClearPileSearch", "ResetPileFilters", "ClosePileInspector" }));
|
||||
Assert.That(view.Q<Label>(className: "pile-title").text, Is.EqualTo(pile.ToUpperInvariant() + " PILE"));
|
||||
Assert.That(view.Q<Label>("PileCount").text, Is.EqualTo("1 card"));
|
||||
Assert.That(view.Q<Label>(className: "pile-upgrades").text, Does.Contain("magnitude +2"));
|
||||
Assert.That(view.Q<Label>(className: "software-name").text, Is.EqualTo(card.Definition.DisplayName));
|
||||
Assert.That(view.Q<TextField>("PileSearch"), Is.Not.Null);
|
||||
var grid = view.Q("PileCardGrid");
|
||||
Assert.That(grid, Is.Not.Null);
|
||||
Assert.That(view.Q<ScrollView>("PileCards").contentContainer.Contains(grid), Is.True);
|
||||
Assert.That(grid.Query(className: "pile-card").ToList(), Has.Count.EqualTo(1));
|
||||
string inlineRules = string.Join(" ", grid.Q(className: "software-body").Query<Label>().ToList().Select(label => label.text));
|
||||
Assert.That(inlineRules, Is.EqualTo(CardEffectFactory.GetRulesText(card) + " Draw 1."),
|
||||
"Reading full rules must not require hover or playing a card.");
|
||||
// TextField change callbacks are dispatched by an attached panel. The viewport/focus
|
||||
// regression test exercises real search edits; this detached test checks static content.
|
||||
}
|
||||
|
||||
[TestCase("upgrade")]
|
||||
[TestCase("cost")]
|
||||
[TestCase("temporary")]
|
||||
[TestCase("draw")]
|
||||
[TestCase("broken")]
|
||||
[TestCase("recovery")]
|
||||
[TestCase("locked")]
|
||||
[TestCase("estimate")]
|
||||
public void GroupedCopiesKeepGameplayVariantsSeparate(string variant)
|
||||
{
|
||||
var definition = Cards.AllCards.First(card => card != null && card.CycleCost > 0);
|
||||
var first = new CardInstance(definition);
|
||||
var duplicate = new CardInstance(definition);
|
||||
var different = new CardInstance(definition);
|
||||
switch (variant)
|
||||
{
|
||||
case "upgrade": different.ApplyMagnitudeUpgrade(2); break;
|
||||
case "cost": different.ApplyCostUpgrade(-1); break;
|
||||
case "temporary": different.TemporaryCostDelta = -1; break;
|
||||
case "draw": different.ApplyDrawRider(1); break;
|
||||
case "broken": different.IsBroken = true; break;
|
||||
case "recovery": first.CorruptForRounds(1, 1); duplicate.CorruptForRounds(1, 1); different.CorruptForRounds(2, 1); break;
|
||||
case "locked": different.IsLocked = true; break;
|
||||
}
|
||||
var original = new[] { first, different, duplicate };
|
||||
var groups = CardPileView.GroupIdenticalCopies(original,
|
||||
card => variant == "estimate" && card == different ? "different current estimate" : "same estimate");
|
||||
Assert.That(groups.Count, Is.EqualTo(2));
|
||||
Assert.That(groups.Single(group => group.Length == 2), Is.EqualTo(new[] { first, duplicate }));
|
||||
Assert.That(groups.Single(group => group.Length == 1).Single(), Is.SameAs(different));
|
||||
Assert.That(original, Is.EqualTo(new[] { first, different, duplicate }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PileMetadataKeepsRamButOmitsZeroValueUpgradeNoise()
|
||||
{
|
||||
var card = new CardInstance(Cards.AllCards.First(definition => definition != null));
|
||||
var view = CardPileView.Build("draw", new[] { card }, () => { });
|
||||
Assert.That(view.Q<Label>(className: "pile-upgrades").text,
|
||||
Is.EqualTo($"RAM {HandController.GetRamCost(card)}"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PileMetadataIncludesPermanentAndTemporaryChangesWithoutChangingTheCard()
|
||||
{
|
||||
var card = new CardInstance(Cards.AllCards.First(definition => definition != null && definition.CycleCost > 0));
|
||||
card.ApplyCostUpgrade(-1);
|
||||
card.ApplyMagnitudeUpgrade(2);
|
||||
card.ApplyDrawRider(1);
|
||||
card.TemporaryCostDelta = 3;
|
||||
var view = CardPileView.Build("discard", new[] { card }, () => { });
|
||||
string metadata = view.Q<Label>(className: "pile-upgrades").text;
|
||||
Assert.That(metadata, Does.StartWith($"RAM {HandController.GetRamCost(card)}"));
|
||||
Assert.That(metadata, Does.Contain("Patch 3"));
|
||||
Assert.That(metadata, Does.Contain("cost adjustment -1"));
|
||||
Assert.That(metadata, Does.Contain("magnitude +2"));
|
||||
Assert.That(metadata, Does.Contain("draw +1"));
|
||||
Assert.That(metadata.ToLowerInvariant(), Does.Contain("temp"));
|
||||
Assert.That(metadata, Does.Contain("+3"));
|
||||
Assert.That(metadata, Does.Not.Contain("+0"));
|
||||
Assert.That(card.PermanentCostDelta, Is.EqualTo(-1));
|
||||
Assert.That(card.TemporaryCostDelta, Is.EqualTo(3));
|
||||
Assert.That(card.UpgradeLevel, Is.EqualTo(3));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PileCardsRetainCorruptionAndLockedStateBadges()
|
||||
{
|
||||
var definition = Cards.AllCards.First(card => card != null);
|
||||
var corrupted = new CardInstance(definition);
|
||||
corrupted.CorruptForRounds(2, 1);
|
||||
var locked = new CardInstance(definition) { IsLocked = true };
|
||||
var view = CardPileView.Build("exhaust", new[] { corrupted, locked }, () => { });
|
||||
Assert.That(view.Q(className: "software-corrupted").Q<Label>(className: "software-state").text,
|
||||
Does.Contain("RECOVER 2 ROUNDS"));
|
||||
Assert.That(view.Q(className: "software-corrupted").Q<Label>(className: "pile-status-detail").text,
|
||||
Is.EqualTo(CardPreviewService.CorruptionDetails(corrupted)),
|
||||
"Corruption's full explanation must remain available inline without a duplicate hover tooltip.");
|
||||
Assert.That(view.Q(className: "software-locked").Q<Label>(className: "software-state").text,
|
||||
Does.Contain("UNLOCK"));
|
||||
Assert.That(corrupted.CorruptionRoundsRemaining, Is.EqualTo(2));
|
||||
Assert.That(locked.IsLocked, Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FinalRoundTracksActualUptimeAndShieldDamageAndKillingAction()
|
||||
{
|
||||
var player = new CombatantState(10, 5, 3) { Shield = 5 };
|
||||
var enemy = new CombatantState(30, 0, 0);
|
||||
using var telemetry = new CombatRunTelemetry(() => player, _ => "fallback enemy");
|
||||
telemetry.BeginRound();
|
||||
var pipeline = new DamagePipeline();
|
||||
pipeline.DealDamage(new DamageRequest(player, enemy, 4, Language.C, false, false));
|
||||
pipeline.DealDamage(new DamageRequest(enemy, player, 7, Language.C, false, false).WithCause("zombie: bite"));
|
||||
pipeline.DealDamage(new DamageRequest(enemy, player, 12, Language.C, false, false).WithCause("daemon: overload"));
|
||||
Assert.That(telemetry.DamageDealt, Is.EqualTo(4));
|
||||
Assert.That(telemetry.DamageTaken, Is.EqualTo(10), "Report actual uptime lost, not overkill.");
|
||||
Assert.That(telemetry.ShieldBlocked, Is.EqualTo(5));
|
||||
Assert.That(telemetry.KillingAction, Does.Contain("daemon: overload: 8 uptime / 0 shield"));
|
||||
Assert.That(telemetry.IncomingHits, Has.Count.EqualTo(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MemoryLeakDeathUsesStatusCauseNotEnemiesNextIntent()
|
||||
{
|
||||
var player = new CombatantState(2, 5, 3);
|
||||
var enemy = new CombatantState(20, 0, 0);
|
||||
using var telemetry = new CombatRunTelemetry(() => player, _ => "incorrect future intent");
|
||||
var statuses = new StatusEffectController();
|
||||
statuses.Apply(player, StatusType.MemoryLeak, 3, -1, enemy);
|
||||
statuses.Tick(player, StatusTickTiming.StartOfTurn, player, new DamagePipeline());
|
||||
Assert.That(telemetry.KillingAction, Does.StartWith("Memory Leak status tick"));
|
||||
Assert.That(telemetry.DamageTaken, Is.EqualTo(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RecoveryDoesNotRecordKillAndNextRoundClearsPreviousDamage()
|
||||
{
|
||||
var player = new CombatantState(3, 5, 3) { ArchRollingReleaseSavesRemaining = 1 };
|
||||
using var telemetry = new CombatRunTelemetry(() => player, _ => "attack");
|
||||
telemetry.BeginRound();
|
||||
new DamagePipeline().DealDamage(new DamageRequest(null, player, 5, Language.C, false, false));
|
||||
Assert.That(player.CurrentUptime, Is.EqualTo(1));
|
||||
Assert.That(telemetry.KillingAction, Is.Null);
|
||||
GameEvents.RaisePhaseChanged(new PhaseChangedEvent(TurnPhase.GarbageCollection, TurnPhase.Allocate));
|
||||
Assert.That(telemetry.Round, Is.EqualTo(2));
|
||||
Assert.That(telemetry.DamageTaken, Is.Zero);
|
||||
Assert.That(telemetry.IncomingHits, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SurrenderDoesNotReportSyntheticShutdownAsCombatDamage()
|
||||
{
|
||||
var player = new CombatantState(50, 5, 3);
|
||||
using var telemetry = new CombatRunTelemetry(() => player, _ => "unknown");
|
||||
telemetry.MarkSurrender();
|
||||
new DamagePipeline().DefeatCombatant(player, null, Language.C);
|
||||
var entry = new RunHistoryEntry { surrendered = true };
|
||||
telemetry.FillReport(entry);
|
||||
Assert.That(entry.damageTaken, Is.Zero);
|
||||
Assert.That(entry.cause, Is.EqualTo("Shutdown signal accepted."));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CanonicalSurrenderFlagIgnoresDirectManagerShutdownDamage()
|
||||
{
|
||||
var player = new CombatantState(50, 5, 3);
|
||||
using var telemetry = new CombatRunTelemetry(() => player, _ => "unknown") { SurrenderRequested = () => true };
|
||||
new DamagePipeline().DefeatCombatant(player, null, Language.C);
|
||||
Assert.That(telemetry.DamageTaken, Is.Zero);
|
||||
Assert.That(telemetry.KillingAction, Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void IncomingHitListIsBoundedAndTrueDamageExplainsShieldBypass()
|
||||
{
|
||||
var player = new CombatantState(100, 5, 3) { Shield = 10 };
|
||||
using var telemetry = new CombatRunTelemetry(() => player, _ => "recoil");
|
||||
var pipeline = new DamagePipeline();
|
||||
for (int i = 0; i < 12; i++) pipeline.DealDamage(new DamageRequest(null, player, 1, Language.C, true, false));
|
||||
Assert.That(telemetry.IncomingHits, Has.Count.EqualTo(8));
|
||||
Assert.That(telemetry.IncomingHits.Last(), Does.Contain("bypasses shield"));
|
||||
Assert.That(telemetry.ShieldBlocked, Is.Zero);
|
||||
Assert.That(player.Shield, Is.EqualTo(10));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RunHistoryKeepsNewestTwentyAndRepeatedIdDoesNotDuplicate()
|
||||
{
|
||||
var entries = new List<RunHistoryEntry>();
|
||||
for (int i = 0; i < 25; i++) RunHistory.Record(entries, new RunHistoryEntry { runId = i.ToString(), waveReached = i });
|
||||
RunHistory.Record(entries, new RunHistoryEntry { runId = "24", waveReached = 30 });
|
||||
Assert.That(entries, Has.Count.EqualTo(RunHistory.Capacity));
|
||||
Assert.That(entries[0].waveReached, Is.EqualTo(30));
|
||||
Assert.That(entries.Last().runId, Is.EqualTo("5"));
|
||||
Assert.That(entries.Select(entry => entry.runId).Distinct().Count(), Is.EqualTo(RunHistory.Capacity));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RunHistoryNormalizationRepairsNullListsAndInvalidEntries()
|
||||
{
|
||||
var entries = new List<RunHistoryEntry>
|
||||
{
|
||||
null,
|
||||
new() { runId = "" },
|
||||
new() { runId = "a", finalHits = null, damageTaken = -4 },
|
||||
new() { runId = "a" }
|
||||
};
|
||||
RunHistory.Normalize(entries);
|
||||
Assert.That(entries, Has.Count.EqualTo(1));
|
||||
Assert.That(entries[0].finalHits, Is.Empty);
|
||||
Assert.That(entries[0].damageTaken, Is.Zero);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HistoryPersistsWithProgressionInOneSave()
|
||||
{
|
||||
string directory = Path.Combine(Path.GetTempPath(), "KernelPanic-HistoryTest-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(directory);
|
||||
try
|
||||
{
|
||||
var service = new SaveService(Path.Combine(directory, "progression.json"));
|
||||
var data = SaveData.CreateDefault();
|
||||
data.bandwidthBalance = 12;
|
||||
RunHistory.Record(data.recentRuns, new RunHistoryEntry
|
||||
{
|
||||
runId = "run-one", seed = -42, cause = "Memory Leak status tick", shieldBlocked = 8,
|
||||
finalHits = new List<string> { "tick: 2 uptime / 0 shield" }
|
||||
});
|
||||
service.Save(data);
|
||||
var saved = service.Load();
|
||||
Assert.That(saved.bandwidthBalance, Is.EqualTo(12));
|
||||
Assert.That(saved.recentRuns.Single().seed, Is.EqualTo(-42));
|
||||
Assert.That(saved.recentRuns.Single().finalHits.Single(), Does.StartWith("tick:"));
|
||||
}
|
||||
finally { Directory.Delete(directory, true); }
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EmptyHistoryViewOffersAnAccessibleCloseControl()
|
||||
{
|
||||
var view = RunHistoryView.Build(Array.Empty<RunHistoryEntry>(), () => { });
|
||||
Assert.That(view.name, Is.EqualTo("RunHistoryOverlay"));
|
||||
Assert.That(view.Q<Button>("CloseRunHistory"), Is.Not.Null);
|
||||
Assert.That(view.Query<Label>().ToList().Any(label => label.text.Contains("No completed runs")), Is.True);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b434642aa00dcf7d416a51a46e11852c
|
||||
@@ -0,0 +1,163 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Run;
|
||||
using NUnit.Framework;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
public class RunReproducibilityTests
|
||||
{
|
||||
private GameObject _owner;
|
||||
private RunManager _run;
|
||||
private CardDatabase _cards;
|
||||
private LanguageDeckDatabase _languages;
|
||||
private DistroDefinition _distro;
|
||||
private object _combatRandom;
|
||||
private UnityEngine.Random.State _unityRandom;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_combatRandom = typeof(RandomRoll).GetField("_random", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null);
|
||||
_unityRandom = UnityEngine.Random.state;
|
||||
_owner = new GameObject("seeded repository regression");
|
||||
_run = _owner.AddComponent<RunManager>();
|
||||
_cards = AssetDatabase.LoadAssetAtPath<CardDatabase>("Assets/Data/Cards/CardDatabase.asset");
|
||||
_languages = AssetDatabase.LoadAssetAtPath<LanguageDeckDatabase>("Assets/Data/Cards/Languages/LanguageDeckDatabase.asset");
|
||||
_distro = AssetDatabase.LoadAssetAtPath<DistroDefinition>("Assets/Data/Distros/Gentoo.asset");
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
UnityEngine.Object.DestroyImmediate(_owner);
|
||||
typeof(RandomRoll).GetField("_random", BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, _combatRandom);
|
||||
UnityEngine.Random.state = _unityRandom;
|
||||
}
|
||||
|
||||
[TestCase(0)]
|
||||
[TestCase(72531)]
|
||||
[TestCase(int.MinValue)]
|
||||
[TestCase(int.MaxValue)]
|
||||
public void SameSeedReplaysPurchasesRerollsAndLaterRepositoryVisits(int seed)
|
||||
{
|
||||
string expected = CaptureShopSequence(seed, false);
|
||||
string actual = CaptureShopSequence(seed, true);
|
||||
Assert.That(actual, Is.EqualTo(expected), "Combat rolls and unrelated Unity random calls must not change repository offers.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DifferentSeedsProduceDifferentRepositorySequences()
|
||||
{
|
||||
Assert.That(CaptureShopSequence(1001, false), Is.Not.EqualTo(CaptureShopSequence(1002, false)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ShopBrowsingDoesNotAdvanceCombatOrPresentationRandomness()
|
||||
{
|
||||
RandomRoll.Seed(47);
|
||||
int[] expected = Enumerable.Range(0, 12).Select(_ => RandomRoll.RollRange(1, 100, RollContext.None)).ToArray();
|
||||
RandomRoll.Seed(47);
|
||||
var unityState = UnityEngine.Random.state;
|
||||
CaptureShopSequence(47, false);
|
||||
Assert.That(UnityEngine.Random.state, Is.EqualTo(unityState));
|
||||
Assert.That(Enumerable.Range(0, 12).Select(_ => RandomRoll.RollRange(1, 100, RollContext.None)), Is.EqualTo(expected));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeckAndEnemyIntentsReplayDespiteExtraRepositoryBrowsing()
|
||||
{
|
||||
string Capture(bool browse)
|
||||
{
|
||||
_run.StartRun(Config(912));
|
||||
RandomRoll.Seed(912);
|
||||
var output = new List<string>();
|
||||
var enemy = new EnemyInstance(EnemyArchetypeCatalog.Get("zombie_process"), 20);
|
||||
for (int wave = 0; wave < 4; wave++)
|
||||
{
|
||||
if (browse) _run.GenerateRepositoryOffers(_cards, _languages);
|
||||
var deck = new DeckController();
|
||||
deck.Initialize(_run.RunDeck);
|
||||
output.Add(string.Join(",", deck.Draw(20).Select(card => card.Definition.Id)));
|
||||
for (int turn = 0; turn < 8; turn++)
|
||||
{
|
||||
enemy.PickNextIntent();
|
||||
output.Add(enemy.CurrentIntent.DisplayText);
|
||||
}
|
||||
}
|
||||
return string.Join("|", output);
|
||||
}
|
||||
Assert.That(Capture(true), Is.EqualTo(Capture(false)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ExplicitSeedSurvivesSceneHandoffIncludingZeroAndNegativeValues()
|
||||
{
|
||||
const BindingFlags flags = BindingFlags.Static | BindingFlags.NonPublic;
|
||||
FieldInfo pending = typeof(RunContext).GetField("_pendingRun", flags);
|
||||
FieldInfo last = typeof(RunContext).GetField("<LastRunSeed>k__BackingField", flags);
|
||||
object previousPending = pending.GetValue(null);
|
||||
object previousLast = last.GetValue(null);
|
||||
try
|
||||
{
|
||||
foreach (int seed in new[] { 0, int.MinValue, int.MaxValue, -17 })
|
||||
{
|
||||
RunContext.Set(_distro, Config(seed).StartingDeck, Array.Empty<PackageInstance>(), Language.C, Language.Haskell, 3, seed);
|
||||
Assert.That(RunContext.TryCreateRunConfig(_languages, out RunConfig config), Is.True);
|
||||
Assert.That(config.RunSeed, Is.EqualTo(seed));
|
||||
Assert.That(config.DistroVersion, Is.EqualTo(3));
|
||||
Assert.That(RunContext.LastRunSeed, Is.EqualTo(seed));
|
||||
Assert.That(RunContext.HasPendingRun, Is.False);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
pending.SetValue(null, previousPending);
|
||||
last.SetValue(null, previousLast);
|
||||
}
|
||||
}
|
||||
|
||||
private RunConfig Config(int seed) => new(_distro, Language.C, Language.Haskell,
|
||||
new[] { _cards.FindById("lang_c_malloc"), _cards.FindById("lang_c_printf"), _cards.FindById("lang_c_pointer") }, seed);
|
||||
|
||||
private string CaptureShopSequence(int seed, bool consumeUnrelatedRandom)
|
||||
{
|
||||
_run.StartRun(Config(seed));
|
||||
Assert.That(_run.RepositoryVisitActive, Is.False);
|
||||
Assert.That(_run.RepositoryOffers, Is.Empty, "Restarting a run clears the previous repository visit.");
|
||||
_run.AddBits(1000);
|
||||
var player = new CombatantState(50, 8, 4);
|
||||
var output = new List<string>();
|
||||
for (int visit = 0; visit < 4; visit++)
|
||||
{
|
||||
if (consumeUnrelatedRandom)
|
||||
{
|
||||
for (int i = 0; i < 31 + visit; i++)
|
||||
{
|
||||
RandomRoll.RollRange(0, 999, RollContext.None);
|
||||
UnityEngine.Random.Range(0, 999);
|
||||
}
|
||||
}
|
||||
_run.GenerateRepositoryOffers(_cards, _languages);
|
||||
for (int roll = 0; roll < 3; roll++)
|
||||
{
|
||||
Assert.That(_run.RepositoryOffers, Is.Not.Empty);
|
||||
output.Add(string.Join(";", _run.RepositoryOffers.Select(OfferSignature)));
|
||||
Assert.That(_run.BuyOffer(_run.RepositoryOffers[0], player), Is.True);
|
||||
Assert.That(_run.RerollRepositoryOffers(_cards, _languages), Is.True);
|
||||
}
|
||||
}
|
||||
return string.Join("|", output);
|
||||
}
|
||||
|
||||
private string OfferSignature(RepositoryOffer offer)
|
||||
{
|
||||
int targetIndex = offer.TargetCard == null ? -1 : _run.RunDeck.ToList().IndexOf(offer.TargetCard);
|
||||
return $"{offer.Kind}:{offer.CardDefinition?.Id}:{targetIndex}:{offer.CardUpgradeKind}:{offer.StatUpgradeKind}:{offer.Price}:{offer.Description}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 14143dbcc8ee40b8aeaa4b44531e1571
|
||||
@@ -0,0 +1,244 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using KernelPanic.Meta;
|
||||
using NUnit.Framework;
|
||||
using UnityEngine;
|
||||
using UnityEngine.TestTools;
|
||||
|
||||
public class SaveServiceTests
|
||||
{
|
||||
private string _directory;
|
||||
private SaveService _service;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_directory = Path.Combine(Path.GetTempPath(), "KernelPanic-SaveTests-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(_directory);
|
||||
_service = new SaveService(Path.Combine(_directory, "progression.json"));
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
if (Directory.Exists(_directory))
|
||||
{
|
||||
Directory.Delete(_directory, true);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SchemaOneEnvelopeUpgradesWithoutInventingCheckpointOrLosingProgression()
|
||||
{
|
||||
_service.Save(Progression(12));
|
||||
string oldEnvelope = File.ReadAllText(_service.SavePath)
|
||||
.Replace("\"schemaVersion\": " + SaveService.CurrentSchemaVersion, "\"schemaVersion\": 1");
|
||||
File.WriteAllText(_service.SavePath, oldEnvelope);
|
||||
SaveData loaded = _service.Load();
|
||||
Assert.That(loaded.entropyBalance, Is.EqualTo(12));
|
||||
Assert.That(loaded.activeRun, Is.Null);
|
||||
_service.Save(loaded);
|
||||
Assert.That(File.ReadAllText(_service.SavePath), Does.Contain("\"schemaVersion\": " + SaveService.CurrentSchemaVersion));
|
||||
Assert.That(_service.Load().activeRun, Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MissingSaveReturnsFreshProgressionWithoutWritingFiles()
|
||||
{
|
||||
SaveData loaded = _service.Load();
|
||||
Assert.That(loaded.starterChosen, Is.False);
|
||||
Assert.That(loaded.ownedUnits, Is.Empty);
|
||||
Assert.That(Directory.GetFiles(_directory), Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SaveRoundTripsProgressionAndKeepsPreviousSnapshotAsBackup()
|
||||
{
|
||||
SaveData data = Progression(12);
|
||||
_service.Save(data);
|
||||
string firstSnapshot = File.ReadAllText(_service.SavePath);
|
||||
data.entropyBalance = 29;
|
||||
data.ownedUnits[0].version = 4;
|
||||
_service.Save(data);
|
||||
|
||||
SaveData loaded = _service.Load();
|
||||
Assert.That(loaded.entropyBalance, Is.EqualTo(29));
|
||||
Assert.That(loaded.ownedUnits.Single().version, Is.EqualTo(4));
|
||||
Assert.That(loaded.ownedUnits.Single().merges, Is.EqualTo(120));
|
||||
Assert.That(loaded.GetBestWave("gentoo"), Is.EqualTo(7));
|
||||
Assert.That(File.ReadAllText(_service.BackupPath), Is.EqualTo(firstSnapshot));
|
||||
Assert.That(File.ReadAllText(_service.SavePath), Does.Contain("\"schemaVersion\": " + SaveService.CurrentSchemaVersion));
|
||||
Assert.That(Directory.GetFiles(_directory, "*.tmp.*"), Is.Empty);
|
||||
}
|
||||
|
||||
[TestCase("{\"starterChosen\":")]
|
||||
[TestCase("{}")]
|
||||
[TestCase("null")]
|
||||
[TestCase("")]
|
||||
public void CorruptPrimaryRecoversBackupAndRepairDoesNotOverwriteGoodBackup(string corruption)
|
||||
{
|
||||
_service.Save(Progression(12));
|
||||
_service.Save(Progression(29));
|
||||
string backup = File.ReadAllText(_service.BackupPath);
|
||||
File.WriteAllText(_service.SavePath, corruption);
|
||||
|
||||
ExpectRecovery();
|
||||
SaveData recovered = _service.Load();
|
||||
Assert.That(recovered.entropyBalance, Is.EqualTo(12));
|
||||
Assert.That(File.ReadAllText(_service.SavePath), Is.EqualTo(corruption), "Loading must not modify evidence or backup files.");
|
||||
|
||||
recovered.entropyBalance = 18;
|
||||
_service.Save(recovered);
|
||||
Assert.That(_service.Load().entropyBalance, Is.EqualTo(18));
|
||||
Assert.That(File.ReadAllText(_service.BackupPath), Is.EqualTo(backup));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MissingPrimaryRecoversBackup()
|
||||
{
|
||||
_service.Save(Progression(12));
|
||||
_service.Save(Progression(29));
|
||||
File.Delete(_service.SavePath);
|
||||
|
||||
ExpectRecovery();
|
||||
SaveData recovered = _service.Load();
|
||||
Assert.That(recovered.entropyBalance, Is.EqualTo(12));
|
||||
_service.Save(recovered);
|
||||
Assert.That(_service.Load().entropyBalance, Is.EqualTo(12));
|
||||
Assert.That(File.Exists(_service.BackupPath), Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ValidJsonWithDamagedPayloadFailsIntegrityCheckAndRecoversBackup()
|
||||
{
|
||||
_service.Save(Progression(12));
|
||||
_service.Save(Progression(29));
|
||||
string damaged = File.ReadAllText(_service.SavePath).Replace("\\\"entropyBalance\\\": 29", "\\\"entropyBalance\\\": 99");
|
||||
Assert.That(damaged, Is.Not.EqualTo(File.ReadAllText(_service.SavePath)));
|
||||
File.WriteAllText(_service.SavePath, damaged);
|
||||
|
||||
ExpectRecovery();
|
||||
Assert.That(_service.Load().entropyBalance, Is.EqualTo(12));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InterruptedTemporaryWriteNeverDisplacesCommittedProgression()
|
||||
{
|
||||
_service.Save(Progression(12));
|
||||
File.WriteAllText(_service.SavePath + ".tmp.interrupted", "{\"schemaVersion\":1,\"payload\":");
|
||||
|
||||
Assert.That(_service.Load().entropyBalance, Is.EqualTo(12));
|
||||
_service.Save(Progression(29));
|
||||
Assert.That(_service.Load().entropyBalance, Is.EqualTo(29));
|
||||
Assert.That(new SaveService(_service.BackupPath).Load().entropyBalance, Is.EqualTo(12));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FailedAtomicReplacementLeavesCommittedProgressionIntact()
|
||||
{
|
||||
_service.Save(Progression(12));
|
||||
string original = File.ReadAllText(_service.SavePath);
|
||||
// A directory at the backup destination makes atomic replacement fail on each
|
||||
// supported desktop platform, without platform-specific file-sharing assumptions.
|
||||
Directory.CreateDirectory(_service.BackupPath);
|
||||
|
||||
Exception failure = Assert.Catch(() => _service.Save(Progression(29)));
|
||||
Assert.That(failure is IOException || failure is UnauthorizedAccessException, Is.True);
|
||||
Assert.That(File.ReadAllText(_service.SavePath), Is.EqualTo(original));
|
||||
Assert.That(_service.Load().entropyBalance, Is.EqualTo(12));
|
||||
Assert.That(Directory.GetFiles(_directory, "*.tmp.*"), Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LegacySaveMigratesCurrencyOwnershipAndMergeBalancesWithoutDoubleGranting()
|
||||
{
|
||||
const string legacy = "{\"starterChosen\":true,\"entropyBalance\":12,\"standardPullCurrency\":44,\"merges\":50,\"ownedUnitIds\":[\"arch\"],\"ownedPackageIds\":[\"apt\"]}";
|
||||
File.WriteAllText(_service.SavePath, legacy);
|
||||
|
||||
SaveData migrated = _service.Load();
|
||||
Assert.That(migrated.entropyBalance, Is.EqualTo(12));
|
||||
Assert.That(migrated.bandwidthBalance, Is.EqualTo(44));
|
||||
Assert.That(migrated.commitsBalance, Is.Zero);
|
||||
Assert.That(migrated.standardPullCurrency, Is.Zero);
|
||||
Assert.That(migrated.ownedUnits.Single().id, Is.EqualTo("arch"));
|
||||
Assert.That(migrated.ownedUnits.Single().merges, Is.EqualTo(50));
|
||||
Assert.That(migrated.ownedPackages.Single().id, Is.EqualTo("apt"));
|
||||
_service.Save(migrated);
|
||||
|
||||
SaveData reloaded = _service.Load();
|
||||
Assert.That(reloaded.bandwidthBalance, Is.EqualTo(44));
|
||||
Assert.That(reloaded.ownedUnits.Single().merges, Is.EqualTo(50));
|
||||
Assert.That(File.ReadAllText(_service.BackupPath), Is.EqualTo(legacy));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LegacyDuplicateRefundEvidenceSurvivesLoadUntilBootstrapConsumesIt()
|
||||
{
|
||||
File.WriteAllText(_service.SavePath, "{\"ownedPackages\":[{\"id\":\"apt\",\"upgradeLevel\":1},{\"id\":\"apt\",\"upgradeLevel\":3}],\"ownedUnits\":[]}");
|
||||
|
||||
SaveData migrated = _service.Load();
|
||||
Assert.That(migrated.ownedPackages.Single().upgradeLevel, Is.EqualTo(3));
|
||||
Assert.That(migrated.CollapsedPackageDuplicates.Single().Id, Is.EqualTo("apt"));
|
||||
Assert.That(migrated.CollapsedPackageDuplicates.Single().ExtraCount, Is.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FuturePrimaryCannotBeLoadedOrOverwrittenEvenWithCompatibleBackup()
|
||||
{
|
||||
_service.Save(Progression(12));
|
||||
_service.Save(Progression(29));
|
||||
string future = "{\"schemaVersion\":" + (SaveService.CurrentSchemaVersion + 1) + ",\"unknownProgression\":123}";
|
||||
File.WriteAllText(_service.SavePath, future);
|
||||
string backup = File.ReadAllText(_service.BackupPath);
|
||||
|
||||
Assert.Throws<InvalidDataException>(() => _service.Load());
|
||||
Assert.Throws<InvalidDataException>(() => new SaveService(_service.SavePath).Save(Progression(99)));
|
||||
Assert.That(File.ReadAllText(_service.SavePath), Is.EqualTo(future));
|
||||
Assert.That(File.ReadAllText(_service.BackupPath), Is.EqualTo(backup));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FutureBackupCannotBeReplacedByOlderBuild()
|
||||
{
|
||||
_service.Save(Progression(12));
|
||||
string primary = File.ReadAllText(_service.SavePath);
|
||||
string future = "{\"schemaVersion\":" + (SaveService.CurrentSchemaVersion + 1) + "}";
|
||||
File.WriteAllText(_service.BackupPath, future);
|
||||
|
||||
Assert.Throws<InvalidDataException>(() => _service.Save(Progression(29)));
|
||||
Assert.That(File.ReadAllText(_service.SavePath), Is.EqualTo(primary));
|
||||
Assert.That(File.ReadAllText(_service.BackupPath), Is.EqualTo(future));
|
||||
File.Delete(_service.SavePath);
|
||||
Assert.Throws<InvalidDataException>(() => _service.Load());
|
||||
}
|
||||
|
||||
[TestCase(false)]
|
||||
[TestCase(true)]
|
||||
public void UnrecoverableSaveIsPreservedAndNeverSilentlyReset(bool hasBackup)
|
||||
{
|
||||
File.WriteAllText(_service.SavePath, "corrupt primary");
|
||||
if (hasBackup) File.WriteAllText(_service.BackupPath, "corrupt backup");
|
||||
|
||||
Assert.Throws<InvalidDataException>(() => _service.Load());
|
||||
Assert.Throws<InvalidDataException>(() => _service.Save(SaveData.CreateDefault()));
|
||||
Assert.That(File.ReadAllText(_service.SavePath), Is.EqualTo("corrupt primary"));
|
||||
if (hasBackup) Assert.That(File.ReadAllText(_service.BackupPath), Is.EqualTo("corrupt backup"));
|
||||
Assert.That(Directory.GetFiles(_directory, "*.tmp.*"), Is.Empty);
|
||||
}
|
||||
|
||||
private static SaveData Progression(int entropy)
|
||||
{
|
||||
SaveData data = SaveData.CreateDefault();
|
||||
data.starterChosen = true;
|
||||
data.entropyBalance = entropy;
|
||||
data.ownedUnits.Add(new OwnedUnitSaveEntry { id = "gentoo", version = 2, merges = 120 });
|
||||
data.RecordRunStats("gentoo", 7);
|
||||
return data;
|
||||
}
|
||||
|
||||
private static void ExpectRecovery()
|
||||
{
|
||||
LogAssert.Expect(LogType.Warning, "Recovered progression from the backup save. The primary save will be repaired on the next successful save.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c3d8f265c5894eedb1bfa2a047672ca2
|
||||
@@ -0,0 +1,162 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Data;
|
||||
using NUnit.Framework;
|
||||
using UnityEngine;
|
||||
|
||||
public class SerializedEffectTargetingTests
|
||||
{
|
||||
private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
private readonly List<UnityEngine.Object> temporary = new();
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
foreach (UnityEngine.Object item in temporary) UnityEngine.Object.DestroyImmediate(item);
|
||||
temporary.Clear();
|
||||
}
|
||||
|
||||
[TestCase("lang_c_malloc", CardTargeting.None, false, false)]
|
||||
[TestCase("lang_c_malloc", CardTargeting.SingleEnemy, true, false)]
|
||||
[TestCase("lang_c_malloc", CardTargeting.AllEnemies, false, true)]
|
||||
[TestCase("external_card", CardTargeting.None, false, false)]
|
||||
[TestCase("external_card", CardTargeting.SingleEnemy, true, false)]
|
||||
[TestCase("external_card", CardTargeting.AllEnemies, false, true)]
|
||||
public void SerializedTargetingOverridesCatalogForKnownAndUnknownCards(
|
||||
string id, CardTargeting targeting, bool single, bool all)
|
||||
{
|
||||
var effect = Effect(targeting);
|
||||
var definition = Card(id, null, effect);
|
||||
|
||||
Assert.That(CardEffectFactory.RequiresSingleTarget(definition), Is.EqualTo(single));
|
||||
Assert.That(CardEffectFactory.TargetsAllEnemies(definition), Is.EqualTo(all));
|
||||
Assert.That(effect.FactoryCalls, Is.Zero, "Targeting only reads authoring metadata.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TargetingAndRulesNeverInstantiateRuntimeEffects()
|
||||
{
|
||||
var effect = Effect(CardTargeting.AllEnemies);
|
||||
effect.ThrowOnCreate = true;
|
||||
var definition = Card("lang_c_malloc", effect);
|
||||
typeof(CardDefinition).GetField("description", Private).SetValue(definition, "custom all-enemy effect");
|
||||
|
||||
Assert.That(CardEffectFactory.RequiresSingleTarget(definition), Is.False);
|
||||
Assert.That(CardEffectFactory.TargetsAllEnemies(definition), Is.True);
|
||||
Assert.That(CardEffectFactory.GetRulesText(new CardInstance(definition)), Is.EqualTo("custom all-enemy effect"));
|
||||
Assert.That(effect.FactoryCalls, Is.Zero);
|
||||
}
|
||||
|
||||
[TestCase(false)]
|
||||
[TestCase(true)]
|
||||
public void MixedTargetingPreservesSingleEnemySelectionRegardlessOfEffectOrder(bool reverse)
|
||||
{
|
||||
var effects = new[] { Effect(CardTargeting.AllEnemies), Effect(CardTargeting.None), Effect(CardTargeting.SingleEnemy) };
|
||||
if (reverse) Array.Reverse(effects);
|
||||
var definition = Card("lang_py_for_loop", effects);
|
||||
|
||||
Assert.That(CardEffectFactory.RequiresSingleTarget(definition), Is.True);
|
||||
Assert.That(CardEffectFactory.TargetsAllEnemies(definition), Is.False,
|
||||
"The card must capture the selected enemy; all-enemy effects resolve their own enemy list.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UntargetedEffectsDoNotHideAllEnemyTargeting()
|
||||
{
|
||||
var definition = Card("lang_c_malloc", Effect(CardTargeting.None), null, Effect(CardTargeting.AllEnemies));
|
||||
|
||||
Assert.That(CardEffectFactory.RequiresSingleTarget(definition), Is.False);
|
||||
Assert.That(CardEffectFactory.TargetsAllEnemies(definition), Is.True);
|
||||
}
|
||||
|
||||
[TestCase("lang_c_malloc", true, false)]
|
||||
[TestCase("lang_py_for_loop", false, true)]
|
||||
[TestCase("lang_rs_borrow", false, false)]
|
||||
[TestCase("external_card", false, false)]
|
||||
public void EmptyAndNullOnlyOverridesUseCatalogTargeting(string id, bool single, bool all)
|
||||
{
|
||||
var definition = Card(id);
|
||||
Assert.That(CardEffectFactory.RequiresSingleTarget(definition), Is.EqualTo(single));
|
||||
Assert.That(CardEffectFactory.TargetsAllEnemies(definition), Is.EqualTo(all));
|
||||
|
||||
typeof(CardDefinition).GetField("effects", Private).SetValue(definition, new List<CardEffectDefinition> { null });
|
||||
Assert.That(CardEffectFactory.RequiresSingleTarget(definition), Is.EqualTo(single));
|
||||
Assert.That(CardEffectFactory.TargetsAllEnemies(definition), Is.EqualTo(all));
|
||||
if (id == "external_card")
|
||||
Assert.That(CardEffectFactory.CreateEffects(definition)[0], Is.TypeOf<NoOpCardEffect>());
|
||||
else
|
||||
Assert.That(CardEffectFactory.CreateEffects(definition)[0], Is.Not.TypeOf<NoOpCardEffect>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NullRuntimeResultKeepsOverrideTargetingAndDoesNotExecuteCatalogEffect()
|
||||
{
|
||||
var effect = Effect(CardTargeting.None);
|
||||
effect.ReturnNull = true;
|
||||
var definition = Card("lang_c_malloc", effect);
|
||||
|
||||
var runtime = CardEffectFactory.CreateEffects(definition);
|
||||
|
||||
Assert.That(runtime.Count, Is.EqualTo(1));
|
||||
Assert.That(runtime[0], Is.TypeOf<NoOpCardEffect>());
|
||||
Assert.That(CardEffectFactory.RequiresSingleTarget(definition), Is.False);
|
||||
Assert.That(CardEffectFactory.TargetsAllEnemies(definition), Is.False);
|
||||
Assert.That(effect.FactoryCalls, Is.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NullRuntimeResultRejectsEntireSerializedOverride()
|
||||
{
|
||||
var empty = Effect(CardTargeting.None);
|
||||
empty.ReturnNull = true;
|
||||
var valid = Effect(CardTargeting.None);
|
||||
var definition = Card("lang_c_malloc", empty, null, valid);
|
||||
|
||||
var runtime = CardEffectFactory.CreateEffects(definition);
|
||||
|
||||
Assert.That(runtime.Count, Is.EqualTo(1));
|
||||
Assert.That(runtime[0], Is.TypeOf<NoOpCardEffect>());
|
||||
Assert.That(empty.FactoryCalls, Is.EqualTo(1));
|
||||
Assert.That(valid.FactoryCalls, Is.Zero, "Do not instantiate more effects after an invalid override is found.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NullDefinitionRequiresNoTarget()
|
||||
{
|
||||
Assert.That(CardEffectFactory.RequiresSingleTarget(null), Is.False);
|
||||
Assert.That(CardEffectFactory.TargetsAllEnemies(null), Is.False);
|
||||
}
|
||||
|
||||
private CardDefinition Card(string id, params CardEffectDefinition[] effects)
|
||||
{
|
||||
var definition = ScriptableObject.CreateInstance<CardDefinition>();
|
||||
temporary.Add(definition);
|
||||
typeof(CardDefinition).GetField("id", Private).SetValue(definition, id);
|
||||
typeof(CardDefinition).GetField("effects", Private).SetValue(definition, new List<CardEffectDefinition>(effects));
|
||||
return definition;
|
||||
}
|
||||
|
||||
private SerializedTargetingTestEffect Effect(CardTargeting targeting)
|
||||
{
|
||||
var effect = ScriptableObject.CreateInstance<SerializedTargetingTestEffect>();
|
||||
temporary.Add(effect);
|
||||
typeof(CardEffectDefinition).GetField("targeting", Private).SetValue(effect, targeting);
|
||||
return effect;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SerializedTargetingTestEffect : CardEffectDefinition
|
||||
{
|
||||
public int FactoryCalls;
|
||||
public bool ReturnNull;
|
||||
public bool ThrowOnCreate;
|
||||
|
||||
public override ICardEffect CreateRuntimeEffect()
|
||||
{
|
||||
FactoryCalls++;
|
||||
if (ThrowOnCreate) throw new InvalidOperationException("Targeting must not instantiate runtime effects.");
|
||||
return ReturnNull ? null : new ShieldEffect(37);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 93067886b75548ca99482fdef8923bb1
|
||||
@@ -0,0 +1,124 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Data;
|
||||
using NUnit.Framework;
|
||||
using UnityEngine;
|
||||
using UnityEngine.TestTools;
|
||||
|
||||
public class SerializedEffectValidationTests
|
||||
{
|
||||
private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
private readonly List<UnityEngine.Object> temporary = new();
|
||||
private readonly List<string> executed = new();
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
foreach (UnityEngine.Object item in temporary) UnityEngine.Object.DestroyImmediate(item);
|
||||
temporary.Clear();
|
||||
executed.Clear();
|
||||
}
|
||||
|
||||
[TestCase(false)]
|
||||
[TestCase(true)]
|
||||
public void InvalidOverrideExecutesNoPartialEffectsAndReportsAuthoredLocation(bool invalidFirst)
|
||||
{
|
||||
var first = Effect("first effect");
|
||||
var invalid = Effect("broken barrier");
|
||||
invalid.RuntimeEffect = null;
|
||||
var last = Effect("last effect");
|
||||
var definition = Card("lang_c_malloc", invalidFirst
|
||||
? new CardEffectDefinition[] { invalid, null, first, last }
|
||||
: new CardEffectDefinition[] { first, null, invalid, last });
|
||||
var owner = new GameObject(nameof(SerializedEffectValidationTests));
|
||||
temporary.Add(owner);
|
||||
var combat = owner.AddComponent<CombatManager>();
|
||||
var messages = new List<string>();
|
||||
combat.CombatLog += messages.Add;
|
||||
var context = new CombatContext(new CardInstance(definition), null, Array.Empty<CombatantState>(),
|
||||
combat, combat.DamagePipeline, new StatusEffectController(), combat.DeckController,
|
||||
null, combat.Enemies);
|
||||
|
||||
string expectedDiagnostic = $"Card '{definition.Id}': serialized effect {(invalidFirst ? 1 : 3)} '{invalid.name}' "
|
||||
+ $"({nameof(SerializedValidationTestEffect)}) returned no runtime effect; card effects were not executed.";
|
||||
LogAssert.Expect(LogType.Warning, expectedDiagnostic);
|
||||
var runtime = CardEffectFactory.CreateEffects(definition);
|
||||
foreach (ICardEffect effect in runtime) effect.Execute(context);
|
||||
foreach (ICardEffect effect in runtime) effect.Execute(context);
|
||||
|
||||
Assert.That(runtime.Count, Is.EqualTo(1));
|
||||
Assert.That(runtime[0], Is.TypeOf<NoOpCardEffect>(),
|
||||
"A broken override cannot fall back to this card's catalog damage effect.");
|
||||
Assert.That(executed, Is.Empty, "Effects created before the invalid slot must also be discarded.");
|
||||
Assert.That(last.FactoryCalls, Is.Zero, "Validation stops at the first invalid authored effect.");
|
||||
Assert.That(messages.Count, Is.EqualTo(1), "Repeated plays should not flood the combat log.");
|
||||
Assert.That(messages[0], Does.Contain(definition.Id));
|
||||
Assert.That(messages[0], Does.Contain("serialized effect " + (invalidFirst ? 1 : 3)),
|
||||
"The diagnostic uses the original 1-based slot, including unassigned entries.");
|
||||
Assert.That(messages[0], Does.Contain(invalid.name));
|
||||
Assert.That(messages[0], Does.Contain(nameof(SerializedValidationTestEffect)));
|
||||
Assert.That(messages[0], Does.Contain("not executed"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UnassignedSlotsPreserveValidSerializedEffectOrder()
|
||||
{
|
||||
var first = Effect("first effect");
|
||||
var last = Effect("last effect");
|
||||
var definition = Card("external_card", null, first, null, last, null);
|
||||
|
||||
var runtime = CardEffectFactory.CreateEffects(definition);
|
||||
foreach (ICardEffect effect in runtime) effect.Execute(null);
|
||||
|
||||
Assert.That(runtime.Count, Is.EqualTo(2));
|
||||
Assert.That(executed, Is.EqualTo(new[] { "first effect", "last effect" }));
|
||||
Assert.That(first.FactoryCalls, Is.EqualTo(1));
|
||||
Assert.That(last.FactoryCalls, Is.EqualTo(1));
|
||||
}
|
||||
|
||||
private CardDefinition Card(string id, params CardEffectDefinition[] effects)
|
||||
{
|
||||
var definition = ScriptableObject.CreateInstance<CardDefinition>();
|
||||
temporary.Add(definition);
|
||||
typeof(CardDefinition).GetField("id", Private).SetValue(definition, id);
|
||||
typeof(CardDefinition).GetField("effects", Private).SetValue(definition, new List<CardEffectDefinition>(effects));
|
||||
return definition;
|
||||
}
|
||||
|
||||
private SerializedValidationTestEffect Effect(string effectName)
|
||||
{
|
||||
var effect = ScriptableObject.CreateInstance<SerializedValidationTestEffect>();
|
||||
temporary.Add(effect);
|
||||
effect.name = effectName;
|
||||
effect.RuntimeEffect = new RecordingEffect(effectName, executed);
|
||||
return effect;
|
||||
}
|
||||
|
||||
private sealed class RecordingEffect : ICardEffect
|
||||
{
|
||||
private readonly string name;
|
||||
private readonly List<string> executed;
|
||||
|
||||
public RecordingEffect(string name, List<string> executed)
|
||||
{
|
||||
this.name = name;
|
||||
this.executed = executed;
|
||||
}
|
||||
|
||||
public void Execute(CombatContext context) => executed.Add(name);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SerializedValidationTestEffect : CardEffectDefinition
|
||||
{
|
||||
public int FactoryCalls;
|
||||
public ICardEffect RuntimeEffect;
|
||||
|
||||
public override ICardEffect CreateRuntimeEffect()
|
||||
{
|
||||
FactoryCalls++;
|
||||
return RuntimeEffect;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2a8d37ddba2444589503c9c7eaa82b79
|
||||
@@ -0,0 +1,154 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Run;
|
||||
using NUnit.Framework;
|
||||
using UnityEngine;
|
||||
|
||||
public class ShieldEffectExecutionTests
|
||||
{
|
||||
private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
private readonly List<ScriptableObject> _definitions = new();
|
||||
private readonly List<string> _messages = new();
|
||||
private GameObject _owner;
|
||||
private CombatManager _combat;
|
||||
private CombatantState Player => _combat.PlayerState;
|
||||
|
||||
private static object Call(object owner, string method) => owner.GetType().GetMethod(method, Private).Invoke(owner, null);
|
||||
private static void Set(object owner, string field, object value) => owner.GetType().GetField(field, Private).SetValue(owner, value);
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_owner = new GameObject("shield execution regression");
|
||||
_combat = _owner.AddComponent<CombatManager>();
|
||||
Call(_combat, "OnDisable");
|
||||
Call(_combat, "Awake");
|
||||
Set(_combat, "_playerState", new CombatantState(100, 32, 10) { FlatEffectBonus = 3 });
|
||||
Set(_combat, "_handController", new HandController(32));
|
||||
Set(_combat, "currentPhase", TurnPhase.Execute);
|
||||
_combat.Compilation.BeginWave(4);
|
||||
_combat.Compilation.AdvanceFromEquipment(3, 1); // 120% explicit Shield.
|
||||
_combat.CombatLog += _messages.Add;
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
if (_combat != null)
|
||||
{
|
||||
_combat.CombatLog -= _messages.Add;
|
||||
Call(_combat, "OnDisable");
|
||||
}
|
||||
UnityEngine.Object.DestroyImmediate(_owner);
|
||||
foreach (var definition in _definitions) UnityEngine.Object.DestroyImmediate(definition);
|
||||
_definitions.Clear();
|
||||
_messages.Clear();
|
||||
}
|
||||
|
||||
private CardInstance Card(string id)
|
||||
{
|
||||
var definition = ScriptableObject.CreateInstance<CardDefinition>();
|
||||
_definitions.Add(definition);
|
||||
Set(definition, "id", id);
|
||||
Set(definition, "language", Language.Haskell);
|
||||
return new CardInstance(definition);
|
||||
}
|
||||
|
||||
private CombatContext Context(CardInstance card)
|
||||
{
|
||||
var context = new CombatContext(card, Player, Array.Empty<CombatantState>(), _combat,
|
||||
_combat.DamagePipeline, new StatusEffectController(), _combat.DeckController,
|
||||
_combat.HandController, _combat.Enemies);
|
||||
typeof(CombatContext).GetProperty(nameof(CombatContext.LazyMultiplierPercent)).SetValue(context, 150);
|
||||
return context;
|
||||
}
|
||||
|
||||
private ICardEffect Effect(string kind)
|
||||
{
|
||||
if (kind == "minimal")
|
||||
{
|
||||
Assert.That(_combat.HandController.Add(Card("exhaust_a")), Is.True);
|
||||
Assert.That(_combat.HandController.Add(Card("exhaust_b")), Is.True);
|
||||
return new MinimalInstallEffect();
|
||||
}
|
||||
return kind switch
|
||||
{
|
||||
"first" => new FirstCardShieldEffect(4, 5),
|
||||
"maybe" => new HaskellMaybeEffect(),
|
||||
_ => new ShieldEffect(4)
|
||||
};
|
||||
}
|
||||
|
||||
private void ConfigureMint(CardInstance exclusive = null)
|
||||
{
|
||||
var distro = ScriptableObject.CreateInstance<DistroDefinition>();
|
||||
_definitions.Add(distro);
|
||||
Set(distro, "id", "mint");
|
||||
if (exclusive != null) Set(distro, "exclusiveCards", new List<CardDefinition> { exclusive.Definition });
|
||||
Set(_combat, "_runConfig", new RunConfig(distro, Language.Haskell, Language.C, Array.Empty<CardDefinition>()));
|
||||
}
|
||||
|
||||
[TestCase("normal", false, 16)]
|
||||
[TestCase("first", false, 16)]
|
||||
[TestCase("first", true, 25)]
|
||||
[TestCase("minimal", false, 11)]
|
||||
[TestCase("maybe", false, 16)]
|
||||
public void ShieldRewardsApplyTheirBonusesAndExplicitMultipliersOnce(string kind, bool firstCard, int expected)
|
||||
{
|
||||
var card = Card("shield_test");
|
||||
card.ApplyMagnitudeUpgrade(2);
|
||||
card.MarkPlayedThisTurn(firstCard);
|
||||
|
||||
Effect(kind).Execute(Context(card));
|
||||
|
||||
Assert.That(Player.Shield, Is.EqualTo(expected),
|
||||
"Normal rewards include +3 source and +2 magnitude before 150% lazy and 120% compilation scaling; Minimal Install keeps its fixed reward.");
|
||||
if (kind == "minimal")
|
||||
{
|
||||
Assert.That(Player.Cycles, Is.EqualTo(12));
|
||||
Assert.That(_combat.DeckController.ExhaustPile, Has.Count.EqualTo(2));
|
||||
Assert.That(_combat.HandController.Cards, Is.Empty);
|
||||
}
|
||||
}
|
||||
|
||||
[TestCase("normal", 9)]
|
||||
[TestCase("first", 14)]
|
||||
[TestCase("minimal", 6)]
|
||||
[TestCase("maybe", 9)]
|
||||
public void MintBlocksAndReportsEveryExplicitCardShieldPath(string kind, int blockedAmount)
|
||||
{
|
||||
ConfigureMint();
|
||||
var card = Card("nonexclusive_shield_test");
|
||||
card.ApplyMagnitudeUpgrade(2);
|
||||
card.MarkPlayedThisTurn(true);
|
||||
Player.Shield = 7;
|
||||
|
||||
Effect(kind).Execute(Context(card));
|
||||
|
||||
Assert.That(Player.Shield, Is.EqualTo(7));
|
||||
Assert.That(_messages.FindAll(message => message.StartsWith("shield blocked:")),
|
||||
Is.EqualTo(new[] { $"shield blocked: {blockedAmount}" }));
|
||||
if (kind == "minimal")
|
||||
{
|
||||
Assert.That(Player.Cycles, Is.EqualTo(12), "Shield eligibility does not block the exhaust or Cycle rewards.");
|
||||
Assert.That(_combat.DeckController.ExhaustPile, Has.Count.EqualTo(2));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MintStillAllowsShieldFromItsExclusiveCards()
|
||||
{
|
||||
var card = Card("mint_exclusive_shield_test");
|
||||
card.ApplyMagnitudeUpgrade(2);
|
||||
ConfigureMint(card);
|
||||
|
||||
new ShieldEffect(4).Execute(Context(card));
|
||||
|
||||
Assert.That(Player.Shield, Is.EqualTo(16));
|
||||
Assert.That(_messages, Has.No.Member("shield blocked: 9"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2f09a9c0c8874afda45c0250d528ba64
|
||||
@@ -0,0 +1,499 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Meta;
|
||||
using KernelPanic.UI;
|
||||
using NUnit.Framework;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using UnityEngine.TestTools;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
public class TerminalUiTests
|
||||
{
|
||||
private static readonly Assembly Runtime = typeof(MainMenuController).Assembly;
|
||||
private static readonly BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator SymbolButtonsStayCenteredWithoutRealigningTerminalCommands()
|
||||
{
|
||||
if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Null)
|
||||
Assert.Ignore("Resolved style tests require an editor panel; run Unity without -nographics.");
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
try
|
||||
{
|
||||
window.position = new Rect(0, 0, 400, 300);
|
||||
window.Show();
|
||||
var root = window.rootVisualElement;
|
||||
root.styleSheets.Add(AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/UI/MainMenu.uss"));
|
||||
Runtime.GetType("KernelPanic.UI.TerminalTheme").GetMethod("Attach").Invoke(null, new object[] { root });
|
||||
var menu = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/MainMenu.uxml").CloneTree();
|
||||
var plus = menu.Q<Button>("RootCreditsToEntropyButton");
|
||||
var close = menu.Q<Button>("RootCreditExchangeCloseButton");
|
||||
var dynamicClose = new Button { text = "x" };
|
||||
dynamicClose.AddToClassList("modal-close-button");
|
||||
var symbols = new[] { plus, close, dynamicClose };
|
||||
foreach (var symbol in symbols)
|
||||
{
|
||||
root.Add(symbol);
|
||||
// Keep the close controls in normal flow for this style fixture.
|
||||
symbol.style.position = Position.Relative;
|
||||
symbol.style.top = 0;
|
||||
symbol.style.right = 0;
|
||||
}
|
||||
var steps = menu.Query<Button>(className: "exchange-step-button").ToList();
|
||||
var stepRow = new VisualElement();
|
||||
stepRow.style.flexDirection = FlexDirection.Row;
|
||||
stepRow.style.flexWrap = Wrap.Wrap;
|
||||
root.Add(stepRow);
|
||||
foreach (var step in steps) stepRow.Add(step);
|
||||
var command = new Button { text = "> boot" };
|
||||
command.AddToClassList("terminal-button");
|
||||
root.Add(command);
|
||||
|
||||
foreach (int state in new[] { 0, 1, 2 })
|
||||
{
|
||||
foreach (var symbol in symbols) symbol.SetEnabled(state != 2);
|
||||
if (state == 1) dynamicClose.Focus();
|
||||
yield return null;
|
||||
yield return null;
|
||||
foreach (var symbol in symbols)
|
||||
{
|
||||
var style = symbol.resolvedStyle;
|
||||
Assert.That(style.unityTextAlign, Is.EqualTo(TextAnchor.MiddleCenter), symbol.text);
|
||||
Assert.That(style.paddingLeft, Is.Zero);
|
||||
Assert.That(style.paddingRight, Is.Zero);
|
||||
Assert.That(style.paddingTop, Is.Zero);
|
||||
Assert.That(style.paddingBottom, Is.Zero);
|
||||
Assert.That(style.flexShrink, Is.Zero);
|
||||
Assert.That(style.whiteSpace, Is.EqualTo(WhiteSpace.NoWrap));
|
||||
}
|
||||
foreach (var step in steps)
|
||||
Assert.That(step.resolvedStyle.unityTextAlign, Is.EqualTo(TextAnchor.MiddleCenter), step.text);
|
||||
Assert.That(command.resolvedStyle.unityTextAlign, Is.EqualTo(TextAnchor.MiddleLeft));
|
||||
}
|
||||
LogAssert.NoUnexpectedReceived();
|
||||
}
|
||||
finally { window.Close(); }
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator FocusRevealIgnoresScrollViewChrome()
|
||||
{
|
||||
if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Null)
|
||||
Assert.Ignore("Focus event tests require an editor panel; run Unity without -nographics.");
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
try
|
||||
{
|
||||
window.position = new Rect(0, 0, 360, 260);
|
||||
window.Show();
|
||||
var root = window.rootVisualElement;
|
||||
Runtime.GetType("KernelPanic.UI.TerminalTheme").GetMethod("Attach").Invoke(null, new object[] { root });
|
||||
var scroll = new ScrollView(ScrollViewMode.VerticalAndHorizontal);
|
||||
scroll.style.width = 240;
|
||||
scroll.style.height = 160;
|
||||
var content = new VisualElement();
|
||||
content.style.width = 800;
|
||||
content.style.height = 800;
|
||||
scroll.Add(content);
|
||||
root.Add(scroll);
|
||||
yield return null;
|
||||
yield return null;
|
||||
|
||||
// Scrollbar controls are descendants of ScrollView, but not of its contentContainer.
|
||||
foreach (var control in new VisualElement[]
|
||||
{
|
||||
scroll.verticalScroller.slider, scroll.verticalScroller.lowButton, scroll.verticalScroller.highButton,
|
||||
scroll.horizontalScroller.slider, scroll.horizontalScroller.lowButton, scroll.horizontalScroller.highButton,
|
||||
scroll.contentViewport, scroll.contentContainer, scroll
|
||||
})
|
||||
{
|
||||
control.focusable = true;
|
||||
control.Focus();
|
||||
yield return null;
|
||||
Assert.That(root.focusController.focusedElement, Is.SameAs(control));
|
||||
LogAssert.NoUnexpectedReceived();
|
||||
}
|
||||
}
|
||||
finally { window.Close(); }
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator FocusRevealStillScrollsNestedContentIntoView()
|
||||
{
|
||||
if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Null)
|
||||
Assert.Ignore("Focus event tests require an editor panel; run Unity without -nographics.");
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
try
|
||||
{
|
||||
window.position = new Rect(0, 0, 360, 260);
|
||||
window.Show();
|
||||
var root = window.rootVisualElement;
|
||||
Runtime.GetType("KernelPanic.UI.TerminalTheme").GetMethod("Attach").Invoke(null, new object[] { root });
|
||||
var outer = new ScrollView();
|
||||
outer.style.width = 260;
|
||||
outer.style.height = 180;
|
||||
var outerSpacer = new VisualElement();
|
||||
outerSpacer.style.height = 400;
|
||||
outer.Add(outerSpacer);
|
||||
var inner = new ScrollView();
|
||||
inner.style.height = 100;
|
||||
inner.style.flexShrink = 0;
|
||||
var innerSpacer = new VisualElement();
|
||||
innerSpacer.style.height = 400;
|
||||
inner.Add(innerSpacer);
|
||||
var target = new Button { text = "last operation" };
|
||||
inner.Add(target);
|
||||
outer.Add(inner);
|
||||
root.Add(outer);
|
||||
yield return null;
|
||||
yield return null;
|
||||
|
||||
target.Focus();
|
||||
yield return null;
|
||||
Assert.That(root.focusController.focusedElement, Is.SameAs(target));
|
||||
Assert.That(inner.scrollOffset.y, Is.GreaterThan(0));
|
||||
Assert.That(outer.scrollOffset.y, Is.GreaterThan(0));
|
||||
LogAssert.NoUnexpectedReceived();
|
||||
}
|
||||
finally { window.Close(); }
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SharedScreenFramesGiveTemplatesOneExplicitLayoutSlot()
|
||||
{
|
||||
var root = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/MainMenu.uxml").CloneTree();
|
||||
foreach (var id in new[] { "CollectionPanel", "GachaPanel", "SettingsPanel" })
|
||||
{
|
||||
var panel = root.Q(id);
|
||||
var frame = new ScreenFrameController();
|
||||
frame.Bind(panel, "$ test", "[esc] back [tab] focus", () => { });
|
||||
Assert.That(panel.parent.ClassListContains("screen-slot"), Is.True, id);
|
||||
Assert.That(panel.parent.ClassListContains("hidden"), Is.True, id);
|
||||
Assert.That(panel.Q<Button>(className: "screen-back").focusable, Is.True);
|
||||
Assert.That(panel.Q<Label>(className: "screen-frame-hint").text, Is.EqualTo("[tab] focus"));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UnitIdentityAndTabsSurviveAllFourDetailViews()
|
||||
{
|
||||
var root = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/MainMenu.uxml").CloneTree();
|
||||
var unit = AssetDatabase.LoadAssetAtPath<DistroDefinition>("Assets/Data/Distros/Ubuntu.asset");
|
||||
var owned = new PlayerCollection(); owned.Add(unit);
|
||||
var screen = new CollectionScreenController();
|
||||
screen.Bind(root, null, null, null, owned, packageLoadout: new PackageLoadout(owned, null));
|
||||
screen.RefreshUnits(owned.OwnedUnits);
|
||||
screen.ActivateSelected();
|
||||
var identity = root.Q(className: "unit-detail-header");
|
||||
var tabs = root.Q(className: "unit-detail-tabs");
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
screen.SwitchUnitDetailTabRelative(1);
|
||||
Assert.That(root.Q(className: "unit-detail-header"), Is.SameAs(identity));
|
||||
Assert.That(root.Q(className: "unit-detail-tabs"), Is.SameAs(tabs));
|
||||
Assert.That(screen.IsUnitDetail, Is.True);
|
||||
if (i == 2)
|
||||
{
|
||||
Assert.That(root.Q(className: "collection-manifest"), Is.Not.Null);
|
||||
Assert.That(root.Q<ScrollView>("CollectionList").Query<Button>().ToList().Count, Is.GreaterThan(0));
|
||||
}
|
||||
}
|
||||
Assert.That(screen.BackFromSubview(), Is.True);
|
||||
Assert.That(root.Q("CollectionContextHeader").ClassListContains("hidden"), Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InventoryRowsUseCompactMetadataAndKeepEffectsInDetails()
|
||||
{
|
||||
var root = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/MainMenu.uxml").CloneTree();
|
||||
var owned = new PlayerCollection();
|
||||
var package = AssetDatabase.LoadAssetAtPath<PackageDefinition>("Assets/Data/Packages/Aur.asset");
|
||||
owned.AddPackage(package);
|
||||
var screen = new CollectionScreenController();
|
||||
screen.Bind(root, null, null, null, owned, getSaveData: () => new SaveData());
|
||||
screen.ShowPackages();
|
||||
var row = root.Q<Button>(className: "inventory-row");
|
||||
Assert.That(row, Is.Not.Null);
|
||||
Assert.That(row.Q<Label>(className: "inventory-name").text, Is.Not.Empty);
|
||||
Assert.That(row.Q(className: "inventory-metadata"), Is.Not.Null);
|
||||
Assert.That(row.Q(className: "package-slot-effect"), Is.Null);
|
||||
Assert.That(root.Q("CollectionFilters").Query<Button>().ToList().Count, Is.EqualTo(4));
|
||||
Assert.That(root.Q("CollectionDetail").Q(className: "destructive-action"), Is.Not.Null);
|
||||
}
|
||||
|
||||
[TestCase("AptFast", 3)]
|
||||
[TestCase("CinnamonPackage", 4)]
|
||||
[TestCase("GentooPortage", 4)]
|
||||
[TestCase("GentooCcache", 4)]
|
||||
[TestCase("GentooOpenRC", 5)]
|
||||
[TestCase("Apt", 5)]
|
||||
public void PackageRarityUsesTheSameBadgeInInventoryDetailsAndEquipment(string asset, int stars)
|
||||
{
|
||||
var root = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/MainMenu.uxml").CloneTree();
|
||||
var package = AssetDatabase.LoadAssetAtPath<PackageDefinition>($"Assets/Data/Packages/{asset}.asset");
|
||||
var unit = AssetDatabase.LoadAssetAtPath<DistroDefinition>("Assets/Data/Distros/Ubuntu.asset");
|
||||
var database = AssetDatabase.LoadAssetAtPath<PackageDatabase>("Assets/Data/Packages/PackageDatabase.asset");
|
||||
var owned = new PlayerCollection();
|
||||
owned.Add(unit);
|
||||
owned.AddPackage(package);
|
||||
var loadout = new PackageLoadout(owned, database);
|
||||
var screen = new CollectionScreenController();
|
||||
screen.Bind(root, null, null, null, owned, packageLoadout: loadout, getSaveData: () => new SaveData());
|
||||
screen.ShowPackages();
|
||||
|
||||
var inventory = root.Q<Button>(className: "inventory-row");
|
||||
var detail = root.Q("CollectionDetail").Q(className: "package-heading");
|
||||
Assert.That(inventory.Q(className: "inventory-metadata").Q(className: "package-rarity"), Is.Null);
|
||||
Assert.That(inventory.Q(className: "package-heading").Q(className: "package-rarity"), Is.Not.Null);
|
||||
typeof(CollectionScreenController).GetMethod("OpenPackageEquipWindow", Private)
|
||||
.Invoke(screen, new object[] { unit, package.Slot });
|
||||
var equip = root.Q<Button>(className: "package-equip-row");
|
||||
|
||||
Assert.That(loadout.TryEquip(unit.Id, package.Slot, package.Id, out _), Is.True);
|
||||
var slots = new VisualElement();
|
||||
typeof(CollectionScreenController).GetMethod("AddPackageSlotSummaryRow", Private)
|
||||
.Invoke(screen, new object[] { slots, unit, package.Slot });
|
||||
foreach (var view in new[] { inventory, detail, equip, slots.Q(className: "package-slot-row") })
|
||||
{
|
||||
Assert.That(view.ClassListContains("package-tier"), Is.True);
|
||||
Assert.That(view.ClassListContains($"rarity-{stars}"), Is.True);
|
||||
var badge = view.Q<Label>(className: "package-rarity");
|
||||
Assert.That(badge.text, Is.EqualTo($"{stars}★"));
|
||||
Assert.That(badge.tooltip, Is.EqualTo($"{stars}-star package"));
|
||||
}
|
||||
|
||||
loadout.TryUnequip(unit.Id, package.Slot, out _);
|
||||
slots.Clear();
|
||||
typeof(CollectionScreenController).GetMethod("AddPackageSlotSummaryRow", Private)
|
||||
.Invoke(screen, new object[] { slots, unit, package.Slot });
|
||||
Assert.That(slots.Q(className: "package-rarity"), Is.Null, "Empty slots must not imply a rarity.");
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator PackageRarityColorsAndBadgesSurviveSelectionAndNarrowRows()
|
||||
{
|
||||
if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Null)
|
||||
Assert.Ignore("Resolved style tests require an editor panel; run Unity without -nographics.");
|
||||
var window = ScriptableObject.CreateInstance<TerminalFocusTestWindow>();
|
||||
try
|
||||
{
|
||||
window.position = new Rect(0, 0, 400, 650);
|
||||
window.Show();
|
||||
var root = window.rootVisualElement;
|
||||
root.styleSheets.Add(AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/UI/MainMenu.uss"));
|
||||
root.styleSheets.Add(Resources.Load<StyleSheet>("RarityPresentation"));
|
||||
Runtime.GetType("KernelPanic.UI.TerminalTheme").GetMethod("Attach").Invoke(null, new object[] { root });
|
||||
var collection = new PlayerCollection();
|
||||
var screen = new CollectionScreenController();
|
||||
var assets = new[] { "AptFast", "CinnamonPackage", "Apt" };
|
||||
var colors = new[] { "#9aaa9f", "#83c6cc", "#e7bb72" };
|
||||
for (int i = 0; i < assets.Length; i++)
|
||||
{
|
||||
var package = AssetDatabase.LoadAssetAtPath<PackageDefinition>($"Assets/Data/Packages/{assets[i]}.asset");
|
||||
collection.AddPackage(package);
|
||||
var row = (Button)typeof(CollectionScreenController).GetMethod("BuildPackageInventoryRow", Private)
|
||||
.Invoke(screen, new object[] { collection.GetOwnedPackage(package.Id), 10000, 10000 });
|
||||
root.Add(row);
|
||||
var name = row.Q<Label>(className: "inventory-name");
|
||||
name.text += " / long package name";
|
||||
var badge = row.Q<Label>(className: "package-rarity");
|
||||
ColorUtility.TryParseHtmlString(colors[i], out var color);
|
||||
foreach (int width in new[] { 220, 340 })
|
||||
{
|
||||
row.style.width = width;
|
||||
foreach (bool selected in new[] { false, true })
|
||||
{
|
||||
row.EnableInClassList("selected", selected);
|
||||
if (selected) row.Focus();
|
||||
yield return null;
|
||||
yield return null;
|
||||
Assert.That(badge.resolvedStyle.color, Is.EqualTo(color));
|
||||
Assert.That(name.resolvedStyle.color, Is.EqualTo(color));
|
||||
Assert.That(badge.worldBound.xMax, Is.LessThanOrEqualTo(row.worldBound.xMax));
|
||||
Assert.That(name.worldBound.xMax, Is.LessThanOrEqualTo(badge.worldBound.xMin));
|
||||
Assert.That(row.Q(className: "inventory-metadata").worldBound.yMin,
|
||||
Is.GreaterThanOrEqualTo(name.worldBound.yMax));
|
||||
}
|
||||
}
|
||||
}
|
||||
LogAssert.NoUnexpectedReceived();
|
||||
}
|
||||
finally { window.Close(); }
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CommandsUseExistingActionIndicesAndRejectShellInput()
|
||||
{
|
||||
var root = new VisualElement();
|
||||
var input = new TextField { name = "CommandInput" };
|
||||
root.Add(input);
|
||||
root.Add(new Label { name = "CommandOutput" });
|
||||
int activated = -1;
|
||||
var type = Runtime.GetType("KernelPanic.UI.TerminalCommandLine");
|
||||
var line = Activator.CreateInstance(type, root, (Action<int>)(i => activated = i), (Func<bool>)(() => true));
|
||||
var commands = (string[])type.GetField("Commands", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
|
||||
Assert.That(commands, Is.EqualTo(new[]
|
||||
{
|
||||
"./start_run", "ls ~/collection", "curl gacha.sh | sh", "dpkg-reconfigure", "history --runs", "shutdown -h now", "cat /etc/cron.daily/quests"
|
||||
}));
|
||||
for (int i = 0; i < commands.Length; i++)
|
||||
{
|
||||
input.value = commands[i];
|
||||
type.GetMethod("Submit", Private).Invoke(line, null);
|
||||
Assert.That(activated, Is.EqualTo(i));
|
||||
Assert.That(input.value, Is.Empty);
|
||||
}
|
||||
input.value = "./start_run; shutdown";
|
||||
type.GetMethod("Submit", Private).Invoke(line, null);
|
||||
Assert.That(activated, Is.EqualTo(6));
|
||||
Assert.That(root.Q<Label>("CommandOutput").text, Does.Contain("command not found"));
|
||||
}
|
||||
|
||||
[TestCase("his", "history --runs", 4)]
|
||||
[TestCase("shut", "shutdown -h now", 5)]
|
||||
[TestCase("cat /etc/cron", "cat /etc/cron.daily/quests", 6)]
|
||||
public void ArchiveAndQuitCommandsCompleteAndKeepTheirOwnActionIndices(string prefix, string command, int index)
|
||||
{
|
||||
var root = new VisualElement();
|
||||
var input = new TextField { name = "CommandInput" };
|
||||
root.Add(input);
|
||||
root.Add(new Label { name = "CommandOutput" });
|
||||
int activated = -1;
|
||||
var type = Runtime.GetType("KernelPanic.UI.TerminalCommandLine");
|
||||
var line = Activator.CreateInstance(type, root, (Action<int>)(i => activated = i), (Func<bool>)(() => true));
|
||||
input.value = prefix;
|
||||
Send(type, line, KeyCode.Tab);
|
||||
Assert.That(input.value, Is.EqualTo(command));
|
||||
Send(type, line, KeyCode.Return);
|
||||
Assert.That(activated, Is.EqualTo(index));
|
||||
}
|
||||
|
||||
[TestCase(KeyCode.Alpha5, 4)]
|
||||
[TestCase(KeyCode.Keypad5, 4)]
|
||||
[TestCase(KeyCode.Alpha6, 5)]
|
||||
[TestCase(KeyCode.Keypad6, 5)]
|
||||
public void NumberShortcutsIncludeArchiveAndTheMovedQuitCommand(KeyCode key, int expected)
|
||||
{
|
||||
var type = Runtime.GetType("KernelPanic.UI.CommandKeyBindings");
|
||||
Assert.That(type.GetMethod("GetDigitIndex").Invoke(null, new object[] { key }), Is.EqualTo(expected));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RunArchiveCommandSitsBetweenSettingsAndQuitWithSharedScreenChrome()
|
||||
{
|
||||
var root = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/MainMenu.uxml").CloneTree();
|
||||
var commands = root.Q("MainMenuPanel").Query<VisualElement>(className: "command-row").ToList();
|
||||
Assert.That(commands.ConvertAll(command => command.name), Is.EqualTo(new[]
|
||||
{
|
||||
"CommandStartRun", "CommandCollection", "CommandGacha", "CommandSettings", "CommandRunArchive", "CommandQuit"
|
||||
}));
|
||||
var archiveCommand = root.Q("CommandRunArchive");
|
||||
Assert.That(archiveCommand.Q<Label>(className: "command-text").text, Is.EqualTo("history --runs"));
|
||||
Assert.That(archiveCommand.Q<Label>(className: "command-description").text, Is.EqualTo("run archive"));
|
||||
var panel = root.Q("RunArchivePanel");
|
||||
Assert.That(panel.ClassListContains("hidden"), Is.True);
|
||||
Assert.That(panel.Q("RunArchiveActions"), Is.Not.Null);
|
||||
var frame = new ScreenFrameController();
|
||||
frame.Bind(panel, "$ history --runs", "[esc] back [tab/enter] actions", () => { });
|
||||
Assert.That(panel.Q<Label>(className: "screen-frame-title").text, Is.EqualTo("$ history --runs"));
|
||||
Assert.That(panel.Q<Button>(className: "screen-back").focusable, Is.True);
|
||||
Assert.That(panel.Q<Label>(className: "screen-frame-hint").text, Is.EqualTo("[tab/enter] actions"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HistoryRestoresDraftAndTabCompletes()
|
||||
{
|
||||
var root = new VisualElement();
|
||||
var input = new TextField { name = "CommandInput" };
|
||||
root.Add(input);
|
||||
root.Add(new Label { name = "CommandOutput" });
|
||||
var type = Runtime.GetType("KernelPanic.UI.TerminalCommandLine");
|
||||
var line = Activator.CreateInstance(type, root, (Action<int>)(_ => { }), (Func<bool>)(() => true));
|
||||
input.value = "ls ~/collection";
|
||||
type.GetMethod("Submit", Private).Invoke(line, null);
|
||||
input.value = "./st";
|
||||
Send(type, line, KeyCode.UpArrow);
|
||||
Assert.That(input.value, Is.EqualTo("ls ~/collection"));
|
||||
Send(type, line, KeyCode.DownArrow);
|
||||
Assert.That(input.value, Is.EqualTo("./st"));
|
||||
Send(type, line, KeyCode.Tab);
|
||||
Assert.That(input.value, Is.EqualTo("./start_run"));
|
||||
}
|
||||
|
||||
private static void Send(Type type, object line, KeyCode key)
|
||||
{
|
||||
using var evt = KeyDownEvent.GetPooled('\0', key, EventModifiers.None);
|
||||
type.GetMethod("OnKeyDown", Private).Invoke(line, new object[] { evt });
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ManifestKeepsExactRulesAndShowsMutableStates()
|
||||
{
|
||||
var card = AssetDatabase.LoadAssetAtPath<CardDefinition>("Assets/Data/Cards/Languages/C/Malloc.asset");
|
||||
Assert.That(card, Is.Not.Null);
|
||||
var instance = new CardInstance(card) { IsBroken = true };
|
||||
instance.ApplyDrawRider(2);
|
||||
var face = new VisualElement();
|
||||
Runtime.GetType("KernelPanic.UI.SoftwareCardView").GetMethod("Populate").Invoke(null, new object[] { face, instance, 3 });
|
||||
Assert.That(face.ClassListContains("software-c"), Is.True);
|
||||
Assert.That(face.ClassListContains("software-corrupted"), Is.True);
|
||||
Assert.That(face.Q<Label>(className: "software-cost").text, Is.EqualTo("3c"));
|
||||
Assert.That(face.tooltip, Does.StartWith(CardEffectFactory.GetRulesText(instance)));
|
||||
Assert.That(face.tooltip, Does.Contain("Draw 2."));
|
||||
Assert.That(face.Q<Label>(className: "software-state").text, Does.Contain("CORRUPTED"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EveryCardRetainsItsCompleteRulesInTheManifest()
|
||||
{
|
||||
var populate = Runtime.GetType("KernelPanic.UI.SoftwareCardView").GetMethod("Populate");
|
||||
var guids = AssetDatabase.FindAssets("t:CardDefinition", new[] { "Assets/Data/Cards" });
|
||||
Assert.That(guids.Length, Is.GreaterThan(0));
|
||||
foreach (string guid in guids)
|
||||
{
|
||||
var definition = AssetDatabase.LoadAssetAtPath<CardDefinition>(AssetDatabase.GUIDToAssetPath(guid));
|
||||
var instance = new CardInstance(definition);
|
||||
var face = new VisualElement();
|
||||
populate.Invoke(null, new object[] { face, instance, CombatManager.GetCardCost(instance) });
|
||||
string rules = face.Q<Label>(className: "software-effect").text;
|
||||
var conditions = face.Q<Label>(className: "software-conditions");
|
||||
if (conditions != null) rules += " " + conditions.text;
|
||||
Assert.That(rules, Is.EqualTo(CardEffectFactory.GetRulesText(instance)), definition.name);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TrackViewsMatchActualDequeueAndPopOrder()
|
||||
{
|
||||
var a = new CardInstance(null);
|
||||
var b = new CardInstance(null);
|
||||
var queue = new InterpreterQueue();
|
||||
var stack = new LazyStack();
|
||||
queue.Enqueue(a); queue.Enqueue(b);
|
||||
stack.Enqueue(a); stack.Enqueue(b);
|
||||
Assert.That(queue.Cards[0], Is.SameAs(a));
|
||||
Assert.That(stack.Cards[0], Is.SameAs(b));
|
||||
queue.TryDequeue(out var first);
|
||||
stack.TryPop(out var top);
|
||||
Assert.That(first, Is.SameAs(a));
|
||||
Assert.That(top, Is.SameAs(b));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MenuImportsWithPromptAndAllScreenBindings()
|
||||
{
|
||||
var tree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/MainMenu.uxml");
|
||||
var root = tree.CloneTree();
|
||||
foreach (string id in new[] { "MainMenuPanel", "RunSetupPanel", "CollectionPanel", "GachaPanel", "SettingsPanel", "RunArchivePanel", "StarterModal", "RootCreditExchangeModal" })
|
||||
Assert.That(root.Q(id), Is.Not.Null, id);
|
||||
Assert.That(root.Q<TextField>("CommandInput"), Is.Not.Null);
|
||||
Assert.That(root.Q<Toggle>("ReducedMotionToggle"), Is.Not.Null);
|
||||
Assert.That(AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/Resources/KernelTheme.uss"), Is.Not.Null);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class TerminalFocusTestWindow : EditorWindow { }
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b73ddac91da44a8fb6ba634517d01005
|
||||
@@ -0,0 +1,306 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Meta;
|
||||
using KernelPanic.Run;
|
||||
using KernelPanic.UI;
|
||||
using NUnit.Framework;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
public class TutorialTests
|
||||
{
|
||||
private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
private GameObject _owner;
|
||||
private RunManager _run;
|
||||
private CombatManager _combat;
|
||||
private SaveService _save;
|
||||
private CardDatabase _cards;
|
||||
private DistroDefinition _distro;
|
||||
private string _directory;
|
||||
private int _seed, _draws;
|
||||
private static void Set(object o, string field, object value) => o.GetType().GetField(field, Private).SetValue(o, value);
|
||||
private static object Call(object o, string method, params object[] args) => o.GetType().GetMethod(method, Private | BindingFlags.Public).Invoke(o, args);
|
||||
|
||||
[SetUp]
|
||||
public void Setup()
|
||||
{
|
||||
_seed = RandomRoll.CurrentSeed; _draws = RandomRoll.DrawCount;
|
||||
_directory = Path.Combine(Path.GetTempPath(), "KernelPanic-TutorialTests-" + Guid.NewGuid().ToString("N"));
|
||||
_save = new SaveService(Path.Combine(_directory, "progression.json"));
|
||||
_cards = AssetDatabase.LoadAssetAtPath<CardDatabase>("Assets/Data/Cards/CardDatabase.asset");
|
||||
_distro = AssetDatabase.LoadAssetAtPath<DistroDefinition>("Assets/Data/Distros/Ubuntu.asset");
|
||||
_owner = new GameObject("training tests"); _owner.SetActive(false);
|
||||
_run = _owner.AddComponent<RunManager>(); _combat = _owner.AddComponent<CombatManager>();
|
||||
Call(_run, "OnEnable"); Call(_combat, "Awake");
|
||||
Configure(1);
|
||||
var data = SaveData.CreateDefault(); data.starterChosen = true; data.bandwidthBalance = 17;
|
||||
TutorialCampaign.Enroll(data, _distro.Id); _save.Save(data);
|
||||
}
|
||||
|
||||
private RunConfig Configure(int lesson)
|
||||
{
|
||||
var config = TutorialCampaign.CreateConfig(_distro, _cards, lesson);
|
||||
_run.StartRun(config); Set(_combat, "_runConfig", config); Set(_combat, "_runManager", _run);
|
||||
Set(_combat, "_playerState", new CombatantState(60, 6, 4));
|
||||
Set(_combat, "_handController", new HandController(6)); Set(_combat, "currentPhase", TurnPhase.Execute);
|
||||
return config;
|
||||
}
|
||||
|
||||
private object Flow(int lesson, Action complete = null)
|
||||
{
|
||||
var config = Configure(lesson);
|
||||
var type = typeof(CombatSceneController).Assembly.GetType("KernelPanic.UI.TutorialFlow");
|
||||
return Activator.CreateInstance(type, new object[] { new VisualElement(), _run, _combat, _cards, null, _save, config, complete ?? (() => {}) });
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void Cleanup()
|
||||
{
|
||||
Call(_run, "OnDisable"); UnityEngine.Object.DestroyImmediate(_owner);
|
||||
RandomRoll.Restore(_seed, _draws);
|
||||
if (Directory.Exists(_directory)) Directory.Delete(_directory, true);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ExistingProfilesAreNotEnrolledAndStarterEnrollmentSurvivesReload()
|
||||
{
|
||||
Assert.That(TutorialCampaign.Required(JsonUtility.FromJson<SaveData>("{\"starterChosen\":true}")), Is.False);
|
||||
Assert.That(TutorialCampaign.Required(_save.Load()), Is.True);
|
||||
Assert.That(_save.Load().tutorialDistroId, Is.EqualTo("ubuntu"));
|
||||
Assert.That(TutorialCampaign.Lesson(_save.Load()), Is.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TwoWavesHaveRealCardsAndBasicEnemiesWithoutRngConsumption()
|
||||
{
|
||||
int draws = RandomRoll.DrawCount;
|
||||
string[] expected = { "zombie_process", "memory_leak", "orphan_process", "firewalld", "cron_job", "daemon" };
|
||||
Assert.That(TutorialCampaign.LessonCount, Is.EqualTo(3));
|
||||
var ids = Enumerable.Range(1, TutorialCampaign.LessonCount).SelectMany(lesson => TutorialCampaign.Plan(lesson).Enemies).Distinct();
|
||||
Assert.That(ids, Is.EquivalentTo(expected));
|
||||
foreach (int lesson in Enumerable.Range(1, TutorialCampaign.LessonCount))
|
||||
{
|
||||
var config = TutorialCampaign.CreateConfig(_distro, _cards, lesson);
|
||||
Assert.That(config.StartingDeck.All(card => card != null && !card.IsToken), Is.True);
|
||||
Assert.That(config.StartingDeck.Select(card => card.ResolutionTrack).Distinct().Count(), Is.EqualTo(3));
|
||||
Assert.That(config.EquippedPackages, Is.Empty);
|
||||
Assert.That(TutorialGuide.Build(lesson).All(step => step.Copy.Length < 130), Is.True, "Keep steps short and contextual.");
|
||||
}
|
||||
Assert.That(RandomRoll.DrawCount, Is.EqualTo(draws));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CompletionIsOrderedPersistentAndCannotBeRepeated()
|
||||
{
|
||||
var data = _save.Load();
|
||||
Assert.Throws<InvalidOperationException>(() => TutorialCampaign.Complete(data));
|
||||
data.tutorialLesson = 2;
|
||||
Assert.Throws<InvalidOperationException>(() => TutorialCampaign.Complete(data));
|
||||
data.tutorialLesson = 3;
|
||||
TutorialCampaign.Complete(data); _save.Save(data); data = _save.Load();
|
||||
Assert.That(TutorialCampaign.Required(data), Is.False);
|
||||
Assert.That(data.tutorialRewardClaimed, Is.True);
|
||||
Assert.That(data.bandwidthBalance, Is.EqualTo(1017));
|
||||
Assert.That(data.entropyBalance, Is.EqualTo(GachaService.StandardTenPullCost * GachaService.EntropyPerCommit));
|
||||
Assert.Throws<InvalidOperationException>(() => TutorialCampaign.Complete(data));
|
||||
TutorialCampaign.Enroll(data, "ubuntu"); data.tutorialLesson = 3; TutorialCampaign.Complete(data);
|
||||
Assert.That(data.bandwidthBalance, Is.EqualTo(1017));
|
||||
Assert.That(data.entropyBalance, Is.EqualTo(1000));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TutorialCannotAdvanceNormalWavesOrSaveNormalCheckpoint()
|
||||
{
|
||||
Set(_combat, "_awaitingWaveContinue", true);
|
||||
_combat.ContinueToNextWave();
|
||||
Assert.That(_combat.AwaitingWaveContinue, Is.True);
|
||||
Assert.Throws<InvalidDataException>(() => _run.CaptureCheckpoint(_combat));
|
||||
Assert.That(_run.Journey.campaign, Is.False);
|
||||
Assert.Throws<InvalidDataException>(() => RunCheckpointService.SaveAndSuspend(_save, _run, _combat));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RealWaveClearDoesNotAccrueMetaRewardsAndSceneSettlementIsExcluded()
|
||||
{
|
||||
GameEvents.RaiseWaveCleared(new WaveClearedEvent(1));
|
||||
Assert.That(_run.AccruedBandwidth, Is.Zero); Assert.That(_run.AccruedEntropy, Is.Zero);
|
||||
var view = _owner.AddComponent<CombatSceneController>();
|
||||
Set(view, "_runManager", _run); Set(view, "_combatManager", _combat); Set(view, "_saveService", _save);
|
||||
Call(view, "SettleRunRewardsIfNeeded");
|
||||
Assert.That(_save.Load().recentRuns, Is.Empty); Assert.That(_save.Load().bandwidthBalance, Is.EqualTo(17));
|
||||
Set(view, "_saveService", null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ReadingBlocksCardsTargetsUnlocksAndEndTurn()
|
||||
{
|
||||
_ = Flow(1);
|
||||
var card = new CardInstance(_cards.FindById("lang_rs_fn_main")); _combat.HandController.Add(card);
|
||||
int cycles = _combat.PlayerState.Cycles;
|
||||
Assert.That(_combat.PlayCard(card), Is.False);
|
||||
_combat.EndPlayerTurn(); Assert.That(_combat.CurrentPhase, Is.EqualTo(TurnPhase.Execute));
|
||||
Assert.That(_combat.CanSurrenderRun, Is.False); Assert.That(_combat.PlayerState.Cycles, Is.EqualTo(cycles));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NextCannotSkipReadingPracticeOrEncounterClear()
|
||||
{
|
||||
var flow = Flow(1);
|
||||
Call(flow, "Continue"); Assert.That(_save.Load().tutorialLesson, Is.EqualTo(1));
|
||||
for (int p = 0; p < 40; p++) Call(flow, "AdvancePage");
|
||||
Assert.That(_combat.TutorialGuide.Step.Id, Is.EqualTo("select-attack"));
|
||||
Call(flow, "Continue"); Assert.That(_save.Load().tutorialLesson, Is.EqualTo(1));
|
||||
Set(_combat, "_awaitingWaveContinue", true);
|
||||
Call(flow, "Continue"); Assert.That(_save.Load().tutorialLesson, Is.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TrainingShopAlwaysHasAnAffordablePatchAndPurchasePersistsInCheckpoint()
|
||||
{
|
||||
Set(_combat, "_awaitingWaveContinue", true);
|
||||
GameEvents.RaiseWaveCleared(new WaveClearedEvent(1));
|
||||
_run.GenerateRepositoryOffers(_cards, null);
|
||||
var offer = _run.RepositoryOffers.First(o => o.Kind == RepositoryOfferKind.CardUpgrade);
|
||||
Assert.That(offer.TargetCard.Definition.Id, Is.EqualTo("lang_rs_unwrap"));
|
||||
Assert.That(_run.BuyOffer(offer, _combat.PlayerState), Is.True);
|
||||
var snapshot = _run.CaptureCheckpoint(_combat);
|
||||
var distros = AssetDatabase.LoadAssetAtPath<DistroDatabase>("Assets/Data/Distros/DistroDatabase.asset");
|
||||
var restored = snapshot.Resolve(distros, _cards, null, null);
|
||||
Assert.That(restored.Snapshot.runId, Is.EqualTo(_run.RunId));
|
||||
Assert.That(restored.Snapshot.wave, Is.EqualTo(2));
|
||||
Assert.That(restored.Snapshot.combat.uptime, Is.EqualTo(_combat.PlayerState.CurrentUptime));
|
||||
Assert.That(restored.Deck.Single(c => c.InstanceId == offer.TargetCard.InstanceId).MagnitudeBonus,
|
||||
Is.EqualTo(offer.TargetCard.MagnitudeBonus));
|
||||
Assert.That(restored.Offers.Any(o => o.Sold), Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TargetingRequiresSelectingTheExpectedCardAndActualZombieRevival()
|
||||
{
|
||||
var guide = new TutorialGuide(1); _combat.TutorialGuide = guide;
|
||||
foreach (var card in _run.RunDeck) _combat.HandController.Add(card);
|
||||
var zombie = new EnemyInstance(EnemyArchetypeCatalog.Get("zombie_process"), 6);
|
||||
var orphan = new EnemyInstance(EnemyArchetypeCatalog.Get("orphan_process"), 4);
|
||||
var enemies = (System.Collections.Generic.List<EnemyInstance>)typeof(CombatManager).GetField("_enemies", Private).GetValue(_combat);
|
||||
enemies.Add(zombie); enemies.Add(orphan);
|
||||
guide.Update(_combat);
|
||||
for (int i = 0; i < 20; i++) guide.Acknowledge(_combat);
|
||||
Assert.That(guide.Step.Id, Is.EqualTo("select-attack"));
|
||||
Assert.That(guide.AllowsEnemy(zombie), Is.False);
|
||||
Assert.That(guide.AllowsCard(_combat.HandController.Cards.First(c => c.Definition.Id == "lang_rs_borrow")), Is.False);
|
||||
int cycles = _combat.PlayerState.Cycles;
|
||||
_combat.SelectEnemy(0);
|
||||
Assert.That(_combat.PlayCard(guide.Card), Is.False, "First click must only select.");
|
||||
Assert.That(_combat.PendingTargetCard, Is.SameAs(guide.Card));
|
||||
Assert.That(_combat.PlayerState.Cycles, Is.EqualTo(cycles));
|
||||
guide.Update(_combat);
|
||||
Assert.That(guide.Step.Id, Is.EqualTo("target-zombie"));
|
||||
Assert.That(guide.AllowsEnemy(zombie), Is.True);
|
||||
Assert.That(guide.AllowsEnemy(orphan), Is.False);
|
||||
guide.Acknowledge(_combat); Assert.That(guide.Step.Id, Is.EqualTo("target-zombie"));
|
||||
guide.CardPlayed(ResolutionTrack.Native); guide.Update(_combat);
|
||||
Assert.That(guide.Step.Id, Is.EqualTo("target-zombie"), "Dispatch alone is not a kill.");
|
||||
zombie.MarkPendingRevive(); guide.Update(_combat);
|
||||
Assert.That(guide.Step.Id, Is.EqualTo("pending-revival"));
|
||||
guide.Acknowledge(_combat);
|
||||
Assert.That(guide.Step.Id, Is.EqualTo("end-turn"));
|
||||
guide.PhaseChanged(TurnPhase.Interpret); guide.Update(_combat);
|
||||
Assert.That(guide.Step.Id, Is.EqualTo("end-turn"), "Must wait for actual respawn.");
|
||||
zombie.ReviveAtHalfUptime(); guide.Update(_combat);
|
||||
Assert.That(guide.Step.Id, Is.EqualTo("revived"));
|
||||
Assert.That(zombie.CurrentUptime, Is.EqualTo(3));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ThirdLessonRequiresActualDaemonRevealAndCompletedCountdownTurns()
|
||||
{
|
||||
Configure(3);
|
||||
var guide = new TutorialGuide(3); _combat.TutorialGuide = guide;
|
||||
foreach (var card in _run.RunDeck) _combat.HandController.Add(card);
|
||||
var daemon = new EnemyInstance(EnemyArchetypeCatalog.Get("daemon"), 14);
|
||||
var cron = new EnemyInstance(EnemyArchetypeCatalog.Get("cron_job"), 9);
|
||||
var enemies = (System.Collections.Generic.List<EnemyInstance>)typeof(CombatManager).GetField("_enemies", Private).GetValue(_combat);
|
||||
enemies.Add(cron); enemies.Add(daemon); cron.PickNextIntent(); daemon.PickNextIntent();
|
||||
guide.Update(_combat);
|
||||
for (int i = 0; i < 20; i++) guide.Acknowledge(_combat);
|
||||
Assert.That(guide.Step.Id, Is.EqualTo("select-reveal"));
|
||||
Assert.That(guide.Card.Definition.Id, Is.EqualTo("lang_rs_fn_main"));
|
||||
Assert.That(_combat.PlayCard(guide.Card), Is.False);
|
||||
guide.Update(_combat);
|
||||
Assert.That(guide.Step.Id, Is.EqualTo("target-daemon"));
|
||||
Assert.That(guide.AllowsEnemy(cron), Is.False);
|
||||
Assert.That(guide.AllowsEnemy(daemon), Is.True);
|
||||
guide.CardResolved(ResolutionTrack.Native); guide.Update(_combat);
|
||||
Assert.That(guide.Step.Id, Is.EqualTo("target-daemon"), "A dispatch without damage must not count as revealing.");
|
||||
daemon.MarkDamaged(); guide.Update(_combat);
|
||||
Assert.That(guide.Step.Id, Is.EqualTo("revealed-daemon"));
|
||||
guide.Acknowledge(_combat);
|
||||
foreach (string next in new[] { "cron-ticking", "cron-armed" })
|
||||
{
|
||||
guide.Acknowledge(_combat);
|
||||
Assert.That(guide.Step.Action, Is.EqualTo(TutorialAction.EndTurn));
|
||||
guide.PhaseChanged(TurnPhase.Interpret);
|
||||
Set(_combat, "currentPhase", TurnPhase.Interpret); guide.Update(_combat);
|
||||
Assert.That(guide.Step.Action, Is.EqualTo(TutorialAction.EndTurn), "Wait for the exchange to finish.");
|
||||
cron.AdvanceCountdownAfterAction(); cron.PickNextIntent();
|
||||
Set(_combat, "currentPhase", TurnPhase.Execute); guide.Update(_combat);
|
||||
Assert.That(guide.Step.Id, Is.EqualTo(next));
|
||||
}
|
||||
Assert.That(cron.CountdownRemaining, Is.Zero);
|
||||
Assert.That(cron.CurrentIntent.Kind, Is.EqualTo(EnemyIntentKind.Attack));
|
||||
guide.Acknowledge(_combat);
|
||||
Assert.That(guide.Step.Action, Is.EqualTo(TutorialAction.PlayShield));
|
||||
Assert.That(guide.Card.Definition.Id, Is.EqualTo("lang_rs_borrow"));
|
||||
Assert.That(guide.CanEndTurn, Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ThirdWaveCheckpointKeepsTheUpgradeAndDoesNotPayEarly()
|
||||
{
|
||||
Configure(2);
|
||||
_run.RunDeck[0].ApplyMagnitudeUpgrade(2);
|
||||
GameEvents.RaiseWaveCleared(new WaveClearedEvent(2));
|
||||
Set(_combat, "_awaitingWaveContinue", true);
|
||||
_run.GenerateRepositoryOffers(_cards, null);
|
||||
var data = _save.Load();
|
||||
data.tutorialCheckpoint = _run.CaptureCheckpoint(_combat);
|
||||
data.tutorialLesson = 3; _save.Save(data);
|
||||
var restored = _save.Load();
|
||||
Assert.That(TutorialCampaign.Lesson(restored), Is.EqualTo(3));
|
||||
Assert.That(restored.tutorialCheckpoint.wavesCleared, Is.EqualTo(2));
|
||||
Assert.That(restored.tutorialCheckpoint.deck.Any(card => card.magnitude == 2), Is.True);
|
||||
Assert.That(restored.tutorialRewardClaimed, Is.False);
|
||||
Assert.That(restored.bandwidthBalance, Is.EqualTo(17));
|
||||
var distros = AssetDatabase.LoadAssetAtPath<DistroDatabase>("Assets/Data/Distros/DistroDatabase.asset");
|
||||
Assert.DoesNotThrow(() => restored.tutorialCheckpoint.Resolve(distros, _cards, null, null));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FailedCompletionSaveKeepsTrainingRequiredAndCanRetry()
|
||||
{
|
||||
var data = _save.Load(); data.tutorialLesson = 3; _save.Save(data);
|
||||
int exits = 0; var flow = Flow(3, () => exits++);
|
||||
Set(flow, "_resuming", false);
|
||||
Set(_combat.TutorialGuide, "<Index>k__BackingField", _combat.TutorialGuide.Count);
|
||||
_combat.TutorialReading = false;
|
||||
Set(_run, "_wavesCleared", 3);
|
||||
Set(_combat, "_awaitingWaveContinue", true);
|
||||
// Make the isolated backup target unwritable as a file.
|
||||
File.Delete(_save.BackupPath);
|
||||
Directory.CreateDirectory(_save.BackupPath);
|
||||
Call(flow, "Continue");
|
||||
Assert.That(exits, Is.Zero); Assert.That(_save.Load().tutorialRequired, Is.True);
|
||||
Directory.Delete(_save.BackupPath);
|
||||
Call(flow, "Continue");
|
||||
Assert.That(exits, Is.EqualTo(1)); Assert.That(_save.Load().tutorialRequired, Is.False);
|
||||
Call(flow, "Continue"); Assert.That(exits, Is.EqualTo(1));
|
||||
Assert.That(_save.Load().bandwidthBalance, Is.EqualTo(1017));
|
||||
Assert.That(_save.Load().entropyBalance, Is.EqualTo(1000));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5acd5c5f74304eedb99e5b9e48f76827
|
||||
@@ -0,0 +1,202 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Run;
|
||||
using NUnit.Framework;
|
||||
using UnityEngine;
|
||||
|
||||
public class WaveCompletionTests
|
||||
{
|
||||
private const BindingFlags Private = BindingFlags.NonPublic | BindingFlags.Instance;
|
||||
private GameObject _owner;
|
||||
private CombatManager _combat;
|
||||
private RunManager _run;
|
||||
private int _clearedEvents;
|
||||
private UnityEngine.Random.State _randomState;
|
||||
private object _combatRandom;
|
||||
|
||||
private static object Call(object owner, string method, params object[] args) =>
|
||||
owner.GetType().GetMethod(method, Private).Invoke(owner, args);
|
||||
|
||||
private static void Set(object owner, string field, object value) =>
|
||||
owner.GetType().GetField(field, Private).SetValue(owner, value);
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_randomState = UnityEngine.Random.state;
|
||||
_combatRandom = typeof(RandomRoll).GetField("_random", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null);
|
||||
RandomRoll.Seed(0);
|
||||
_clearedEvents = 0;
|
||||
_owner = new GameObject("wave completion regression");
|
||||
_run = _owner.AddComponent<RunManager>();
|
||||
_combat = _owner.AddComponent<CombatManager>();
|
||||
// EditMode does not run the normal MonoBehaviour activation lifecycle.
|
||||
// Register each instance exactly once, without a scene or player save.
|
||||
Call(_run, "OnDisable");
|
||||
Call(_run, "OnEnable");
|
||||
Call(_combat, "OnDisable");
|
||||
Call(_combat, "OnEnable");
|
||||
_run.StartRun(null);
|
||||
Set(_combat, "_runManager", _run);
|
||||
Set(_combat, "_playerState", new CombatantState(100, 5, 3));
|
||||
Set(_combat, "currentPhase", TurnPhase.Execute);
|
||||
GameEvents.WaveCleared += OnWaveCleared;
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
GameEvents.WaveCleared -= OnWaveCleared;
|
||||
if (_combat != null) Call(_combat, "OnDisable");
|
||||
if (_run != null) Call(_run, "OnDisable");
|
||||
UnityEngine.Object.DestroyImmediate(_owner);
|
||||
UnityEngine.Random.state = _randomState;
|
||||
typeof(RandomRoll).GetField("_random", BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, _combatRandom);
|
||||
}
|
||||
|
||||
private void OnWaveCleared(WaveClearedEvent _) => _clearedEvents++;
|
||||
private bool CheckWin() => (bool)Call(_combat, "CheckWin");
|
||||
|
||||
private EnemyInstance AddEnemy(string id)
|
||||
{
|
||||
var enemy = new EnemyInstance(EnemyArchetypeCatalog.Get(id), 10);
|
||||
((List<EnemyInstance>)_combat.Enemies).Add(enemy);
|
||||
return enemy;
|
||||
}
|
||||
|
||||
private void LethalHit(EnemyInstance enemy) => _combat.DamagePipeline.DealDamage(
|
||||
new DamageRequest(null, enemy.State, enemy.MaxUptime, Language.Python, false, false));
|
||||
|
||||
[TestCase(1)]
|
||||
[TestCase(2)]
|
||||
public void PendingRevivalDoesNotCompleteWaveOrPayKillReward(int zombieCount)
|
||||
{
|
||||
for (int i = 0; i < zombieCount; i++)
|
||||
{
|
||||
var zombie = AddEnemy("zombie_process");
|
||||
LethalHit(zombie);
|
||||
Assert.That(zombie.PendingRevive, Is.True);
|
||||
Assert.That(zombie.State.IsDefeated, Is.True, "Reproduce the pipeline's post-hit defeat flag");
|
||||
}
|
||||
Call(_combat, "RemoveDefeatedEnemies");
|
||||
|
||||
Assert.That(CheckWin(), Is.False);
|
||||
Assert.That(_combat.AwaitingWaveContinue, Is.False);
|
||||
Assert.That(_run.CurrentWaveNumber, Is.EqualTo(1));
|
||||
Assert.That(_clearedEvents, Is.Zero);
|
||||
Assert.That(_run.Bits, Is.Zero, "Only permanent kills pay Bits");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LastNormalEnemyExitingDoesNotSkipAnotherEnemysRevival()
|
||||
{
|
||||
var zombie = AddEnemy("zombie_process");
|
||||
LethalHit(zombie);
|
||||
KillAndQueueExit(AddEnemy("memory_leak"));
|
||||
FinishQueuedExits();
|
||||
|
||||
Assert.That(_run.Bits, Is.EqualTo(CombatTuning.BitsPerKill));
|
||||
Assert.That(zombie.PendingRevive, Is.True);
|
||||
Assert.That(CheckWin(), Is.False);
|
||||
Assert.That(_combat.AwaitingWaveContinue, Is.False);
|
||||
Assert.That(_clearedEvents, Is.Zero);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RevivedZombieAndItsOrphanPayOnceAndThenCompleteWave()
|
||||
{
|
||||
var zombie = AddEnemy("zombie_process");
|
||||
LethalHit(zombie);
|
||||
Assert.That(CheckWin(), Is.False);
|
||||
Call(_combat, "RevivePendingEnemies");
|
||||
Assert.That(zombie.HasRevived && !zombie.PendingRevive, Is.True);
|
||||
Assert.That(CheckWin(), Is.False, "A revived, living enemy still blocks completion");
|
||||
|
||||
RandomRoll.Seed(1); // First permanent-death roll is 25: exercise the orphan branch.
|
||||
KillAndQueueExit(zombie);
|
||||
Assert.That(CheckWin(), Is.False, "Pending exits and death spawns still block completion");
|
||||
FinishQueuedExits();
|
||||
Assert.That(_run.Bits, Is.EqualTo(CombatTuning.BitsPerKill));
|
||||
Assert.That(_combat.Enemies.Count, Is.EqualTo(1));
|
||||
var orphan = _combat.Enemies[0];
|
||||
Assert.That(orphan.ArchetypeId, Is.EqualTo("orphan_process"));
|
||||
Assert.That(CheckWin(), Is.False);
|
||||
|
||||
KillAndQueueExit(orphan);
|
||||
FinishQueuedExits();
|
||||
Assert.That(_combat.Enemies, Is.Empty);
|
||||
Assert.That(_combat.AwaitingWaveContinue, Is.True);
|
||||
Assert.That(_run.Bits, Is.EqualTo(2 * CombatTuning.BitsPerKill));
|
||||
Assert.That(_run.CurrentWaveNumber, Is.EqualTo(2));
|
||||
Assert.That(_clearedEvents, Is.EqualTo(1));
|
||||
Assert.That(CheckWin(), Is.True);
|
||||
Assert.That(_clearedEvents, Is.EqualTo(1), "Repeated checks must not award another wave");
|
||||
Assert.That(_run.Bits, Is.EqualTo(2 * CombatTuning.BitsPerKill));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RevivedZombieWithoutAnOrphanPaysOnceAndCompletesWave()
|
||||
{
|
||||
var zombie = AddEnemy("zombie_process");
|
||||
LethalHit(zombie);
|
||||
Assert.That(zombie.PendingRevive, Is.True);
|
||||
Call(_combat, "RevivePendingEnemies");
|
||||
RandomRoll.Seed(0); // First permanent-death roll is 73: exercise the no-spawn branch.
|
||||
KillAndQueueExit(zombie);
|
||||
Assert.That(CheckWin(), Is.False, "Even a no-spawn death waits for its exit presentation.");
|
||||
FinishQueuedExits();
|
||||
Assert.That(_combat.Enemies, Is.Empty);
|
||||
Assert.That(_combat.AwaitingWaveContinue, Is.True);
|
||||
Assert.That(_run.Bits, Is.EqualTo(CombatTuning.BitsPerKill));
|
||||
Assert.That(_run.CurrentWaveNumber, Is.EqualTo(2));
|
||||
Assert.That(_clearedEvents, Is.EqualTo(1));
|
||||
Assert.That(CheckWin(), Is.True);
|
||||
Assert.That(_clearedEvents, Is.EqualTo(1));
|
||||
Assert.That(_run.Bits, Is.EqualTo(CombatTuning.BitsPerKill));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OrdinaryPermanentKillStillPaysAndCompletesWave()
|
||||
{
|
||||
var enemy = AddEnemy("memory_leak");
|
||||
Assert.That(CheckWin(), Is.False);
|
||||
KillAndQueueExit(enemy);
|
||||
FinishQueuedExits();
|
||||
Assert.That(_combat.AwaitingWaveContinue, Is.True);
|
||||
Assert.That(_run.Bits, Is.EqualTo(CombatTuning.BitsPerKill));
|
||||
Assert.That(_clearedEvents, Is.EqualTo(1));
|
||||
}
|
||||
|
||||
private void KillAndQueueExit(EnemyInstance enemy)
|
||||
{
|
||||
// Stage the queue for a deterministic EditMode drain instead of starting a Unity coroutine.
|
||||
Set(_combat, "_enemyExitQueueDraining", true);
|
||||
LethalHit(enemy);
|
||||
_combat.QueueDefeatedCombatantForRemoval(enemy.State);
|
||||
int bits = _run.Bits;
|
||||
_combat.QueueDefeatedCombatantForRemoval(enemy.State);
|
||||
Assert.That(_run.Bits, Is.EqualTo(bits), "The same kill cannot pay twice");
|
||||
GameEvents.RaiseCombatantDeathVisualCompleted(new CombatantDeathVisualCompletedEvent(enemy.State));
|
||||
}
|
||||
|
||||
private void FinishQueuedExits()
|
||||
{
|
||||
Set(_combat, "_enemyExitQueueDraining", false);
|
||||
FinishRoutine((IEnumerator)Call(_combat, "DrainEnemyExitQueue"));
|
||||
}
|
||||
|
||||
private static void FinishRoutine(IEnumerator routine)
|
||||
{
|
||||
int steps = 0;
|
||||
while (routine.MoveNext())
|
||||
{
|
||||
Assert.That(++steps, Is.LessThan(100), "Exit processing must finish");
|
||||
if (routine.Current is IEnumerator nested) FinishRoutine(nested);
|
||||
// Presentation waits are skipped; the actual exit, spawn, payout and victory code runs.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0f82c19cf70e407ea9413888610c58ae
|
||||
Reference in New Issue
Block a user