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()
{