Make some overall changes to utilities

This commit is contained in:
2026-10-26 22:09:36 +01:00
parent a4109f5be0
commit 881b61a66d
22 changed files with 376 additions and 790 deletions
+142 -6
View File
@@ -83,6 +83,8 @@ namespace KernelPanic.Editor
public int maxWaves = 10;
public int maxRounds = 100;
public WaveRoute route = WaveRoute.Repair;
public string routePolicy = "legacy";
public bool startersOnly;
public bool prefetch = true;
public string outputDirectory = "Artifacts/Balance";
@@ -107,6 +109,8 @@ namespace KernelPanic.Editor
break;
case "-balanceWaves": result.maxWaves = int.Parse(Value(args, ref i), CultureInfo.InvariantCulture); break;
case "-balancePrefetch": result.prefetch = bool.Parse(Value(args, ref i)); break;
case "-balanceStartersOnly": result.startersOnly = bool.Parse(Value(args, ref i)); break;
case "-balanceRoutePolicy": result.routePolicy = Value(args, ref i).ToLowerInvariant(); break;
case "-balanceRoute":
result.route = Value(args, ref i).ToLowerInvariant() switch
{
@@ -123,6 +127,8 @@ namespace KernelPanic.Editor
throw new ArgumentException("Specify at least one seed, 1..100 waves, and 1..1000 total rounds per run.");
if (result.packageLevels.Length == 0 || result.packageLevels.Any(level => level < 0 || level > PackageTuning.MaxPackageLevel))
throw new ArgumentException($"Package levels must be 0..{PackageTuning.MaxPackageLevel}.");
if (!new[] { "legacy", "repair", "elite", "deck", "adaptive" }.Contains(result.routePolicy))
throw new ArgumentException("balanceRoutePolicy must be legacy, repair, elite, deck, or adaptive.");
result.outputDirectory = Path.GetFullPath(result.outputDirectory);
return result;
}
@@ -165,6 +171,15 @@ namespace KernelPanic.Editor
public static List<Scenario> CreateScenarios(DistroDatabase distros, Options options)
{
var result = new List<Scenario>();
if (options.startersOnly)
{
foreach (string id in new[] { "ubuntu", "fedora", "mint" })
{
var starter = distros.FindById(id) ?? throw new InvalidOperationException($"Missing starter {id}.");
Add(id, 1, starter.PrimaryLanguage, starter.SecondaryLanguage);
}
return result;
}
foreach (var distro in distros.AllDistros.Where(d => d != null).OrderBy(d => d.Id, StringComparer.Ordinal))
{
Add(distro.Id, 1, distro.PrimaryLanguage, distro.SecondaryLanguage);
@@ -208,6 +223,22 @@ namespace KernelPanic.Editor
return cards;
}
[Serializable]
public sealed class WaveResult
{
public int wave, entryUptime, maxUptime, exitUptime, rounds, cardsPlayed;
public string route;
public bool cleared;
}
[Serializable]
public sealed class RouteDecision
{
public int wave, uptime, maxUptime, deckSize;
public string[] available;
public string selected, outcome;
}
[Serializable]
public sealed class RunResult
{
@@ -237,13 +268,17 @@ namespace KernelPanic.Editor
public string stopReason;
public string traceHash;
public bool repeatVerified;
public bool campaignCompleted;
public double elapsedSeconds;
public List<WaveResult> waves = new();
public List<RouteDecision> decisions = new();
public double DamagePerRound => rounds == 0 ? 0 : (double)enemyUptimeDamage / rounds;
}
[Serializable]
public sealed class Report
{
public int schemaVersion = 4;
public int schemaVersion = 5;
public string generatedUtc = DateTime.UtcNow.ToString("o");
public string unityVersion = Application.unityVersion;
public string policy = "Greedy preview value per (cost+1), lowest-uptime target, hand-order ties; 64 plays/round cap. First four authored distro exclusives plus both language starter decks. Paired no-shop and upgrade-shop policies, package levels 0 and 5 by default. Upgrade-shop buys affordable offers in this order: healing at <=50% uptime, draw riders, magnitude, cost reduction, max uptime, RAM, Cycles, cards, then useful healing; offer-order ties; no rerolls/removals. Actual Play Mode combat; death visuals acknowledged on the next editor update. First seed repeats for every scenario.";
@@ -328,11 +363,42 @@ namespace KernelPanic.Editor
};
}
// Deliberately simple, disclosed policies. All use reachable nodes and the same combat,
// shopping, reward and event-target rules; no knowledge of future random draws.
public static int RoutePriority(WaveRoute route, string policy, int uptime, int maxUptime, int deckSize)
{
if (policy == "repair" && route == WaveRoute.Repair) return 100;
if (policy == "elite" && route == WaveRoute.Challenge) return 100;
if (policy == "adaptive")
{
if (route == WaveRoute.Repair && uptime <= maxUptime * .6) return 100;
if (route == WaveRoute.Challenge) return uptime >= maxUptime * .8 ? 65 : 5;
}
return route switch
{
WaveRoute.Forge => 80,
WaveRoute.Sacrifice => deckSize > 8 ? 75 : 10,
WaveRoute.Recycle => deckSize > 8 ? 70 : 10,
WaveRoute.Cache => 60,
WaveRoute.Repair => uptime < maxUptime ? 50 : 0,
WaveRoute.Challenge => 5,
_ => 0
};
}
public static string ReplayData(RunResult result)
{
var copy = JsonUtility.FromJson<RunResult>(JsonUtility.ToJson(result));
copy.elapsedSeconds = 0; // Execution speed is not deterministic gameplay state.
copy.repeatVerified = false;
return JsonUtility.ToJson(copy);
}
public static string ToMarkdown(Report report)
{
var text = new StringBuilder("# Seeded combat comparison\n\n");
text.AppendLine(report.policy).AppendLine().AppendLine(report.limitations).AppendLine();
text.AppendLine($"Encounter revision: seeded campaign variants, then endless. Preferred route: {report.options.route}, when reachable on the seeded map; otherwise the default reachable path. Interactive stops are passed without changing the deck. Repair restores up to {RunJourney.RepairUptime} Uptime on departure; challenge adds a modified Daemon and awards Bits plus a draw rider on clear. Build rewards take Bits. Prefetch enabled: {report.options.prefetch}; used only when the bot cannot play another card. Total prefetches: {report.runs.Sum(run => run.prefetches)}. Milestone automatically continues into endless when the wave cap exceeds five. These results are not directly comparable to benchmarks without the route map.").AppendLine();
text.AppendLine($"Encounter/map revision 2, ten-wave campaign, then endless. Route policy: {report.options.routePolicy}; legacy preference: {report.options.route}. Legacy skips events; other policies prefer reachable nodes using RoutePriority, and resolve events by improving the highest preview-value eligible card and removing the lowest preview-value card only above eight cards. Deck-order ties. Adaptive prioritizes repair at <=60% Uptime and ranks elites above Cache at >=80%; otherwise prefers deck improvements. Repair restores up to {RunJourney.RepairUptime} Uptime; elites award Bits and a draw rider on clear. Build rewards take Bits for all policies. Shopping happens before route choice/events, matching the UI. Prefetch: {report.options.prefetch}, only when no further play is possible; total {report.runs.Sum(run => run.prefetches)}. Endless starts only if the cap exceeds the campaign milestone. These results are not directly comparable to benchmarks without the route map.").AppendLine();
text.AppendLine($"Seeds: {string.Join(", ", report.options.seeds)}. Limits: {report.options.maxWaves} waves / {report.options.maxRounds} total rounds. Unity {report.unityVersion}.").AppendLine();
text.AppendLine($"Package levels: {string.Join(", ", report.options.packageLevels)}. Shop policies: {string.Join(", ", report.options.shoppingPolicies.Select(shop => shop ? "upgrade-shop" : "no-shop"))}.").AppendLine();
text.AppendLine("| Loadout | Runs | Uptime damage / round | Mean rounds | Mean waves cleared | Wave cap reached | Round cap alive | Died | Repeat checked |");
@@ -344,6 +410,16 @@ namespace KernelPanic.Editor
text.AppendLine(FormattableString.Invariant($"| {group.Key} | {group.Count()} | {damage:0.00} | {group.Average(run => run.rounds):0.00} | {group.Average(run => run.wavesCleared):0.00} | {group.Count(run => run.stopReason == "wave-cap")} | {group.Count(run => run.stopReason == "round-cap")} | {group.Count(run => run.stopReason == "defeat")} | {group.Count(run => run.repeatVerified)} |"));
}
text.AppendLine().AppendLine("Damage/round is total observed enemy uptime damage divided by total rounds, including partial defeat/clear rounds. JSON contains per-seed outcomes, exact starter decks, shield damage, incoming uptime damage, and deterministic event trace hashes. Every scenario's first seed is replayed and must match before this report is written.");
text.AppendLine().AppendLine("## Campaign pacing").AppendLine();
text.AppendLine("| Loadout | Boss cleared | Reached boss | Mean boss entry Uptime | Mean completed-run rounds | Mean bot seconds (all runs) |");
text.AppendLine("| --- | ---: | ---: | ---: | ---: | ---: |");
foreach (var group in report.runs.GroupBy(run => run.scenario))
{
var bosses = group.SelectMany(run => run.waves).Where(wave => wave.wave == RunJourney.BossWave).ToArray();
var wins = group.Where(run => run.campaignCompleted).ToArray();
text.AppendLine(FormattableString.Invariant($"| {group.Key} | {wins.Length}/{group.Count()} | {bosses.Length} | {(bosses.Length == 0 ? 0 : bosses.Average(wave => wave.entryUptime)):0.0} | {(wins.Length == 0 ? 0 : wins.Average(run => run.rounds)):0.0} | {group.Average(run => run.elapsedSeconds):0.0} |"));
}
text.AppendLine().AppendLine("Boss entry is sampled at the first Execute phase, after departure healing and opening allocation. Zero with no boss arrivals/wins means no observation. JSON records per-wave rounds, cards, health and per-stop choices. Elapsed seconds measure the automated editor, not human thinking time or expected player run duration; replay checks exclude only elapsed time and the verification flag. Campaign completion means the real boss was cleared, independently of the wave cap stop reason.");
text.AppendLine().AppendLine("## Card flow and repository use").AppendLine();
text.AppendLine("| Loadout | Ended turns | Unused Cycles / ended turn | Empty hand % | Empty hand + unused Cycles % | No usable cards + unused Cycles % | Plays / round | Purchases / run | Draw riders / run | Bits spent / run | Play-cap hits |");
text.AppendLine("| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |");
@@ -382,6 +458,7 @@ namespace KernelPanic.Editor
private bool _roundCapReached;
private int _roundCapUptime;
private string _runtimeError;
private double _runStarted;
public Batch(Options options)
{
@@ -419,10 +496,11 @@ namespace KernelPanic.Editor
}
if (_combat.AwaitingWaveContinue)
{
FinishWave(true);
if (_run.WavesCleared >= _report.options.maxWaves) { Complete("wave-cap"); return false; }
if (_current.rounds >= _report.options.maxRounds) { Complete("round-cap"); return false; }
VisitRepository();
if (_run.RouteEventPending) _run.ResolveRouteEvent(skip: true);
ChooseRoute();
if (_run.CampaignChoicePending) _combat.ContinueEndless();
else _combat.ContinueToNextWave();
Progress();
@@ -465,7 +543,6 @@ namespace KernelPanic.Editor
{
_run.GenerateRepositoryOffers(_cards, _languages);
if (_run.BuildRewardPending) _run.ClaimBuildReward(null, CardUpgradeKind.MagnitudeUp, true);
_run.SelectRoute(_report.options.route);
_current.repositoryVisits++;
if (!_report.scenarios[_scenarioIndex].shop) return;
// The real market and public purchase method determine affordability,
@@ -500,6 +577,54 @@ namespace KernelPanic.Editor
return chosen;
}
private double RouteCardValue(CardInstance card)
{
var preview = CardPreviewService.Build(_combat, card);
return ((preview.MinimumDamage + (double)preview.MaximumDamage) / 2
+ preview.Shield * .7 + preview.Heal * 1.5 + preview.Repairs * 3 + 1) / (preview.Cost + 1);
}
private void ChooseRoute()
{
if (_run.CampaignChoicePending) return;
string policy = _report.options.routePolicy;
if (policy == "legacy") _run.SelectRoute(_report.options.route);
else
{
var node = _run.AvailableRouteNodes.OrderByDescending(n => RoutePriority(n.Route, policy,
_combat.PlayerState.CurrentUptime, _combat.PlayerState.MaxUptime, _run.RunDeck.Count)).FirstOrDefault();
if (node != null && !_run.SelectRouteNode(node.Id)) throw new InvalidOperationException("Reachable route rejected.");
}
var decision = new RouteDecision { wave = _run.CurrentWaveNumber,
uptime = _combat.PlayerState.CurrentUptime, maxUptime = _combat.PlayerState.MaxUptime,
deckSize = _run.RunDeck.Count, available = _run.AvailableRouteNodes.Select(n => n.Route.ToString()).ToArray(),
selected = _run.Journey.selectedRoute.ToString() };
if (_run.RouteEventPending)
{
var target = _run.RunDeck.Where(_run.CanImproveRouteCard).OrderByDescending(RouteCardValue).FirstOrDefault();
var donor = _run.RunDeck.Where(c => c != target && c.Definition != null && !c.Definition.IsToken
&& (_run.Journey.selectedRoute != WaveRoute.Sacrifice || !c.Definition.IsJunk))
.OrderBy(RouteCardValue).FirstOrDefault();
bool remove = _run.Journey.selectedRoute is WaveRoute.Sacrifice or WaveRoute.Recycle;
bool upgrade = _run.Journey.selectedRoute is WaveRoute.Sacrifice or WaveRoute.Forge;
bool skip = policy == "legacy" || (remove && (_run.RunDeck.Count <= 8 || donor == null)) || (upgrade && target == null);
if (!_run.ResolveRouteEvent(donor, target, skip)) throw new InvalidOperationException("Route event rejected.");
decision.outcome = _run.Journey.eventOutcome;
}
_current.decisions.Add(decision);
_trace.Append("route:").Append(JsonUtility.ToJson(decision)).Append(';');
}
private void FinishWave(bool cleared)
{
var wave = _current.waves.LastOrDefault();
if (wave == null || wave.cleared) return;
wave.cleared = cleared;
wave.exitUptime = _combat.PlayerState.CurrentUptime;
wave.rounds = _current.rounds - _current.waves.Take(_current.waves.Count - 1).Sum(w => w.rounds);
wave.cardsPlayed = _current.cardsPlayed - _current.waves.Take(_current.waves.Count - 1).Sum(w => w.cardsPlayed);
}
private void Begin()
{
var scenario = _report.scenarios[_scenarioIndex];
@@ -509,6 +634,7 @@ namespace KernelPanic.Editor
?? throw new InvalidOperationException($"Missing package {id}"), scenario.packageLevel)).ToArray();
int seed = _report.options.seeds[_seedIndex];
_current = new RunResult { scenario = scenario.Label, seed = seed, startingDeck = deck.Select(card => card.Id).ToArray() };
_runStarted = EditorApplication.timeSinceStartup;
_trace.Clear();
_roundCapReached = false;
_owner = new GameObject("Isolated balance comparison");
@@ -524,7 +650,10 @@ namespace KernelPanic.Editor
private void Complete(string reason)
{
FinishWave(_combat.AwaitingWaveContinue);
_current.stopReason = reason;
_current.campaignCompleted = _run.WavesCleared >= _run.Journey.FinalWave;
_current.elapsedSeconds = EditorApplication.timeSinceStartup - _runStarted;
_current.wavesCleared = _run.WavesCleared;
_current.uptimeRemaining = _roundCapReached ? _roundCapUptime : _combat.PlayerState.CurrentUptime;
_current.maxUptime = _combat.PlayerState.MaxUptime;
@@ -533,7 +662,7 @@ namespace KernelPanic.Editor
DestroyRun();
if (_repeatOf != null)
{
if (JsonUtility.ToJson(_repeatOf) != JsonUtility.ToJson(_current))
if (ReplayData(_repeatOf) != ReplayData(_current))
throw new InvalidOperationException($"Non-reproducible combat: {_current.scenario}, seed {_current.seed}. First {_repeatOf.traceHash}, repeat {_current.traceHash}.");
_repeatOf.repeatVerified = true;
_repeatOf = null;
@@ -564,7 +693,14 @@ namespace KernelPanic.Editor
_roundCapReached = true;
return;
}
if (payload.NextPhase == TurnPhase.Execute) _current.rounds++;
if (payload.NextPhase == TurnPhase.Execute)
{
if (_current.waves.All(w => w.wave != _run.CurrentWaveNumber))
_current.waves.Add(new WaveResult { wave = _run.CurrentWaveNumber,
entryUptime = _combat.PlayerState.CurrentUptime, maxUptime = _combat.PlayerState.MaxUptime,
route = _run.Journey.activeRoute.ToString() });
_current.rounds++;
}
_trace.Append("phase:").Append(payload.NextPhase).Append(';');
Progress();
}
@@ -75,6 +75,7 @@ public class BalanceComparisonTests
[TestCase("-balancePackageLevels", "-1")]
[TestCase("-balancePackageLevels", "6")]
[TestCase("-balanceShop", "random")]
[TestCase("-balanceRoutePolicy", "random")]
public void InvalidOptionsFailBeforeStartingPlayMode(string option, string value) =>
Assert.That(() => BalanceComparison.Options.Parse(new[] { option, value }), Throws.Exception);
@@ -124,6 +125,47 @@ public class BalanceComparisonTests
Assert.That(result.turnPlayCapHits, Is.EqualTo(1));
}
[Test]
public void StarterStudyPairsOnlyTheThreeNewPlayerLoadoutsAndShoppingPolicies()
{
var options = BalanceComparison.Options.Parse(new[] { "-balanceStartersOnly", "true", "-balanceRoutePolicy", "adaptive" });
var distros = AssetDatabase.LoadAssetAtPath<DistroDatabase>("Assets/Data/Distros/DistroDatabase.asset");
var scenarios = BalanceComparison.CreateScenarios(distros, options);
Assert.That(scenarios.Count, Is.EqualTo(6));
Assert.That(scenarios.Select(s => s.distroId).Distinct(), Is.EquivalentTo(new[] { "ubuntu", "fedora", "mint" }));
Assert.That(scenarios.All(s => s.version == 1 && s.packages.Length == 0), Is.True);
foreach (var group in scenarios.GroupBy(s => s.distroId))
Assert.That(group.Select(s => s.shop), Is.EquivalentTo(new[] { false, true }));
}
[Test]
public void AdaptiveRouteRespondsToHealthAndPreservesSmallDecks()
{
int Score(WaveRoute route, int health, int cards = 12) => BalanceComparison.RoutePriority(route, "adaptive", health, 60, cards);
Assert.That(Score(WaveRoute.Repair, 30), Is.GreaterThan(Score(WaveRoute.Forge, 30)));
Assert.That(Score(WaveRoute.Forge, 60), Is.GreaterThan(Score(WaveRoute.Repair, 60)));
Assert.That(Score(WaveRoute.Challenge, 60), Is.GreaterThan(Score(WaveRoute.Cache, 60)));
Assert.That(Score(WaveRoute.Challenge, 40), Is.LessThan(Score(WaveRoute.Cache, 40)));
Assert.That(Score(WaveRoute.Sacrifice, 60, 8), Is.LessThan(Score(WaveRoute.Cache, 60, 8)));
Assert.That(Score(WaveRoute.Recycle, 60, 8), Is.LessThan(Score(WaveRoute.Cache, 60, 8)));
}
[Test]
public void ReplayIgnoresWallClockButDetectsChangedWaveHealthAndRouteOutcomes()
{
var first = new BalanceComparison.RunResult { elapsedSeconds = 12, repeatVerified = true };
first.waves.Add(new BalanceComparison.WaveResult { wave = 10, entryUptime = 35 });
first.decisions.Add(new BalanceComparison.RouteDecision { wave = 2, selected = "Sacrifice", outcome = "upgrade" });
var repeat = JsonUtility.FromJson<BalanceComparison.RunResult>(JsonUtility.ToJson(first));
repeat.elapsedSeconds = 17; repeat.repeatVerified = false;
Assert.That(BalanceComparison.ReplayData(repeat), Is.EqualTo(BalanceComparison.ReplayData(first)));
repeat.waves[0].entryUptime--;
Assert.That(BalanceComparison.ReplayData(repeat), Is.Not.EqualTo(BalanceComparison.ReplayData(first)));
repeat.waves[0].entryUptime++;
repeat.decisions[0].outcome = "pass";
Assert.That(BalanceComparison.ReplayData(repeat), Is.Not.EqualTo(BalanceComparison.ReplayData(first)));
}
[Test]
public void RepositoryPolicyPrefersUsefulHealingThenDrawUpgradesAndSkipsSoldOffers()
{
+6 -6
View File
@@ -58,7 +58,7 @@ namespace KernelPanic.Combat
advice = "Race partners act in uncertain order; defeating one enrages the survivor. Choose between support and paired threats.";
break;
case RunJourney.LegacyBossWave:
title = variant == 1 ? "Kernel Overseer / scheduled interrupt" : "Kernel Overseer / memory pressure";
title = variant == 1 ? "Kernel Overseer: scheduled interrupt" : "Kernel Overseer: memory pressure";
enemies = new[] { "kernel_overseer", variant == 1 ? "cron_job" : "memory_leak" };
advice = baseline.Advice;
break;
@@ -72,7 +72,7 @@ namespace KernelPanic.Combat
string detail = modifier == 0 ? "Veiled escort: damage the extra Daemon to reveal its intent."
: modifier == 1 ? "Armored escort: the extra Daemon starts with 6 Shield; damage reveals its intent."
: "Hardened escort: the extra Daemon has +4 Uptime; damage reveals its intent.";
plan = new EncounterPlan(title + " / challenge", advice + " " + detail, baseline.UptimeBonus, escort.ToArray())
plan = new EncounterPlan(title + " (elite)", advice + " " + detail, baseline.UptimeBonus, escort.ToArray())
{ EscortShield = modifier == 1 ? 6 : 0, EscortUptime = modifier == 2 ? 4 : 0 };
}
return plan;
@@ -105,7 +105,7 @@ namespace KernelPanic.Combat
advice = "Boss cycle: shield, probe, heavy interrupt. At half uptime its NEXT announced attacks become stronger.";
enemies = new[] { "kernel_overseer", "firewalld" }; break;
default:
title = "Endless / " + wave;
title = "Endless wave " + wave;
advice = "Threats return in stronger combinations. Race partners remain paired.";
enemies = (wave % 4) switch
{
@@ -119,7 +119,7 @@ namespace KernelPanic.Combat
{
var harder = new List<string>(enemies) { "daemon" };
enemies = harder.ToArray();
title += " / challenge";
title += " (elite)";
advice += " An elite Daemon escorts this route; damage it to expose its intent.";
}
return new EncounterPlan(title, advice, Math.Max(0, wave - 1) * CombatTuning.EnemyUptimeGrowthPerWave, enemies);
@@ -159,11 +159,11 @@ namespace KernelPanic.Combat
}
if (wave >= 5 && wave < RunJourney.BossWave && route == WaveRoute.Challenge)
{
enemies.Add("daemon"); title += " / challenge";
enemies.Add("daemon"); title += " (elite)";
advice += baseline.EscortShield > 0 ? " Extra Daemon: 6 starting Shield, hidden intent."
: baseline.EscortUptime > 0 ? " Extra Daemon: +4 Uptime, hidden intent." : " Extra Daemon: hidden intent.";
}
if (wave > RunJourney.BossWave) title = "Survival / " + wave;
if (wave > RunJourney.BossWave) title = "Survival wave " + wave;
return new EncounterPlan(title, advice, Math.Max(0, wave - 1) * CombatTuning.EnemyUptimeGrowthPerWave, enemies.ToArray())
{ EscortShield = baseline.EscortShield, EscortUptime = baseline.EscortUptime };
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9e526fa835864ba184af24843e02ad71
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a41d2608975f4d4c99e00d5f20eeac02
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a41d2608975f4d4c99e00d5f20eeac01
+1 -1
View File
@@ -13,7 +13,7 @@ namespace KernelPanic.Run
public const int BossWave = 10;
public const int LegacyBossWave = 5;
public const int RepairUptime = 6;
public const int ChallengeBits = 4;
public const int ChallengeBits = 8;
public bool campaign;
public bool endless;
public WaveRoute selectedRoute;
+1 -1
View File
@@ -126,7 +126,7 @@ namespace KernelPanic.Run
public static string Detail(WaveRoute route) => route switch
{
WaveRoute.Repair => "Restore up to 6 Uptime on departure.",
WaveRoute.Challenge => "Fight an extra Daemon. On clear: +4 Bits and a draw rider on the first eligible card; +4 more Bits if none is eligible.",
WaveRoute.Challenge => $"Fight an extra Daemon. On clear: +{RunJourney.ChallengeBits} Bits and a draw rider on the first eligible card; +{RunJourney.ChallengeBits} more Bits if none is eligible.",
WaveRoute.Cache => "Recover 6 Bits on departure. No extra enemy.",
WaveRoute.Forge => "Choose a card to gain +2 effect magnitude for this run. You may pass.",
WaveRoute.Sacrifice => "Remove one card from this run's deck. Give a different card +4 effect magnitude for this run. You may pass.",
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 372820aa42b941dfb4d10fa36ef42dec
+33 -5
View File
@@ -520,6 +520,26 @@ namespace KernelPanic.UI
_handRow = new();
_handRow.AddToClassList("hand-row");
_handScroll.Add(_handRow);
_handScroll.contentViewport.RegisterCallback<GeometryChangedEvent>(_ => FitHandCardsToViewport());
// ScrollView aligns oversized focused cards to the bottom, hiding identity/cost.
// Handle focus before it reaches the scroller and reveal the top of tall cards.
handPanel.RegisterCallback<FocusInEvent>(evt =>
{
if (evt.target is not Button face || !face.ClassListContains("hand-card")) return;
evt.StopPropagation();
void RevealCard()
{
// Reveal the identity region itself: requesting the full face lets
// ScrollView's deferred layout scroll back down to its bottom edge.
_handScroll.ScrollTo(face.Q(className: "software-name"));
_handScroll.ScrollTo(face.Q(className: "software-header"));
}
RevealCard();
_handScroll.schedule.Execute(() =>
{
if (handPanel.focusController?.focusedElement == face) RevealCard();
});
}, TrickleDown.TrickleDown);
VisualElement commandPanel = CreatePanel("dispatch", "turn controls", 0);
commandPanel.AddToClassList("turn-panel");
@@ -1080,6 +1100,14 @@ namespace KernelPanic.UI
}
}
private void FitHandCardsToViewport()
{
float width = _handScroll.contentViewport.contentRect.width;
if (width <= 0) return;
foreach (var face in _retainedHandCards.Values)
face.style.maxWidth = Mathf.Max(1, width - face.resolvedStyle.marginLeft - face.resolvedStyle.marginRight);
}
private void RefreshHand()
{
TerminalTheme.PreserveFocus(_handRow);
@@ -1106,7 +1134,6 @@ namespace KernelPanic.UI
if (added)
{
face = CardFace(card);
face.RegisterCallback<FocusInEvent>(_ => _handScroll.ScrollTo(face));
_retainedHandCards[card] = face;
_handRow.Add(face);
}
@@ -1130,6 +1157,7 @@ namespace KernelPanic.UI
_handCardElements[card] = face;
if (added) PlayElementBeat(face, "hand-card-drawn", 180);
}
FitHandCardsToViewport();
}
private void RefreshTurnPanel()
@@ -1639,9 +1667,9 @@ namespace KernelPanic.UI
copy.Add(title);
var subtitle = new Label(_runManager.CampaignChoicePending
? "bank your rewards or continue into endless"
: reward ? "1 / claim reward > 2 / choose route > 3 / enter stop"
: eventScreen ? committed ? "stop complete / ready for battle" : "choose your cards / nothing changes until you confirm"
: $"preparing wave {_runManager.CurrentWaveNumber} / {_runManager.Bits} bits remaining");
: reward ? "1. claim reward > 2. choose route > 3. enter stop"
: eventScreen ? committed ? "stop complete. ready for battle" : "choose your cards. nothing changes until you confirm"
: $"preparing wave {_runManager.CurrentWaveNumber} {_runManager.Bits} bits remaining");
subtitle.AddToClassList("repository-subtitle");
copy.Add(subtitle);
header.Add(copy);
@@ -1664,7 +1692,7 @@ namespace KernelPanic.UI
}
if (committed)
{
var save = new Button(SaveAndExitRun) { name = "SaveAndExitRunButton", text = "save and exit / keep this result" };
var save = new Button(SaveAndExitRun) { name = "SaveAndExitRunButton", text = "save and exit" };
save.AddToClassList("secondary-action"); body.Add(save);
}
screen.Add(body);
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a41d2608975f4d4c99e00d5f20eeac03
+9 -8
View File
@@ -36,16 +36,17 @@ namespace KernelPanic.UI
bool boss = node.Wave == run.Journey.FinalWave && !run.Journey.endless;
string phase = run.Journey.endless ? "SURVIVAL" : node.Wave <= 3 ? "BOOT SECTOR"
: node.Wave <= 6 ? "ESCALATION" : boss ? "FINAL ENCOUNTER" : "KERNEL PERIMETER";
preview.Add(Text($"{node.Wave:00} / {(run.Journey.endless ? "ENDLESS" : run.Journey.FinalWave.ToString("00"))} {phase}", "route-map-eyebrow"));
string progress = run.Journey.endless ? $"WAVE {node.Wave:00}" : $"WAVE {node.Wave:00} OF {run.Journey.FinalWave:00}";
preview.Add(Text($"{progress}\n{phase}", "route-map-eyebrow"));
string state = node.Wave < current ? run.Journey.visits.Any(v => v.nodeId == node.Id) ? "CLEARED" : "NOT TAKEN"
: node.Wave > current ? "FUTURE STOP" : node.Id == run.Journey.selectedNodeId ? "SELECTED DESTINATION"
: run.AvailableRouteNodes.Any(n => n.Id == node.Id) ? "AVAILABLE / select to take this path" : "UNREACHABLE FROM HERE";
: run.AvailableRouteNodes.Any(n => n.Id == node.Id) ? "AVAILABLE" : "UNREACHABLE FROM HERE";
preview.Add(Text(state, "route-preview-state"));
preview.Add(Text(boss ? "Kernel Overseer" : RunRouteMap.Title(node.Route), "route-detail-title"));
preview.Add(Text(boss ? "Defeat the Overseer to complete the route. Bank your rewards, or continue this build in endless survival."
: RunRouteMap.Detail(node.Route), "route-detail-copy"));
var encounter = EncounterDirector.Plan(node.Wave, node.Route, seed, run.Journey.encounterRevision);
preview.Add(Text("BATTLE / " + encounter.Title, "route-map-eyebrow"));
preview.Add(Text("BATTLE: " + encounter.Title, "route-map-eyebrow"));
preview.Add(Text(encounter.Advice, "route-detail-copy"));
if (node.Wave == current && run.Journey.resolvedEventWave == current && node.Id == run.Journey.selectedNodeId)
preview.Add(Text("[ resolved ]\n" + run.Journey.eventOutcome, "route-map-history"));
@@ -114,7 +115,7 @@ namespace KernelPanic.UI
tile.EnableInClassList("map-boss", wave == run.Journey.FinalWave && !run.Journey.endless);
tile.Add(Glyph(node.Route));
tile.Add(Text(wave == run.Journey.FinalWave && !run.Journey.endless ? "BOSS" : CompactTitle(node.Route), "route-map-name"));
tile.tooltip = $"Wave {wave} / {RunRouteMap.Title(node.Route)}\n{RunRouteMap.Detail(node.Route)}";
tile.tooltip = $"Wave {wave}: {RunRouteMap.Title(node.Route)}\n{RunRouteMap.Detail(node.Route)}";
tile.RegisterCallback<MouseEnterEvent>(_ => Preview(node));
tile.RegisterCallback<MouseLeaveEvent>(_ => SelectedPreview());
tile.RegisterCallback<FocusInEvent>(_ => Preview(node));
@@ -209,10 +210,10 @@ namespace KernelPanic.UI
});
if (run.Journey.visits.Count > 0)
{
var history = new Foldout { text = "Travel journal / " + run.Journey.visits.Count + " decisions", value = false, name = "RouteHistory" };
var history = new Foldout { text = $"Travel journal ({run.Journey.visits.Count})", value = false, name = "RouteHistory" };
history.AddToClassList("route-map-journal");
foreach (var visit in run.Journey.visits)
history.Add(Text($"Wave {visit.wave} / {RunRouteMap.Title(visit.route)}\n{visit.outcome}", "route-map-history"));
history.Add(Text($"Wave {visit.wave}: {RunRouteMap.Title(visit.route)}\n{visit.outcome}", "route-map-history"));
detail.Add(history);
}
layout.Add(map);
@@ -310,7 +311,7 @@ namespace KernelPanic.UI
{
previews.Add(Preview(target, run, "BEFORE UPGRADE"));
var after = target.CopyForCombat(); after.ApplyMagnitudeUpgrade(amount);
previews.Add(Preview(after, run, $"AFTER / +{amount} EFFECT"));
previews.Add(Preview(after, run, $"AFTER: +{amount} EFFECT"));
}
bool valid = (!remove || (donor != null && run.RunDeck.Count > 1)) && (!upgrade || target != null)
&& (!remove || !upgrade || donor != target);
@@ -336,7 +337,7 @@ namespace KernelPanic.UI
panel.Add(previews); panel.Add(result);
commit.clicked += () => run.ResolveRouteEvent(Donor(), Target());
panel.Add(commit);
var skip = new Button(() => run.ResolveRouteEvent(skip: true)) { text = "pass / keep my deck", name = "SkipRouteEventButton" };
var skip = new Button(() => run.ResolveRouteEvent(skip: true)) { text = "keep my deck", name = "SkipRouteEventButton" };
skip.AddToClassList("secondary-action"); skip.SetEnabled(!run.BuildRewardPending); panel.Add(skip);
Refresh();
return panel;
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 903793052b8846bf84d043d40c69cd31
+3 -3
View File
@@ -35,7 +35,7 @@ namespace KernelPanic.UI
AddChoice(choices, run, WaveRoute.Repair, "Repair stop",
$"Restore up to {RunJourney.RepairUptime} Uptime on departure. Fight the standard encounter.");
AddChoice(choices, run, WaveRoute.Challenge, "Elite detour",
$"Extra Daemon. On clear: +{RunJourney.ChallengeBits} Bits and +1 draw on the first card without a draw rider (or +{RunJourney.ChallengeBits} Bits if none)."
RunRouteMap.Detail(WaveRoute.Challenge)
+ (run.Journey.selectedRoute == WaveRoute.Challenge
? $"\nElite: {(plan.EscortShield > 0 ? $"+{plan.EscortShield} Shield" : plan.EscortUptime > 0 ? $"+{plan.EscortUptime} Uptime" : "hidden intent")}." : ""));
section.Add(choices);
@@ -63,7 +63,7 @@ namespace KernelPanic.UI
var draw = new Button { name = "RewardDraw", text = "Draw +1 on resolution" };
effect.AddToClassList("primary-action"); draw.AddToClassList("primary-action");
modes.Add(effect); modes.Add(draw);
var claim = Action("claim upgrade / open map", "ClaimBuildRewardButton", () => run.ClaimBuildReward(cards[index], kind));
var claim = Action("claim upgrade", "ClaimBuildRewardButton", () => run.ClaimBuildReward(cards[index], kind));
content.Add(claim);
void Refresh()
{
@@ -93,7 +93,7 @@ namespace KernelPanic.UI
Refresh();
content.Add(target);
}
content.Add(Action($"take {RunManager.BuildRewardBits} Bits instead / open map", "RewardBits",
content.Add(Action($"take {RunManager.BuildRewardBits} Bits instead", "RewardBits",
() => run.ClaimBuildReward(null, CardUpgradeKind.MagnitudeUp, true)));
return content;
}
+13 -5
View File
@@ -115,6 +115,7 @@ public class CampaignTests
for (int wave = 1; wave <= 12; wave++)
{
var plan = EncounterDirector.Plan(wave, WaveRoute.Repair, seed, 2);
Assert.That(plan.Title, Does.Not.Contain("/"));
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 < 10) Assert.That(plan.Enemies, Does.Not.Contain("kernel_overseer"));
@@ -314,19 +315,26 @@ public class CampaignTests
Assert.That(_run.SelectRoute(WaveRoute.Challenge), Is.False, "No changing route during combat.");
}
[Test]
public void ChallengeChangesEncounterAndPaysOneRewardOnlyAfterClear()
[TestCase(false, 8)]
[TestCase(true, 16)]
public void ChallengeChangesEncounterAndPaysOneRewardOnlyAfterClear(bool allCardsHaveRiders, int expectedBits)
{
RepositoryAfter(1);
if (allCardsHaveRiders)
foreach (var card in _run.RunDeck) card.ApplyDrawRider(1);
int ridersBefore = _run.RunDeck.Sum(card => card.DrawRider);
_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);
Assert.That(_run.Bits, Is.Zero, "Selecting or entering an elite pays nothing.");
Assert.That(_run.RunDeck.Sum(card => card.DrawRider), Is.EqualTo(ridersBefore));
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.Bits, Is.EqualTo(expectedBits));
Assert.That(_run.RunDeck.Sum(card => card.DrawRider), Is.EqualTo(ridersBefore + (allCardsHaveRiders ? 0 : 1)));
Assert.That(_run.Journey.lastReward, Does.Contain($"+{expectedBits} Bits"));
Assert.That(RunRouteMap.Detail(WaveRoute.Challenge), Does.Contain("+8 Bits").And.Contain("+8 more Bits"));
Assert.That(_run.CurrentWaveNumber, Is.EqualTo(3));
}
@@ -173,6 +173,52 @@ public class CombatLayoutTests
}
}
[UnityTest]
public IEnumerator HandFocusRevealsNameAndCostAndStillAllowsRulesScrolling()
{
bool testedOversizedCard = false;
foreach (var size in Viewports)
foreach (var textSize in new[] { UITextSize.Standard, UITextSize.Large })
{
UIPreferences.TextSize = textSize;
Resize(size);
Call(_view, "RefreshHand");
for (int frame = 0; frame < 5; frame++) yield return null;
var scroll = _root.Q<ScrollView>(className: "hand-scroll");
var faces = scroll.Query<Button>(className: "hand-card").ToList();
string context = $"{size}, {textSize}";
testedOversizedCard |= faces.Any(face => face.worldBound.height > scroll.contentViewport.worldBound.height);
scroll.scrollOffset = new Vector2(scroll.horizontalScroller.highValue, scroll.verticalScroller.highValue);
// Moving focus twice before layout must not restore a stale card's position.
faces[0].Focus();
faces[faces.Count - 1].Focus();
for (int frame = 0; frame < 3; frame++) yield return null;
foreach (var face in new[] { faces[faces.Count - 1], faces[0] })
{
face.Focus();
for (int frame = 0; frame < 3; frame++) yield return null;
foreach (string className in new[] { "software-name", "software-cost" })
{
var label = face.Q<Label>(className: className);
AssertContainedHorizontally(label, scroll.contentViewport, context);
Assert.That(label.worldBound.yMin, Is.GreaterThanOrEqualTo(scroll.contentViewport.worldBound.yMin - 1),
$"{context}; {className}; face={face.worldBound}; viewport={scroll.contentViewport.worldBound}; content={scroll.contentContainer.worldBound}; offset={scroll.scrollOffset}; focus={_root.focusController.focusedElement == face}");
Assert.That(label.worldBound.yMax, Is.LessThanOrEqualTo(scroll.contentViewport.worldBound.yMax + 1), context);
}
}
Call(_view, "RefreshHand");
for (int frame = 0; frame < 3; frame++) yield return null;
Assert.That(_root.focusController.focusedElement, Is.SameAs(faces[0]), context);
scroll.scrollOffset = new Vector2(scroll.scrollOffset.x, scroll.verticalScroller.highValue);
float rulesOffset = scroll.scrollOffset.y;
for (int frame = 0; frame < 3; frame++) yield return null;
Assert.That(rulesOffset, Is.EqualTo(scroll.verticalScroller.highValue).Within(1), context);
Assert.That(scroll.scrollOffset.y, Is.EqualTo(rulesOffset).Within(1), context + ": focus must not pin scrolling");
faces[0].Blur();
}
Assert.That(testedOversizedCard, Is.True, "Exercise at least one card taller than the hand viewport.");
}
[UnityTest]
public IEnumerator FirstBattleGuideAndReplayControlFitAcrossViewports()
{
@@ -315,6 +361,8 @@ public class CombatLayoutTests
for (int i = 0; i < 8; i++) yield return null;
var scroll = _root.Q<ScrollView>("RouteMapScroll");
var canvas = _root.Q("RouteCanvas");
Assert.That(_root.Q("RunMap").Query<Label>().ToList().Any(l => l.text.Contains("/")), Is.False,
"Route labels should not use decorative slash separators.");
Assert.That(scroll.worldBound.width, Is.GreaterThan(size.x * .55f));
Assert.That(scroll.worldBound.height, Is.GreaterThan(size.y * .5f));
Assert.That(canvas.Query(className: "route-map-wave").ToList().Count, Is.EqualTo(9));