Refactor alot of stuff

This commit is contained in:
2026-10-29 22:54:29 +01:00
parent c23b666ee4
commit 260abc2c98
138 changed files with 2835 additions and 466 deletions
+9 -7
View File
@@ -86,6 +86,7 @@ namespace KernelPanic.Editor
public string routePolicy = "legacy";
public bool startersOnly;
public bool prefetch = true;
public string combatPolicy = "language";
public string outputDirectory = "Artifacts/Balance";
public static Options Parse(string[] args)
@@ -109,6 +110,7 @@ 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 "-balanceCombatPolicy": result.combatPolicy = Value(args, ref i).ToLowerInvariant(); break;
case "-balanceStartersOnly": result.startersOnly = bool.Parse(Value(args, ref i)); break;
case "-balanceRoutePolicy": result.routePolicy = Value(args, ref i).ToLowerInvariant(); break;
case "-balanceRoute":
@@ -130,6 +132,7 @@ namespace KernelPanic.Editor
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);
if (result.combatPolicy != "greedy" && result.combatPolicy != "language") throw new ArgumentException("balanceCombatPolicy must be greedy or language.");
return result;
}
@@ -278,11 +281,11 @@ namespace KernelPanic.Editor
[Serializable]
public sealed class Report
{
public int schemaVersion = 5;
public int schemaVersion = 6;
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.";
public string limitations = "A bounded heuristic benchmark, not optimal play or a balance verdict. Conditional/draw/setup effects are undervalued during combat; fixed exclusive choice; upgrade-first shopping is not optimal deckbuilding; different loadouts consume RNG differently. Wave/round caps are censored survivors, not wins. Uptime damage excludes shield and overkill; partial final rounds count. Resource metrics sample explicitly ended Execute turns only: native clears and mid-turn defeats are excluded. Empty hand does not prove lack of draw is the cause of a defeat.";
public string policy = "Combat policy selected by options.combatPolicy: greedy preview or language-aware setup/draw/persistent-work scoring; 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.";
public string limitations = "A bounded heuristic benchmark, not optimal play or a balance verdict. Language-aware scoring estimates setup value but does not search future turns; fixed exclusive choice; upgrade-first shopping is not optimal deckbuilding; different loadouts consume RNG differently. Wave/round caps are censored survivors, not wins. Uptime damage excludes shield and overkill; partial final rounds count. Resource metrics sample explicitly ended Execute turns only: native clears and mid-turn defeats are excluded. Empty hand does not prove lack of draw is the cause of a defeat.";
public Options options;
public List<Scenario> scenarios;
public List<RunResult> runs = new();
@@ -398,7 +401,7 @@ namespace KernelPanic.Editor
{
var text = new StringBuilder("# Seeded combat comparison\n\n");
text.AppendLine(report.policy).AppendLine().AppendLine(report.limitations).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($"Encounter revision 4 / map revision 2, ten-wave campaign, then endless. Combat policy: {report.options.combatPolicy}. 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 |");
@@ -524,9 +527,7 @@ namespace KernelPanic.Editor
if (card.Definition == null || card.Definition.IsToken || card.IsBroken || card.IsLocked
|| _combat.GoPlayBlockReason(card) != null
|| _combat.GetDisplayedPlayCost(card) > _combat.PlayerState.Cycles) continue;
var preview = CardPreviewService.Build(_combat, card, target);
double damage = (preview.MinimumDamage + (double)preview.MaximumDamage) / 2;
double score = (damage + preview.Shield * 0.7 + preview.Heal * 1.5 + preview.Repairs * 3 + 1) / (preview.Cost + 1);
double score = BalancePolicy.Score(_combat, card, target, _report.options.combatPolicy == "language");
if (score <= best) continue;
best = score;
chosen = card;
@@ -685,6 +686,7 @@ namespace KernelPanic.Editor
if (++_seedIndex >= _report.options.seeds.Length) { _seedIndex = 0; _scenarioIndex++; }
if (_scenarioIndex < _report.scenarios.Count) { Begin(); return; }
Directory.CreateDirectory(_report.options.outputDirectory);
// Export standalone reports without a baseline-comparison dependency.
File.WriteAllText(Path.Combine(_report.options.outputDirectory, "balance-comparison.json"), JsonUtility.ToJson(_report, true), new UTF8Encoding(false));
File.WriteAllText(Path.Combine(_report.options.outputDirectory, "balance-comparison.md"), ToMarkdown(_report), new UTF8Encoding(false));
Debug.Log($"Balance comparison complete: {_report.runs.Count} measured runs, {_report.scenarios.Count} verified repeats. {_report.options.outputDirectory}");
+66
View File
@@ -0,0 +1,66 @@
using System;
using System.Linq;
using KernelPanic.Combat;
using KernelPanic.Core;
namespace KernelPanic.Editor
{
/// <summary>Public-state heuristics; no hidden intent, random sampling or speculative execution.</summary>
public static class BalancePolicy
{
public static double Score(CombatManager combat, CardInstance card, CombatantState target, bool languageAware)
{
var preview = CardPreviewService.Build(combat, card, target);
double damage = (preview.MinimumDamage + (double)preview.MaximumDamage) / 2;
double value = damage + preview.Shield * .7 + preview.Heal * 1.5 + preview.Repairs * 3 + 1;
if (!languageAware || !CardCatalog.TryGet(card.Definition.Id, out var entry)) return value / (preview.Cost + 1);
int remainingCycles = combat.PlayerState.Cycles - preview.Cost;
int freeRam = combat.HandController.RemainingRam + HandController.GetRamCost(card);
var payloads = combat.HandController.Cards.Where(c => c != card && !c.IsBroken && !c.IsLocked
&& PythonPipeline.IsPayload(c.Definition) && combat.GetDisplayedPlayCost(c) <= remainingCycles).ToArray();
double payloadValue = payloads.Select(c => CardPreviewService.Build(combat, c, target))
.Select(p => (p.MinimumDamage + (double)p.NormalMaximumDamage) / 2 + p.Shield * .7).DefaultIfEmpty(0).Max();
foreach (var effect in entry.Effects)
{
switch (effect.Kind)
{
case CardEffectKind.Draw: case CardEffectKind.FixedDraw:
value += Math.Min(freeRam, Math.Max(0, effect.Amount)) * (remainingCycles > 0 ? 5 : 1); break;
case CardEffectKind.Python:
switch ((PythonOperation)effect.SecondaryAmount)
{
case PythonOperation.Loop: if (combat.Python.RepeatCount == 0) value += payloadValue; break;
case PythonOperation.Zip: if (combat.Python.AreaCount == 0) value += payloadValue * Math.Min(2, combat.Enemies.Count(e => !e.State.IsDefeated) - 1); break;
case PythonOperation.Async: if (combat.Python.AutomationCount < 2) value += payloadValue * 1.5; break;
case PythonOperation.Draw: case PythonOperation.Inspect: value += Math.Min(2, freeRam) * (remainingCycles > 0 ? 5 : 1); break;
case PythonOperation.Install: value += Math.Min(3, combat.HandController.Cards.Count(c => c != card && c.Definition.Language == Language.Python)) * 3; break;
}
break;
case CardEffectKind.Go:
if ((GoOperation)effect.SecondaryAmount == GoOperation.Deploy) value += damage * Math.Min(2, Math.Max(0, effect.MaxAmount - 1));
if ((GoOperation)effect.SecondaryAmount == GoOperation.Extend)
value += combat.Go.Active.Where(g => combat.Go.CanExtend(g)).Select(g => (double)g.BaseDamage).DefaultIfEmpty(0).Max();
if ((GoOperation)effect.SecondaryAmount == GoOperation.ExtendAll)
value += combat.Go.Active.Where(g => combat.Go.CanExtend(g)).Sum(g => (double)g.BaseDamage);
break;
case CardEffectKind.MakeJ4: value += combat.LazyStack.Count * 4; break;
case CardEffectKind.CompilationDraw: value += Math.Min(freeRam, combat.Compilation.Level) * 4; break;
}
}
if (card.Definition.Language == Language.Java && preview.Cost > 0) value += 1.5;
if (card.Definition.Language == Language.Haskell && card.Definition.ResolutionTrack == ResolutionTrack.LazyStack)
{
// Cheap setup entries deepen the stack before the larger payload is placed on top.
double nextPayload = combat.HandController.Cards.Where(c => c != card && c.Definition.Language == Language.Haskell
&& !c.IsBroken && !c.IsLocked && combat.GetDisplayedPlayCost(c) <= remainingCycles)
.Select(c => CardPreviewService.Build(combat, c, target)).Select(p => (double)p.NormalMaximumDamage).DefaultIfEmpty(0).Max();
if (nextPayload > damage) value += nextPayload * .5;
}
// Shield loses value beyond the publicly announced attack total; hidden intents remain unknown.
int incoming = combat.Enemies.Where(e => !e.State.IsDefeated).Sum(e =>
e.DisplayIntent.Kind is EnemyIntentKind.Attack or EnemyIntentKind.StatusAttack ? e.DisplayIntent.MaxValue : 0);
if (combat.PlayerState.Shield >= incoming && incoming > 0) value -= preview.Shield * .4;
return value / (preview.Cost + 1);
}
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ad13c81c8b4580447a294437a99596bb
+43
View File
@@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using KernelPanic.Combat;
using KernelPanic.Core;
using KernelPanic.Data;
using KernelPanic.Editor;
using KernelPanic.Run;
using NUnit.Framework;
using UnityEditor;
using UnityEngine;
public class BalancePolicyTests
{
[Test]
public void PythonSetupGetsValueOnlyWhenAnAffordablePayloadCanFollow()
{
var cards = AssetDatabase.LoadAssetAtPath<CardDatabase>("Assets/Data/Cards/CardDatabase.asset");
var distro = AssetDatabase.LoadAssetAtPath<DistroDefinition>("Assets/Data/Distros/Ubuntu.asset");
CardDefinition Find(PythonOperation operation) => cards.AllCards.First(c => c != null && CardCatalog.TryGet(c.Id, out var e)
&& e.Effects.Any(f => f.Kind == CardEffectKind.Python && f.SecondaryAmount == (int)operation));
var owner = new GameObject("balance policy test"); owner.SetActive(false);
try
{
var combat = owner.AddComponent<CombatManager>();
void Set(string field, object value) => typeof(CombatManager).GetField(field, BindingFlags.Instance | BindingFlags.NonPublic).SetValue(combat, value);
var loop = new CardInstance(Find(PythonOperation.Loop)); var payload = new CardInstance(Find(PythonOperation.Print));
Set("_runConfig", new RunConfig(distro, Language.Python, Language.Go, new[] { loop.Definition, payload.Definition }, Array.Empty<PackageInstance>(), 123, 1));
Set("_playerState", new CombatantState(60, 8, 10)); Set("_handController", new HandController(8));
combat.Python.Bind(combat); combat.HandController.Add(loop); combat.HandController.Add(payload);
var enemy = new EnemyInstance(EnemyArchetypeCatalog.Get("firewalld"), 100);
((List<EnemyInstance>)combat.Enemies).Add(enemy);
int cursor = RandomRoll.DrawCount;
double greedy = BalancePolicy.Score(combat, loop, enemy.State, false);
Assert.That(BalancePolicy.Score(combat, loop, enemy.State, true), Is.GreaterThan(greedy));
combat.HandController.Remove(payload);
Assert.That(BalancePolicy.Score(combat, loop, enemy.State, true), Is.EqualTo(greedy));
Assert.That(RandomRoll.DrawCount, Is.EqualTo(cursor));
}
finally { UnityEngine.Object.DestroyImmediate(owner); }
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 3ab219f11f294145bf115ce0b054ceb1