add C++, Typescript and more stuff

This commit is contained in:
2026-10-28 00:15:08 +01:00
parent e99e6386e8
commit ea0f475cae
108 changed files with 2488 additions and 980 deletions
+3 -2
View File
@@ -89,7 +89,7 @@ namespace KernelPanic.Combat
CardEffectKind.ConsultWiki => new ConsultWikiEffect(),
CardEffectKind.RandomCommonLanguageCard => new RandomCommonLanguageCardEffect(),
CardEffectKind.MinimalInstall => new MinimalInstallEffect(),
CardEffectKind.SizeofDamage => new SizeofDamageEffect(),
CardEffectKind.SizeofDamage => Language == Language.CPlusPlus ? new CppSizeofDamageEffect() : new SizeofDamageEffect(),
CardEffectKind.RepairCorruptedCards => new RepairCorruptedCardsEffect(Amount),
_ => throw new InvalidOperationException($"Unsupported authored effect {Kind}.")
};
@@ -174,7 +174,7 @@ namespace KernelPanic.Combat
/// Each built-in card ID is authored once here. Asset IDs and serialized effect overrides
/// stay unchanged; adding a card no longer requires parallel effect, targeting and rules switches.
/// </summary>
public static class CardCatalog
public static partial class CardCatalog
{
private const CardTargeting None = CardTargeting.None;
private const CardTargeting Single = CardTargeting.SingleEnemy;
@@ -322,6 +322,7 @@ namespace KernelPanic.Combat
Add("shop_java_system_gc", None, false, "uses 2 RAM. repair up to {amount:0} corrupted cards in your active deck. gain {shield:1} Shield. advances JIT warmup.", Fx(CardEffectKind.RepairCorruptedCards, 2), Shield(4));
Add("shop_java_jit_compile", Single, true, "uses 2 RAM. deal {amount:0}. Java cards cost 1 less this turn." + Jit, Fx(CardEffectKind.FirstToPackage, 8, language: Language.Java));
AddEvolvedCards(entries);
var byId = new Dictionary<string, CardCatalogEntry>(StringComparer.Ordinal);
foreach (CardCatalogEntry entry in entries) byId.Add(entry.Id, entry);
Entries = entries.AsReadOnly();
@@ -46,6 +46,8 @@ namespace KernelPanic.Combat
{
int capacity = request.Target == null ? 0 : CardDamageLanguageRules.GetDamageCapacity(request.Target, request.TrueDamage);
DamageResult result = context.DamagePipeline.DealDamage(request);
if (ReferenceEquals(request.Source, context.CombatManager.PlayerState) && !ReferenceEquals(request.Target, request.Source))
GameEvents.RaiseCardContribution(new CardContributionEvent(context.Card, result.UptimeDamage, result.ShieldDamage));
// Preserve ordering: shield conversion precedes enemy death payloads, then spill follows removal queuing.
if (request.IsCardDamage)
CardDamageLanguageRules.ApplyOverkillShield(context, result, capacity, request.Language, overkillToShield);
@@ -48,8 +48,8 @@ namespace KernelPanic.Combat
private static bool IsSpillDamage(CombatContext context, Language language)
{
Language cardLanguage = context.Card?.Definition?.Language ?? language;
return language == Language.C || language == Language.Java
|| cardLanguage == Language.C || cardLanguage == Language.Java;
return language is Language.C or Language.CPlusPlus or Language.Java
|| cardLanguage is Language.C or Language.CPlusPlus or Language.Java;
}
private static bool SpillOverkillDamage(CombatContext context, CombatantState firstTarget,
@@ -87,7 +87,10 @@ namespace KernelPanic.Combat
context.CombatManager.ReportEffectResult($"overkill shield blocked: {overkill}");
return;
}
int before = context.Source.Shield;
context.CombatManager.GrantPlayerShield(overkill, reason);
GameEvents.RaiseCardContribution(new CardContributionEvent(context.Card,
shieldGranted: System.Math.Max(0, context.Source.Shield - before)));
}
}
}
+4 -2
View File
@@ -203,7 +203,8 @@ namespace KernelPanic.Combat
damage = true;
break;
case CardEffectKind.SizeofDamage:
low = high = effect.Amount * HandAfterPlay(combat, card).Count(c => c.Definition?.Language == Language.C);
low = high = effect.Amount * HandAfterPlay(combat, card).Count(c => c.Definition?.Language == Language.C
|| effect.Language == Language.CPlusPlus && c.Definition?.Language == Language.CPlusPlus);
damage = true;
break;
case CardEffectKind.ShieldRepeatDamage:
@@ -334,7 +335,8 @@ namespace KernelPanic.Combat
if (hitCount > 1) notes.Add($"{hitCount} hits in total; later hits can stop when a target dies or combat ends.");
if (trueDamage) notes.Add("True damage bypasses Shield.");
if (random) notes.Add("Random amounts show the full normal range.");
if (critical) notes.Add($"Critical chance: C {CombatTuning.CCriticalChancePercent}%, other languages 25%; each hit rolls independently.");
if (critical) notes.Add($"Critical chance: C {CombatTuning.CCriticalChancePercent}%, C++ {CombatTuning.CCriticalChancePercent}%, other languages 25%; each hit rolls independently.");
if (card.Definition.Language == Language.CPlusPlus) notes.Add("C++ spills all remaining excess damage. No segfault recoil.");
if (card.Definition.Language == Language.C)
notes.Add($"C spills {CombatTuning.COverkillSpillPercent}% of remaining overkill per jump, rounded down; spill cannot crit or reapply source bonuses.");
if (rust) notes.Add(source.ForceMaxRolls
@@ -17,7 +17,10 @@ namespace KernelPanic.Combat
return;
}
int before = context.Source.Shield;
context.CombatManager.GrantPlayerShield(context.ScaleExplicitShield(amount), label);
Core.GameEvents.RaiseCardContribution(new Core.CardContributionEvent(context.Card,
shieldGranted: System.Math.Max(0, context.Source.Shield - before)));
}
}
}
@@ -0,0 +1,117 @@
using System;
using System.Collections.Generic;
using KernelPanic.Core;
namespace KernelPanic.Combat
{
public sealed class ExecutionAction
{
public string Stage { get; internal set; }
public string Label { get; internal set; }
public bool Complete { get; internal set; }
public long UptimeDamage { get; internal set; }
public long ShieldDamage { get; internal set; }
public long ShieldGranted { get; internal set; }
public long PlayerUptimeLost { get; internal set; }
public long PlayerShieldBlocked { get; internal set; }
public List<string> Details { get; } = new();
}
/// <summary>A bounded journal of observed actions. Never predicts or executes combat.</summary>
public sealed class CombatExecutionTrace : IDisposable
{
private readonly List<ExecutionAction> _actions = new();
private readonly Stack<ExecutionAction> _active = new();
private readonly CombatManager _combat;
public IReadOnlyList<ExecutionAction> Actions => _actions;
public string Stage { get; private set; } = "Native";
public event Action Changed;
public CombatExecutionTrace(CombatManager combat)
{
_combat = combat;
GameEvents.CardResolving += BeginCard;
GameEvents.CardResolved += EndCard;
GameEvents.BackgroundAction += Background;
GameEvents.EnemyWouldAct += BeginEnemy;
GameEvents.EnemyActed += EndEnemy;
GameEvents.DamageDealt += Damage;
GameEvents.CardContribution += Contribution;
GameEvents.PhaseChanged += Phase;
if (_combat != null) _combat.CombatLog += Detail;
}
private void Begin(string stage, string label)
{
Stage = stage;
var action = new ExecutionAction { Stage = stage, Label = label };
_actions.Add(action); _active.Push(action);
if (_actions.Count > 12) _actions.RemoveAt(0);
Changed?.Invoke();
}
private void End()
{
if (_active.Count > 0) _active.Pop().Complete = true;
Changed?.Invoke();
}
private void BeginCard(CardResolvedEvent value) => Begin(value.Track switch
{ ResolutionTrack.InterpreterQueue => "FIFO", ResolutionTrack.LazyStack => "LIFO", _ => "Native" }, value.Card?.Definition?.DisplayName ?? "Card");
private void EndCard(CardResolvedEvent value) => End();
private void Background(BackgroundActionEvent value)
{ if (value.Started) Begin(value.Stage, value.Label); else End(); }
private void BeginEnemy(EnemyWouldActEvent value) => Begin("Enemies", value.Enemy.Name + " / " + value.Enemy.DisplayIntent.DisplayText);
private void EndEnemy(EnemyActedEvent value) => End();
private void Damage(DamageDealtEvent value)
{
bool standalone = _active.Count == 0;
if (standalone) Begin(Stage, value.Cause ?? "Status or passive damage");
var action = _active.Peek();
if (_combat != null && ReferenceEquals(value.Target, _combat.PlayerState))
{
action.PlayerUptimeLost += Math.Max(0, value.UptimeDamage);
action.PlayerShieldBlocked += Math.Max(0, value.ShieldDamage);
}
else
{
action.UptimeDamage += Math.Max(0, value.UptimeDamage);
action.ShieldDamage += Math.Max(0, value.ShieldDamage);
}
if (standalone) End();
Changed?.Invoke();
}
private void Contribution(CardContributionEvent value)
{
if (_active.Count == 0) return;
_active.Peek().ShieldGranted += Math.Max(0, value.ShieldGranted);
Changed?.Invoke();
}
private void Detail(string text)
{
if (_active.Count == 0 || string.IsNullOrWhiteSpace(text)) return;
var details = _active.Peek().Details;
if (details.Count == 3) details.RemoveAt(0);
details.Add(text);
Changed?.Invoke();
}
private void Phase(PhaseChangedEvent value)
{
if (value.NextPhase == TurnPhase.Boot) { _actions.Clear(); _active.Clear(); }
Stage = value.NextPhase switch
{
TurnPhase.Interpret => "Go", TurnPhase.EnemyProcess => "Enemies",
TurnPhase.GarbageCollection => "Cleanup", _ => "Native"
};
// Completed results stay readable during the next planning phase.
Changed?.Invoke();
}
public void Dispose()
{
GameEvents.CardResolving -= BeginCard; GameEvents.CardResolved -= EndCard;
GameEvents.BackgroundAction -= Background;
GameEvents.EnemyWouldAct -= BeginEnemy; GameEvents.EnemyActed -= EndEnemy;
GameEvents.DamageDealt -= Damage; GameEvents.CardContribution -= Contribution;
GameEvents.PhaseChanged -= Phase;
if (_combat != null) _combat.CombatLog -= Detail;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 6022b4bda31aa9a48a5e9db43f5713e7
@@ -129,6 +129,7 @@ namespace KernelPanic.Combat
CardScaling.Add(_playerState?.FlatEffectBonus ?? 0, _playerState?.FlatCardDamageBonus ?? 0));
internal void ResolveGoroutineTick(Goroutine work)
{
using var observed = new ObservedBackgroundAction(work.SourceCard, "Go", $"PID {work.Id:000} / {work.SourceCard.Definition.DisplayName}");
if (!IsLiveGoTarget(work.Target)) work.Target = FirstLivingGoTarget();
StateChanged?.Invoke();
if (work.Target == null) { Log($"[go] PID {work.Id:000} skipped / no living target"); return; }
+1
View File
@@ -1479,6 +1479,7 @@ namespace KernelPanic.Combat
private void GarbageCollect()
{
using var observed = new ObservedBackgroundAction(null, "Cleanup", "Status ticks and delayed effects");
_selectedEnemyIndex = -1;
_pendingTargetCard = null;
_statusEffects.Tick(_playerState, StatusTickTiming.EndOfTurn, _playerState, _damagePipeline);
@@ -19,6 +19,9 @@ namespace KernelPanic.Combat
public int ShieldBlocked { get; private set; }
public string KillingAction { get; private set; }
public Func<bool> SurrenderRequested { get; set; }
private readonly RunPerformanceSnapshot _performance = new();
public Func<RunPerformanceSnapshot> PerformanceSource { get; set; }
private RunPerformanceSnapshot Performance => PerformanceSource?.Invoke() ?? _performance;
public IReadOnlyCollection<string> IncomingHits => _hits;
public CombatRunTelemetry(Func<CombatantState> player, Func<CombatantState, string> describeSource)
@@ -28,8 +31,13 @@ namespace KernelPanic.Combat
GameEvents.PhaseChanged += OnPhaseChanged;
GameEvents.DamageDealt += ObserveDamage;
GameEvents.WaveAdvanced += OnWaveAdvanced;
GameEvents.CardPlayed += ObservePlay;
GameEvents.CardContribution += ObserveContribution;
}
private void ObservePlay(CardPlayedEvent payload) => Performance.RecordPlay(payload.Card);
private void ObserveContribution(CardContributionEvent payload) => Performance.Record(payload);
public void BeginRound()
{
if (!string.IsNullOrEmpty(KillingAction)) return;
@@ -70,6 +78,8 @@ namespace KernelPanic.Combat
{
DamageTaken += Math.Max(0, payload.UptimeDamage);
ShieldBlocked += Math.Max(0, payload.ShieldDamage);
Performance.damageTaken += Math.Max(0, payload.UptimeDamage);
Performance.shieldBlocked += Math.Max(0, payload.ShieldDamage);
string cause = !string.IsNullOrWhiteSpace(payload.Cause) ? payload.Cause
: _describeSource?.Invoke(payload.Source) ?? "Unattributed system damage";
string hit = $"{cause}: {payload.UptimeDamage} uptime / {payload.ShieldDamage} shield" +
@@ -83,7 +93,10 @@ namespace KernelPanic.Combat
KillingAction = hit;
}
else if (ReferenceEquals(payload.Source, player))
{
DamageDealt += Math.Max(0, payload.UptimeDamage);
Performance.damageDealt += Math.Max(0, payload.UptimeDamage);
}
}
public void FillReport(RunHistoryEntry entry)
@@ -94,6 +107,7 @@ namespace KernelPanic.Combat
entry.shieldBlocked = ShieldBlocked;
entry.cause = entry.surrendered ? "Shutdown signal accepted." : KillingAction ?? "Uptime reached 0; no damaging action recorded.";
entry.finalHits = new List<string>(_hits);
entry.performance = Performance.Copy();
}
public void Dispose()
@@ -101,6 +115,8 @@ namespace KernelPanic.Combat
GameEvents.PhaseChanged -= OnPhaseChanged;
GameEvents.DamageDealt -= ObserveDamage;
GameEvents.WaveAdvanced -= OnWaveAdvanced;
GameEvents.CardPlayed -= ObservePlay;
GameEvents.CardContribution -= ObserveContribution;
}
}
}
+2 -2
View File
@@ -239,13 +239,13 @@ namespace KernelPanic.Combat
return amount;
}
int critChance = request.Language == Language.C ? CombatTuning.CCriticalChancePercent : 25;
int critChance = request.Language is Language.C or Language.CPlusPlus ? CombatTuning.CCriticalChancePercent : 25;
wasCritical = RandomRoll.RollRange(1, 100, new RollContext(request.Source)) <= critChance;
return wasCritical ? ScaleCritical(amount) : amount;
}
private static bool CanRollCritical(DamageRequest request, int amount) =>
request.CanCrit && amount > 0 && amount != int.MaxValue && !(request.Source?.ForceMaxRolls ?? false);
request.CanCrit && request.Language != Language.TypeScript && amount > 0 && amount != int.MaxValue && !(request.Source?.ForceMaxRolls ?? false);
private static int ScaleCritical(int amount) =>
(int)System.Math.Min(int.MaxValue, ((long)amount * 3 + 1) / 2);
@@ -22,6 +22,7 @@ namespace KernelPanic.Combat
// A stable integer mixer, independent of both gameplay random streams and runtime hash codes.
public static EncounterPlan Plan(int wave, WaveRoute route, int seed, int revision)
{
if (revision >= 3 && wave >= 5 && wave <= 9) return VariedCampaignPlan(wave, route, seed);
if (revision >= 2) return CampaignPlan(wave, route, seed);
if (revision == 0) return Plan(wave, route);
uint hash = unchecked((uint)seed ^ ((uint)wave * 0x9E3779B9u));
@@ -125,6 +126,37 @@ namespace KernelPanic.Combat
return new EncounterPlan(title, advice, Math.Max(0, wave - 1) * CombatTuning.EnemyUptimeGrowthPerWave, enemies);
}
private static EncounterPlan VariedCampaignPlan(int wave, WaveRoute route, int seed)
{
uint hash = unchecked((uint)seed ^ ((uint)wave * 0x9E3779B9u));
hash ^= hash >> 16; hash = unchecked(hash * 0x7FEB352Du); hash ^= hash >> 15;
int variant = (int)(hash % 3);
if (variant == 0) return CampaignPlan(wave, route, seed);
var baseline = CampaignPlan(wave, route, seed);
var (title, advice, enemies) = (wave, variant) switch
{
(5, 1) => ("Replicating privileges", "Fork Bomb copies itself after acting. Kill it early to expose Rootkit, which resists damage while allies remain.", new[] { "rootkit", "fork_bomb", "zombie_process" }),
(5, _) => ("Scheduled escalation", "Cron Job counts down while Memory Leak grows. Remove urgent threats to expose Rootkit.", new[] { "rootkit", "cron_job", "memory_leak" }),
(6, 1) => ("Protected telemetry", "Firewalld protects Telemetry Collector. Break through Shield before resource interference wears down your build.", new[] { "telemetry_collector", "firewalld", "zombie_process" }),
(6, _) => ("Scheduled collection", "Telemetry Collector interferes with resources while two Cron Jobs count down. Front-load damage or prepare defense for their heavy attacks.", new[] { "telemetry_collector", "cron_job", "cron_job" }),
(7, 1) => ("Growing restrictions", "DRM Guardian and Firewalld shelter a growing Memory Leak. Pick a target you can finish before its next turn.", new[] { "drm_guardian", "firewalld", "memory_leak" }),
(7, _) => ("Licensed replication", "Fork Bomb multiplies behind DRM Guardian's defenses. Segfault leaves a death payload; reserve damage for the process it creates.", new[] { "drm_guardian", "fork_bomb", "segfault" }),
(8, 1) => ("Leaking concurrency", "Race partners can swap order and the survivor enrages. Memory Leak grows each round; balance paired kills against stopping its growth.", new[] { "race_condition", "race_condition", "memory_leak" }),
(8, _) => ("Veiled concurrency", "Damage the Daemon to reveal its committed action. Race partners can swap order; killing one enrages the survivor.", new[] { "race_condition", "race_condition", "daemon" }),
(9, 1) => ("Leaking kernel", "Kernel Panic pressures RAM while Memory Leak grows. Firewalld adds defense; use efficient attacks and leave room to draw.", new[] { "kernel_panic", "memory_leak", "firewalld" }),
_ => ("Scheduled panic", "Kernel Panic pressures RAM, Cron Job counts down, and Segfault leaves a death payload. Save a follow-up for the new process.", new[] { "kernel_panic", "cron_job", "segfault" })
};
var composition = new List<string>(enemies);
if (route == WaveRoute.Challenge)
{
composition.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.";
}
return new EncounterPlan(title, advice, baseline.UptimeBonus, composition.ToArray())
{ EscortShield = baseline.EscortShield, EscortUptime = baseline.EscortUptime };
}
private static EncounterPlan CampaignPlan(int wave, WaveRoute route, int seed)
{
// Keep introductory encounters familiar; introduce the heavier systems before the final boss.
@@ -0,0 +1,54 @@
using System.Collections.Generic;
using System.Linq;
using KernelPanic.Core;
namespace KernelPanic.Combat
{
public sealed class CppSizeofDamageEffect : ICardEffect
{
public void Execute(CombatContext context)
{
int count = context.HandController.Cards.Count(c => c.Definition?.Language is Language.C or Language.CPlusPlus);
new DealDamageEffect(6 * count, 6 * count, Language.CPlusPlus).Execute(context);
}
}
public static partial class CardCatalog
{
private static void AddEvolvedCards(List<CardCatalogEntry> entries)
{
const string cpp = " Full overkill spills. No segfault recoil.";
void Add(string id, CardTargeting target, bool bleeding, string rules, params CardEffectSpec[] effects)
=> entries.Add(new CardCatalogEntry(id, target, bleeding, rules, effects));
CardEffectSpec Typed(int amount, bool all = false) => new(CardEffectKind.Damage, amount,
language: Language.TypeScript, allEnemies: all, canCrit: false);
Add("lang_cpp_malloc", Single, true, "deal {amount:0}." + cpp, Damage(15, Language.CPlusPlus));
Add("lang_cpp_printf", Single, true, "deal {amount:0}. repair {amount:1} corrupted cards." + cpp,
Damage(6, Language.CPlusPlus), Fx(CardEffectKind.RepairCorruptedCards, 2));
Add("lang_cpp_pointer", Single, true, "deal {amount:0}; {secondary:0} if the previous card was C++." + cpp,
Fx(CardEffectKind.PreviousLanguageDamage, 12, secondary: 20, language: Language.CPlusPlus));
Add("shop_cpp_free", Single, true, "deal {amount:0}. repair {amount:1} corrupted cards. draw 2 (fixed)." + cpp,
Damage(22, Language.CPlusPlus), Fx(CardEffectKind.RepairCorruptedCards, 2), Fx(CardEffectKind.FixedDraw, 2));
Add("shop_cpp_sizeof", Single, true, "deal 6 x C and C++ cards in hand." + cpp,
Fx(CardEffectKind.SizeofDamage, 6, language: Language.CPlusPlus));
Add("shop_cpp_kernel_exploit", Single, true, "deal {amount:0} ignoring Shield." + cpp, Damage(40, Language.CPlusPlus, trueDamage: true));
Add("shop_cpp_gdb", None, false, "repair {amount:0} corrupted cards. draw {amount:1}.", Fx(CardEffectKind.RepairCorruptedCards, 3), Draw(2));
Add("shop_cpp_valgrind", None, false, "repair {amount:0} corrupted cards. gain {shield:1} Shield.", Fx(CardEffectKind.RepairCorruptedCards, 4), Shield(9));
Add("shop_cpp_memcpy", Single, true, "deal {amount:0}. draw 1 (fixed)." + cpp, Damage(9, Language.CPlusPlus), Fx(CardEffectKind.FixedDraw, 1));
Add("shop_cpp_memset", All, true, "deal {amount:0} to all enemies." + cpp, Damage(6, Language.CPlusPlus, all: true));
Add("shop_cpp_realloc", Single, true, "deal {amount:0}. repair {amount:1} corrupted cards." + cpp, Damage(16, Language.CPlusPlus), Fx(CardEffectKind.RepairCorruptedCards, 3));
const string fixedHit = " Fixed damage; no critical roll.";
Add("lang_ts_console_log", Single, true, "deal {amount:0}." + fixedHit, Typed(9));
Add("lang_ts_fetch", Single, true, "deal {amount:0}." + fixedHit, Typed(13));
Add("lang_ts_typeof", Single, true, "deal {amount:0}. Always succeeds." + fixedHit, Typed(16));
Add("shop_ts_math_random", Single, true, "deal {amount:0}." + fixedHit, Typed(20));
Add("shop_ts_promise_all", Single, true, "deal {amount:0} three times." + fixedHit, Typed(10), Typed(10), Typed(10));
Add("shop_ts_spread", None, false, "copy the lowest-cost card in hand. gain {shield:1} Shield.", Fx(CardEffectKind.CopyLowestCostHandCard), Shield(3));
Add("shop_ts_array_map", All, true, "deal {amount:0} to each enemy." + fixedHit, Typed(6, true));
Add("shop_ts_promise_resolve", Single, true, "deal {amount:0}." + fixedHit, Typed(5));
Add("shop_ts_try_catch", None, false, "gain {shield:0} Shield. cleanse harmful statuses.", Shield(8), Fx(CardEffectKind.Cleanse));
Add("shop_ts_json_parse", Single, true, "deal {amount:0}. draw 1 (fixed)." + fixedHit, Typed(9), Fx(CardEffectKind.FixedDraw, 1));
Add("shop_ts_eval", Single, true, "deal {amount:0}." + fixedHit, Typed(30));
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 04b71832a8f90724d9e23cc2e64797cd
@@ -0,0 +1,38 @@
using System;
namespace KernelPanic.Combat
{
public enum NixGovernorSwitchBlockReason
{
None,
InvalidGovernor,
Inactive,
AlreadySelected,
AlreadySwitchedThisRound,
InsufficientCycles,
SwitchingInProgress,
TutorialActive,
OutsideExecutePhase,
CombatUnavailable,
NoLivingTarget
}
public static class NixGovernorSwitchFeedback
{
public static string GetMessage(this NixGovernorSwitchBlockReason reason) => reason switch
{
NixGovernorSwitchBlockReason.None => null,
NixGovernorSwitchBlockReason.InvalidGovernor => "unknown governor",
NixGovernorSwitchBlockReason.Inactive => "CPU governors are unavailable for this wave",
NixGovernorSwitchBlockReason.AlreadySelected => "this governor is already active",
NixGovernorSwitchBlockReason.AlreadySwitchedThisRound => "already switched governor this turn",
NixGovernorSwitchBlockReason.InsufficientCycles => "not enough Cycles to switch governor",
NixGovernorSwitchBlockReason.SwitchingInProgress => "a governor switch is resolving",
NixGovernorSwitchBlockReason.TutorialActive => "governor switching is unavailable during the tutorial",
NixGovernorSwitchBlockReason.OutsideExecutePhase => "governors can only be switched during Execute",
NixGovernorSwitchBlockReason.CombatUnavailable => "governor switching is unavailable while combat is resolving or inactive",
NixGovernorSwitchBlockReason.NoLivingTarget => "performance requires a living enemy for its specialisation",
_ => throw new ArgumentOutOfRangeException(nameof(reason), reason, "Unknown switch rejection reason.")
};
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9dd0a76aad8942d48a5e52cc28879d79
+1
View File
@@ -150,6 +150,7 @@ namespace KernelPanic.Combat
if (script.Waiting || script.Restore || round < script.FirstRound || round <= script.LastRunRound) continue;
script.LastRunRound = round;
AutomationRan = true;
using var observed = new ObservedBackgroundAction(script.Payload.Card, "Automation", script.Name + " / " + script.Payload.Card.Definition.DisplayName);
Run(script.Payload, script.Payload.All);
if (--script.Remaining == 0) _scripts.Remove(script);
if (_combat.RunFinished || _combat.AwaitingWaveContinue || _combat.PlayerState.IsDefeated) break;
@@ -0,0 +1,46 @@
using System;
using KernelPanic.Combat;
namespace KernelPanic.Core
{
public sealed class ObservedBackgroundAction : IDisposable
{
private readonly CardInstance _card;
private readonly string _stage, _label;
public ObservedBackgroundAction(CardInstance card, string stage, string label)
{
_card = card; _stage = stage; _label = label;
GameEvents.RaiseBackgroundAction(new BackgroundActionEvent(card, stage, label, true));
}
public void Dispose() => GameEvents.RaiseBackgroundAction(new BackgroundActionEvent(_card, _stage, _label, false));
}
public static partial class GameEvents
{
// Observation only. These never replay card-play/equipment hooks.
public static event Action<CardContributionEvent> CardContribution;
public static event Action<BackgroundActionEvent> BackgroundAction;
public static void RaiseCardContribution(CardContributionEvent value) => CardContribution?.Invoke(value);
public static void RaiseBackgroundAction(BackgroundActionEvent value) => BackgroundAction?.Invoke(value);
}
public readonly struct CardContributionEvent
{
public CardContributionEvent(CardInstance card, int uptimeDamage = 0, int shieldDamage = 0, int shieldGranted = 0)
{ Card = card; UptimeDamage = uptimeDamage; ShieldDamage = shieldDamage; ShieldGranted = shieldGranted; }
public CardInstance Card { get; }
public int UptimeDamage { get; }
public int ShieldDamage { get; }
public int ShieldGranted { get; }
}
public readonly struct BackgroundActionEvent
{
public BackgroundActionEvent(CardInstance card, string stage, string label, bool started)
{ Card = card; Stage = stage; Label = label; Started = started; }
public CardInstance Card { get; }
public string Stage { get; }
public string Label { get; }
public bool Started { get; }
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a60e1bc59f36f3944b9698abf0fa29d0
+1 -1
View File
@@ -7,7 +7,7 @@ namespace KernelPanic.Core
/// <summary>
/// Provides runtime events for gameplay systems that need to observe combat and run milestones.
/// </summary>
public static class GameEvents
public static partial class GameEvents
{
public static event Action<CardPlayedEvent> CardPlayed;
public static event Action<CardResolvedEvent> CardResolved;
+2 -2
View File
@@ -13,11 +13,11 @@ namespace KernelPanic.Data
private static readonly LanguageCatalogEntry[] Entries =
{
new(Language.C, "C", "bare metal", ResolutionTrack.Native, $"C is immediate, high-risk burst damage. C damage rolls a {CombatTuning.CCriticalChancePercent}% crit chance instead of the normal 25%, spills {CombatTuning.COverkillSpillPercent}% of remaining overkill into other enemies per jump (rounded down), and C cards can segfault: hurting you and corrupting a hand card. Segfault corruption recovers automatically after 3 rounds. C repair cards restore corrupted cards sooner.", null, Distro("arch", "Arch"), Distro("gentoo", "Gentoo"), Distro("templeos", "TempleOS")),
new(Language.CPlusPlus, "C++", "template arsenal", ResolutionTrack.Native, "C++ is planned as a Native setup/payoff language built from upgraded C cards. It should keep C's direct-hit pressure while adding heavier combo requirements.", "unlock: upgrade a C card during a run"),
new(Language.CPlusPlus, "C++", "compiled evolution", ResolutionTrack.Native, "Upgraded C cards: stronger immediate attacks, full overkill spill, the same elevated critical chance, and no segfault recoil. Chain C++ cards for pointer's combo. sizeof counts both C and C++ cards in hand.", "unlock: clear all 10 campaign waves with C selected"),
new(Language.Rust, "Rust", "safe systems", ResolutionTrack.Native, "Rust is immediate, reliable damage with defensive payoff. Rust overkill becomes Shield, and Rust damage has a tiny 0.001% chance to overflow into the unsigned 64-bit limit.", null, Distro("arch", "Arch"), Distro("fedora", "Fedora")),
new(Language.Python, "Python", "pipelines and automation", ResolutionTrack.InterpreterQueue, "Preparation acts immediately. Payloads and modifiers resolve FIFO before enemies: for loop repeats the next payload, zip spreads a single-target payload to all enemies. Unused modifiers expire after the following round. Two automation slots run captured operations for two future rounds. Replays copy damage and Shield only, never draw, growth or installation. Scripts and modifiers clear each wave.", null, Distro("ubuntu", "Ubuntu"), Distro("kali", "Kali"), Distro("mint", "Mint")),
new(Language.JavaScript, "JavaScript", "runtime chaos", ResolutionTrack.Native, "JavaScript resolves immediately and is intentionally swingy: wide damage ranges, chance-based outcomes, and conditional repeat effects. It rewards embracing variance.", null, Distro("ubuntu", "Ubuntu"), Distro("endeavouros", "EndeavourOS"), Distro("mint", "Mint")),
new(Language.TypeScript, "TypeScript", "typed runtime", ResolutionTrack.Native, "TypeScript is planned as the steadier JavaScript branch: Native timing with less chaos and more controlled setup/payoff patterns.", "unlock: upgrade a JavaScript card during a run"),
new(Language.TypeScript, "TypeScript", "typed evolution", ResolutionTrack.Native, "Upgraded JavaScript cards with fixed damage, guaranteed typeof, and stronger utility. TypeScript damage never rolls critical hits. Current buffs, Shield and enemy defenses still apply.", "unlock: clear all 10 campaign waves with JavaScript selected"),
new(Language.Haskell, "Haskell", "lazy proofs", ResolutionTrack.LazyStack, "Lazy proofs. Build a stack of delayed operations. Later cards gain stronger effects when evaluated. Snapshot x1.5 / x1.75 / x2.0 / x2.5 at play; LIFO after Python. Only damage and explicit Shield multiply.", null, Distro("gentoo", "Gentoo"), Distro("nixos", "NixOS")),
new(Language.Assembly, "Assembly", "raw opcodes", ResolutionTrack.Native, "Assembly is planned as the most direct Native language: low-level, high-commitment effects that should trade flexibility for extreme precision or shield-bypass pressure.", null, Distro("templeos", "TempleOS")),
new(Language.Java, "Java", "warming vm", ResolutionTrack.Native, "Each Java card uses 2 RAM and spills overkill into other enemies. JIT gives -1 Cycle per 2 Java plays, capped at -3. Store at most 6 warmup plays; lose 2 after each wave, cooling the discount by 1.", null, Distro("debian", "Debian"), Distro("fedora", "Fedora")),
+15 -2
View File
@@ -1,6 +1,7 @@
using System;
using KernelPanic.Core;
using KernelPanic.Data;
using KernelPanic.Run;
namespace KernelPanic.Meta
{
@@ -13,8 +14,7 @@ namespace KernelPanic.Meta
{
if (language == Language.CPlusPlus || language == Language.TypeScript)
{
// TODO: evolved-language unlock gate, separate from distro ownership.
return false;
return collection?.HasCampaignClear(language == Language.CPlusPlus ? Language.C : Language.JavaScript) == true;
}
if (collection == null)
@@ -42,5 +42,18 @@ namespace KernelPanic.Meta
return false;
}
// Qualifying languages are the selected build languages, not generated or exclusive cards.
public static bool RecordCampaignClear(SaveData data, RunConfig config, RunJourney journey, int wavesCleared)
{
if (data == null || config == null || config.IsTutorial || journey?.campaign != true
|| journey.FinalWave != RunJourney.BossWave || wavesCleared < RunJourney.BossWave) return false;
data.campaignClearLanguages ??= new();
bool changed = false;
foreach (var language in new[] { config.PrimaryLanguage, config.SecondaryLanguage })
if ((language == Language.C || language == Language.JavaScript) && !data.campaignClearLanguages.Contains(language))
{ data.campaignClearLanguages.Add(language); changed = true; }
return changed;
}
}
}
+8
View File
@@ -13,6 +13,14 @@ namespace KernelPanic.Meta
private readonly List<OwnedPackageInstance> _ownedPackages = new();
private readonly Dictionary<string, int> _versions = new(StringComparer.OrdinalIgnoreCase);
private int _featuredIndex;
private readonly HashSet<KernelPanic.Core.Language> _campaignClears = new();
public bool HasCampaignClear(KernelPanic.Core.Language language) => _campaignClears.Contains(language);
public void LoadCampaignClears(IEnumerable<KernelPanic.Core.Language> languages)
{
_campaignClears.Clear();
if (languages != null) foreach (var language in languages) _campaignClears.Add(language);
}
// TODO: Populate owned units from SaveService during bootstrap.
public IReadOnlyList<DistroDefinition> OwnedUnits => _ownedUnits;
+2
View File
@@ -27,6 +27,8 @@ namespace KernelPanic.Meta
public int shieldBlocked;
public List<string> finalHits = new();
public RunHistoryBuildSnapshot build;
public RunPerformanceSnapshot performance;
public List<CheckpointCard> finalDeck;
}
/// <summary>The original starting build, not the deck after repository upgrades.</summary>
@@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using KernelPanic.Combat;
using KernelPanic.Core;
namespace KernelPanic.Meta
{
[Serializable]
public sealed class CardPerformance
{
public string cardId;
public string name;
public long plays, uptimeDamage, shieldDamage, shieldGranted;
public CardPerformance Copy() => (CardPerformance)MemberwiseClone();
}
[Serializable]
public sealed class RunPerformanceSnapshot
{
public int schemaVersion = 1;
public bool complete = true;
public long damageDealt, damageTaken, shieldBlocked, cardsPlayed;
public List<CardPerformance> cards = new();
public RunPerformanceSnapshot Copy()
{
var copy = (RunPerformanceSnapshot)MemberwiseClone();
copy.cards = (cards ?? new()).Where(c => c != null).Select(c => c.Copy()).ToList();
return copy;
}
private CardPerformance Find(CardInstance card)
{
if (card?.Definition == null) return null;
cards ??= new();
var result = cards.Find(c => c.cardId == card.Definition.Id);
if (result != null) return result;
result = new CardPerformance { cardId = card.Definition.Id, name = card.Definition.DisplayName };
cards.Add(result);
return result;
}
public void RecordPlay(CardInstance card)
{
var entry = Find(card);
if (entry == null) return;
entry.plays++; cardsPlayed++;
}
public void Record(CardContributionEvent contribution)
{
var entry = Find(contribution.Card);
if (entry == null) return;
entry.uptimeDamage += Math.Max(0, contribution.UptimeDamage);
entry.shieldDamage += Math.Max(0, contribution.ShieldDamage);
entry.shieldGranted += Math.Max(0, contribution.ShieldGranted);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1e105ff509f06ff499a0682524640b32
+3 -1
View File
@@ -16,7 +16,7 @@ namespace KernelPanic.Meta
public sealed class SaveService
{
private const string SaveFileName = "kernel-panic-save.json";
public const int CurrentSchemaVersion = 8;
public const int CurrentSchemaVersion = 9;
private static readonly object FileLock = new();
public string SavePath { get; }
@@ -305,6 +305,7 @@ namespace KernelPanic.Meta
public string lastSetupDistroId;
public RunCheckpoint activeRun;
public List<RunHistoryEntry> recentRuns = new();
public List<Language> campaignClearLanguages = new();
public string lastRunDistroId;
public List<DistroBestWaveSaveEntry> distroBestWaves = new();
@@ -348,6 +349,7 @@ namespace KernelPanic.Meta
runBuildDrafts ??= new List<RunBuildDraftSaveEntry>();
foreach (RunBuildDraftSaveEntry draft in runBuildDrafts) draft?.EnsureLists();
recentRuns ??= new List<RunHistoryEntry>();
campaignClearLanguages ??= new List<Language>();
RunHistory.Normalize(recentRuns);
if (string.IsNullOrWhiteSpace(lastRunDistroId) && !string.IsNullOrWhiteSpace(lastRunLoadout.distroId))
{
+17 -1
View File
@@ -11,7 +11,7 @@ namespace KernelPanic.Run
public static class LanguageTraining
{
public static readonly IReadOnlyList<Language> Supported = Array.AsReadOnly(new[]
{ Language.C, Language.Rust, Language.Python, Language.JavaScript, Language.Haskell, Language.Java, Language.Go });
{ Language.C, Language.CPlusPlus, Language.Rust, Language.Python, Language.JavaScript, Language.TypeScript, Language.Haskell, Language.Java, Language.Go });
public static bool IsSupported(Language language) => Supported.Contains(language);
@@ -29,6 +29,8 @@ namespace KernelPanic.Run
Language.Python => new[] { "lang_py_import_antigravity", "shop_py_async_def", "lang_py_for_loop", "mint_cinnamon", "lang_py_print", "lang_py_print" },
Language.Haskell => new[] { "lang_hs_map", "lang_hs_thunk", "lang_hs_foldr" },
Language.C => new[] { "lang_c_malloc", "lang_c_pointer", "lang_c_printf" },
Language.CPlusPlus => new[] { "lang_cpp_malloc", "lang_cpp_pointer", "lang_cpp_printf" },
Language.TypeScript => new[] { "lang_ts_console_log", "lang_ts_fetch", "lang_ts_typeof" },
Language.Rust => new[] { "lang_rs_fn_main", "lang_rs_unwrap", "lang_rs_borrow" },
Language.JavaScript => new[] { "lang_js_console_log", "lang_js_fetch", "lang_js_typeof" },
Language.Java => new[] { "lang_java_new_object", "lang_java_system_out_println", "lang_java_public_static_main" },
@@ -56,6 +58,8 @@ namespace KernelPanic.Run
string name = LanguageCatalog.Get(language).DisplayName;
string objective = language switch
{
Language.CPlusPlus => "Learn C's evolved cards: stronger hits, full overkill spill and combos without segfault recoil.",
Language.TypeScript => "Learn to plan reliable attacks using JavaScript's evolved cards, with fixed damage and no failed typeof rolls.",
Language.Python => "You'll learn to build a combo that attacks this turn and repeats on later turns. First, we'll draw the cards we need. Then we'll put them in order.",
Language.Haskell => "You'll learn to make a stronger attack by playing your cards in the right order. We'll build a stack together, then work through why it resolves backward.",
Language.Rust => "You'll learn to turn an attack into protection. We'll defeat the weaker enemy first, use the leftover damage as Shield, then attack the stronger one.",
@@ -68,6 +72,16 @@ namespace KernelPanic.Run
Read("welcome", "Learn to use " + name, objective, "enemies");
switch (language)
{
case Language.CPlusPlus:
Read("evolution", "C without the segfault", "C++ keeps C's immediate attacks and elevated critical chance. Damage is stronger, all overkill spills, and playing C++ never causes segfault recoil.", "enemies");
Play("burst", "lang_cpp_malloc", "Start with upgraded malloc", "Play malloc to begin your C++ chain. Your hand stays safe from segfault corruption.");
Read("combo", "Follow with pointer", "Pointer deals 20 base damage after a C++ card instead of 12. Use printf to repair corruption from other sources. Full excess damage spills to the next living enemy.", "enemies");
break;
case Language.TypeScript:
Read("evolution", "Plan around fixed values", "TypeScript upgrades JavaScript's cards. Damage has a fixed value and no critical roll. Buffs and enemy defenses still apply.", "enemies");
Play("fixed", "lang_ts_console_log", "Deal a reliable 9", "Play console.log(). Its base damage is always 9 instead of a random 3 to 9.");
Read("guarantee", "No failed typeof", "Fetch deals 13 base damage. Typeof always deals 16 instead of risking a failed roll. Check enemy defenses, then choose your follow-up.", "enemies");
break;
case Language.Go:
Read("go-slots", "Start a worker for future turns", "Go has 3 active slots, separate from hand RAM. A deployed worker leaves your hand and starts attacking next round. Its card returns to the discard pile when it stops.", "GoroutineScheduler");
Play("go-worker", "lang_go_worker", "Deploy your first worker", "Select go worker(). It will deal 3 base damage on each of its next 3 eligible rounds. Its first tick is next round, so you still need to plan for this turn's enemies.",
@@ -149,6 +163,8 @@ namespace KernelPanic.Run
}
string practice = language switch
{
Language.CPlusPlus => "Finish the fight. Chain C++ cards for pointer's bonus, use full overkill spill, and repair corruption with printf. Your C++ attacks never cause segfaults.",
Language.TypeScript => "Finish the fight. Use fixed damage to plan each kill, accounting for Shield and other modifiers. Typeof always succeeds.",
Language.Python => "Finish the fight yourself. Draw before committing to a combo, put setup before payloads, and check your active script. End your turn when the queue is ready.",
Language.Haskell => "Finish the fight yourself. Start with a smaller card, save a bigger effect for a higher multiplier, then check the stack from top to bottom before ending your turn.",
Language.Rust => "Finish the fight yourself. Compare the enemy's intent with your Shield. Use overkill for protection when you can, and borrow() when you need Shield without a kill.",
+17
View File
@@ -63,6 +63,7 @@ namespace KernelPanic.Run
fixture.starterChosen = true;
fixture.tutorialRequired = false;
fixture.tutorialRewardClaimed = true;
fixture.campaignClearLanguages.AddRange(new[] { Language.C, Language.JavaScript });
foreach (string id in new[] { "ubuntu", "arch", "gentoo", "fedora", "nixos" })
fixture.ownedUnits.Add(new OwnedUnitSaveEntry { id = id, version = id == "nixos" ? 5 : 1 });
new SaveService().Save(fixture);
@@ -555,6 +556,7 @@ namespace KernelPanic.Run
var flow = Field<TutorialFlow>(view, "_tutorial");
Require(combat.RunConfig.TrainingLanguage == language, "Collection launched the wrong lesson.");
int actions = 0;
bool capturedResolution = false;
while (!combat.AwaitingWaveContinue && !combat.RunLost)
{
if (!combat.TutorialInputReady) { yield return null; continue; }
@@ -582,6 +584,21 @@ namespace KernelPanic.Run
else if (combat.CanSurrenderRun)
{
_stage = language + " / free practice";
if (!capturedResolution)
{
capturedResolution = true;
var trace = Field<CombatExecutionTrace>(view, "_executionTrace");
Require(trace.Actions.Count > 0 && trace.Actions.Any(a => a.Complete), "Practice has no observed resolution results.");
var resolution = root.Q<Foldout>("TurnResolution");
Require(resolution != null, "Turn-resolution view is missing.");
resolution.value = true;
var workspace = resolution.GetFirstAncestorOfType<ScrollView>();
for (int frame = 0; frame < 4; frame++) yield return null;
workspace?.ScrollTo(resolution);
for (int frame = 0; frame < 4; frame++) yield return null;
var capture = CapturePanel(document, "training-" + language + "-resolution");
while (capture.MoveNext()) yield return capture.Current;
}
if (combat.PendingGoroutineCard != null)
{
var work = combat.Go.Active.FirstOrDefault(g => combat.IsEligibleGoSelection(g, combat.PendingGoroutineCard));
+3 -1
View File
@@ -39,11 +39,12 @@ namespace KernelPanic.Run
public int shopRandomDraws;
public CheckpointCombat combat;
public RunJourney journey;
public RunPerformanceSnapshot performance;
public ResolvedRunCheckpoint Resolve(DistroDatabase distros, CardDatabase cards,
LanguageDeckDatabase languages, PackageDatabase packageDatabase)
{
Require(version >= 1 && version <= 4, "This checkpoint needs a different game version.");
Require(version >= 1 && version <= 5, "This checkpoint needs a different game version.");
Require(version < 2 || journey != null, "Missing saved route decisions.");
journey?.Validate(wave);
journey?.ValidateMap(seed, wave);
@@ -201,6 +202,7 @@ namespace KernelPanic.Run
RunCheckpoint snapshot = run.CaptureCheckpoint(combat);
SaveData data = saves.Load();
data.activeRun = snapshot;
LanguageUnlock.RecordCampaignClear(data, run.CurrentConfig, run.Journey, run.WavesCleared);
saves.Save(data);
run.MarkSuspended(); // Never suppress settlement or leave the scene on a failed save.
}
+2 -2
View File
@@ -33,7 +33,7 @@ namespace KernelPanic.Run
public int FinalWave => encounterRevision >= 2 ? BossWave : LegacyBossWave;
public bool IsRewardWave(int wave) => encounterRevision > 0 && wave >= 2 && wave < FinalWave && wave % 2 == 0;
public bool AtMilestone(int wavesCleared) => campaign && !endless && wavesCleared >= FinalWave;
public static RunJourney NewCampaign() => new() { campaign = true, encounterRevision = 2, mapRevision = 2 };
public static RunJourney NewCampaign() => new() { campaign = true, encounterRevision = 3, mapRevision = 2 };
public RunJourney Copy()
{
var copy = (RunJourney)MemberwiseClone();
@@ -43,7 +43,7 @@ namespace KernelPanic.Run
public void Validate(int wave)
{
RunCheckpoint.Require(encounterRevision >= 0 && encounterRevision <= 2, "Unsupported encounter revision.");
RunCheckpoint.Require(encounterRevision >= 0 && encounterRevision <= 3, "Unsupported encounter revision.");
RunCheckpoint.Require((pendingRewardWave == 0 || IsRewardWave(pendingRewardWave))
&& (claimedRewardWave == 0 || IsRewardWave(claimedRewardWave))
&& claimedRewardWave < wave
+8 -1
View File
@@ -56,6 +56,8 @@ namespace KernelPanic.Run
public string RunId { get; private set; }
public bool IsSuspended { get; private set; }
public RunJourney Journey { get; private set; } = new();
public Meta.RunPerformanceSnapshot Performance { get; private set; } = new();
public List<CheckpointCard> FinalDeck { get; private set; }
public bool CampaignChoicePending => Journey.AtMilestone(_wavesCleared);
public bool BuildRewardPending => Journey.pendingRewardWave > 0;
public const int BuildRewardBits = 8;
@@ -216,6 +218,8 @@ namespace KernelPanic.Run
public void StartRun(RunConfig config)
{
CurrentConfig = config;
Performance = new();
FinalDeck = null;
Journey = RunJourney.NewCampaign();
if (config?.IsTutorial == true) Journey = new RunJourney();
RunId = Guid.NewGuid().ToString("N");
@@ -265,7 +269,7 @@ namespace KernelPanic.Run
bandwidth = _accruedBandwidth, entropy = _accruedEntropy,
maxUptimeBonus = _maxUptimeBonus, maxCyclesBonus = _maxCyclesBonus, ramBonus = _ramBonus,
rerolls = _rerollsThisVisit, shopRandomDraws = _repositoryRandom.Draws,
version = 4, journey = Journey.Copy(),
version = 5, journey = Journey.Copy(), performance = Performance.Copy(),
combat = combat.CaptureBoundaryState()
};
foreach (PackageInstance package in CurrentConfig.EquippedPackages)
@@ -288,6 +292,8 @@ namespace KernelPanic.Run
if (resume == null) throw new ArgumentNullException(nameof(resume));
RunCheckpoint snapshot = resume.Snapshot;
CurrentConfig = resume.Config;
Performance = snapshot.performance?.schemaVersion == 1 ? snapshot.performance.Copy() : new Meta.RunPerformanceSnapshot { complete = false };
FinalDeck = null;
Journey = snapshot.journey?.Copy() ?? new RunJourney();
RunId = snapshot.runId;
IsSuspended = false;
@@ -540,6 +546,7 @@ namespace KernelPanic.Run
private void HandleRunEnded(RunEndedEvent payload)
{
FinalDeck = _runDeck.Select(CheckpointCard.Capture).ToList();
isRunActive = false;
isPlayerDead = payload.PlayerDied;
_bits = 0;
@@ -0,0 +1,110 @@
using System;
using System.Collections.Generic;
using System.Linq;
using KernelPanic.Combat;
using KernelPanic.Core;
using KernelPanic.Data;
using KernelPanic.Meta;
using KernelPanic.Run;
using UnityEngine;
using UnityEngine.TextCore.Text;
using UnityEngine.UIElements;
namespace KernelPanic.UI
{
public sealed partial class CollectionScreenController
{
private void RenderLanguages()
{
_contextHeader.Clear();
_contextHeader.AddToClassList("hidden");
_headerIdentity = null;
_filters.Clear();
_filters.EnableInClassList("hidden", true);
if (_list == null || _detail == null)
{
return;
}
_rows.Clear();
_list.Clear();
TerminalTheme.PreserveFocus(_detail);
_detail.Clear();
_list.RemoveFromClassList("hidden");
_detailScroll?.RemoveFromClassList("collection-detail-full");
if (_detailScroll != null)
{
_detailScroll.verticalScrollerVisibility = ScrollerVisibility.Auto;
}
_selectedLanguageIndex = Mathf.Clamp(_selectedLanguageIndex, 0, _languages.Count - 1);
for (int i = 0; i < _languages.Count; i++)
{
int index = i;
LanguageCatalogEntry language = _languages[i];
bool unlocked = LanguageUnlock.IsUnlocked(language.Language, _playerCollection);
Button row = new();
row.AddToClassList("collection-row");
row.EnableInClassList("locked", !unlocked);
row.RegisterCallback<FocusInEvent>(_ => SelectLanguage(index));
((Button)row).clicked += () => SelectLanguage(index);
Label name = new(unlocked ? language.DisplayName : $"{language.DisplayName} [locked]");
name.AddToClassList("collection-row-name");
Label tag = new(language.IdentityTag);
tag.AddToClassList("collection-row-languages");
row.Add(name);
row.Add(tag);
_list.Add(row);
_rows.Add(row);
}
SelectLanguage(_selectedLanguageIndex);
}
private void RenderLanguageDetail(LanguageCatalogEntry language)
{
TerminalTheme.PreserveFocus(_detail);
_detail.Clear();
bool unlocked = LanguageUnlock.IsUnlocked(language.Language, _playerCollection);
Label name = new(language.DisplayName);
name.AddToClassList("collection-detail-name");
_detail.Add(name);
_detail.Add(BuildDetailLine("track", language.ResolutionTrack.ToString()));
Label how = new(language.HowItWorks);
how.AddToClassList("collection-detail-description");
_detail.Add(how);
if (!unlocked)
{
string hintText = string.IsNullOrWhiteSpace(language.UnlockHint)
? $"unlock: own a distro that speaks {language.DisplayName} ({FormatSupportingDistros(language)})"
: language.UnlockHint;
Label hint = new(hintText);
hint.AddToClassList("package-notice");
_detail.Add(hint);
return;
}
_detail.Add(BuildSubviewCommand($"cat ~/lang/{GetLanguageId(language.Language)}/deck", "starter deck", true, () => OpenLanguageDeck(language), null));
if (LanguageTraining.IsSupported(language.Language))
{
var learn = new Button(() =>
{
if (LanguageUnlock.IsUnlocked(language.Language, _playerCollection))
LanguageTrainingRequested?.Invoke(language.Language);
}) { name = "LearnLanguageButton", text = "Learn more / practice fight" };
learn.AddToClassList("terminal-button");
_detail.Add(learn);
_detail.Add(TerminalLayout.BodyText("Learn the basics by playing a guided fight. You can retry or leave without changing your saved campaign."));
}
else _detail.Add(TerminalLayout.BodyText("Practice fight unavailable: this language's playable cards are still planned."));
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 83393bcf5ae34db49461d65e3858855f
@@ -16,7 +16,7 @@ namespace KernelPanic.UI
/// Renders Collection tabs and the pushed read-only card subview.
/// </summary>
[Serializable]
public sealed class CollectionScreenController
public sealed partial class CollectionScreenController
{
private readonly List<VisualElement> _rows = new();
@@ -334,57 +334,6 @@ namespace KernelPanic.UI
ApplySelection(_selectedUnitIndex);
}
private void RenderLanguages()
{
_contextHeader.Clear();
_contextHeader.AddToClassList("hidden");
_headerIdentity = null;
_filters.Clear();
_filters.EnableInClassList("hidden", true);
if (_list == null || _detail == null)
{
return;
}
_rows.Clear();
_list.Clear();
TerminalTheme.PreserveFocus(_detail);
_detail.Clear();
_list.RemoveFromClassList("hidden");
_detailScroll?.RemoveFromClassList("collection-detail-full");
if (_detailScroll != null)
{
_detailScroll.verticalScrollerVisibility = ScrollerVisibility.Auto;
}
_selectedLanguageIndex = Mathf.Clamp(_selectedLanguageIndex, 0, _languages.Count - 1);
for (int i = 0; i < _languages.Count; i++)
{
int index = i;
LanguageCatalogEntry language = _languages[i];
bool unlocked = LanguageUnlock.IsUnlocked(language.Language, _playerCollection);
Button row = new();
row.AddToClassList("collection-row");
row.EnableInClassList("locked", !unlocked);
row.RegisterCallback<FocusInEvent>(_ => SelectLanguage(index));
((Button)row).clicked += () => SelectLanguage(index);
Label name = new(unlocked ? language.DisplayName : $"{language.DisplayName} [locked]");
name.AddToClassList("collection-row-name");
Label tag = new(language.IdentityTag);
tag.AddToClassList("collection-row-languages");
row.Add(name);
row.Add(tag);
_list.Add(row);
_rows.Add(row);
}
SelectLanguage(_selectedLanguageIndex);
}
private void RenderPackages()
{
_contextHeader.Clear();
@@ -1679,47 +1628,6 @@ namespace KernelPanic.UI
}
}
private void RenderLanguageDetail(LanguageCatalogEntry language)
{
TerminalTheme.PreserveFocus(_detail);
_detail.Clear();
bool unlocked = LanguageUnlock.IsUnlocked(language.Language, _playerCollection);
Label name = new(language.DisplayName);
name.AddToClassList("collection-detail-name");
_detail.Add(name);
_detail.Add(BuildDetailLine("track", language.ResolutionTrack.ToString()));
Label how = new(language.HowItWorks);
how.AddToClassList("collection-detail-description");
_detail.Add(how);
if (!unlocked)
{
string hintText = string.IsNullOrWhiteSpace(language.UnlockHint)
? $"unlock: own a distro that speaks {language.DisplayName} ({FormatSupportingDistros(language)})"
: language.UnlockHint;
Label hint = new(hintText);
hint.AddToClassList("package-notice");
_detail.Add(hint);
return;
}
_detail.Add(BuildSubviewCommand($"cat ~/lang/{GetLanguageId(language.Language)}/deck", "starter deck", true, () => OpenLanguageDeck(language), null));
if (LanguageTraining.IsSupported(language.Language))
{
var learn = new Button(() =>
{
if (LanguageUnlock.IsUnlocked(language.Language, _playerCollection))
LanguageTrainingRequested?.Invoke(language.Language);
}) { name = "LearnLanguageButton", text = "Learn more / practice fight" };
learn.AddToClassList("terminal-button");
_detail.Add(learn);
_detail.Add(TerminalLayout.BodyText("Learn the basics by playing a guided fight. You can retry or leave without changing your saved campaign."));
}
else _detail.Add(TerminalLayout.BodyText("Practice fight unavailable: this language's playable cards are still planned."));
}
private void OpenUnitCards(DistroDefinition unit)
{
if (_mode == CollectionMode.UnitDetail)
@@ -0,0 +1,46 @@
using System;
using System.IO;
using KernelPanic.Meta;
using KernelPanic.Run;
using UnityEngine.UIElements;
namespace KernelPanic.UI
{
public sealed partial class CombatSceneController
{
private bool _campaignUnlocksSaved;
private string _campaignUnlockNotice;
private string _campaignUnlockError;
private void PersistCampaignUnlocks()
{
if (_campaignUnlocksSaved || _saveService == null || _runManager?.CurrentConfig == null
|| _runManager.CurrentConfig.IsTutorial || _runManager.Journey.FinalWave != RunJourney.BossWave
|| !_runManager.Journey.campaign || _runManager.WavesCleared < RunJourney.BossWave) return;
try
{
var data = _saveService.Load();
int before = data.campaignClearLanguages.Count;
if (LanguageUnlock.RecordCampaignClear(data, _runManager.CurrentConfig, _runManager.Journey, _runManager.WavesCleared))
{
_saveService.Save(data);
var names = data.campaignClearLanguages.GetRange(before, data.campaignClearLanguages.Count - before)
.ConvertAll(language => language == Core.Language.C ? "C++" : "TypeScript");
_campaignUnlockNotice = "Campaign unlock saved: " + string.Join(" + ", names) + ". Available in collection and run setup.";
}
_campaignUnlocksSaved = true;
_campaignUnlockError = null;
}
catch (Exception ex) when (ex is IOException || ex is InvalidDataException || ex is UnauthorizedAccessException)
{ _campaignUnlockError = "Language unlock could not be saved: " + ex.Message; }
}
private void AddCampaignUnlockNotice(VisualElement parent)
{
if (!string.IsNullOrEmpty(_campaignUnlockNotice)) parent.Add(TerminalLayout.BodyText(_campaignUnlockNotice));
if (string.IsNullOrEmpty(_campaignUnlockError)) return;
parent.Add(TerminalLayout.BodyText(_campaignUnlockError));
parent.Add(new Button(() => { PersistCampaignUnlocks(); Refresh(); }) { text = "Retry saving language unlock" });
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7d9a4d0d62dfebc4fa35f6a7d4305c29
@@ -0,0 +1,413 @@
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.Run;
using UnityEngine;
using UnityEngine.UIElements;
namespace KernelPanic.UI
{
public sealed partial class CombatSceneController
{
private VisualElement BuildRepositoryView()
{
VisualElement repo = new();
repo.AddToClassList("repository");
repo.AddToClassList("screen-frame");
repo.Add(BuildRepositoryHeader());
AddCampaignUnlockNotice(repo);
ScrollView body = new(ScrollViewMode.Vertical);
body.AddToClassList("repository-body");
body.AddToClassList("screen-frame-content");
VisualElement offers = new();
offers.AddToClassList("repository-offers");
if (_runManager.RepositoryOffers.Count == 0)
{
offers.Add(EmptyState("repository clean: no offers left this visit"));
}
else
{
for (int i = 0; i < _runManager.RepositoryOffers.Count; i++)
{
offers.Add(RepositoryOfferTile(_runManager.RepositoryOffers[i]));
}
}
body.Add(offers);
body.Add(RemoveCardBlock());
repo.Add(body);
VisualElement footer = new();
footer.AddToClassList("repository-footer");
footer.AddToClassList("screen-frame-footer");
Button reroll = new(() => _runManager.RerollRepositoryOffers(cardDatabase, languageDeckDatabase))
{
text = $"apt update {_runManager.RerollCost} bits"
};
reroll.AddToClassList("primary-action");
reroll.AddToClassList("repository-footer-action");
reroll.AddToClassList("repository-reroll-action");
reroll.EnableInClassList("repo-unaffordable", _runManager.Bits < _runManager.RerollCost);
reroll.SetEnabled(_runManager.Bits >= _runManager.RerollCost);
footer.Add(reroll);
Button leave = new(() =>
{
if (_runManager.Journey.campaign) SetRouteSelectionOpen(true);
else _combatManager.ContinueToNextWave();
}) { name = "BootNextWaveButton", text = "> boot next-wave" };
leave.AddToClassList("primary-action");
leave.AddToClassList("repository-leave-action");
leave.SetEnabled(!_runManager.IsSuspended);
VisualElement leaveBlock = new();
leaveBlock.AddToClassList("repository-leave-block");
leaveBlock.Add(leave);
Label banked = new($"{_runManager.Bits} bits remaining");
banked.AddToClassList("repository-banked-hint");
banked.AddToClassList("screen-frame-hint");
leaveBlock.Add(banked);
var suspend = new Button(SaveAndExitRun) { name = "SaveAndExitRunButton", text = "save & exit" };
suspend.AddToClassList("primary-action");
suspend.AddToClassList("repository-leave-action");
suspend.SetEnabled(!_runManager.IsSuspended);
leaveBlock.Add(suspend);
if (!string.IsNullOrEmpty(_checkpointError))
leaveBlock.Add(TerminalLayout.BodyText("Save failed: " + _checkpointError + " Stay here and retry.", className: "screen-frame-hint"));
footer.Add(leaveBlock);
repo.Add(footer);
return repo;
}
private void SetRouteSelectionOpen(bool open)
{
_routeSelectionOpen = open;
_routeEventOpen = false;
RefreshOverlay();
_overlay.Q<Button>(open ? "BackToRepositoryButton" : "BootNextWaveButton")?.Focus();
}
private VisualElement BuildRouteSelectionView()
{
bool reward = _runManager.BuildRewardPending;
bool eventScreen = !reward && _routeEventOpen && !_runManager.CampaignChoicePending;
bool committed = eventScreen && !_runManager.RouteEventPending;
var screen = new VisualElement { name = reward ? "BuildRewardScreen" : eventScreen ? "RouteEventScreen" : "RouteSelectionScreen" };
screen.AddToClassList("repository");
screen.AddToClassList("screen-frame");
screen.AddToClassList("route-map-screen");
var header = new VisualElement();
header.AddToClassList("repository-header");
header.AddToClassList("screen-frame-header");
var copy = new VisualElement();
copy.AddToClassList("repository-header-copy");
var title = new Label(_runManager.CampaignChoicePending ? "campaign complete" : reward ? "claim your build reward"
: eventScreen ? RunRouteMap.Title(_runManager.Journey.selectedRoute) : "choose your route");
title.AddToClassList("screen-frame-title");
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");
subtitle.AddToClassList("repository-subtitle");
copy.Add(subtitle);
header.Add(copy);
screen.Add(header);
var body = new ScrollView(ScrollViewMode.Vertical);
body.AddToClassList("repository-body");
body.AddToClassList("screen-frame-content");
body.Add(reward ? RunRouteView.BuildReward(_runManager)
: eventScreen ? RunMapView.BuildEvent(_runManager) : RunRouteView.Build(_runManager, _combatManager));
if (!reward && !eventScreen && !_runManager.CampaignChoicePending)
{
body.AddToClassList("route-map-body");
body.contentViewport.RegisterCallback<GeometryChangedEvent>(evt =>
{
var mapScroll = body.Q<ScrollView>("RouteMapScroll");
if (mapScroll != null)
mapScroll.style.height = Mathf.Max(260, evt.newRect.height - 20);
});
}
if (committed)
{
var save = new Button(SaveAndExitRun) { name = "SaveAndExitRunButton", text = "save and exit" };
save.AddToClassList("secondary-action"); body.Add(save);
}
screen.Add(body);
var footer = new VisualElement();
footer.AddToClassList("screen-frame-footer");
footer.AddToClassList("route-map-footer");
var back = new Button(() =>
{
if (!eventScreen) SetRouteSelectionOpen(false);
else if (_runManager.RouteEventPending)
{
_routeEventOpen = false; RefreshOverlay();
_overlay.Q<Button>("ConfirmRouteButton")?.Focus();
}
})
{ name = eventScreen ? "BackToRouteButton" : "BackToRepositoryButton",
text = committed ? "stop committed" : eventScreen ? "< back to map" : "< back to repository" };
back.SetEnabled(!committed);
back.AddToClassList("primary-action");
back.AddToClassList("route-map-back");
footer.Add(back);
screen.RegisterCallback<KeyDownEvent>(evt =>
{
if (evt.keyCode != KeyCode.Escape || !back.enabledSelf) return;
using var submit = NavigationSubmitEvent.GetPooled();
submit.target = back; back.SendEvent(submit); evt.StopPropagation();
});
void MoveAction(string name, string caption = null)
{
var button = body.Q<Button>(name);
if (button == null) return;
button.RemoveFromHierarchy();
if (caption != null) button.text = caption;
if (name == "ResolveRouteEventButton")
{
string fullCaption = button.text;
button.RegisterCallback<GeometryChangedEvent>(evt => button.text = evt.newRect.width < 160 ? "apply" : fullCaption);
}
button.AddToClassList("primary-action");
button.AddToClassList(name is "ClaimBuildRewardButton" or "ResolveRouteEventButton" ? "route-map-continue" : "route-map-back");
footer.Add(button);
}
if (reward)
{
back.text = "< back"; back.tooltip = "Back to repository";
MoveAction("RewardBits", $"{RunManager.BuildRewardBits} Bits");
MoveAction("ClaimBuildRewardButton", "claim");
}
else if (eventScreen && !committed)
{
back.text = "< map";
MoveAction("SkipRouteEventButton", "pass");
MoveAction("ResolveRouteEventButton");
}
else if (!_runManager.CampaignChoicePending)
{
var confirm = new Button(() =>
{
if (_runManager.RouteEventPending && !eventScreen)
{
_routeEventOpen = true; RefreshOverlay();
_overlay.Q<Button>("BackToRouteButton")?.Focus();
}
else _combatManager.ContinueToNextWave();
})
{
name = "ConfirmRouteButton",
text = eventScreen ? committed ? "> continue to battle" : "confirm or pass above"
: _runManager.RouteEventPending ? "> enter stop" : "> continue to battle"
};
confirm.AddToClassList("primary-action");
confirm.AddToClassList("route-map-continue");
confirm.SetEnabled((!eventScreen || committed) && !_runManager.IsSuspended);
footer.Add(confirm);
}
screen.Add(footer);
if (committed) screen.schedule.Execute(() => screen.Q<Button>("ConfirmRouteButton")?.Focus());
return screen;
}
private void SaveAndExitRun()
{
if (_runManager.IsSuspended || !_combatManager.AwaitingWaveContinue) return;
try
{
if (_dailyQuestTracker?.Flush() == false)
throw new IOException("Daily quest progress: " + _dailyQuestTracker.SaveError);
RunCheckpointService.SaveAndSuspend(_saveService, _runManager, _combatManager);
_checkpointError = null;
_overlay.SetEnabled(false);
SceneLoader.LoadMainMenu(_root);
}
catch (Exception ex) when (ex is IOException || ex is InvalidDataException || ex is UnauthorizedAccessException)
{
_checkpointError = ex.Message;
Refresh();
}
}
private VisualElement BuildRepositoryHeader()
{
VisualElement header = new();
header.AddToClassList("repository-header");
header.AddToClassList("screen-frame-header");
VisualElement copy = new();
copy.AddToClassList("repository-header-copy");
Label title = new("repository");
title.AddToClassList("repository-title");
title.AddToClassList("screen-frame-title");
Label subtitle = new($"wave {_runManager.CurrentWaveNumber - 1} cleared / {_runManager.RepositoryOffers.Count} packages indexed");
subtitle.AddToClassList("repository-subtitle");
copy.Add(title);
copy.Add(subtitle);
VisualElement wallet = new();
wallet.AddToClassList("repository-wallet");
Label walletLabel = new("available bits");
walletLabel.AddToClassList("status-label");
Label walletValue = new($"◆ {_runManager.Bits}");
walletValue.AddToClassList("repository-wallet-value");
wallet.Add(walletLabel);
wallet.Add(walletValue);
header.Add(copy);
header.Add(wallet);
return header;
}
private VisualElement RepositoryOfferTile(RepositoryOffer offer)
{
VisualElement tile = new();
tile.AddToClassList("repository-tile");
tile.AddToClassList(OfferTileClass(offer.Kind));
bool unavailable = offer.Sold || _runManager.Bits < offer.Price;
tile.EnableInClassList("repo-unaffordable", unavailable);
tile.EnableInClassList("repo-sold", offer.Sold);
VisualElement top = new();
top.AddToClassList("repository-tile-top");
Label kind = new($"{OfferKindIcon(offer.Kind)} {OfferKindText(offer.Kind)}");
kind.AddToClassList("repository-kind");
top.Add(kind);
top.Add(PriceBadge(offer.Price, unavailable));
tile.Add(top);
VisualElement content = offer.Kind switch
{
RepositoryOfferKind.NewCard => CardOfferContent(offer),
RepositoryOfferKind.CardUpgrade => UpgradeOfferContent(offer),
RepositoryOfferKind.StatUpgrade => StatOfferContent(offer),
_ => GenericOfferContent(offer)
};
tile.Add(content);
Button buy = new(() => _runManager.BuyOffer(offer, _combatManager.PlayerState))
{
text = offer.Sold ? "installed" : OfferActionText(offer.Kind)
};
buy.tooltip = OfferCommandText(offer);
buy.AddToClassList("repository-action");
buy.SetEnabled(!offer.Sold && _runManager.Bits >= offer.Price);
tile.Add(buy);
return tile;
}
private VisualElement CardOfferContent(RepositoryOffer offer)
{
VisualElement content = new();
content.AddToClassList("repository-card-content");
CardInstance preview = new(offer.CardDefinition);
VisualElement card = CardFaceView(preview);
card.AddToClassList("repository-card-preview");
content.Add(card);
if (offer.CardDefinition != null && offer.CardDefinition.IsRunOnly)
{
content.Add(Tag("run-only", "repository-run-only-tag"));
}
return content;
}
private VisualElement UpgradeOfferContent(RepositoryOffer offer)
{
VisualElement content = new();
content.AddToClassList("repository-upgrade-content");
if (offer.TargetCard != null)
{
VisualElement target = CardFaceView(offer.TargetCard);
target.AddToClassList("repository-upgrade-card");
content.Add(target);
}
VisualElement delta = new();
delta.AddToClassList("repository-delta");
Label arrow = new("▲");
arrow.AddToClassList("repository-delta-icon");
Label text = new(offer.Description);
text.AddToClassList("repository-delta-text");
delta.Add(arrow);
delta.Add(text);
content.Add(delta);
return content;
}
private VisualElement StatOfferContent(RepositoryOffer offer)
{
VisualElement content = new();
content.AddToClassList("repository-stat-content");
Label icon = new(StatOfferIcon(offer.StatUpgradeKind));
icon.AddToClassList("repository-stat-icon");
Label name = new(offer.DisplayName);
name.AddToClassList("repository-name");
Label description = new(offer.Description);
description.AddToClassList("repository-description");
content.Add(icon);
content.Add(name);
content.Add(description);
return content;
}
private static VisualElement GenericOfferContent(RepositoryOffer offer)
{
VisualElement content = new();
Label name = new(offer.DisplayName);
name.AddToClassList("repository-name");
Label description = new(offer.Description);
description.AddToClassList("repository-description");
content.Add(name);
content.Add(description);
return content;
}
private static VisualElement PriceBadge(int price, bool warning)
{
Label badge = new($"◆ {price}");
badge.AddToClassList("repository-price");
badge.EnableInClassList("repository-price-warning", warning);
return badge;
}
private VisualElement RemoveCardBlock()
{
VisualElement block = new();
block.AddToClassList("repository-remove");
Label title = new($"installed deck maintenance / remove for {CombatTuning.RemoveCardCost} bit");
title.AddToClassList("repository-name");
block.Add(title);
VisualElement rows = new();
rows.AddToClassList("repository-remove-list");
for (int i = 0; i < _runManager.RunDeck.Count; i++)
{
CardInstance card = _runManager.RunDeck[i];
Button remove = new(() => _runManager.RemoveCard(card))
{
text = $"apt remove {DisplayName(card.Definition)}"
};
remove.AddToClassList("repo-remove-button");
remove.EnableInClassList("repo-unaffordable", _runManager.Bits < CombatTuning.RemoveCardCost || _runManager.RunDeck.Count <= 1);
remove.SetEnabled(_runManager.Bits >= CombatTuning.RemoveCardCost && _runManager.RunDeck.Count > 1);
rows.Add(remove);
}
block.Add(rows);
return block;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ffd46b87c84b4504a7fb080b6b44bfe4
@@ -0,0 +1,153 @@
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.Run;
using UnityEngine;
using UnityEngine.UIElements;
namespace KernelPanic.UI
{
public sealed partial class CombatSceneController
{
private VisualElement BuildRunEndOverlay()
{
_runEndedBySurrender |= _combatManager.RunEndedBySurrender;
VisualElement screen = new();
screen.AddToClassList("death-overlay");
screen.EnableInClassList("death-surrender", _runEndedBySurrender);
screen.EnableInClassList("run-victory", _combatManager.RunCompleted);
if (!_runEndOverlayPresented)
{
_runEndOverlayPresented = true;
if (!UIPreferences.ReducedMotion && !_combatManager.RunCompleted)
{
VisualElement beat = new();
beat.AddToClassList("death-crash-beat");
screen.Add(beat);
screen.schedule.Execute(() => beat.AddToClassList("death-crash-beat-settled")).StartingIn(25);
screen.schedule.Execute(() => beat.RemoveFromHierarchy()).StartingIn(260);
}
}
VisualElement content = new();
content.AddToClassList("death-content");
AddCampaignUnlockNotice(content);
var config = _runManager.CurrentConfig;
VisualElement reportHeader = new();
reportHeader.AddToClassList("death-report-header");
reportHeader.Add(SoftwareCardView.Text("RUN REPORT", "death-eyebrow"));
reportHeader.Add(SoftwareCardView.Text($"seed {config?.RunSeed ?? 0}", "death-seed"));
content.Add(reportHeader);
content.Add(OverlayTitle(_combatManager.RunCompleted ? "KERNEL SECURED" : _runEndedBySurrender ? "SYSTEM HALTED" : "KERNEL PANIC"));
var report = GetRunHistoryEntry();
string cause = report.cause;
Label causeLabel = OverlayLine(cause);
causeLabel.AddToClassList("death-cause");
content.Add(causeLabel);
if (config?.Distro != null)
content.Add(SoftwareCardView.Text($"{DisplayName(config.Distro)} V{config.DistroVersion} / {config.PrimaryLanguage} + {config.SecondaryLanguage}", "death-session"));
VisualElement summary = new();
summary.AddToClassList("death-section");
summary.AddToClassList("death-summary");
summary.AddToClassList("death-wave-stats");
summary.Add(DeathStat("wave reached", report.waveReached.ToString()));
summary.Add(DeathStat("waves cleared", _runManager.WavesCleared.ToString()));
content.Add(summary);
bool recapUnavailable = report.victory && report.finalRound == 0;
content.Add(SoftwareCardView.Text(recapUnavailable ? "COMBAT RECAP" : $"FINAL ROUND {report.finalRound}", "death-eyebrow"));
var recap = new VisualElement();
recap.AddToClassList("death-section");
recap.Add(OverlayLine(recapUnavailable ? "Combat recap unavailable after resuming this checkpoint."
: $"{report.damageDealt} uptime dealt / {report.damageTaken} uptime lost / {report.shieldBlocked} blocked by shield"));
if (report.finalHits.Count > 0)
{
var hits = new Foldout { text = "Last incoming hits (up to 8)", value = false };
foreach (string hit in report.finalHits) hits.Add(OverlayLine(hit));
recap.Add(hits);
}
content.Add(recap);
var performance = new Foldout { text = "Full run statistics & final deck", value = false };
performance.Add(RunPerformanceView.Build(report, cardDatabase));
content.Add(performance);
content.Add(SoftwareCardView.Text("RECOVERED RESOURCES", "death-eyebrow"));
VisualElement rewards = new();
rewards.AddToClassList("death-section");
rewards.AddToClassList("death-rewards");
rewards.Add(RewardReadout("#", _runManager.AccruedBandwidth, "bandwidth", false));
rewards.Add(RewardReadout("*", _runManager.AccruedEntropy, "entropy", _runManager.AccruedEntropy <= 0));
content.Add(rewards);
content.Add(SoftwareCardView.Text("Return to your collection to prepare the next run.", "death-next-run"));
Button returnButton = new(() => SceneLoader.LoadMainMenu(_root)) { text = "> return to menu" };
returnButton.AddToClassList("primary-action");
returnButton.AddToClassList("death-return-action");
if (!string.IsNullOrEmpty(_saveError))
{
content.Add(OverlayLine((_runManager.RewardsSettled ? "Could not reload saved progress: " : "Rewards are not saved yet: ") + _saveError));
var retrySave = new Button(() => { SettleRunRewardsIfNeeded(); Refresh(); }) { text = "Retry saving rewards" };
content.Add(retrySave);
returnButton.SetEnabled(_runManager.RewardsSettled);
}
content.Add(returnButton);
var scroll = new ScrollView(ScrollViewMode.Vertical);
scroll.AddToClassList("death-scroll");
scroll.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
// Center within the actual viewport, including Unity's internal ScrollView wrapper.
// A minimum (not fixed) height lets short windows scroll the entire report.
scroll.contentContainer.style.alignItems = Align.Center;
scroll.contentContainer.style.justifyContent = Justify.Center;
scroll.contentViewport.RegisterCallback<GeometryChangedEvent>(evt =>
scroll.contentContainer.style.minHeight = evt.newRect.height);
scroll.Add(content);
screen.Add(scroll);
return screen;
}
private void SettleRunRewardsIfNeeded()
{
if (_runManager?.CurrentConfig?.IsTutorial == true) return;
if (_runManager == null || _saveService == null || _runManager.IsSuspended || _runManager.CurrentConfig == null)
{
return;
}
if (_runManager.RewardsSettled)
{
return;
}
try
{
SaveData data = _saveService.Load();
data.bandwidthBalance = Math.Max(0, data.bandwidthBalance) + _runManager.AccruedBandwidth;
LanguageUnlock.RecordCampaignClear(data, _runManager.CurrentConfig, _runManager.Journey, _runManager.WavesCleared);
data.entropyBalance = Math.Max(0, data.entropyBalance) + _runManager.AccruedEntropy;
data.RecordRunStats(_runManager.CurrentConfig?.Distro?.Id,
_combatManager.RunCompleted ? _runManager.WavesCleared : _runManager.CurrentWaveNumber);
if (_combatManager.RunFinished) RunHistory.Record(data.recentRuns, GetRunHistoryEntry());
if (data.activeRun?.runId == _runManager.RunId) data.activeRun = null;
_saveService.Save(data);
_lastKnownSave = data;
_runManager.MarkRunRewardsSettled();
_saveError = null;
}
catch (Exception ex) when (ex is IOException || ex is InvalidDataException || ex is UnauthorizedAccessException)
{
_saveError = ex.Message;
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 80958a8e6206413886610cfb272f89f5
+17 -525
View File
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using KernelPanic.Combat;
using KernelPanic.Core;
using KernelPanic.Data;
@@ -69,6 +70,8 @@ namespace KernelPanic.UI
private ExecutionTrackView _queueView;
private ExecutionTrackView _stackView;
private ExecutionPreviewView _executionPreview;
private TurnResolutionView _turnResolution;
private CombatExecutionTrace _executionTrace;
private Label _encounterBrief;
private float _journalStartedAt;
private readonly Dictionary<EnemyInstance, Button> _enemyCards = new();
@@ -153,10 +156,16 @@ namespace KernelPanic.UI
private void OnEnable()
{
_campaignUnlocksSaved = false;
_campaignUnlockNotice = _campaignUnlockError = null;
_executionTrace?.Dispose();
_executionTrace = new CombatExecutionTrace(_combatManager);
_turnResolution?.Bind(_executionTrace);
_runTelemetry?.Dispose();
_runTelemetry = new CombatRunTelemetry(() => _combatManager.PlayerState, DescribeDamageSource)
{
SurrenderRequested = () => _combatManager.RunEndedBySurrender
SurrenderRequested = () => _combatManager.RunEndedBySurrender,
PerformanceSource = () => _runManager.Performance
};
_queueView ??= new ExecutionTrackView(_interpreterStrip, false);
_stackView ??= new ExecutionTrackView(_lazyStackPile, true);
@@ -296,6 +305,9 @@ namespace KernelPanic.UI
_feedbackLayer?.Clear();
_runTelemetry?.Dispose();
_runTelemetry = null;
_turnResolution?.Dispose();
_executionTrace?.Dispose();
_executionTrace = null;
}
private void HandleKeyDown(KeyDownEvent evt)
@@ -464,6 +476,8 @@ namespace KernelPanic.UI
workspace.Add(_encounterBrief);
_executionPreview = new ExecutionPreviewView();
workspace.Add(_executionPreview.Element);
_turnResolution = new TurnResolutionView();
workspace.Add(_turnResolution.Element);
VisualElement main = new();
main.AddToClassList("main-layout");
workspace.Add(main);
@@ -691,6 +705,7 @@ namespace KernelPanic.UI
private void Refresh()
{
PersistCampaignUnlocks();
if (_combatManager.PlayerState == null)
{
return;
@@ -1253,6 +1268,7 @@ namespace KernelPanic.UI
languages = $"{config?.PrimaryLanguage} + {config?.SecondaryLanguage}",
seed = config?.RunSeed ?? 0,
build = RunHistory.CaptureBuild(config),
finalDeck = _runManager.FinalDeck ?? _runManager.RunDeck.Select(CheckpointCard.Capture).ToList(),
waveReached = _combatManager.RunCompleted ? _runManager.WavesCleared : _runManager.CurrentWaveNumber,
wavesCleared = _runManager.WavesCleared,
surrendered = _runEndedBySurrender || _combatManager.RunEndedBySurrender,
@@ -1461,530 +1477,6 @@ namespace KernelPanic.UI
_overlay.style.display = DisplayStyle.None;
}
private VisualElement BuildRunEndOverlay()
{
_runEndedBySurrender |= _combatManager.RunEndedBySurrender;
VisualElement screen = new();
screen.AddToClassList("death-overlay");
screen.EnableInClassList("death-surrender", _runEndedBySurrender);
screen.EnableInClassList("run-victory", _combatManager.RunCompleted);
if (!_runEndOverlayPresented)
{
_runEndOverlayPresented = true;
if (!UIPreferences.ReducedMotion && !_combatManager.RunCompleted)
{
VisualElement beat = new();
beat.AddToClassList("death-crash-beat");
screen.Add(beat);
screen.schedule.Execute(() => beat.AddToClassList("death-crash-beat-settled")).StartingIn(25);
screen.schedule.Execute(() => beat.RemoveFromHierarchy()).StartingIn(260);
}
}
VisualElement content = new();
content.AddToClassList("death-content");
var config = _runManager.CurrentConfig;
VisualElement reportHeader = new();
reportHeader.AddToClassList("death-report-header");
reportHeader.Add(SoftwareCardView.Text("RUN REPORT", "death-eyebrow"));
reportHeader.Add(SoftwareCardView.Text($"seed {config?.RunSeed ?? 0}", "death-seed"));
content.Add(reportHeader);
content.Add(OverlayTitle(_combatManager.RunCompleted ? "KERNEL SECURED" : _runEndedBySurrender ? "SYSTEM HALTED" : "KERNEL PANIC"));
var report = GetRunHistoryEntry();
string cause = report.cause;
Label causeLabel = OverlayLine(cause);
causeLabel.AddToClassList("death-cause");
content.Add(causeLabel);
if (config?.Distro != null)
content.Add(SoftwareCardView.Text($"{DisplayName(config.Distro)} V{config.DistroVersion} / {config.PrimaryLanguage} + {config.SecondaryLanguage}", "death-session"));
VisualElement summary = new();
summary.AddToClassList("death-section");
summary.AddToClassList("death-summary");
summary.AddToClassList("death-wave-stats");
summary.Add(DeathStat("wave reached", report.waveReached.ToString()));
summary.Add(DeathStat("waves cleared", _runManager.WavesCleared.ToString()));
content.Add(summary);
bool recapUnavailable = report.victory && report.finalRound == 0;
content.Add(SoftwareCardView.Text(recapUnavailable ? "COMBAT RECAP" : $"FINAL ROUND {report.finalRound}", "death-eyebrow"));
var recap = new VisualElement();
recap.AddToClassList("death-section");
recap.Add(OverlayLine(recapUnavailable ? "Combat recap unavailable after resuming this checkpoint."
: $"{report.damageDealt} uptime dealt / {report.damageTaken} uptime lost / {report.shieldBlocked} blocked by shield"));
if (report.finalHits.Count > 0)
{
var hits = new Foldout { text = "Last incoming hits (up to 8)", value = false };
foreach (string hit in report.finalHits) hits.Add(OverlayLine(hit));
recap.Add(hits);
}
content.Add(recap);
content.Add(SoftwareCardView.Text("RECOVERED RESOURCES", "death-eyebrow"));
VisualElement rewards = new();
rewards.AddToClassList("death-section");
rewards.AddToClassList("death-rewards");
rewards.Add(RewardReadout("#", _runManager.AccruedBandwidth, "bandwidth", false));
rewards.Add(RewardReadout("*", _runManager.AccruedEntropy, "entropy", _runManager.AccruedEntropy <= 0));
content.Add(rewards);
content.Add(SoftwareCardView.Text("Return to your collection to prepare the next run.", "death-next-run"));
Button returnButton = new(() => SceneLoader.LoadMainMenu(_root)) { text = "> return to menu" };
returnButton.AddToClassList("primary-action");
returnButton.AddToClassList("death-return-action");
if (!string.IsNullOrEmpty(_saveError))
{
content.Add(OverlayLine((_runManager.RewardsSettled ? "Could not reload saved progress: " : "Rewards are not saved yet: ") + _saveError));
var retrySave = new Button(() => { SettleRunRewardsIfNeeded(); Refresh(); }) { text = "Retry saving rewards" };
content.Add(retrySave);
returnButton.SetEnabled(_runManager.RewardsSettled);
}
content.Add(returnButton);
var scroll = new ScrollView(ScrollViewMode.Vertical);
scroll.AddToClassList("death-scroll");
scroll.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
// Center within the actual viewport, including Unity's internal ScrollView wrapper.
// A minimum (not fixed) height lets short windows scroll the entire report.
scroll.contentContainer.style.alignItems = Align.Center;
scroll.contentContainer.style.justifyContent = Justify.Center;
scroll.contentViewport.RegisterCallback<GeometryChangedEvent>(evt =>
scroll.contentContainer.style.minHeight = evt.newRect.height);
scroll.Add(content);
screen.Add(scroll);
return screen;
}
private void SettleRunRewardsIfNeeded()
{
if (_runManager?.CurrentConfig?.IsTutorial == true) return;
if (_runManager == null || _saveService == null || _runManager.IsSuspended || _runManager.CurrentConfig == null)
{
return;
}
if (_runManager.RewardsSettled)
{
return;
}
try
{
SaveData data = _saveService.Load();
data.bandwidthBalance = Math.Max(0, data.bandwidthBalance) + _runManager.AccruedBandwidth;
data.entropyBalance = Math.Max(0, data.entropyBalance) + _runManager.AccruedEntropy;
data.RecordRunStats(_runManager.CurrentConfig?.Distro?.Id,
_combatManager.RunCompleted ? _runManager.WavesCleared : _runManager.CurrentWaveNumber);
if (_combatManager.RunFinished) RunHistory.Record(data.recentRuns, GetRunHistoryEntry());
if (data.activeRun?.runId == _runManager.RunId) data.activeRun = null;
_saveService.Save(data);
_lastKnownSave = data;
_runManager.MarkRunRewardsSettled();
_saveError = null;
}
catch (Exception ex) when (ex is IOException || ex is InvalidDataException || ex is UnauthorizedAccessException)
{
_saveError = ex.Message;
}
}
private VisualElement BuildRepositoryView()
{
VisualElement repo = new();
repo.AddToClassList("repository");
repo.AddToClassList("screen-frame");
repo.Add(BuildRepositoryHeader());
ScrollView body = new(ScrollViewMode.Vertical);
body.AddToClassList("repository-body");
body.AddToClassList("screen-frame-content");
VisualElement offers = new();
offers.AddToClassList("repository-offers");
if (_runManager.RepositoryOffers.Count == 0)
{
offers.Add(EmptyState("repository clean: no offers left this visit"));
}
else
{
for (int i = 0; i < _runManager.RepositoryOffers.Count; i++)
{
offers.Add(RepositoryOfferTile(_runManager.RepositoryOffers[i]));
}
}
body.Add(offers);
body.Add(RemoveCardBlock());
repo.Add(body);
VisualElement footer = new();
footer.AddToClassList("repository-footer");
footer.AddToClassList("screen-frame-footer");
Button reroll = new(() => _runManager.RerollRepositoryOffers(cardDatabase, languageDeckDatabase))
{
text = $"apt update {_runManager.RerollCost} bits"
};
reroll.AddToClassList("primary-action");
reroll.AddToClassList("repository-footer-action");
reroll.AddToClassList("repository-reroll-action");
reroll.EnableInClassList("repo-unaffordable", _runManager.Bits < _runManager.RerollCost);
reroll.SetEnabled(_runManager.Bits >= _runManager.RerollCost);
footer.Add(reroll);
Button leave = new(() =>
{
if (_runManager.Journey.campaign) SetRouteSelectionOpen(true);
else _combatManager.ContinueToNextWave();
}) { name = "BootNextWaveButton", text = "> boot next-wave" };
leave.AddToClassList("primary-action");
leave.AddToClassList("repository-leave-action");
leave.SetEnabled(!_runManager.IsSuspended);
VisualElement leaveBlock = new();
leaveBlock.AddToClassList("repository-leave-block");
leaveBlock.Add(leave);
Label banked = new($"{_runManager.Bits} bits remaining");
banked.AddToClassList("repository-banked-hint");
banked.AddToClassList("screen-frame-hint");
leaveBlock.Add(banked);
var suspend = new Button(SaveAndExitRun) { name = "SaveAndExitRunButton", text = "save & exit" };
suspend.AddToClassList("primary-action");
suspend.AddToClassList("repository-leave-action");
suspend.SetEnabled(!_runManager.IsSuspended);
leaveBlock.Add(suspend);
if (!string.IsNullOrEmpty(_checkpointError))
leaveBlock.Add(TerminalLayout.BodyText("Save failed: " + _checkpointError + " Stay here and retry.", className: "screen-frame-hint"));
footer.Add(leaveBlock);
repo.Add(footer);
return repo;
}
private void SetRouteSelectionOpen(bool open)
{
_routeSelectionOpen = open;
_routeEventOpen = false;
RefreshOverlay();
_overlay.Q<Button>(open ? "BackToRepositoryButton" : "BootNextWaveButton")?.Focus();
}
private VisualElement BuildRouteSelectionView()
{
bool reward = _runManager.BuildRewardPending;
bool eventScreen = !reward && _routeEventOpen && !_runManager.CampaignChoicePending;
bool committed = eventScreen && !_runManager.RouteEventPending;
var screen = new VisualElement { name = reward ? "BuildRewardScreen" : eventScreen ? "RouteEventScreen" : "RouteSelectionScreen" };
screen.AddToClassList("repository");
screen.AddToClassList("screen-frame");
screen.AddToClassList("route-map-screen");
var header = new VisualElement();
header.AddToClassList("repository-header");
header.AddToClassList("screen-frame-header");
var copy = new VisualElement();
copy.AddToClassList("repository-header-copy");
var title = new Label(_runManager.CampaignChoicePending ? "campaign complete" : reward ? "claim your build reward"
: eventScreen ? RunRouteMap.Title(_runManager.Journey.selectedRoute) : "choose your route");
title.AddToClassList("screen-frame-title");
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");
subtitle.AddToClassList("repository-subtitle");
copy.Add(subtitle);
header.Add(copy);
screen.Add(header);
var body = new ScrollView(ScrollViewMode.Vertical);
body.AddToClassList("repository-body");
body.AddToClassList("screen-frame-content");
body.Add(reward ? RunRouteView.BuildReward(_runManager)
: eventScreen ? RunMapView.BuildEvent(_runManager) : RunRouteView.Build(_runManager, _combatManager));
if (!reward && !eventScreen && !_runManager.CampaignChoicePending)
{
body.AddToClassList("route-map-body");
body.contentViewport.RegisterCallback<GeometryChangedEvent>(evt =>
{
var mapScroll = body.Q<ScrollView>("RouteMapScroll");
if (mapScroll != null)
mapScroll.style.height = Mathf.Max(260, evt.newRect.height - 20);
});
}
if (committed)
{
var save = new Button(SaveAndExitRun) { name = "SaveAndExitRunButton", text = "save and exit" };
save.AddToClassList("secondary-action"); body.Add(save);
}
screen.Add(body);
var footer = new VisualElement();
footer.AddToClassList("screen-frame-footer");
footer.AddToClassList("route-map-footer");
var back = new Button(() =>
{
if (!eventScreen) SetRouteSelectionOpen(false);
else if (_runManager.RouteEventPending)
{
_routeEventOpen = false; RefreshOverlay();
_overlay.Q<Button>("ConfirmRouteButton")?.Focus();
}
})
{ name = eventScreen ? "BackToRouteButton" : "BackToRepositoryButton",
text = committed ? "stop committed" : eventScreen ? "< back to map" : "< back to repository" };
back.SetEnabled(!committed);
back.AddToClassList("primary-action");
back.AddToClassList("route-map-back");
footer.Add(back);
screen.RegisterCallback<KeyDownEvent>(evt =>
{
if (evt.keyCode != KeyCode.Escape || !back.enabledSelf) return;
using var submit = NavigationSubmitEvent.GetPooled();
submit.target = back; back.SendEvent(submit); evt.StopPropagation();
});
void MoveAction(string name, string caption = null)
{
var button = body.Q<Button>(name);
if (button == null) return;
button.RemoveFromHierarchy();
if (caption != null) button.text = caption;
if (name == "ResolveRouteEventButton")
{
string fullCaption = button.text;
button.RegisterCallback<GeometryChangedEvent>(evt => button.text = evt.newRect.width < 160 ? "apply" : fullCaption);
}
button.AddToClassList("primary-action");
button.AddToClassList(name is "ClaimBuildRewardButton" or "ResolveRouteEventButton" ? "route-map-continue" : "route-map-back");
footer.Add(button);
}
if (reward)
{
back.text = "< back"; back.tooltip = "Back to repository";
MoveAction("RewardBits", $"{RunManager.BuildRewardBits} Bits");
MoveAction("ClaimBuildRewardButton", "claim");
}
else if (eventScreen && !committed)
{
back.text = "< map";
MoveAction("SkipRouteEventButton", "pass");
MoveAction("ResolveRouteEventButton");
}
else if (!_runManager.CampaignChoicePending)
{
var confirm = new Button(() =>
{
if (_runManager.RouteEventPending && !eventScreen)
{
_routeEventOpen = true; RefreshOverlay();
_overlay.Q<Button>("BackToRouteButton")?.Focus();
}
else _combatManager.ContinueToNextWave();
})
{
name = "ConfirmRouteButton",
text = eventScreen ? committed ? "> continue to battle" : "confirm or pass above"
: _runManager.RouteEventPending ? "> enter stop" : "> continue to battle"
};
confirm.AddToClassList("primary-action");
confirm.AddToClassList("route-map-continue");
confirm.SetEnabled((!eventScreen || committed) && !_runManager.IsSuspended);
footer.Add(confirm);
}
screen.Add(footer);
if (committed) screen.schedule.Execute(() => screen.Q<Button>("ConfirmRouteButton")?.Focus());
return screen;
}
private void SaveAndExitRun()
{
if (_runManager.IsSuspended || !_combatManager.AwaitingWaveContinue) return;
try
{
if (_dailyQuestTracker?.Flush() == false)
throw new IOException("Daily quest progress: " + _dailyQuestTracker.SaveError);
RunCheckpointService.SaveAndSuspend(_saveService, _runManager, _combatManager);
_checkpointError = null;
_overlay.SetEnabled(false);
SceneLoader.LoadMainMenu(_root);
}
catch (Exception ex) when (ex is IOException || ex is InvalidDataException || ex is UnauthorizedAccessException)
{
_checkpointError = ex.Message;
Refresh();
}
}
private VisualElement BuildRepositoryHeader()
{
VisualElement header = new();
header.AddToClassList("repository-header");
header.AddToClassList("screen-frame-header");
VisualElement copy = new();
copy.AddToClassList("repository-header-copy");
Label title = new("repository");
title.AddToClassList("repository-title");
title.AddToClassList("screen-frame-title");
Label subtitle = new($"wave {_runManager.CurrentWaveNumber - 1} cleared / {_runManager.RepositoryOffers.Count} packages indexed");
subtitle.AddToClassList("repository-subtitle");
copy.Add(title);
copy.Add(subtitle);
VisualElement wallet = new();
wallet.AddToClassList("repository-wallet");
Label walletLabel = new("available bits");
walletLabel.AddToClassList("status-label");
Label walletValue = new($"◆ {_runManager.Bits}");
walletValue.AddToClassList("repository-wallet-value");
wallet.Add(walletLabel);
wallet.Add(walletValue);
header.Add(copy);
header.Add(wallet);
return header;
}
private VisualElement RepositoryOfferTile(RepositoryOffer offer)
{
VisualElement tile = new();
tile.AddToClassList("repository-tile");
tile.AddToClassList(OfferTileClass(offer.Kind));
bool unavailable = offer.Sold || _runManager.Bits < offer.Price;
tile.EnableInClassList("repo-unaffordable", unavailable);
tile.EnableInClassList("repo-sold", offer.Sold);
VisualElement top = new();
top.AddToClassList("repository-tile-top");
Label kind = new($"{OfferKindIcon(offer.Kind)} {OfferKindText(offer.Kind)}");
kind.AddToClassList("repository-kind");
top.Add(kind);
top.Add(PriceBadge(offer.Price, unavailable));
tile.Add(top);
VisualElement content = offer.Kind switch
{
RepositoryOfferKind.NewCard => CardOfferContent(offer),
RepositoryOfferKind.CardUpgrade => UpgradeOfferContent(offer),
RepositoryOfferKind.StatUpgrade => StatOfferContent(offer),
_ => GenericOfferContent(offer)
};
tile.Add(content);
Button buy = new(() => _runManager.BuyOffer(offer, _combatManager.PlayerState))
{
text = offer.Sold ? "installed" : OfferActionText(offer.Kind)
};
buy.tooltip = OfferCommandText(offer);
buy.AddToClassList("repository-action");
buy.SetEnabled(!offer.Sold && _runManager.Bits >= offer.Price);
tile.Add(buy);
return tile;
}
private VisualElement CardOfferContent(RepositoryOffer offer)
{
VisualElement content = new();
content.AddToClassList("repository-card-content");
CardInstance preview = new(offer.CardDefinition);
VisualElement card = CardFaceView(preview);
card.AddToClassList("repository-card-preview");
content.Add(card);
if (offer.CardDefinition != null && offer.CardDefinition.IsRunOnly)
{
content.Add(Tag("run-only", "repository-run-only-tag"));
}
return content;
}
private VisualElement UpgradeOfferContent(RepositoryOffer offer)
{
VisualElement content = new();
content.AddToClassList("repository-upgrade-content");
if (offer.TargetCard != null)
{
VisualElement target = CardFaceView(offer.TargetCard);
target.AddToClassList("repository-upgrade-card");
content.Add(target);
}
VisualElement delta = new();
delta.AddToClassList("repository-delta");
Label arrow = new("▲");
arrow.AddToClassList("repository-delta-icon");
Label text = new(offer.Description);
text.AddToClassList("repository-delta-text");
delta.Add(arrow);
delta.Add(text);
content.Add(delta);
return content;
}
private VisualElement StatOfferContent(RepositoryOffer offer)
{
VisualElement content = new();
content.AddToClassList("repository-stat-content");
Label icon = new(StatOfferIcon(offer.StatUpgradeKind));
icon.AddToClassList("repository-stat-icon");
Label name = new(offer.DisplayName);
name.AddToClassList("repository-name");
Label description = new(offer.Description);
description.AddToClassList("repository-description");
content.Add(icon);
content.Add(name);
content.Add(description);
return content;
}
private static VisualElement GenericOfferContent(RepositoryOffer offer)
{
VisualElement content = new();
Label name = new(offer.DisplayName);
name.AddToClassList("repository-name");
Label description = new(offer.Description);
description.AddToClassList("repository-description");
content.Add(name);
content.Add(description);
return content;
}
private static VisualElement PriceBadge(int price, bool warning)
{
Label badge = new($"◆ {price}");
badge.AddToClassList("repository-price");
badge.EnableInClassList("repository-price-warning", warning);
return badge;
}
private VisualElement RemoveCardBlock()
{
VisualElement block = new();
block.AddToClassList("repository-remove");
Label title = new($"installed deck maintenance / remove for {CombatTuning.RemoveCardCost} bit");
title.AddToClassList("repository-name");
block.Add(title);
VisualElement rows = new();
rows.AddToClassList("repository-remove-list");
for (int i = 0; i < _runManager.RunDeck.Count; i++)
{
CardInstance card = _runManager.RunDeck[i];
Button remove = new(() => _runManager.RemoveCard(card))
{
text = $"apt remove {DisplayName(card.Definition)}"
};
remove.AddToClassList("repo-remove-button");
remove.EnableInClassList("repo-unaffordable", _runManager.Bits < CombatTuning.RemoveCardCost || _runManager.RunDeck.Count <= 1);
remove.SetEnabled(_runManager.Bits >= CombatTuning.RemoveCardCost && _runManager.RunDeck.Count > 1);
rows.Add(remove);
}
block.Add(rows);
return block;
}
private VisualElement CardFace(CardInstance card)
{
Button button = new(() =>
@@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using KernelPanic.Combat;
using KernelPanic.Core;
using KernelPanic.Data;
using KernelPanic.Meta;
using KernelPanic.Run;
using UnityEngine;
using UnityEngine.TextCore.Text;
using UnityEngine.UIElements;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace KernelPanic.UI
{
public sealed partial class MainMenuController
{
private void OpenRunHistory()
{
if (PersistenceBlocked || _runHistoryOverlay != null) return;
_runHistoryOverlay = RunHistoryView.Build(_saveData.recentRuns, CloseRunHistory,
cardDatabase, packageDatabase, LoadArchivedBuildIntoSetup, ArchivedBuildUnavailableReason);
_root.Add(_runHistoryOverlay);
TerminalTheme.ConstrainModalFocus(_runHistoryOverlay);
(_runHistoryOverlay.Q<Button>("CopyRunSeed_0") ?? _runHistoryOverlay.Q<Button>("CloseRunHistory"))?.Focus();
}
private void CloseRunHistory()
{
_runHistoryOverlay?.RemoveFromHierarchy();
_runHistoryOverlay = null;
_root.Q<Button>("RecentRunsButton")?.Focus();
}
private string ArchivedBuildUnavailableReason(RunHistoryEntry entry)
{
return RunHistory.TryResolveBuild(entry, _playerCollection, distroDatabase, cardDatabase,
packageDatabase, languageDeckDatabase, out _, out string reason) ? null : reason;
}
private void LoadArchivedBuildIntoSetup(RunHistoryEntry entry)
{
if (PersistenceBlocked || _runLaunchPending) return;
if (!RunHistory.TryResolveBuild(entry, _playerCollection, distroDatabase, cardDatabase,
packageDatabase, languageDeckDatabase, out var build, out string reason))
{
var notice = _runHistoryOverlay?.Q<Label>("RunHistoryNotice");
if (notice != null) notice.text = reason + " Your setup has not been changed.";
return;
}
// Validation completes before replacing any draft. Loading is not launching: do not
// change the last-run retry snapshot, hand off a run, or consume a saved repository.
CaptureSelectedDraftLanguages();
_cardLoadout.TryLoad(build.Distro.Id, build.CardIds, out _);
_packageLoadout.Load(build.Distro.Id, build.PackageSlots);
for (int i = 0; i < _playerCollection.OwnedUnits.Count; i++)
if (string.Equals(_playerCollection.OwnedUnits[i].Id, build.Distro.Id, StringComparison.OrdinalIgnoreCase))
_selectedPackageIndex = i;
_draftLanguagesByDistro[build.Distro.Id] = new List<Language>(build.Languages);
RestoreSelectedDraftLanguages();
_runSeedText = build.Seed.ToString(CultureInfo.InvariantCulture);
SaveCurrentState();
if (PersistenceBlocked) return;
CloseRunHistory();
HandleStartRunClicked();
_runSetupNotice = build.Notice
+ (_saveData.activeRun == null ? "" : " Your saved repository run is still available.");
RenderSelectedPackageDetail();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5021c7e6b7034ae4b1e46105e9ef9563
+2 -55
View File
@@ -67,7 +67,7 @@ namespace KernelPanic.UI
/// Binds the main menu terminal UI document and routes command activation between panels.
/// </summary>
[RequireComponent(typeof(UIDocument))]
public sealed class MainMenuController : MonoBehaviour
public sealed partial class MainMenuController : MonoBehaviour
{
private const string HiddenClassName = "hidden";
private const string SelectedClassName = "selected";
@@ -770,6 +770,7 @@ namespace KernelPanic.UI
// Snapshot before normalization, which clears the duplicate migration information.
List<CollapsedPackageDuplicate> collapsedPackageDuplicates = new(_saveData.CollapsedPackageDuplicates);
_saveData.EnsureLists();
_playerCollection.LoadCampaignClears(_saveData.campaignClearLanguages);
_wallet.SetBalance(_saveData.entropyBalance);
for (int i = 0; i < _saveData.ownedUnits.Count; i++)
@@ -2589,60 +2590,6 @@ namespace KernelPanic.UI
actions.Add(history);
}
private void OpenRunHistory()
{
if (PersistenceBlocked || _runHistoryOverlay != null) return;
_runHistoryOverlay = RunHistoryView.Build(_saveData.recentRuns, CloseRunHistory,
cardDatabase, packageDatabase, LoadArchivedBuildIntoSetup, ArchivedBuildUnavailableReason);
_root.Add(_runHistoryOverlay);
TerminalTheme.ConstrainModalFocus(_runHistoryOverlay);
(_runHistoryOverlay.Q<Button>("CopyRunSeed_0") ?? _runHistoryOverlay.Q<Button>("CloseRunHistory"))?.Focus();
}
private void CloseRunHistory()
{
_runHistoryOverlay?.RemoveFromHierarchy();
_runHistoryOverlay = null;
_root.Q<Button>("RecentRunsButton")?.Focus();
}
private string ArchivedBuildUnavailableReason(RunHistoryEntry entry)
{
return RunHistory.TryResolveBuild(entry, _playerCollection, distroDatabase, cardDatabase,
packageDatabase, languageDeckDatabase, out _, out string reason) ? null : reason;
}
private void LoadArchivedBuildIntoSetup(RunHistoryEntry entry)
{
if (PersistenceBlocked || _runLaunchPending) return;
if (!RunHistory.TryResolveBuild(entry, _playerCollection, distroDatabase, cardDatabase,
packageDatabase, languageDeckDatabase, out var build, out string reason))
{
var notice = _runHistoryOverlay?.Q<Label>("RunHistoryNotice");
if (notice != null) notice.text = reason + " Your setup has not been changed.";
return;
}
// Validation completes before replacing any draft. Loading is not launching: do not
// change the last-run retry snapshot, hand off a run, or consume a saved repository.
CaptureSelectedDraftLanguages();
_cardLoadout.TryLoad(build.Distro.Id, build.CardIds, out _);
_packageLoadout.Load(build.Distro.Id, build.PackageSlots);
for (int i = 0; i < _playerCollection.OwnedUnits.Count; i++)
if (string.Equals(_playerCollection.OwnedUnits[i].Id, build.Distro.Id, StringComparison.OrdinalIgnoreCase))
_selectedPackageIndex = i;
_draftLanguagesByDistro[build.Distro.Id] = new List<Language>(build.Languages);
RestoreSelectedDraftLanguages();
_runSeedText = build.Seed.ToString(CultureInfo.InvariantCulture);
SaveCurrentState();
if (PersistenceBlocked) return;
CloseRunHistory();
HandleStartRunClicked();
_runSetupNotice = build.Notice
+ (_saveData.activeRun == null ? "" : " Your saved repository run is still available.");
RenderSelectedPackageDetail();
}
private void AddResumeRunControl(VisualElement actions)
{
if (_saveData?.activeRun == null) return;
+1
View File
@@ -89,6 +89,7 @@ namespace KernelPanic.UI
load.AddToClassList("terminal-button");
buildDetails.Add(load);
item.Add(buildDetails);
item.Add(RunPerformanceView.Build(entry, cards));
var copySeed = new Button { text = "copy seed", name = $"CopyRunSeed_{index}" };
copySeed.AddToClassList("terminal-button");
copySeed.clicked += () =>
+42
View File
@@ -0,0 +1,42 @@
using System.Linq;
using KernelPanic.Data;
using KernelPanic.Meta;
using UnityEngine.UIElements;
namespace KernelPanic.UI
{
internal static class RunPerformanceView
{
public static VisualElement Build(RunHistoryEntry entry, CardDatabase cards = null)
{
var root = new VisualElement { name = "RunPerformance" };
root.style.flexShrink = 0;
var stats = entry.performance;
if (stats == null || stats.schemaVersion != 1)
root.Add(TerminalLayout.BodyText("Run-wide statistics unavailable for this older run."));
else
{
root.Add(TerminalLayout.BodyText(stats.complete ? "FULL RUN" : "SINCE RESUMING / earlier statistics unavailable"));
root.Add(TerminalLayout.BodyText($"{stats.cardsPlayed} cards played / {stats.damageDealt} Uptime dealt / {stats.damageTaken} lost / {stats.shieldBlocked} blocked"));
var contributions = new Foldout { text = "Card contributions", name = "CardContributions", value = false };
contributions.Add(TerminalLayout.BodyText("Grouped by card type, including repeats, Go ticks and Python payload replays. Damage excludes overkill. Shield granted is not Shield blocked. Utility effects are not scored."));
foreach (var card in (stats.cards ?? new()).Where(c => c != null)
.OrderByDescending(c => c.uptimeDamage + c.shieldDamage).ThenBy(c => c.name))
contributions.Add(TerminalLayout.BodyText($"{card.name ?? card.cardId}: {card.plays} plays / {card.uptimeDamage} Uptime damage / {card.shieldDamage} Shield damage / {card.shieldGranted} Shield granted"));
root.Add(contributions);
}
int count = entry.finalDeck?.Count ?? 0;
var deck = new Foldout { text = $"Final deck ({count} {(count == 1 ? "card" : "cards")})", name = "FinalRunDeck", value = false };
if (entry.finalDeck == null || entry.finalDeck.Count == 0)
deck.Add(TerminalLayout.BodyText("Final deck unavailable for this older run."));
else foreach (var card in entry.finalDeck.Where(c => c != null))
{
var definition = cards == null ? null : cards.FindById(card.cardId);
string name = definition?.DisplayName ?? stats?.cards?.Find(c => c.cardId == card.cardId)?.name ?? card.cardId;
deck.Add(TerminalLayout.BodyText($"{name} / upgrade {card.upgradeLevel} / magnitude +{card.magnitude} / draw +{card.drawRider} / Cycle adjustment {card.costDelta:+0;-0;0}"));
}
root.Add(deck);
return root;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: e4f28a0f71074d85933440391c043362
+75
View File
@@ -0,0 +1,75 @@
using System;
using System.Linq;
using KernelPanic.Combat;
using UnityEngine;
using UnityEngine.UIElements;
namespace KernelPanic.UI
{
internal sealed class TurnResolutionView : IDisposable
{
public Foldout Element { get; } = new() { text = "Turn resolution / actual results", name = "TurnResolution", value = true };
private readonly Label _sequence = new() { name = "ResolutionSequence", enableRichText = false };
private readonly ScrollView _actions = new(ScrollViewMode.Vertical) { name = "ResolutionActions" };
private CombatExecutionTrace _trace;
public TurnResolutionView()
{
Element.AddToClassList("execution-preview");
_sequence.style.whiteSpace = WhiteSpace.Normal;
_sequence.text = "Go > Python automation > Python FIFO > Haskell LIFO > Enemies > Cleanup";
_actions.style.maxHeight = 160;
_actions.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
Element.Add(_sequence); Element.Add(_actions);
Element.RegisterValueChangedCallback(_ => { Refresh(); FitRows(); });
Element.RegisterCallback<GeometryChangedEvent>(_ => FitRows());
_sequence.RegisterCallback<GeometryChangedEvent>(_ => FitRows());
}
private void FitRows()
{
var workspace = Element.GetFirstAncestorOfType<ScrollView>();
if (workspace == null) return;
float available = workspace.contentViewport.resolvedStyle.height;
float heading = Element.Q<Toggle>()?.resolvedStyle.height ?? 24;
float sequence = _sequence.resolvedStyle.height;
if (float.IsNaN(available) || float.IsNaN(heading) || float.IsNaN(sequence) || available <= 0) return;
_actions.style.maxHeight = Math.Max(20, Math.Min(160, available - heading - sequence - 20));
}
public void Bind(CombatExecutionTrace trace)
{
if (_trace != null) _trace.Changed -= Refresh;
_trace = trace;
if (_trace != null) _trace.Changed += Refresh;
Refresh();
}
private void Refresh()
{
string stage = _trace?.Stage ?? "Native";
Element.text = "Turn resolution / " + (stage == "Native" ? "planning & immediate cards" : stage);
_sequence.text = string.Join(" > ", new[] { "Go", "Automation", "FIFO", "LIFO", "Enemies", "Cleanup" }
.Select(s => s == stage ? "[ " + s + " ]" : s));
if (!Element.value) return;
_actions.Clear();
if (_trace == null || _trace.Actions.Count == 0)
_actions.Add(TerminalLayout.BodyText("Play a card or end your turn to see actual results. Hidden intents and random outcomes are revealed only when combat reveals them."));
else foreach (var action in _trace.Actions)
{
var row = new VisualElement();
row.style.marginBottom = 6;
var title = TerminalLayout.BodyText($"{(action.Complete ? "done" : "> resolving")} / {action.Stage} / {action.Label}");
if (!action.Complete) title.style.color = new Color(1f, .75f, .35f);
row.Add(title);
row.Add(TerminalLayout.BodyText($"{action.UptimeDamage} Uptime damage / {action.ShieldDamage} Shield damage / +{action.ShieldGranted} Shield"));
if (action.PlayerUptimeLost > 0 || action.PlayerShieldBlocked > 0)
row.Add(TerminalLayout.BodyText($"Host: {action.PlayerUptimeLost} Uptime lost / {action.PlayerShieldBlocked} blocked by Shield"));
foreach (var detail in action.Details) row.Add(TerminalLayout.BodyText(detail));
_actions.Add(row);
}
if (_actions.childCount > 0)
{
var latest = _actions[_actions.childCount - 1];
_actions.schedule.Execute(() => { if (latest.parent != null && Element.value) _actions.ScrollTo(latest); });
}
}
public void Dispose() => Bind(null);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: e9ef9a007159d3b47b11f772962472d1