Implement more QoL features and rebalances

This commit is contained in:
2026-10-25 02:16:30 +02:00
parent 0578913451
commit 53f831d91e
220 changed files with 14700 additions and 420 deletions
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 59b9870361cbdec4b9419c57a3ff71df
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+4 -4
View File
@@ -167,7 +167,7 @@ namespace KernelPanic.Combat
private const CardTargeting None = CardTargeting.None;
private const CardTargeting Single = CardTargeting.SingleEnemy;
private const CardTargeting All = CardTargeting.AllEnemies;
private const string CRecoil = " overkill spills. 25%: segfault, uptime -3 and corrupt a hand card.";
private const string CRecoil = " 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card.";
private const string Jit = " overkill spills. JIT applies; discount decays by 1 after each wave.";
private static readonly IReadOnlyDictionary<string, CardCatalogEntry> ById;
public static IReadOnlyList<CardCatalogEntry> Entries { get; }
@@ -182,7 +182,7 @@ namespace KernelPanic.Combat
Add("gentoo_ebuild", Single, false, "stack: deal {amount:0}.", Damage(4, Language.Haskell));
Add("gentoo_use_flags", None, false, "gain {shield:0} Shield. if Compilation >= {rawSecondary:1}, draw {amount:1}.",
Shield(4), Fx(CardEffectKind.CompilationDraw, CompilationDrawEffect.DrawCount, secondary: CompilationDrawEffect.RequiredCompilation));
Add("gentoo_make_j4", Single, true, "deal {amount:0}; {secondary:0} if Compilation >= {rawMax:0}. one C hit; overkill spills; 25%: segfault, uptime -3 and corrupt a hand card.",
Add("gentoo_make_j4", Single, true, "deal {amount:0}; {secondary:0} if Compilation >= {rawMax:0}. one C hit; 50% of overkill spills per jump (rounded down); 25%: segfault, uptime -3 and corrupt a hand card.",
Fx(CardEffectKind.MakeJ4, MakeJ4Effect.BaseDamage, MakeJ4Effect.RequiredCompilation, MakeJ4Effect.CompiledDamage, Language.C));
Add("gentoo_emerge_world", All, false, "stack: deal {amount:0} to all living enemies. gain {shield:1} Shield.", Damage(3, Language.Haskell, all: true), Shield(2));
Add("lang_hs_map", Single, false, "stack: deal {amount:0}.", Damage(2, Language.Haskell));
@@ -250,10 +250,10 @@ namespace KernelPanic.Combat
Add("arch_aur_helper", None, false, "add a random C/Rust common card to hand; it costs 0 this turn.", Fx(CardEffectKind.RandomCommonLanguageCard));
Add("arch_minimal_install", None, false, "exhaust up to {raw:0} hand cards. per card: gain {rawSecondary:0} Shield and {rawMax:0} Cycle.",
Fx(CardEffectKind.MinimalInstall, MinimalInstallEffect.MaxExhaust, MinimalInstallEffect.CyclesPerCard, MinimalInstallEffect.ShieldPerCard));
Add("shop_c_free", Single, true, "deal {amount:0}. overkill spills. 25%: segfault, uptime -3, corrupt a hand card, and draw 2. then repair up to {amount:1} corrupted card{plural:1} in your active deck.",
Add("shop_c_free", Single, true, "deal {amount:0}. 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3, corrupt a hand card, and draw 2. then repair up to {amount:1} corrupted card{plural:1} in your active deck.",
Damage(18, Language.C), Fx(CardEffectKind.RepairCorruptedCards, 1));
Add("shop_c_sizeof", Single, true, "deal {raw:0} x C cards in hand." + CRecoil, Fx(CardEffectKind.SizeofDamage, SizeofDamageEffect.DamagePerCard, language: Language.C));
Add("shop_c_kernel_exploit", Single, true, "deal {amount:0} ignoring Shield. overkill spills. 50%: segfault, uptime -8 and corrupt a hand card.", Damage(36, Language.C, trueDamage: true));
Add("shop_c_kernel_exploit", Single, true, "deal {amount:0} ignoring Shield. 50% of overkill spills per jump (rounded down). 50%: segfault, uptime -8 and corrupt a hand card.", Damage(36, Language.C, trueDamage: true));
Add("shop_c_gdb", None, false, "repair up to {amount:0} corrupted cards in your active deck. draw {amount:1}.",
Fx(CardEffectKind.RepairCorruptedCards, 2), Draw(1));
Add("shop_c_valgrind", None, false, "repair up to {amount:0} corrupted cards in your active deck. gain {shield:1} Shield.",
@@ -56,6 +56,7 @@ namespace KernelPanic.Combat
int remaining, Language language, bool trueDamage)
{
bool dealtDamage = false;
bool attenuate = language == Language.C || context.Card?.Definition?.Language == Language.C;
// Keep the original target excluded even if a lethal-hit save left it alive.
CombatantState originalTarget = firstTarget;
for (int i = 0; i < context.Enemies.Count && remaining > 0; i++)
@@ -64,6 +65,10 @@ namespace KernelPanic.Combat
if (target == null || target == originalTarget || target == firstTarget || target.IsDefeated)
continue;
// C loses half its excess on every actual jump, after the previous target's defenses.
// Integer division rounds down; one excess damage cannot create another hit.
if (attenuate) remaining = (int)((long)remaining * CombatTuning.COverkillSpillPercent / 100);
if (remaining == 0) break;
int capacity = GetDamageCapacity(target, trueDamage);
GameEvents.RaiseOverflowDamageTravel(new OverflowDamageTravelEvent(context.Source, firstTarget, target, remaining, language));
DamageResult result = CardDamageExecutor.ApplyHit(context,
+3 -1
View File
@@ -271,7 +271,9 @@ 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 50%, other languages 25%; each hit rolls independently.");
if (critical) notes.Add($"Critical chance: C {CombatTuning.CCriticalChancePercent}%, other languages 25%; each hit rolls independently.");
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
? "Rust overkill can grant Shield; max-roll mode prevents unsigned overflow."
: "Rare Rust unsigned overflow is not included in the normal range. Overkill can grant additional Shield.");
+35 -6
View File
@@ -46,6 +46,23 @@ namespace KernelPanic.Combat
private int _fedoraCardsDiscountedThisTurn;
private float _fedoraCrashChance = CombatTuning.FedoraBleedingEdgeBaseCrashChance;
private int _cardsPlayedThisTurn;
private bool _prefetchUsed;
public const int PrefetchCost = 2;
public bool CanPrefetch => CanSurrenderRun && _runConfig?.IsTutorial != true && !_prefetchUsed
&& _playerState.Cycles >= PrefetchCost && _handController != null
&& _handController.RemainingRam >= 2 && _deckController.AvailableToDrawCount > 0;
public bool TryPrefetch()
{
// Reserve two RAM so every possible top card fits, without revealing its identity or
// consuming a shuffle on a rejected action. Java occupies two RAM; other cards use one.
if (!CanPrefetch || !_deckController.TryDrawToHand(_handController, out _)) return false;
_prefetchUsed = true;
_playerState.Cycles -= PrefetchCost;
Log("prefetch: spent 2 Cycles, drew 1 card (once per turn)");
StateChanged?.Invoke();
return true;
}
private int _cardsPlayedThisWave;
private int _cCardsPlayedThisTurn;
private int _turnNumberThisWave;
@@ -280,7 +297,7 @@ namespace KernelPanic.Combat
{
if (_runConfig?.IsTutorial == true) return;
if (!_awaitingWaveContinue || RunFinished || _waveTransitionActive
|| _runManager?.IsSuspended == true || _runManager?.CampaignChoicePending == true)
|| _runManager?.IsSuspended == true || _runManager?.CampaignChoicePending == true || _runManager?.BuildRewardPending == true)
{
return;
}
@@ -308,8 +325,11 @@ namespace KernelPanic.Combat
public bool ContinueTutorialWave()
{
if (_runConfig?.IsTutorial != true || !_awaitingWaveContinue || RunFinished || _waveTransitionActive
|| _runManager.WavesCleared != 1 || !_runManager.RepositoryOffers.Any(offer => offer.Sold)) return false;
_runConfig.TutorialLesson = 2;
|| _runManager.WavesCleared < 1 || _runManager.WavesCleared >= TutorialCampaign.LessonCount
|| (_runManager.WavesCleared == 1 && !_runManager.RepositoryOffers.Any(offer => offer.Sold))) return false;
_runConfig.TutorialLesson = _runManager.WavesCleared + 1;
// The countdown lesson requires two enemy turns. A low-health checkpoint must remain playable.
if (_runConfig.TutorialLesson == 3) _playerState.CurrentUptime = _playerState.MaxUptime;
_waveTransitionActive = true;
_runManager.PrepareNextEncounter(_playerState);
_awaitingWaveContinue = false;
@@ -1232,6 +1252,7 @@ namespace KernelPanic.Combat
RevivePendingEnemies();
UnlockHandCards("license check expired");
_playerState.Cycles = _playerState.MaxCycles;
_prefetchUsed = false;
_fedoraCardsDiscountedThisTurn = 0;
_cardsPlayedThisTurn = 0;
_cCardsPlayedThisTurn = 0;
@@ -1384,7 +1405,8 @@ namespace KernelPanic.Combat
continue;
}
Log($"{enemy.Name} executes {enemy.DisplayIntent.DisplayText}");
// The action is public once execution starts, even if it was not probed beforehand.
Log($"{enemy.Name} executes {enemy.CurrentIntent.DisplayText}");
GameEvents.RaiseEnemyWouldAct(new EnemyWouldActEvent(enemy));
StateChanged?.Invoke();
yield return Wait(CombatTuning.EnemyTelegraphDelaySeconds);
@@ -2073,6 +2095,7 @@ namespace KernelPanic.Combat
}
enemy.ReviveAtHalfUptime();
GameEvents.RaiseEnemyRevived(enemy);
Log($"{enemy.Name} revived at {enemy.CurrentUptime} uptime");
}
}
@@ -2728,14 +2751,20 @@ namespace KernelPanic.Combat
if (_runConfig?.IsTutorial == true || _runManager?.Journey.campaign == true)
{
CurrentEncounter = _runConfig.IsTutorial ? TutorialCampaign.Plan(_runConfig.TutorialLesson)
: EncounterDirector.Plan(CurrentWaveNumber, _runManager.Journey.activeRoute);
: EncounterDirector.Plan(CurrentWaveNumber, _runManager.Journey.activeRoute,
_runConfig.RunSeed, _runManager.Journey.encounterRevision);
for (int slot = 0; slot < CurrentEncounter.Enemies.Count; slot++)
{
string id = CurrentEncounter.Enemies[slot];
if (id == "race_condition" && slot + 1 < CurrentEncounter.Enemies.Count
&& CurrentEncounter.Enemies[slot + 1] == id)
{ SpawnRacePair(CurrentEncounter.UptimeBonus); slot++; }
else SpawnEnemy(id, CurrentEncounter.UptimeBonus);
else
{
bool escort = slot == CurrentEncounter.Enemies.Count - 1 && id == "daemon";
var enemy = SpawnEnemy(id, CurrentEncounter.UptimeBonus + (escort ? CurrentEncounter.EscortUptime : 0));
if (escort) enemy.State.Shield += CurrentEncounter.EscortShield;
}
}
Log(CurrentEncounter.Title + ": " + CurrentEncounter.Advice);
return;
+2
View File
@@ -10,6 +10,8 @@ namespace KernelPanic.Combat
public const int DrawPerTurn = 1;
public const int MinimumHandFloor = 0;
public const int SegfaultCorruptionRecoveryRounds = 3;
public const int CCriticalChancePercent = 35;
public const int COverkillSpillPercent = 50;
public const int OrphanSpawnChancePercent = 25;
public const int BaseEnemyUptimeMin = 5;
+1 -1
View File
@@ -239,7 +239,7 @@ namespace KernelPanic.Combat
return amount;
}
int critChance = request.Language == Language.C ? 50 : 25;
int critChance = request.Language == Language.C ? CombatTuning.CCriticalChancePercent : 25;
wasCritical = RandomRoll.RollRange(1, 100, new RollContext(request.Source)) <= critChance;
return wasCritical ? ScaleCritical(amount) : amount;
}
@@ -10,6 +10,8 @@ namespace KernelPanic.Combat
public string Advice { get; }
public IReadOnlyList<string> Enemies { get; }
public int UptimeBonus { get; }
public int EscortShield { get; internal set; }
public int EscortUptime { get; internal set; }
public EncounterPlan(string title, string advice, int uptimeBonus, params string[] enemies)
{ Title = title; Advice = advice; UptimeBonus = uptimeBonus; Enemies = Array.AsReadOnly(enemies); }
}
@@ -17,6 +19,64 @@ namespace KernelPanic.Combat
/// <summary>Authored encounter composition. Reads no random state; spawning owns stat rolls.</summary>
public static class EncounterDirector
{
// 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 == 0) return Plan(wave, route);
uint hash = unchecked((uint)seed ^ ((uint)wave * 0x9E3779B9u));
hash ^= hash >> 16; hash = unchecked(hash * 0x7FEB352Du); hash ^= hash >> 15;
int variant = (int)(hash % 3);
var baseline = Plan(wave, WaveRoute.Repair);
string title = baseline.Title, advice = baseline.Advice;
string[] enemies = new List<string>(baseline.Enemies).ToArray();
if (variant > 0)
{
switch (wave)
{
case 1:
title = variant == 1 ? "Stale services" : "Scheduled startup";
enemies = variant == 1 ? new[] { "zombie_process", "zombie_process" } : new[] { "zombie_process", "cron_job" };
advice = variant == 1 ? "Both Zombies can revive once. Finish weakened zombies decisively."
: "The Zombie can revive once. Cron Job announces its heavy attack with a countdown.";
break;
case 2:
title = variant == 1 ? "Leaking firewall" : "Orphan cleanup";
enemies = variant == 1 ? new[] { "firewalld", "memory_leak" } : new[] { "zombie_process", "segfault" };
advice = variant == 1 ? "Memory Leak grows each round while firewalld shields its neighbour."
: "The Zombie can revive once. Segfault has a death payload; plan for the process it leaves behind.";
break;
case 3:
title = variant == 1 ? "Hidden dependencies" : "Scheduled replication";
enemies = variant == 1 ? new[] { "rootkit", "zombie_process", "memory_leak" } : new[] { "fork_bomb", "cron_job", "zombie_process" };
advice = variant == 1 ? "Rootkit resists damage while allies remain. Clear its support while containing the growing Memory Leak."
: "Fork Bomb copies itself after acting. Cron Job counts down to a heavy attack; stop their growth early.";
break;
case 4:
title = variant == 1 ? "Protected concurrency" : "Leaking concurrency";
enemies = new[] { "race_condition", "race_condition", variant == 1 ? "firewalld" : "memory_leak" };
advice = "Race partners act in uncertain order; defeating one enrages the survivor. Choose between support and paired threats.";
break;
case RunJourney.BossWave:
title = variant == 1 ? "Kernel Overseer / scheduled interrupt" : "Kernel Overseer / memory pressure";
enemies = new[] { "kernel_overseer", variant == 1 ? "cron_job" : "memory_leak" };
advice = baseline.Advice;
break;
}
}
var plan = new EncounterPlan(title, advice, baseline.UptimeBonus, enemies);
if (wave > 1 && route == WaveRoute.Challenge)
{
int modifier = (int)((hash >> 8) % 3);
var escort = new List<string>(enemies) { "daemon" };
string detail = modifier == 0 ? "Veiled escort: damage the extra Daemon to reveal its intent."
: modifier == 1 ? "Armored escort: the extra Daemon starts with 6 Shield; damage reveals its intent."
: "Hardened escort: the extra Daemon has +4 Uptime; damage reveals its intent.";
plan = new EncounterPlan(title + " / challenge", advice + " " + detail, baseline.UptimeBonus, escort.ToArray())
{ EscortShield = modifier == 1 ? 6 : 0, EscortUptime = modifier == 2 ? 4 : 0 };
}
return plan;
}
public static EncounterPlan Plan(int wave, WaveRoute route)
{
string title, advice;
+3 -1
View File
@@ -122,7 +122,9 @@ namespace KernelPanic.Combat
EnemyBehaviorFlags.ObfuscateIntent | EnemyBehaviorFlags.Elite,
new[]
{
new EnemyIntent(EnemyIntentKind.Attack, 6, 8, Language.C, "daemon hit", "!")
new EnemyIntent(EnemyIntentKind.Attack, 8, 10, Language.C, "surge", "!"),
new EnemyIntent(EnemyIntentKind.Defend, 6, 8, Language.C, "harden", "#"),
new EnemyIntent(EnemyIntentKind.Attack, 3, 4, Language.C, "bypass Shield", "!", true)
},
EnemyTier.Elite);
+2
View File
@@ -64,6 +64,8 @@ namespace KernelPanic.Combat
public void PickNextIntent()
{
// Exposure belongs to the selected action, not the enemy's entire lifetime.
if (HasBehavior(EnemyBehaviorFlags.ObfuscateIntent)) IntentRevealed = false;
if (HasBehavior(EnemyBehaviorFlags.BossCycle) && _intentPool.Count > 0)
{
CurrentIntent = _intentPool[TurnsAlive % _intentPool.Count];
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d51c41fa71b1068438855f64f946cc57
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+2
View File
@@ -20,6 +20,8 @@ namespace KernelPanic.Core
public static event Action<DeathSpawnedEnemyEvent> DeathSpawnedEnemy;
public static event Action<EnemyWouldActEvent> EnemyWouldAct;
public static event Action<EnemyActedEvent> EnemyActed;
public static event Action<EnemyInstance> EnemyRevived;
public static void RaiseEnemyRevived(EnemyInstance enemy) => EnemyRevived?.Invoke(enemy);
public static event Action<PlayerDamagedEvent> PlayerDamaged;
public static event Action<EncounterWonEvent> EncounterWon;
public static event Action<EncounterLostEvent> EncounterLost;
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: cf446c6fd7627294c9e2aa23c9b576e7
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c06078e18f184c84cab3579c0e562dbe
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 542a3f97e8074ed428fd7019177f221b
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 3b76dcac6b8cae447bb9079460692238
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 0d860bbf8e7f4df2a91e2e1e9892d904
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: cbdd46dffec613346ae6191f18a94225
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: e1974726f936d0640943801549b4574e
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e0a39b97df9ee0641b2bbadf5bca417c
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: fd9e459379f339742a14cf224cd91234
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5178747fac4dbfc448ff15d8a687e03c
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: fdb3d58d94b76834598e408448e19d2a
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5af93d291e7d4d51b312bdf1e47dc6ef
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: bd550368fd0c75d43a53aa4fb3b6541e
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b821fa56a5034b9bbd3a000000000203
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8b5b43b43c697c142b33fbfc5160cf90
+2 -1
View File
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using KernelPanic.Core;
using KernelPanic.Combat;
namespace KernelPanic.Data
{
@@ -11,7 +12,7 @@ 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 50% crit chance instead of the normal 25%, spills overkill into other enemies, 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.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.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", "queued scripts", ResolutionTrack.InterpreterQueue, "Python cards enter the interpreter queue instead of resolving immediately. They are slower, but let you stage delayed damage, draw, and repeat effects around the exchange structure.", null, Distro("ubuntu", "Ubuntu"), Distro("kali", "Kali"), Distro("mint", "Mint")),
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 02afff40950e5434192bd919f60a9d22
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a7d10000000000000000000000000002
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a7d10000000000000000000000000001
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 04c3b1510a7d45f3aba1ee24fe0cbc12
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 48447d3db18343398488d3064324147d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9b1f51fb7c354203a2f93ad22fbeb101
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1470a223647d6514f9439de7ded702c9
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 6aad857173769044f861a0c6b1318032
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ae19044bbccbb074da1d5e38b61e5657
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: e003476e8a28025938acf6c377dfbaaa
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 23fc80fee1a14d84d8bfcddf73a00c50
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8b77d0de67282ca4181a7c53feec4343
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 29d7890153d140b2a25b1afb304581f9
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7262840a6d0b4569a70ca757cf4b5d19
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c4c45a4a6b604a7bbba20b0d44ed4b9f
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 6ef2e97a60574b3896db93fd09ec5313
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f62e697e985a8a44ca26ccb8e853ee66
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 57c4aa4526fdaf146a7d4896c27623df
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 542dd3144a914ea5b1e0c0e21db5ec6b
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 28f47ae605f8c30469a300c32bdd4473
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4d8cfb0a91cc485089a35c086d20e11b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 42462c6d90ce487e96d40c26a64dcc8a
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f859567fb24c4ef9a94a3306e955b5f8
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 41b78f2319834ad680d8e32e29c2712c
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4a10ff65b6e9478d9fe638f8a39f8144
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: aebad46fbebf4dc4683d0a46c7f1f5b6
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7be246fb732b4955a259ae231c191178
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 58538a64d0259c30d01a7f083b304a51
+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 = 5;
public const int CurrentSchemaVersion = 8;
private static readonly object FileLock = new();
public string SavePath { get; }
@@ -280,6 +280,7 @@ namespace KernelPanic.Meta
public int rootCredits = GachaService.TestRootCreditsBalance;
public int commitsBalance;
public int bandwidthBalance;
public DailyQuestState dailyQuests = new();
// Legacy conflated balance. Older builds used this for both Commits and Bandwidth.
// Migration preserves it as Bandwidth and starts Commits at 0 because the source is ambiguous.
public int standardPullCurrency;
@@ -321,6 +322,7 @@ namespace KernelPanic.Meta
public void EnsureLists()
{
dailyQuests ??= new DailyQuestState();
if (tutorialCheckpoint != null && string.IsNullOrEmpty(tutorialCheckpoint.runId)) tutorialCheckpoint = null;
// JsonUtility materializes null inline serializable objects as empty instances.
// Preserve malformed/nonempty checkpoints for an explicit recovery error, but
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 752a83f338afd024b8e728a1921e38ee
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 2404f1f357541144399db86d31ca2fa1
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 9ae21840b594d4147a8f5497c992b4fa
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+147 -10
View File
@@ -38,6 +38,18 @@ namespace KernelPanic.Run
}
// Install before the menu's OnEnable can schedule the animated boot sequence.
UIPreferences.ReducedMotion = true; // Session only; never writes preferences.
if (args.Contains("--kernel-panic-quest-ui-smoke"))
{
// The unused, isolated save-path guard above also applies to this UI fixture.
var fixture = SaveData.CreateDefault();
fixture.starterChosen = true;
fixture.ownedUnits.Add(new OwnedUnitSaveEntry { id = "ubuntu", version = 1 });
fixture.dailyQuests.refreshAtUtcTicks = DateTime.UtcNow.AddDays(1).Ticks;
DailyQuests.Record(fixture.dailyQuests, DailyQuestKind.Waves, 3, DateTime.UtcNow);
DailyQuests.Record(fixture.dailyQuests, DailyQuestKind.Cards, 12, DateTime.UtcNow);
DailyQuests.Record(fixture.dailyQuests, DailyQuestKind.Damage, 80, DateTime.UtcNow);
new SaveService().Save(fixture);
}
var owner = new GameObject("Player smoke verification");
Application.runInBackground = true;
DontDestroyOnLoad(owner);
@@ -95,6 +107,12 @@ namespace KernelPanic.Run
yield return new WaitForSecondsRealtime(2);
var menu = FindFirstObjectByType<MainMenuController>();
Require(menu != null, "Main menu scene did not initialize.");
if (Environment.GetCommandLineArgs().Contains("--kernel-panic-quest-ui-smoke"))
{
var questScenario = QuestUiScenario(menu);
while (questScenario.MoveNext()) yield return questScenario.Current;
yield break;
}
var starter = Field<StarterSelectionController>(menu, "starterSelection");
if (!starter.IsActive)
{
@@ -120,7 +138,7 @@ namespace KernelPanic.Run
while (training.MoveNext()) yield return training.Current;
if (Environment.GetCommandLineArgs().Contains("--kernel-panic-tutorial-smoke"))
{
_campaignSuccess = "PASS: two-wave guided tutorial, real targeting/revival/queue/stack, full clears, shop purchase, same-run resume, one-time 1000 Bandwidth + 1000 Entropy, clean normal-run workspace.";
_campaignSuccess = "PASS: three-wave guided tutorial, real targeting/revival/queue/stack/countdown/Daemon reveal, full clears, shop purchase, wave-two and wave-three resume, one-time 1000 Bandwidth + 1000 Entropy, clean normal-run workspace.";
yield break;
}
menu = FindFirstObjectByType<MainMenuController>();
@@ -184,8 +202,10 @@ namespace KernelPanic.Run
_stage = "repository";
var run = combat.GetComponent<RunManager>();
Require(run.WavesCleared == 1 && run.RepositoryVisitActive, "Wave completion did not open repository.");
Submit(view.GetComponent<UIDocument>().rootVisualElement.Q<Button>("BootNextWaveButton"));
Submit(view.GetComponent<UIDocument>().rootVisualElement.Q<Button>("RouteChallenge"));
Require(run.Journey.selectedRoute == WaveRoute.Challenge, "Elite route selection did not reach the run model.");
Submit(view.GetComponent<UIDocument>().rootVisualElement.Q<Button>("BackToRepositoryButton"));
var offer = run.RepositoryOffers.FirstOrDefault(item => item.Price <= run.Bits);
Require(offer != null, "No affordable repository offer.");
int bits = run.Bits;
@@ -265,6 +285,13 @@ namespace KernelPanic.Run
"Run archive command is not between Settings and Quit.");
capture = CapturePanel(menu.GetComponent<UIDocument>(), "home-menu");
while (capture.MoveNext()) yield return capture.Current;
Submit(menuRoot.Q<Button>("DailyQuestWidget"));
Require(menuRoot.Q("DailyQuestOverlay") != null, "Daily quest widget did not open its overlay.");
capture = CapturePanel(menu.GetComponent<UIDocument>(), "daily-quest-details");
while (capture.MoveNext()) yield return capture.Current;
Submit(menuRoot.Q<Button>("CloseDailyQuests"));
Require(menuRoot.Q("DailyQuestOverlay") == null && homePanel.enabledInHierarchy,
"Closing daily quests did not restore the main menu.");
OpenRunArchive(menuRoot);
yield return null;
RequireArchiveVisible(menuRoot);
@@ -397,7 +424,7 @@ namespace KernelPanic.Run
var capture = CapturePanel(document, "tutorial-intro");
while (capture.MoveNext()) yield return capture.Current;
int actions = 0;
bool resumed = false;
int resumedLesson = 1;
var capturedSteps = new System.Collections.Generic.HashSet<string>();
while (TutorialCampaign.Required(save.Load()))
{
@@ -407,12 +434,25 @@ namespace KernelPanic.Run
{
if (!combat.TutorialInputReady) { yield return null; continue; }
var step = flow.Guide.Step;
if (capturedSteps.Add(flow.Lesson + step.Id) && step.Id is "select-attack" or "target-zombie" or "pending-revival" or "revived" or "queued-haskell")
if (capturedSteps.Add(flow.Lesson + step.Id) && step.Id is "select-attack" or "target-zombie" or "pending-revival" or "revived" or "queued-haskell" or "daemon" or "revealed-daemon" or "cron-ticking" or "cron-armed" or "shield-cron")
{
capture = CapturePanel(document, "tutorial-" + step.Id);
while (capture.MoveNext()) yield return capture.Current;
}
var root = document.rootVisualElement;
if (flow.Lesson == 3)
{
var cron = combat.Enemies.Single(enemy => enemy.ArchetypeId == "cron_job");
var daemon = combat.Enemies.Single(enemy => enemy.ArchetypeId == "daemon");
if (step.Id == "daemon") Require(!daemon.IntentRevealed, "Daemon starts hidden.");
if (step.Id == "revealed-daemon") Require(daemon.IntentRevealed && !daemon.State.IsDefeated, "Damage must reveal the live miniboss.");
if (step.Id == "cron-ticking")
{
Require(cron.CountdownRemaining == 1, "Cron did not count down after an enemy turn.");
Require(!daemon.IntentRevealed && daemon.DisplayIntent.ValueText == "?", "Daemon did not hide its new action.");
}
if (step.Id == "cron-armed") Require(cron.CountdownRemaining == 0 && cron.CurrentIntent.Kind == EnemyIntentKind.Attack, "Cron did not ready its heavy attack.");
}
if (flow.Reading)
{
var before = combat.CurrentPhase; combat.EndPlayerTurn();
@@ -456,10 +496,10 @@ namespace KernelPanic.Run
var next = root.Q<Button>("TutorialContinue");
Require(next != null && next.enabledSelf, "Tutorial progression blocked.");
Submit(next);
if (!resumed && save.Load().tutorialCheckpoint != null)
if (save.Load().tutorialCheckpoint is { } checkpoint && checkpoint.wave > resumedLesson)
{
resumed = true;
Require(save.Load().tutorialCheckpoint.offers.Any(offer => offer.sold), "Shop purchase was not saved.");
resumedLesson = checkpoint.wave;
Require(checkpoint.deck.Any(card => card.magnitude > 0), "Shop purchase was not saved.");
SceneLoader.LoadMainMenu(document.rootVisualElement);
while (FindFirstObjectByType<MainMenuController>() == null) yield return null;
combat = null;
@@ -467,9 +507,10 @@ namespace KernelPanic.Run
{ yield return null; combat = FindFirstObjectByType<CombatManager>(); }
view = FindFirstObjectByType<CombatSceneController>();
document = view.GetComponent<UIDocument>(); flow = Field<TutorialFlow>(view, "_tutorial");
Require(flow.Lesson == 2 && flow.Reading && FindFirstObjectByType<RunManager>().RunId == runId,
"Restart did not resume the same run at wave two.");
Require(combat.PlayerState.CurrentUptime == uptime, "Resume reset remaining Uptime.");
Require(flow.Lesson == resumedLesson && flow.Reading && FindFirstObjectByType<RunManager>().RunId == runId,
"Restart did not resume the same run at wave " + resumedLesson);
Require(combat.PlayerState.CurrentUptime == (resumedLesson == 3 ? combat.PlayerState.MaxUptime : uptime),
"Resume did not preserve Uptime or apply the final practice repair.");
}
}
}
@@ -510,6 +551,16 @@ namespace KernelPanic.Run
&& !Field<FirstBattleGuide>(view, "_firstBattleGuide").Visible, "Normal run still has automatic instructional text.");
capture = CapturePanel(document, "normal-run-clean");
while (capture.MoveNext()) yield return capture.Current;
Submit(document.rootVisualElement.Q<Button>("ReplayBattleGuide"));
var quickGuide = Field<FirstBattleGuide>(view, "_firstBattleGuide");
Require(quickGuide.Visible, "Quick guide did not open.");
capture = CapturePanel(document, "quick-guide");
while (capture.MoveNext()) yield return capture.Current;
quickGuide.Element.Q<Foldout>().value = true;
capture = CapturePanel(document, "quick-guide-tracks");
while (capture.MoveNext()) yield return capture.Current;
// Keep smoke validation from changing the user's remembered guide preference.
quickGuide.Element.style.display = DisplayStyle.None;
Require(save.Load().bandwidthBalance == final.bandwidthBalance && save.Load().entropyBalance == final.entropyBalance,
"Scene change paid the tutorial reward again.");
}
@@ -525,6 +576,75 @@ namespace KernelPanic.Run
commandInput.SendEvent(enter);
}
private IEnumerator QuestUiScenario(MainMenuController menu)
{
_stage = "daily quest widget";
var document = menu.GetComponent<UIDocument>();
var root = document.rootVisualElement;
Call(menu, "CompleteBootIntro");
var capture = CapturePanel(document, "quest-home");
while (capture.MoveNext()) yield return capture.Current;
var widget = root.Q<Button>("DailyQuestWidget");
var homeScroll = root.Q<ScrollView>(className: "home-scroll");
if (Screen.width >= 1280)
Require(widget.worldBound.yMax <= homeScroll.contentViewport.worldBound.yMax + 1,
"Quest widget must fit below neofetch without scrolling at 1280x720.");
else
{
homeScroll.ScrollTo(widget);
capture = CapturePanel(document, "quest-widget");
while (capture.MoveNext()) yield return capture.Current;
}
Require(root.Q<Label>("DailyQuestCompleted").text == "1/3 completed", "Quest fixture progress is wrong.");
Require(root.Q<Label>("DailyQuestRewardReady").text == "1 reward ready"
&& root.Q<Label>("DailyQuestInspect").text == "> claim available rewards", "Claimable widget feedback is wrong.");
var widgetPosition = widget.worldBound.center;
using (var down = PointerDownEvent.GetPooled(new Event { type = EventType.MouseDown, button = 0, mousePosition = widgetPosition }))
{ down.target = widget; widget.SendEvent(down); }
using (var up = PointerUpEvent.GetPooled(new Event { type = EventType.MouseUp, button = 0, mousePosition = widgetPosition }))
{ up.target = widget; widget.SendEvent(up); }
Require(root.Q("DailyQuestOverlay") != null, "Mouse click did not open quest details.");
capture = CapturePanel(document, "quest-details");
while (capture.MoveNext()) yield return capture.Current;
Submit(root.Q<Button>("ClaimDailyQuestWaves"));
var saved = new SaveService().Load();
var reward = DailyQuests.Reward(DailyQuestKind.Waves);
Require(saved.bandwidthBalance == reward.Bandwidth && saved.entropyBalance == reward.Entropy
&& !root.Q<Button>("ClaimDailyQuestWaves").enabledSelf, "Quest claim did not commit exactly once.");
Require(root.Q<Button>("ClaimDailyQuestWaves").text == "[ CLAIMED ]"
&& root.Q<Label>("DailyQuestFeedback").text.Contains($"+{reward.Bandwidth} Bandwidth, +{reward.Entropy} Entropy deposited."),
"Successful claim feedback is missing.");
using (var repeatedSubmit = NavigationSubmitEvent.GetPooled())
{
var claimedButton = root.Q<Button>("ClaimDailyQuestWaves");
repeatedSubmit.target = claimedButton;
claimedButton.SendEvent(repeatedSubmit);
}
Require(new SaveService().Load().bandwidthBalance == reward.Bandwidth, "Repeated submit paid a duplicate reward.");
capture = CapturePanel(document, "quest-claimed");
while (capture.MoveNext()) yield return capture.Current;
Submit(root.Q<Button>("CloseDailyQuests"));
Require(root.Q("DailyQuestOverlay") == null && root.Q("ShellRoot").enabledSelf, "Quest overlay did not close.");
Require(root.Q("DailyQuestRewardReady").style.display.value == DisplayStyle.None, "Widget did not update after claim.");
widget = root.Q<Button>("DailyQuestWidget");
Require(root.focusController.focusedElement != widget, "Mouse dismissal left a sticky widget focus highlight.");
using (var move = PointerMoveEvent.GetPooled(new Event { type = EventType.MouseMove, mousePosition = new Vector2(4, 4) }))
{ move.target = root; root.SendEvent(move); }
capture = CapturePanel(document, "quest-dismissed");
while (capture.MoveNext()) yield return capture.Current;
widget.Focus();
Submit(widget);
using (var escape = KeyDownEvent.GetPooled('\0', KeyCode.Escape, EventModifiers.None))
{
var close = root.Q<Button>("CloseDailyQuests");
escape.target = close;
close.SendEvent(escape);
}
Require(root.Q("DailyQuestOverlay") == null && root.focusController.focusedElement == widget,
"Keyboard dismissal must restore widget focus.");
_campaignSuccess = "PASS: daily quest widget, mouse/keyboard focus restoration, overlay, individual reward claim, immediate widget update, close.";
}
private IEnumerator CampaignScenario(CombatManager combat, CombatSceneController view)
{
var run = combat.GetComponent<RunManager>();
@@ -537,14 +657,30 @@ namespace KernelPanic.Run
_stage = "campaign wave " + run.CurrentWaveNumber;
if (combat.AwaitingWaveContinue)
{
Require(document.rootVisualElement.Q("RunRouteChoices") == null, "Shop must not contain route choices.");
Submit(document.rootVisualElement.Q<Button>("BootNextWaveButton"));
Require(combat.AwaitingWaveContinue && document.rootVisualElement.Q("RouteSelectionScreen") != null,
"Boot must open route selection before starting combat.");
if (run.BuildRewardPending)
{
var rewardCapture = CapturePanel(document, "build-reward-" + run.WavesCleared);
while (rewardCapture.MoveNext()) yield return rewardCapture.Current;
int bitsBefore = run.Bits;
Submit(document.rootVisualElement.Q<Button>("RewardBits"));
Require(!run.BuildRewardPending && run.Bits == bitsBefore + RunManager.BuildRewardBits,
"Build reward button must pay once and permit departure.");
Require(!run.ClaimBuildReward(null, CardUpgradeKind.MagnitudeUp, true), "Build reward cannot pay twice.");
}
Submit(document.rootVisualElement.Q<Button>("BackToRepositoryButton"));
foreach (var offer in run.RepositoryOffers.Where(offer => !offer.Sold)
.OrderByDescending(offer => offer.Kind == RepositoryOfferKind.StatUpgrade && offer.StatUpgradeKind == RunStatUpgradeKind.Heal
&& combat.PlayerState.CurrentUptime < combat.PlayerState.MaxUptime / 2 ? 100
: offer.Kind == RepositoryOfferKind.CardUpgrade && offer.CardUpgradeKind == CardUpgradeKind.DrawRider ? 90
: offer.Kind == RepositoryOfferKind.CardUpgrade ? 80 : 10).ToArray())
if (offer.Price <= run.Bits) run.BuyOffer(offer, combat.PlayerState);
Submit(document.rootVisualElement.Q<Button>("BootNextWaveButton"));
Submit(document.rootVisualElement.Q<Button>("RouteRepair"));
combat.ContinueToNextWave();
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
}
else if (combat.CanSurrenderRun)
{
@@ -582,6 +718,7 @@ namespace KernelPanic.Run
}
Require(!combat.RunLost && run.WavesCleared == 5 && capturedBoss, "Seeded campaign bot did not clear the boss.");
_stage = "campaign milestone";
Submit(document.rootVisualElement.Q<Button>("BootNextWaveButton"));
var milestone = CapturePanel(document, "campaign-milestone");
while (milestone.MoveNext()) yield return milestone.Current;
int expectedBandwidth = run.AccruedBandwidth + TutorialCampaign.BandwidthReward;
+1 -1
View File
@@ -43,7 +43,7 @@ namespace KernelPanic.Run
public ResolvedRunCheckpoint Resolve(DistroDatabase distros, CardDatabase cards,
LanguageDeckDatabase languages, PackageDatabase packageDatabase)
{
Require(version == 1 || version == 2, "This checkpoint needs a different game version.");
Require(version >= 1 && version <= 3, "This checkpoint needs a different game version.");
Require(version < 2 || journey != null, "Missing saved route decisions.");
journey?.Validate(wave);
Require(Guid.TryParseExact(runId, "N", out _), "Invalid run identity.");
+10 -1
View File
@@ -16,13 +16,22 @@ namespace KernelPanic.Run
public WaveRoute selectedRoute;
public WaveRoute activeRoute;
public string lastReward;
public int encounterRevision;
public int pendingRewardWave;
public int claimedRewardWave;
public bool AtMilestone(int wavesCleared) => campaign && !endless && wavesCleared >= BossWave;
public static RunJourney NewCampaign() => new() { campaign = true };
public static RunJourney NewCampaign() => new() { campaign = true, encounterRevision = 1 };
public RunJourney Copy() => (RunJourney)MemberwiseClone();
public void Validate(int wave)
{
RunCheckpoint.Require(encounterRevision >= 0 && encounterRevision <= 1, "Unsupported encounter revision.");
RunCheckpoint.Require((pendingRewardWave == 0 || pendingRewardWave == 2 || pendingRewardWave == 4)
&& (claimedRewardWave == 0 || claimedRewardWave == 2 || claimedRewardWave == 4)
&& claimedRewardWave < wave
&& (pendingRewardWave == 0 || (campaign && encounterRevision == 1
&& pendingRewardWave == wave - 1 && pendingRewardWave > claimedRewardWave)), "Invalid saved reward choice.");
RunCheckpoint.Require(Enum.IsDefined(typeof(WaveRoute), selectedRoute)
&& Enum.IsDefined(typeof(WaveRoute), activeRoute), "Invalid saved route.");
RunCheckpoint.Require(!endless || (campaign && wave > BossWave), "Invalid endless-mode checkpoint.");
+24 -2
View File
@@ -57,6 +57,26 @@ namespace KernelPanic.Run
public bool IsSuspended { get; private set; }
public RunJourney Journey { get; private set; } = new();
public bool CampaignChoicePending => Journey.AtMilestone(_wavesCleared);
public bool BuildRewardPending => Journey.pendingRewardWave > 0;
public const int BuildRewardBits = 8;
public bool ClaimBuildReward(CardInstance card, CardUpgradeKind kind, bool takeBits = false)
{
if (!isRunActive || IsSuspended || !_repositoryVisitActive || !BuildRewardPending) return false;
if (!takeBits && (card?.Definition == null || !_runDeck.Contains(card)
|| card.Definition.IsToken || card.Definition.IsJunk
|| (kind != CardUpgradeKind.MagnitudeUp && kind != CardUpgradeKind.DrawRider)
|| (kind == CardUpgradeKind.DrawRider && card.DrawRider > 0))) return false;
if (!takeBits && !ApplyCardUpgrade(card, kind)) return false;
if (takeBits) _bits += BuildRewardBits;
Journey.claimedRewardWave = Journey.pendingRewardWave;
Journey.pendingRewardWave = 0;
Journey.lastReward = takeBits ? $"Build reward: +{BuildRewardBits} Bits."
: $"Build reward: {card.Definition.DisplayName} gained " +
(kind == CardUpgradeKind.DrawRider ? "+1 draw on resolution." : $"+{CombatTuning.UpgradeMagnitudeBonus} effect magnitude.");
RepositoryChanged?.Invoke();
return true;
}
public bool SelectRoute(WaveRoute route)
{
@@ -78,7 +98,7 @@ namespace KernelPanic.Run
// Called exactly once by the guarded combat transition, never by UI callbacks.
public void PrepareNextEncounter(CombatantState player)
{
if (!_repositoryVisitActive || !isRunActive || IsSuspended || CampaignChoicePending) return;
if (!_repositoryVisitActive || !isRunActive || IsSuspended || CampaignChoicePending || BuildRewardPending) return;
Journey.activeRoute = Journey.selectedRoute;
if (Journey.campaign && Journey.activeRoute == WaveRoute.Repair && player != null)
player.CurrentUptime = Mathf.Min(player.MaxUptime, player.CurrentUptime + RunJourney.RepairUptime);
@@ -150,7 +170,7 @@ namespace KernelPanic.Run
bandwidth = _accruedBandwidth, entropy = _accruedEntropy,
maxUptimeBonus = _maxUptimeBonus, maxCyclesBonus = _maxCyclesBonus, ramBonus = _ramBonus,
rerolls = _rerollsThisVisit, shopRandomDraws = _repositoryRandom.Draws,
version = 2, journey = Journey.Copy(),
version = 3, journey = Journey.Copy(),
combat = combat.CaptureBoundaryState()
};
foreach (PackageInstance package in CurrentConfig.EquippedPackages)
@@ -387,6 +407,8 @@ namespace KernelPanic.Run
}
}
Journey.selectedRoute = WaveRoute.Repair;
if (Journey.campaign && Journey.encounterRevision > 0 && (clearedWave == 2 || clearedWave == 4))
Journey.pendingRewardWave = clearedWave;
_wavesCleared = Mathf.Max(_wavesCleared, clearedWave);
if (CurrentConfig?.IsTutorial != true)
{
+6 -5
View File
@@ -8,11 +8,11 @@ namespace KernelPanic.Run
{
public static class TutorialCampaign
{
public const int LessonCount = 2;
public const int LessonCount = 3;
public const int BandwidthReward = 1000;
public const int EntropyReward = GachaService.StandardTenPullCost * GachaService.EntropyPerCommit;
public static bool Required(SaveData save) => save != null && save.starterChosen && save.tutorialRequired;
public static int Lesson(SaveData save) => save?.tutorialCheckpoint != null ? 2 : 1;
public static int Lesson(SaveData save) => save?.tutorialCheckpoint?.wave ?? 1;
public static void Enroll(SaveData save, string distroId)
{
@@ -23,8 +23,8 @@ namespace KernelPanic.Run
// Commit balances and the claimed flag together. Re-enrollment never grants a second payout.
public static void Complete(SaveData save)
{
if (!Required(save) || save.tutorialLesson != 2)
throw new InvalidOperationException("Complete both training waves before claiming the reward.");
if (!Required(save) || save.tutorialLesson != LessonCount)
throw new InvalidOperationException("Complete all three training waves before claiming the reward.");
if (!save.tutorialRewardClaimed)
{
save.bandwidthBalance = checked(Math.Max(0, save.bandwidthBalance) + BandwidthReward);
@@ -37,7 +37,8 @@ namespace KernelPanic.Run
public static EncounterPlan Plan(int wave) => wave switch
{
1 => new("Targeting and revival", "", 0, "zombie_process", "orphan_process"),
2 => new("Queue, stack and finish", "", 0, "memory_leak", "firewalld"),
2 => new("Queue and stack", "", 0, "memory_leak", "firewalld"),
3 => new("Countdown and miniboss", "", 0, "cron_job", "daemon"),
_ => throw new ArgumentOutOfRangeException(nameof(wave))
};
+50 -32
View File
@@ -30,7 +30,7 @@ namespace KernelPanic.Run
public CardInstance Card { get; private set; }
public EnemyInstance Enemy { get; private set; }
public bool CanEndTurn => !Active || Step.Action == TutorialAction.EndTurn;
private ResolutionTrack ExpectedTrack => _lesson == 1 ? ResolutionTrack.Native
private ResolutionTrack ExpectedTrack => _lesson != 2 ? ResolutionTrack.Native
: Step?.Id.Contains("haskell") == true ? ResolutionTrack.LazyStack : ResolutionTrack.InterpreterQueue;
public TutorialGuide(int lesson) { _lesson = lesson; _steps = Build(lesson); }
@@ -68,6 +68,8 @@ namespace KernelPanic.Run
if (Step.Id == "target-zombie" && Enemy?.PendingRevive == true) Advance(combat);
else if (Step.Id == "finish-zombie" && Enemy?.HasRevived == true && Enemy.State.IsDefeated) Advance(combat);
}
else if (_lesson == 3)
{ if (_resolved && Enemy?.IntentRevealed == true) Advance(combat); }
else if (_played && (Queued(combat) || _resolved)) Advance(combat);
break;
case TutorialAction.PlayShield:
@@ -101,10 +103,12 @@ namespace KernelPanic.Run
{
if (!Active) return;
if (Enemy == null)
Enemy = combat.Enemies.FirstOrDefault(enemy => _lesson != 1 || enemy.ArchetypeId == "zombie_process");
Enemy = combat.Enemies.FirstOrDefault(enemy => _lesson == 1 ? enemy.ArchetypeId == "zombie_process"
: _lesson == 3 ? enemy.ArchetypeId == "daemon" : true);
if (Card != null || combat.HandController == null) return;
string id = _lesson == 1 ? Step.Id is "shield-card" or "shield-result" ? "lang_rs_borrow"
: Index >= 13 ? "lang_rs_fn_main" : "lang_rs_unwrap" : null;
: Index >= 13 ? "lang_rs_fn_main" : "lang_rs_unwrap"
: _lesson == 3 ? Step.Action == TutorialAction.PlayShield ? "lang_rs_borrow" : "lang_rs_fn_main" : null;
Card = combat.HandController.Cards.FirstOrDefault(card => !card.IsBroken && !card.IsLocked
&& (id != null ? card.Definition.Id == id : card.Definition.ResolutionTrack == ExpectedTrack)
&& combat.GetDisplayedPlayCost(card) <= combat.PlayerState.Cycles);
@@ -112,39 +116,53 @@ namespace KernelPanic.Run
public static IReadOnlyList<TutorialStep> Build(int lesson)
{
if (lesson == 3) return new[] {
new TutorialStep("cron", "Cron Job / scheduled damage", "Countdown 2 means two enemy turns before its heavy attack is ready. Use that time to prepare.", "enemy:cron_job"),
new TutorialStep("daemon", "Miniboss / Daemon", "Surge: 8-10 damage. Harden: 6-8 Shield. Bypass: 3-4 through Shield. Hit it to reveal which action is coming.", "enemy:daemon"),
new TutorialStep("select-reveal", "Expose the miniboss", "Select fn main(). This Native attack deals damage immediately.", "card", TutorialAction.SelectCard),
new TutorialStep("target-daemon", "Hit the Daemon", "Click the Daemon to reveal what it plans to do.", "enemy", TutorialAction.TargetEnemy),
new TutorialStep("revealed-daemon", "Exposed for this round", "Shield stops Surge, not Bypass. Harden deals no damage. Its next action will be hidden again; hit it each round to reveal.", "enemy:daemon"),
new TutorialStep("countdown-turn", "Watch the timer", "End turn. Daemon carries out its revealed action; Cron Job counts down.", "TutorialEndTurn", TutorialAction.EndTurn),
new TutorialStep("cron-ticking", "One turn left", "Cron Job shows countdown 1. Daemon has hidden its new action again.", "enemy:cron_job"),
new TutorialStep("countdown-ready", "Let the timer expire", "End turn once more. Watch Cron Job's countdown become an attack intent.", "TutorialEndTurn", TutorialAction.EndTurn),
new TutorialStep("cron-armed", "Heavy attack ready", "Cron Job will hit on the next End turn. Defeat it first, or prepare Shield for the displayed damage.", "enemy:cron_job"),
new TutorialStep("shield-cron", "Prepare a defense", "Play borrow() to help absorb Cron Job's hit. Remember: Daemon's Bypass ignores Shield.", "card", TutorialAction.PlayShield),
new TutorialStep("practice", "Clear the final wave", "Finish both enemies. Cron Job resets to countdown 2 after attacking. Clear this wave to claim your training rewards.", "enemies")
};
if (lesson < 1 || lesson > TutorialCampaign.LessonCount) throw new ArgumentOutOfRangeException(nameof(lesson));
if (lesson == 1) return new[] {
new TutorialStep("uptime", "This is your Uptime", "Uptime is your health. At 0, a normal run ends. This practice uses loan cards, full health and no distro passive procs; your collection is safe.", "TutorialUptime"),
new TutorialStep("shield", "Shield protects Uptime", "Shield absorbs ordinary incoming damage first. This number shows how much protection you currently have.", "TutorialShield"),
new TutorialStep("cycles", "Cycles pay for cards", "This is your remaining card budget. The cost in a card's upper-right corner is paid when you play it. Cycles refresh each round.", "TutorialCycles"),
new TutorialStep("ram", "RAM is hand capacity", "This shows used RAM / capacity. Most cards use 1 RAM; Java uses 2. More Cycles do not let extra cards fit in a full hand.", "TutorialRam"),
new TutorialStep("attack-card", "Read your attack card", "unwrap() costs Cycles and deals damage immediately: it is Native. Its rules and current estimate are printed here. Rust overkill can also grant Shield.", "card"),
new TutorialStep("intent", "Read the enemy's intent", "This is what Zombie Process plans to do when enemies act. Check the attack range before ending your turn.", "zombie-intent"),
new TutorialStep("select-attack", "1 / Select the attack", "Click the highlighted unwrap() card first. Selecting a targeted card asks for an enemy; it does not spend Cycles yet.", "card", TutorialAction.SelectCard),
new TutorialStep("target-zombie", "2 / Choose the zombie", "Now click Zombie Process to dispatch your selected card. Other targets and End turn are locked for this demonstration.", "zombie", TutorialAction.TargetEnemy),
new TutorialStep("pending-revival", "Zero Uptime, but not gone", "Your attack reduced the zombie to 0. RESTART PENDING means it will revive next round. A fresh zombie can do this once; finishing it from 30% Uptime or less reaps it instead.", "zombie"),
new TutorialStep("end-turn", "3 / End your turn", "Click End turn (or press E). The remaining enemy acts, then the next round begins and the zombie revives. Watch its Uptime.", "TutorialEndTurn", TutorialAction.EndTurn),
new TutorialStep("revived", "The zombie has respawned", "It has returned at half Uptime. RESTART USED means it cannot revive again. Your Cycles also refreshed for this round.", "zombie"),
new TutorialStep("shield-card", "4 / Add protection", "Click borrow() to gain Shield now. It needs no enemy target. Any Shield you already have from Rust overkill is kept.", "card", TutorialAction.PlayShield),
new TutorialStep("shield-result", "Your Shield increased", "That card added protection to this number. Shield is not healing: it absorbs damage before your Uptime is reduced.", "TutorialShield"),
new TutorialStep("select-finisher", "5 / Select a finisher", "Select the highlighted fn main() card. Then you will choose the revived zombie as its target.", "card", TutorialAction.SelectCard),
new TutorialStep("finish-zombie", "6 / Finish the revived zombie", "Click the zombie again. Its revival is already spent, so this attack can terminate it permanently.", "zombie", TutorialAction.TargetEnemy),
new TutorialStep("piles", "Track your cards", "Played cards go to discard; an empty draw pile reshuffles discard. Exhausted cards stay out for this wave. These counters open pile inspectors.", "TutorialPiles"),
new TutorialStep("practice", "Finish the encounter", "You have practiced targeting, revival and Shield. Clear the remaining orphan processes on your own. Use card → enemy, and End turn when needed. A zombie can leave an orphan when permanently defeated.", "enemies")
new TutorialStep("uptime", "This is your Uptime", "Uptime is your health. At 0, the run ends. These loan cards keep your collection safe.", "TutorialUptime"),
new TutorialStep("shield", "Shield protects Uptime", "Shield absorbs ordinary damage before Uptime. This number is your current protection.", "TutorialShield"),
new TutorialStep("cycles", "Cycles pay for cards", "Cycles pay card costs. Your budget refreshes each round.", "TutorialCycles"),
new TutorialStep("ram", "RAM is hand capacity", "Used RAM / capacity. Most cards use 1 RAM; Java uses 2. Free RAM lets you hold more cards.", "TutorialRam"),
new TutorialStep("attack-card", "Read your attack card", "unwrap() deals damage immediately: it is Native. Read its cost and effect here.", "card"),
new TutorialStep("intent", "Read the enemy's intent", "This is Zombie Process's next action. Check the attack range before ending your turn.", "zombie-intent"),
new TutorialStep("select-attack", "1 / Select the attack", "Click unwrap(). Selecting a targeted card does not spend Cycles yet.", "card", TutorialAction.SelectCard),
new TutorialStep("target-zombie", "2 / Choose the zombie", "Click Zombie Process to dispatch your selected attack.", "zombie", TutorialAction.TargetEnemy),
new TutorialStep("pending-revival", "Zero Uptime, but not gone", "RESTART PENDING: this zombie will revive once. A killing hit from 30% Uptime or less prevents revival.", "zombie"),
new TutorialStep("end-turn", "3 / End your turn", "Press End turn (or E). Watch the zombie return when the next round begins.", "TutorialEndTurn", TutorialAction.EndTurn),
new TutorialStep("revived", "The zombie has respawned", "RESTART USED: it returned at half Uptime and cannot revive again. Your Cycles have refreshed.", "zombie"),
new TutorialStep("shield-card", "4 / Add protection", "Click borrow() to gain Shield. No target needed; existing Shield is kept.", "card", TutorialAction.PlayShield),
new TutorialStep("shield-result", "Your Shield increased", "Your Shield increased. It absorbs damage, but does not heal Uptime.", "TutorialShield"),
new TutorialStep("select-finisher", "5 / Select a finisher", "Select fn main(), then choose the revived zombie.", "card", TutorialAction.SelectCard),
new TutorialStep("finish-zombie", "6 / Finish the revived zombie", "Click the zombie. Its revival is spent, so this hit can terminate it permanently.", "zombie", TutorialAction.TargetEnemy),
new TutorialStep("piles", "Track your cards", "Played cards go to discard; an empty draw pile reshuffles it. Exhausted cards stay out for this wave.", "TutorialPiles"),
new TutorialStep("practice", "Finish the encounter", "Finish the orphan processes. Use card → enemy, then End turn as needed. A defeated zombie can leave an orphan.", "enemies")
};
return new[] {
new TutorialStep("leak", "A new threat: Memory Leak", "This enemy grows stronger each round and applies damage-over-time stacks. Your health and purchased upgrade carried over from wave one.", "enemy:memory_leak"),
new TutorialStep("firewall", "A protector: firewalld", "firewalld shields itself and adjacent processes. Read its intent before choosing which enemy to remove first.", "enemy:firewalld"),
new TutorialStep("queue-intro", "Python uses the queue", "Python waits until End turn. Its cards resolve oldest first (FIFO). Let's put a real card into this queue.", "TutorialQueue"),
new TutorialStep("select-python", "Select the Python card", "Click the highlighted Python card. print() chooses its target when it resolves, so it does not ask you to click an enemy.", "card", TutorialAction.SelectCard),
new TutorialStep("leak", "A new threat: Memory Leak", "Memory Leak grows stronger each round and applies damage over time. Your purchased patch carried over.", "enemy:memory_leak"),
new TutorialStep("firewall", "A protector: firewalld", "firewalld shields itself and its neighbors. Check its intent before choosing a target.", "enemy:firewalld"),
new TutorialStep("queue-intro", "Python uses the queue", "Python waits until End turn. Oldest queued card resolves first (FIFO).", "TutorialQueue"),
new TutorialStep("select-python", "Select the Python card", "Click print(). It chooses a target when it resolves, so no enemy click is needed.", "card", TutorialAction.SelectCard),
new TutorialStep("target-python", "Select a target", "Click the highlighted enemy to complete this play.", "enemy", TutorialAction.TargetEnemy),
new TutorialStep("queued-python", "Python is waiting here", "Your card is now queued, not resolved. With multiple entries, the oldest would execute first.", "TutorialQueue"),
new TutorialStep("stack-intro", "Haskell uses the stack", "Haskell waits until after Python and resolves newest first (LIFO). Each entry captures a multiplier for damage and explicit Shield.", "TutorialStack"),
new TutorialStep("select-haskell", "Select the Haskell card", "Click the highlighted thunk() card, then select the highlighted enemy.", "card", TutorialAction.SelectCard),
new TutorialStep("target-haskell", "Choose its target", "Click this enemy. The attack will wait on the stack rather than dealing damage immediately.", "enemy", TutorialAction.TargetEnemy),
new TutorialStep("queued-haskell", "Both tracks are ready", "Python will resolve first, then Haskell, then surviving enemies. A defeated target can cause deferred damage to retarget.", "TutorialStack"),
new TutorialStep("end-round", "Run the queued actions", "Click End turn (or press E). Watch the queue resolve before the stack. We will continue when the exchange finishes.", "TutorialEndTurn", TutorialAction.EndTurn),
new TutorialStep("resolved", "The waiting cards resolved", "The scheduler has executed the deferred cards. Check enemy Uptime, Shield and intents before choosing your next move.", "enemies"),
new TutorialStep("practice", "Clear wave two", "Finish every remaining enemy on your own. Clearing this wave completes training and unlocks 1,000 Bandwidth plus 1,000 Entropy: enough for a standard 10-pull.", "enemies")
new TutorialStep("queued-python", "Python is waiting here", "The card is queued, not resolved. With multiple entries, the oldest executes first.", "TutorialQueue"),
new TutorialStep("stack-intro", "Haskell uses the stack", "Haskell resolves after Python, newest first (LIFO). Its entry multiplier scales damage and Shield.", "TutorialStack"),
new TutorialStep("select-haskell", "Select the Haskell card", "Click thunk(), then choose the highlighted enemy.", "card", TutorialAction.SelectCard),
new TutorialStep("target-haskell", "Choose its target", "Click this enemy. Your attack will wait on the stack.", "enemy", TutorialAction.TargetEnemy),
new TutorialStep("queued-haskell", "Both tracks are ready", "Order: Python queue → Haskell stack → surviving enemies. Deferred attacks can retarget defeated enemies.", "TutorialStack"),
new TutorialStep("end-round", "Run the queued actions", "Press End turn (or E). Watch Python resolve before Haskell.", "TutorialEndTurn", TutorialAction.EndTurn),
new TutorialStep("resolved", "The waiting cards resolved", "The waiting cards resolved. Check enemy Uptime, Shield and intents.", "enemies"),
new TutorialStep("practice", "Clear wave two", "Finish the remaining enemies. Next: Cron Job's countdown and a Daemon miniboss.", "enemies")
};
}
}
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 84a74d1de7c84009a2cf84394e8a9fa2
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+99
View File
@@ -0,0 +1,99 @@
using System.Collections.Generic;
using KernelPanic.Combat;
using KernelPanic.Core;
using UnityEngine;
namespace KernelPanic.UI
{
/// <summary>Short synthesized terminal cues. Observes gameplay; never delays it or consumes RNG.</summary>
[DisallowMultipleComponent]
public sealed class CombatAudio : MonoBehaviour
{
private AudioSource _source;
private readonly Dictionary<string, AudioClip> _clips = new();
private readonly Dictionary<string, float> _lastPlayed = new();
private void Awake()
{
_source = gameObject.AddComponent<AudioSource>();
_source.playOnAwake = false;
_source.spatialBlend = 0;
if (FindFirstObjectByType<AudioListener>() == null) gameObject.AddComponent<AudioListener>();
CreateCue("dispatch", 420, 700, .07f);
CreateCue("resolve", 660, 920, .10f);
CreateCue("shield", 240, 70, .13f);
CreateCue("hit", 120, 55, .08f);
CreateCue("revive", 160, 540, .24f);
CreateCue("clear", 520, 1040, .26f);
CreateCue("victory", 660, 1320, .48f);
CreateCue("defeat", 220, 55, .35f);
}
private void OnEnable()
{
GameEvents.CardPlayed += OnPlayed;
GameEvents.CardResolving += OnResolving;
GameEvents.DamageDealt += OnDamage;
GameEvents.EnemyRevived += OnRevived;
GameEvents.WaveCleared += OnClear;
GameEvents.RunEnded += OnEnded;
UIPreferences.Changed += OnPreferences;
}
private void OnDisable()
{
GameEvents.CardPlayed -= OnPlayed;
GameEvents.CardResolving -= OnResolving;
GameEvents.DamageDealt -= OnDamage;
GameEvents.EnemyRevived -= OnRevived;
GameEvents.WaveCleared -= OnClear;
GameEvents.RunEnded -= OnEnded;
UIPreferences.Changed -= OnPreferences;
if (_source != null) _source.Stop();
}
private void OnDestroy()
{
foreach (var clip in _clips.Values) Destroy(clip);
if (_source != null) Destroy(_source);
}
private void OnPreferences() { if (UIPreferences.SoundVolume == 0) _source?.Stop(); }
private void OnPlayed(CardPlayedEvent _) => Play("dispatch");
private void OnResolving(CardResolvedEvent e) { if (e.Track != ResolutionTrack.Native) Play("resolve"); }
private void OnDamage(DamageDealtEvent e)
{
if (e.ShieldDamage > 0 && e.Target != null && e.Target.Shield == 0) Play("shield");
else if (e.UptimeDamage > 0) Play("hit");
}
private void OnRevived(EnemyInstance _) => Play("revive");
private void OnClear(WaveClearedEvent _) => Play("clear");
private void OnEnded(RunEndedEvent e) => Play(e.PlayerDied ? "defeat" : "victory");
private void Play(string cue)
{
if (_source == null || UIPreferences.SoundVolume <= 0) return;
// Bound dense multi-hit sequences without dropping different kinds of feedback.
if (_lastPlayed.TryGetValue(cue, out float last) && Time.unscaledTime - last < .075f) return;
_lastPlayed[cue] = Time.unscaledTime;
_source.PlayOneShot(_clips[cue], UIPreferences.SoundVolume / 100f);
}
private void CreateCue(string name, float from, float to, float duration)
{
const int sampleRate = 22050;
float[] samples = new float[Mathf.CeilToInt(sampleRate * duration)];
double phase = 0;
for (int i = 0; i < samples.Length; i++)
{
float t = i / (float)samples.Length;
phase += 2 * System.Math.PI * Mathf.Lerp(from, to, t) / sampleRate;
float envelope = Mathf.Min(1, t * 40) * (1 - t) * (1 - t);
samples[i] = .16f * envelope * (float)(System.Math.Sin(phase) + .2 * System.Math.Sin(phase * 2));
}
var clip = AudioClip.Create("terminal-" + name, samples.Length, 1, sampleRate, false);
clip.SetData(samples, 0);
_clips.Add(name, clip);
}
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a87b533a0cca59546ae15534fa85b80a
+104 -6
View File
@@ -61,6 +61,7 @@ namespace KernelPanic.UI
private VisualElement _journalEntries;
private Foldout _journal;
private Button _endTurnButton;
private Button _prefetchButton;
private Label _targetHint;
private Label _schedulerActivity;
private ScrollView _handScroll;
@@ -115,6 +116,9 @@ namespace KernelPanic.UI
private SaveData _lastKnownSave;
private string _saveError;
private string _checkpointError;
private bool _routeSelectionOpen;
private DailyQuestTracker _dailyQuestTracker;
private IVisualElementScheduledItem _dailyQuestSaveSchedule;
private CombatRunTelemetry _runTelemetry;
private RunHistoryEntry _runHistoryEntry;
private bool _pileInspectorOpen;
@@ -125,6 +129,7 @@ namespace KernelPanic.UI
_document = GetComponent<UIDocument>();
_runManager = GetComponent<RunManager>();
_combatManager = GetComponent<CombatManager>();
if (Application.isPlaying && GetComponent<CombatAudio>() == null) gameObject.AddComponent<CombatAudio>();
_saveService = new SaveService();
_root = _document.rootVisualElement;
LoadStyles();
@@ -191,6 +196,21 @@ namespace KernelPanic.UI
_distroAccent = config.Distro == null ? Color.white : config.Distro.AccentColor;
TerminalTheme.SetDistro(_root, config.Distro);
_combatManager.SetGeneratedCardPool(BuildGeneratedCardPool());
if (!config.IsTutorial)
{
_dailyQuestTracker = new DailyQuestTracker(_saveService,
() => _runManager.CurrentConfig != null && !_runManager.IsSuspended,
() => _combatManager.PlayerState);
var notice = TerminalLayout.BodyText("", "DailyQuestSaveNotice");
notice.style.display = DisplayStyle.None;
_root.Insert(1, notice);
_dailyQuestSaveSchedule = _root.schedule.Execute(() =>
{
bool saved = _dailyQuestTracker.Flush();
notice.text = saved ? "" : "Daily quest progress could not be saved. Retrying...";
notice.style.display = saved ? DisplayStyle.None : DisplayStyle.Flex;
}).Every(2000);
}
if (config.IsTutorial)
{
_tutorial = new TutorialFlow(_overlay, _runManager, _combatManager, cardDatabase, languageDeckDatabase,
@@ -240,6 +260,9 @@ namespace KernelPanic.UI
private void OnDisable()
{
Time.timeScale = 1f;
_dailyQuestSaveSchedule?.Pause();
_dailyQuestTracker?.Dispose();
_dailyQuestTracker = null;
SettleRunRewardsIfNeeded();
_tutorial?.Dispose();
_combatManager.StateChanged -= Refresh;
@@ -500,6 +523,14 @@ namespace KernelPanic.UI
_turnResourceGrid.name = "TutorialPiles";
_turnResourceGrid.AddToClassList("turn-resource-grid");
commandPanel.Add(_turnResourceGrid);
_prefetchButton = new Button(() => _combatManager.TryPrefetch())
{
name = "PrefetchButton", text = "draw 1 / 2 Cycles",
tooltip = "Prefetch: draw 1 card once per turn. Requires 2 free RAM so any card fits. Draws from the deck, reshuffling discard if needed."
};
_prefetchButton.AddToClassList("prefetch-action");
handPanel.Q<Label>(className: "panel-subtitle")?.RemoveFromHierarchy();
handPanel.Q(className: "panel-header").Add(_prefetchButton);
_endTurnButton = new(() => _combatManager.EndPlayerTurn()) { text = "[E] end turn" };
_endTurnButton.name = "TutorialEndTurn";
_endTurnButton.AddToClassList("primary-action");
@@ -925,6 +956,8 @@ namespace KernelPanic.UI
card.EnableInClassList("enemy-card-targeted", highlighted);
card.Q<Label>(className: "enemy-name").text = enemy.Name;
card.tooltip = enemy.Name + " / " + IntentText(enemy.DisplayIntent);
if (enemy.HasBehavior(EnemyBehaviorFlags.ObfuscateIntent))
card.tooltip += "\nSurge: 8-10 damage. Harden: 6-8 Shield. Bypass: 3-4 damage ignoring Shield.\nDamage reveals this round's action, including hits absorbed by Shield. Hides again next round.";
if (enemy.HasBehavior(EnemyBehaviorFlags.LeavesOrphan))
card.tooltip += $"\n{CombatTuning.OrphanSpawnChancePercent}% chance to leave an orphan on permanent death.";
card.Q<Label>(className: "process-behavior").text = EnemyProcessPresentation.Behavior(enemy);
@@ -1098,6 +1131,8 @@ namespace KernelPanic.UI
_turnResourceGrid.Add(PileStat("discard", _combatManager.DeckController.DiscardPile));
_turnResourceGrid.Add(PileStat("exhaust", _combatManager.DeckController.ExhaustPile));
_endTurnButton.SetEnabled(_combatManager.CanSurrenderRun && _combatManager.TutorialGuide?.CanEndTurn != false);
_prefetchButton.style.display = _combatManager.RunConfig?.IsTutorial == true ? DisplayStyle.None : DisplayStyle.Flex;
_prefetchButton.SetEnabled(_combatManager.CanPrefetch);
RefreshSurrenderCommand();
}
@@ -1262,6 +1297,7 @@ namespace KernelPanic.UI
_overlay.Clear();
if (_combatManager.RunFinished)
{
_routeSelectionOpen = false;
SettleRunRewardsIfNeeded();
_overlay.style.display = DisplayStyle.Flex;
_overlay.Add(BuildRunEndOverlay());
@@ -1280,11 +1316,12 @@ namespace KernelPanic.UI
}
_overlay.style.display = DisplayStyle.Flex;
_overlay.Add(BuildRepositoryView());
_overlay.Add(_routeSelectionOpen ? BuildRouteSelectionView() : BuildRepositoryView());
if (!wasVisible) _overlay.Q<Button>()?.Focus();
return;
}
_routeSelectionOpen = false;
_overlay.style.display = DisplayStyle.None;
}
@@ -1428,7 +1465,6 @@ namespace KernelPanic.UI
ScrollView body = new(ScrollViewMode.Vertical);
body.AddToClassList("repository-body");
body.AddToClassList("screen-frame-content");
if (_runManager.Journey.campaign) body.Add(RunRouteView.Build(_runManager, _combatManager));
VisualElement offers = new();
offers.AddToClassList("repository-offers");
@@ -1462,11 +1498,14 @@ namespace KernelPanic.UI
reroll.SetEnabled(_runManager.Bits >= _runManager.RerollCost);
footer.Add(reroll);
Button leave = new(() => _combatManager.ContinueToNextWave()) { text = "> boot next-wave" };
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.CampaignChoicePending);
if (_runManager.CampaignChoicePending) leave.text = "Choose finish or endless above";
leave.SetEnabled(!_runManager.IsSuspended);
VisualElement leaveBlock = new();
leaveBlock.AddToClassList("repository-leave-block");
leaveBlock.Add(leave);
@@ -1486,11 +1525,70 @@ namespace KernelPanic.UI
return repo;
}
private void SetRouteSelectionOpen(bool open)
{
_routeSelectionOpen = open;
RefreshOverlay();
_overlay.Q<Button>(open ? "BackToRepositoryButton" : "BootNextWaveButton")?.Focus();
}
private VisualElement BuildRouteSelectionView()
{
var screen = new VisualElement { name = "RouteSelectionScreen" };
screen.AddToClassList("repository");
screen.AddToClassList("screen-frame");
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" : "choose your route");
title.AddToClassList("screen-frame-title");
copy.Add(title);
var subtitle = new Label(_runManager.CampaignChoicePending
? "bank your rewards or continue into endless"
: $"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(RunRouteView.Build(_runManager, _combatManager));
screen.Add(body);
var footer = new VisualElement();
footer.AddToClassList("screen-frame-footer");
footer.style.flexDirection = FlexDirection.Column;
footer.style.alignItems = Align.Stretch;
var back = new Button(() => SetRouteSelectionOpen(false))
{ name = "BackToRepositoryButton", text = "< back to repository" };
back.AddToClassList("primary-action");
footer.Add(back);
if (!_runManager.CampaignChoicePending)
{
var confirm = new Button(() => _combatManager.ContinueToNextWave())
{
name = "ConfirmRouteButton",
text = _runManager.BuildRewardPending ? "choose a build reward to continue" : "> depart / boot next-wave"
};
confirm.AddToClassList("primary-action");
confirm.SetEnabled(!_runManager.BuildRewardPending && !_runManager.IsSuspended);
footer.Add(confirm);
}
screen.Add(footer);
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);
@@ -3517,7 +3615,7 @@ namespace KernelPanic.UI
{
return intent.Kind switch
{
EnemyIntentKind.Attack => "attack",
EnemyIntentKind.Attack => intent.TrueDamage ? "bypasses Shield" : "attack",
EnemyIntentKind.StatusAttack => $"{intent.DisplayLabel} x{intent.StatusStacks}",
EnemyIntentKind.Defend => "defend",
EnemyIntentKind.Buff => "buff",
@@ -28,7 +28,9 @@ namespace KernelPanic.UI
return $"Growing attack / {enemy.TurnsAlive} turns survived";
if (enemy.HasBehavior(EnemyBehaviorFlags.Countdown)) return $"Countdown: {enemy.CountdownRemaining}";
if (enemy.HasBehavior(EnemyBehaviorFlags.DefendAllies)) return "Shields self and adjacent processes";
if (enemy.HasBehavior(EnemyBehaviorFlags.ObfuscateIntent)) return enemy.IntentRevealed ? "Intent exposed" : "Intent hidden until damaged";
if (enemy.HasBehavior(EnemyBehaviorFlags.ObfuscateIntent)) return enemy.IntentRevealed
? "Exposed this round / hides next round"
: "Hit to reveal / surge, Shield or bypass";
return "";
}
}
+44 -17
View File
@@ -14,6 +14,8 @@ namespace KernelPanic.UI
private readonly Label _title = new();
private readonly Label _instruction = new();
private readonly Label _receipt = new();
private readonly VisualElement _resources = new();
private readonly Foldout _tracks = new() { text = "Resources & turn order", value = false };
private readonly Button _action;
private readonly Button _skip;
private RunConfig _config;
@@ -36,12 +38,18 @@ namespace KernelPanic.UI
header.AddToClassList("guide-header");
header.Add(_title);
Element.Add(header);
_resources.AddToClassList("guide-resources");
foreach (string text in new[] { "Uptime\nHealth", "Shield\nProtection", "Cycles\nCard budget", "RAM\nHand space" })
{
var chip = new Label(text); chip.AddToClassList("guide-resource"); _resources.Add(chip);
}
Element.Add(_instruction);
Element.Add(_receipt);
Element.Add(_tracks);
var actions = new VisualElement();
actions.AddToClassList("guide-actions");
_action = new Button(Advance) { text = "Ready: play a card" };
_skip = new Button(Dismiss) { text = "Skip guide" };
_action = new Button(Advance) { text = "Try a card" };
_skip = new Button(Dismiss) { text = "Close guide" };
actions.Add(_action);
actions.Add(_skip);
header.Add(actions);
@@ -57,9 +65,18 @@ namespace KernelPanic.UI
Element.style.display = DisplayStyle.Flex;
_action.style.display = DisplayStyle.Flex;
_skip.style.display = DisplayStyle.Flex;
_action.text = "Ready: play a card";
_title.text = "First battle / 1 of 4 / read the process table";
_instruction.text = "Uptime = health; Cycles = card budget; RAM = hand capacity. Read enemy intents, then select a card and its target. " + TrackLesson(config);
_action.text = "Try a card";
_resources.style.display = DisplayStyle.Flex;
_tracks.Clear(); _tracks.value = false;
_tracks.Add(_resources);
AddTrack("NOW / Native", "Executes when played.");
if (config?.PrimaryLanguage == Language.Python || config?.SecondaryLanguage == Language.Python)
AddTrack("1 / Python queue", "End turn: oldest first.");
if (config?.PrimaryLanguage == Language.Haskell || config?.SecondaryLanguage == Language.Haskell)
AddTrack("2 / Haskell stack", "After the queue: newest first. Entry multiplier scales damage and Shield.");
AddTrack("LAST / Enemies", "Surviving enemies carry out their intents.");
_title.text = "1 / Read the battlefield";
_instruction.text = "Check enemy intents before you spend your Cycles.";
}
public void Advance()
@@ -68,8 +85,8 @@ namespace KernelPanic.UI
if (_completed) { Dismiss(); return; }
_started = true;
_action.style.display = DisplayStyle.None;
_title.text = "First battle / 2 of 4 / dispatch a card";
_instruction.text = "Play any affordable card. Targeted cards need a living process selected. The preview explains its current effect. " + TrackLesson(_config);
_title.text = "2 / Play a card";
_instruction.text = "Select an affordable card, then its enemy target if needed. Check the preview before dispatching.";
}
public void CardPlayed(ResolutionTrack track, string name)
@@ -77,14 +94,14 @@ namespace KernelPanic.UI
if (!Visible || _completed) return;
_played = _started = true;
_action.style.display = DisplayStyle.None;
_title.text = "First battle / 3 of 4 / finish your turn";
_title.text = "3 / End turn";
_receipt.text = track switch
{
ResolutionTrack.InterpreterQueue => name + " entered the queue. It waits until end turn; the oldest queued card resolves first.",
ResolutionTrack.LazyStack => name + " entered the stack. It waits until after the queue; the newest stacked card resolves first.",
_ => name + " executes immediately on the Native track."
ResolutionTrack.InterpreterQueue => name + " queued / oldest first.",
ResolutionTrack.LazyStack => name + " stacked / newest first.",
_ => name + " / executes now."
};
_instruction.text = "Play more cards if you have Cycles, then choose [E] end turn. Watch the scheduler: queue first, stack second, then enemies act. Shield helps absorb incoming damage.";
_instruction.text = "Spend any remaining Cycles, then press [E] End turn. Shield absorbs incoming damage.";
}
public void CardResolved(string name, ResolutionTrack track)
@@ -99,7 +116,7 @@ namespace KernelPanic.UI
if (phase == TurnPhase.Interpret)
{
_endedTurn = true;
_instruction.text = "Resolving: queued cards execute oldest first, then stacked cards execute newest first. Enemy actions follow. You can inspect the journal for the result of each operation.";
_instruction.text = "Queue: oldest first → Stack: newest first → Enemies.";
}
if (phase == TurnPhase.Execute && _endedTurn) Complete(false);
}
@@ -113,11 +130,13 @@ namespace KernelPanic.UI
private void Complete(bool waveCleared)
{
_completed = true;
_title.text = "First battle / 4 of 4 / plan the next round";
_title.text = waveCleared ? "4 / Wave cleared" : "4 / Reassess";
_instruction.text = waveCleared
? "Wave cleared! Spend Bits in the repository on cards, upgrades or healing, then continue. Cleared waves earn rewards that are banked when the run ends."
: "Check Uptime, Shield and the next enemy intents before your next move. Each completed round refreshes your turn resources. " + (_config?.Distro?.Id == "gentoo" ? "Gentoo's Compilation advances after a completed round, improving damage (and Shield at higher versions), and resets each wave. " : "") + "You can reopen this with '? guide' in dispatch.";
if (!_played && _started) _receipt.text = "You can also end a turn without playing a card; the same execution order applies.";
? "Spend Bits in the repository on cards, upgrades or healing. Then continue your run."
: "Check your Uptime, Shield and next enemy intents. Your turn resources have refreshed.";
_receipt.text = _config?.Distro?.Id == "gentoo" && !waveCleared
? "Compilation grew this round; it resets each wave."
: !_played && _started ? "Ending a turn without playing a card is allowed." : "Reopen anytime with ? guide.";
_action.text = "Got it";
_action.style.display = DisplayStyle.Flex;
_skip.style.display = DisplayStyle.None;
@@ -129,6 +148,14 @@ namespace KernelPanic.UI
_remember();
}
private void AddTrack(string title, string copy)
{
var row = new VisualElement(); row.AddToClassList("guide-track");
var heading = new Label(title); heading.AddToClassList("guide-title"); row.Add(heading);
var detail = new Label(copy); detail.AddToClassList("guide-copy"); row.Add(detail);
_tracks.Add(row);
}
public static string TrackLesson(RunConfig config)
{
string lesson = "Native cards execute now.";
+151 -7
View File
@@ -158,6 +158,10 @@ namespace KernelPanic.UI
private bool _loadingMetaState;
private VisualElement _saveRecoveryOverlay;
private VisualElement _runHistoryOverlay;
private VisualElement _dailyQuestOverlay;
private bool _dailyQuestReturnToPrompt;
private VisualElement _dailyQuestPreviousFocus;
private bool _dailyQuestOpenedWithPointer;
private EntropyWallet _wallet;
private GachaService _gachaService;
private PlayerCollection _playerCollection;
@@ -185,6 +189,7 @@ namespace KernelPanic.UI
private Action _rootCreditExchangePlusHundredClicked;
private IVisualElementScheduledItem _blinkSchedule;
private IVisualElementScheduledItem _bootIntroSchedule;
private IVisualElementScheduledItem _dailyQuestSchedule;
private TerminalCommandLine _commandLine;
private MenuScreen _activeScreen = MenuScreen.Main;
@@ -202,7 +207,7 @@ namespace KernelPanic.UI
LoadSharedStyles();
BindCommandEntries();
TerminalTheme.Attach(_root);
_commandLine = new TerminalCommandLine(_root, ActivateCommand, () => _activeScreen == MenuScreen.Main && !starterSelection.IsActive && !_rootCreditExchangeOpen && _runHistoryOverlay == null && !CheckpointModalOpen && !_runLaunchPending && !PersistenceBlocked);
_commandLine = new TerminalCommandLine(_root, ActivateCommand, () => _activeScreen == MenuScreen.Main && !starterSelection.IsActive && !_rootCreditExchangeOpen && _runHistoryOverlay == null && _dailyQuestOverlay == null && !CheckpointModalOpen && !_runLaunchPending && !PersistenceBlocked);
BindPreferences();
RegisterCommandEntryCallbacks();
BindScreenFrames();
@@ -235,6 +240,12 @@ namespace KernelPanic.UI
});
Button textSize = _root.Q<Button>("TextSizeButton");
Button density = _root.Q<Button>("DensityButton");
_root.Q<Button>("SoundVolumeButton").clicked += () =>
{
UIPreferences.SoundVolume = (UIPreferences.SoundVolume / 25 + 1) % 5 * 25;
UIPreferences.Save();
RefreshPreferenceControls();
};
textSize.clicked += () =>
{
UIPreferences.TextSize = UIPreferences.TextSize == UITextSize.Standard ? UITextSize.Large : UITextSize.Standard;
@@ -257,6 +268,7 @@ namespace KernelPanic.UI
motion.text = UIPreferences.ReducedMotion ? "[ true ]" : "[ false ]";
_root.Q<Button>("TextSizeButton").text = UIPreferences.TextSize == UITextSize.Large ? "[ large ]" : "[ standard ]";
_root.Q<Button>("DensityButton").text = UIPreferences.Density == UILayoutDensity.Comfortable ? "[ comfortable ]" : "[ compact ]";
_root.Q<Button>("SoundVolumeButton").text = UIPreferences.SoundVolume == 0 ? "[ muted ]" : $"[ {UIPreferences.SoundVolume}% ]";
}
private void ComposeMetaServices()
@@ -294,6 +306,8 @@ namespace KernelPanic.UI
StartAmbientSchedules();
PlayBootIntroIfNeeded();
RefreshDailyQuestPanel();
_dailyQuestSchedule = _root.schedule.Execute(TickDailyQuests).Every(1000);
}
private void OnDisable()
@@ -302,6 +316,7 @@ namespace KernelPanic.UI
_blinkSchedule?.Pause();
_backgroundLog?.Stop();
_bootIntroSchedule?.Pause();
_dailyQuestSchedule?.Pause();
starterSelection.PauseSchedules();
}
@@ -797,8 +812,109 @@ namespace KernelPanic.UI
_loadingMetaState = false;
}
DailyQuests.Refresh(_saveData.dailyQuests, DateTime.UtcNow);
SaveCurrentState();
RefreshRunActions();
RefreshDailyQuestPanel();
}
private void RefreshDailyQuestPanel()
{
var host = _root?.Q("DailyQuestsHost");
if (host == null || _saveData == null) return;
TerminalTheme.PreserveFocus(host);
host.Clear();
var widget = DailyQuestView.BuildWidget(_saveData.dailyQuests, DateTime.UtcNow, () => OpenDailyQuestDetails());
// Mouse focus is incidental; only keyboard activation should restore the widget's focus ring.
widget.RegisterCallback<PointerDownEvent>(_ => _dailyQuestOpenedWithPointer = true, TrickleDown.TrickleDown);
widget.RegisterCallback<KeyDownEvent>(_ => _dailyQuestOpenedWithPointer = false, TrickleDown.TrickleDown);
widget.RegisterCallback<NavigationSubmitEvent>(_ => _dailyQuestOpenedWithPointer = false, TrickleDown.TrickleDown);
host.Add(widget);
if (_dailyQuestOverlay != null)
{
var scroll = _dailyQuestOverlay.Q<ScrollView>("DailyQuestDetailScroll");
var offset = scroll.scrollOffset;
var focused = _root.focusController?.focusedElement as VisualElement;
bool restoreFocus = focused != null && _dailyQuestOverlay.Contains(focused);
string name = focused?.name;
scroll.Clear();
scroll.Add(DailyQuestView.Build(_saveData.dailyQuests, DateTime.UtcNow, ClaimDailyQuest));
DailyQuestView.RefreshHeader(_dailyQuestOverlay, _saveData.dailyQuests, DateTime.UtcNow);
scroll.scrollOffset = offset;
if (restoreFocus)
{
var replacement = string.IsNullOrEmpty(name) ? null : _dailyQuestOverlay.Q<Button>(name);
if (replacement?.enabledInHierarchy != true)
replacement = _dailyQuestOverlay.Q<Button>("CloseDailyQuests");
replacement?.Focus();
}
}
}
private void OpenDailyQuestDetails()
{
if (PersistenceBlocked || _runLaunchPending || _dailyQuestOverlay != null || _activeScreen != MenuScreen.Main
|| starterSelection.IsActive || _rootCreditExchangeOpen || _runHistoryOverlay != null || CheckpointModalOpen) return;
_dailyQuestPreviousFocus = _root.focusController?.focusedElement as VisualElement;
TickDailyQuests();
if (PersistenceBlocked) return;
_dailyQuestReturnToPrompt = false;
_dailyQuestOverlay = DailyQuestView.BuildOverlay(_saveData.dailyQuests, DateTime.UtcNow, ClaimDailyQuest, CloseDailyQuestDetails);
_root.Add(_dailyQuestOverlay);
_shellRoot?.SetEnabled(false);
_dailyQuestOverlay.Query<Button>().Where(button => button.enabledInHierarchy).First()?.Focus();
}
private void CloseDailyQuestDetails()
{
_dailyQuestOverlay?.RemoveFromHierarchy();
_dailyQuestOverlay = null;
_shellRoot?.SetEnabled(!PersistenceBlocked);
if (_dailyQuestReturnToPrompt) _commandLine?.Focus();
else if (_dailyQuestOpenedWithPointer) (_root?.Q("Root") ?? _root)?.Focus();
else if (_dailyQuestPreviousFocus?.panel != null && _dailyQuestPreviousFocus.enabledInHierarchy)
_dailyQuestPreviousFocus.Focus();
else _root?.Q<Button>("DailyQuestWidget")?.Focus();
_dailyQuestPreviousFocus = null;
_dailyQuestOpenedWithPointer = false;
}
private void TickDailyQuests()
{
if (_saveData == null || PersistenceBlocked || _runLaunchPending) return;
var now = DateTime.UtcNow;
if (DailyQuests.Refresh(_saveData.dailyQuests, now))
{
var feedback = _dailyQuestOverlay?.Q<Label>("DailyQuestFeedback");
if (feedback != null) feedback.style.display = DisplayStyle.None;
SaveCurrentState();
RefreshDailyQuestPanel();
}
var countdown = _root?.Q<Label>("DailyQuestCountdown");
if (countdown != null) countdown.text = DailyQuests.Countdown(_saveData.dailyQuests, now);
if (_dailyQuestOverlay != null) DailyQuestView.RefreshHeader(_dailyQuestOverlay, _saveData.dailyQuests, now);
}
private void ClaimDailyQuest(DailyQuestKind kind, long period)
{
if (PersistenceBlocked || _runLaunchPending) return;
bool claimed = DailyQuests.Claim(_saveData, kind, period, DateTime.UtcNow);
if (claimed)
_wallet.SetBalance(_saveData.entropyBalance);
// Balances and the claim bit are committed in the same atomic save.
// On failure the existing recovery dialog blocks spending until retry succeeds.
SaveCurrentState();
RefreshDailyQuestPanel();
RefreshCurrencyReadouts();
gachaScreen.Refresh();
var feedback = _dailyQuestOverlay?.Q<Label>("DailyQuestFeedback");
if (feedback != null && claimed && !PersistenceBlocked)
{
var reward = DailyQuests.Reward(kind);
feedback.text = $"[ OK ] Daily task completed.\n[ OK ] +{reward.Bandwidth} Bandwidth, +{reward.Entropy} Entropy deposited.";
feedback.style.display = DisplayStyle.Flex;
}
else if (feedback != null && PersistenceBlocked) feedback.style.display = DisplayStyle.None;
}
private bool PersistenceBlocked => _saveLoadFailed || _saveWriteFailed;
@@ -850,7 +966,7 @@ namespace KernelPanic.UI
{
_saveRecoveryOverlay?.RemoveFromHierarchy();
_saveRecoveryOverlay = null;
_shellRoot?.SetEnabled(true);
_shellRoot?.SetEnabled(_dailyQuestOverlay == null);
_root.Q("StarterModal")?.SetEnabled(true);
_rootCreditExchangeModal?.SetEnabled(true);
}
@@ -970,12 +1086,13 @@ namespace KernelPanic.UI
if (_saveData.tutorialCheckpoint != null)
{
var checkpoint = _saveData.tutorialCheckpoint;
RunCheckpoint.Require(checkpoint.wave == 2 && checkpoint.wavesCleared == 1
RunCheckpoint.Require(checkpoint.wave >= 2 && checkpoint.wave <= TutorialCampaign.LessonCount
&& checkpoint.wavesCleared == checkpoint.wave - 1
&& checkpoint.journey?.campaign == false && checkpoint.packages?.Count == 0
&& checkpoint.offers?.Exists(offer => offer != null && offer.sold) == true,
"Training checkpoint is not a purchased first-wave shop.");
&& (checkpoint.wave > 2 || checkpoint.offers?.Exists(offer => offer != null && offer.sold) == true),
"Training checkpoint is not a completed lesson boundary.");
var resume = _saveData.tutorialCheckpoint.Resolve(distroDatabase, cardDatabase, languageDeckDatabase, packageDatabase);
resume.Config.TutorialLesson = 2;
resume.Config.TutorialLesson = TutorialCampaign.Lesson(_saveData);
RunContext.SetResume(resume);
}
else RunContext.SetTutorial(TutorialCampaign.CreateConfig(distro, cardDatabase, 1));
@@ -1365,7 +1482,16 @@ namespace KernelPanic.UI
int index = i;
_commandEntries[i].Row.focusable = true;
_commandEntries[i].Row.RegisterCallback<FocusInEvent>(_ => SelectCommand(index));
_commandEntries[i].Row.RegisterCallback<PointerEnterEvent>(_ => SelectCommand(index));
_commandEntries[i].Row.RegisterCallback<PointerEnterEvent>(_ =>
{
SelectCommand(index);
// Hover selects a primary command; Enter must no longer target the side widget.
if (_dailyQuestOverlay == null && _root.focusController?.focusedElement == _root.Q<Button>("DailyQuestWidget"))
{
_root.Q<Button>("DailyQuestWidget").Blur();
(_root.Q("Root") ?? _root).Focus();
}
});
_commandEntries[i].Row.RegisterCallback<ClickEvent>(_ => HandleCommandClicked(index));
}
}
@@ -1515,6 +1641,12 @@ namespace KernelPanic.UI
return;
}
if (PersistenceBlocked) return;
if (_dailyQuestOverlay != null)
{
if (evt.keyCode == KeyCode.Escape) CloseDailyQuestDetails();
evt.StopPropagation();
return;
}
if (_runHistoryOverlay != null)
{
if (evt.keyCode == KeyCode.Escape) CloseRunHistory();
@@ -1670,6 +1802,8 @@ namespace KernelPanic.UI
if (evt.keyCode == KeyCode.UpArrow)
{
SelectCommand(_selectedCommandIndex - 1);
_commandEntries[_selectedCommandIndex].Row.Focus();
_root.panel?.focusController.IgnoreEvent(evt);
evt.StopPropagation();
return;
}
@@ -1677,6 +1811,8 @@ namespace KernelPanic.UI
if (evt.keyCode == KeyCode.DownArrow)
{
SelectCommand(_selectedCommandIndex + 1);
_commandEntries[_selectedCommandIndex].Row.Focus();
_root.panel?.focusController.IgnoreEvent(evt);
evt.StopPropagation();
return;
}
@@ -2355,6 +2491,14 @@ namespace KernelPanic.UI
{
if (PersistenceBlocked) return;
_commandLine.Echo(index);
// Prompt-only alias; the six primary navigation commands retain their indices.
if (index == 6)
{
_dailyQuestOpenedWithPointer = false;
OpenDailyQuestDetails();
_dailyQuestReturnToPrompt = true;
return;
}
_commandEntries[index].Activate();
_root.Focus();
}
+38 -6
View File
@@ -1,4 +1,5 @@
using System;
using System.Linq;
using KernelPanic.Combat;
using KernelPanic.Run;
using UnityEngine.UIElements;
@@ -10,9 +11,40 @@ namespace KernelPanic.UI
{
public static VisualElement Build(RunManager run, CombatManager combat)
{
var section = TerminalLayout.Section(run.CampaignChoicePending ? "KERNEL SECURED" : "Next route", "RunRouteChoices");
var section = TerminalLayout.Section(run.CampaignChoicePending ? "KERNEL SECURED" : "Route", "RunRouteChoices");
section.AddToClassList("run-route-section");
if (!string.IsNullOrEmpty(run.Journey.lastReward)) section.Add(TerminalLayout.BodyText(run.Journey.lastReward));
if (run.BuildRewardPending)
{
section.Add(TerminalLayout.BodyText("Build reward / choose one before departure. Upgrade a card for this run, or take Bits to spend freely."));
var cards = run.RunDeck.Where(card => card.Definition != null && !card.Definition.IsToken && !card.Definition.IsJunk).ToList();
if (cards.Count > 0)
{
int selected = 0;
var target = TerminalLayout.BodyText("", "BuildRewardTarget");
section.Add(target);
var navigation = new VisualElement();
navigation.AddToClassList("reward-target-navigation");
section.Add(navigation);
section.Add(Action($"Upgrade effect +{CombatTuning.UpgradeMagnitudeBonus}", "RewardMagnitude",
() => run.ClaimBuildReward(cards[selected], CardUpgradeKind.MagnitudeUp)));
var draw = Action("Add draw 1 on resolution", "RewardDraw",
() => run.ClaimBuildReward(cards[selected], CardUpgradeKind.DrawRider));
void Select(int offset)
{
selected = (selected + offset + cards.Count) % cards.Count;
var card = cards[selected];
target.text = $"Target {selected + 1}/{cards.Count}: {card.Definition.DisplayName}\n+{card.MagnitudeBonus} effect / +{card.DrawRider} draw";
draw.SetEnabled(card.DrawRider == 0);
}
navigation.Add(Action("Previous card", "RewardPrevious", () => Select(-1)));
navigation.Add(Action("Next card", "RewardNext", () => Select(1)));
Select(0);
section.Add(draw);
}
section.Add(Action($"Take {RunManager.BuildRewardBits} Bits", "RewardBits",
() => run.ClaimBuildReward(null, CardUpgradeKind.MagnitudeUp, true)));
}
if (run.CampaignChoicePending)
{
section.Add(TerminalLayout.BodyText("Five waves cleared. Finish this campaign and bank your rewards, or keep this build running in endless mode. Rewards are saved when the run ends."));
@@ -20,17 +52,17 @@ namespace KernelPanic.UI
section.Add(Action("Continue into endless", "ContinueEndlessButton", () => combat.ContinueEndless()));
return section;
}
var plan = EncounterDirector.Plan(run.CurrentWaveNumber, run.Journey.selectedRoute);
section.Add(TerminalLayout.BodyText($"Wave {run.CurrentWaveNumber}: {plan.Title}"));
section.Add(TerminalLayout.BodyText(plan.Advice));
var plan = EncounterDirector.Plan(run.CurrentWaveNumber, run.Journey.selectedRoute,
run.CurrentConfig.RunSeed, run.Journey.encounterRevision);
var choices = new VisualElement();
choices.AddToClassList("route-choices");
AddChoice(choices, run, WaveRoute.Repair, "Repair stop",
$"Restore up to {RunJourney.RepairUptime} Uptime on departure. Fight the standard encounter.");
AddChoice(choices, run, WaveRoute.Challenge, "Elite detour",
$"An extra elite Daemon joins the encounter. On clear: +{RunJourney.ChallengeBits} Bits and +1 draw on the first eligible deck card without a draw rider; +{RunJourney.ChallengeBits} extra Bits if none qualify.");
$"Extra Daemon. On clear: +{RunJourney.ChallengeBits} Bits and +1 draw on the first card without a draw rider (or +{RunJourney.ChallengeBits} Bits if none)."
+ (run.Journey.selectedRoute == WaveRoute.Challenge
? $"\nElite: {(plan.EscortShield > 0 ? $"+{plan.EscortShield} Shield" : plan.EscortUptime > 0 ? $"+{plan.EscortUptime} Uptime" : "hidden intent")}." : ""));
section.Add(choices);
section.Add(TerminalLayout.BodyText("Choose freely before booting. Repairs and difficulty apply only when you leave; the elite reward requires clearing the wave."));
return section;
}
+2 -1
View File
@@ -10,7 +10,8 @@ namespace KernelPanic.UI
{
internal static readonly string[] Commands =
{
"./start_run", "ls ~/collection", "curl gacha.sh | sh", "dpkg-reconfigure", "history --runs", "shutdown -h now"
"./start_run", "ls ~/collection", "curl gacha.sh | sh", "dpkg-reconfigure", "history --runs", "shutdown -h now",
"cat /etc/cron.daily/quests"
};
private readonly List<string> _history = new();
private readonly TextField _input;
+21 -14
View File
@@ -33,7 +33,7 @@ namespace KernelPanic.UI
{
_overlay = overlay; _run = run; _combat = combat; _cards = cards; _languages = languages;
_save = save; _lesson = config.TutorialLesson; _returnToMenu = returnToMenu;
_resuming = _lesson == 2;
_resuming = _lesson > 1;
SetGuide(_lesson);
}
@@ -56,7 +56,7 @@ namespace KernelPanic.UI
{
if (!_resuming) return;
_resuming = false;
if (!_combat.ContinueTutorialWave()) throw new InvalidDataException("Training checkpoint is not a purchased first-wave shop.");
if (!_combat.ContinueTutorialWave()) throw new InvalidDataException("Training checkpoint is not a completed lesson boundary.");
}
public void Refresh()
@@ -78,14 +78,15 @@ namespace KernelPanic.UI
_overlay.Clear(); _overlay.style.display = DisplayStyle.None; _renderKey = null;
return;
}
if (cleared && _lesson == 1 && !_run.RepositoryVisitActive)
if (cleared && _lesson < TutorialCampaign.LessonCount && !_run.RepositoryVisitActive)
_run.GenerateRepositoryOffers(_cards, _languages);
bool purchased = _run.RepositoryOffers.Any(offer => offer.Sold);
string key = $"{_lesson}:{cleared}:{lost}:{_shopStep}:{purchased}:{_error}";
if (_renderKey == key) return;
_renderKey = key;
_overlay.Clear(); _overlay.AddToClassList("tutorial-overlay"); _overlay.style.display = DisplayStyle.Flex;
var panel = TerminalLayout.Section(lost ? "Practice ended" : _lesson == 1 ? "Wave one cleared / repository" : "Training complete", "TutorialDialog");
var panel = TerminalLayout.Section(lost ? "Practice ended" : _lesson == 1 ? "Wave one cleared / repository"
: _lesson < TutorialCampaign.LessonCount ? "Wave two cleared" : "Training complete", "TutorialDialog");
panel.AddToClassList("tutorial-dialog");
var scroll = new ScrollView(ScrollViewMode.Vertical) { name = "TutorialCopy" };
scroll.style.flexShrink = 1; scroll.style.minHeight = 0;
@@ -93,7 +94,7 @@ namespace KernelPanic.UI
Button action;
if (lost)
{
scroll.Add(TerminalLayout.BodyText("Try again. Wave two restarts from your saved shop purchase; wave one restarts with full Uptime. Your collection is safe."));
scroll.Add(TerminalLayout.BodyText("Retry this wave from its start. Your purchased upgrade is saved; your collection is safe."));
action = new Button(RestartLesson) { text = "Retry training", name = "TutorialRetry" };
}
else if (_lesson == 1)
@@ -102,7 +103,7 @@ namespace KernelPanic.UI
if (_shopStep == 0)
{
bits.AddToClassList("tutorial-shop-highlight");
scroll.Add(TerminalLayout.BodyText("Every enemy is gone. Between waves, the repository is your shop. Spend Bits earned in combat to improve this run; Bits are separate from your permanent currencies."));
scroll.Add(TerminalLayout.BodyText("Spend combat Bits here to improve this run. Your permanent currencies are separate."));
action = new Button(() => { _shopStep = 1; Redraw(); }) { text = "Show an upgrade", name = "TutorialShopNext" };
}
else
@@ -118,15 +119,21 @@ namespace KernelPanic.UI
{ text = purchased ? "Purchased" : $"Buy / {offer.Price} Bits", name = "TutorialBuy" };
buy.SetEnabled(!purchased && _run.Bits >= offer.Price); item.Add(buy);
scroll.Add(TerminalLayout.BodyText(purchased
? "Upgrade installed. Your remaining Uptime, deck and purchase carry into wave two. Normal shops also sell new cards and stat upgrades."
? "Upgrade installed. Your Uptime, deck and patch carry into wave two."
: "Buy this upgrade to practice spending Bits. Then start the next wave."));
action = new Button(Continue) { text = "Start wave two", name = "TutorialContinue" };
action.SetEnabled(purchased);
}
}
else if (_lesson < TutorialCampaign.LessonCount)
{
scroll.Add(TerminalLayout.BodyText("Queue and stack mastered. One last practice: Cron Job's countdown and a Daemon miniboss."));
scroll.Add(TerminalLayout.BodyText("Continue to save your progress and restore full Uptime for the final practice."));
action = new Button(Continue) { text = "Start wave three", name = "TutorialContinue" };
}
else
{
scroll.Add(TerminalLayout.BodyText("Both waves are clear. You have completed the combat → shop → combat loop."));
scroll.Add(TerminalLayout.BodyText("All three waves cleared. You're ready for a campaign."));
scroll.Add(TerminalLayout.Heading($"+{TutorialCampaign.BandwidthReward:N0} Bandwidth"));
scroll.Add(TerminalLayout.Heading($"+{TutorialCampaign.EntropyReward:N0} Entropy"));
scroll.Add(TerminalLayout.BodyText("Enough Entropy for one standard 10-pull. This training reward is granted once per profile."));
@@ -143,22 +150,22 @@ namespace KernelPanic.UI
{
if (_leaving || Guide.Active || !_combat.AwaitingWaveContinue || _combat.RunFinished) return;
if (_lesson == 1 && !_run.RepositoryOffers.Any(offer => offer.Sold)) return;
if (_lesson == 2 && _run.WavesCleared < 2) return;
if (_run.WavesCleared < _lesson) return;
try
{
var data = _save.Load();
if (!TutorialCampaign.Required(data)) throw new InvalidOperationException("Training is not active.");
if (_lesson == 1)
if (_lesson < TutorialCampaign.LessonCount)
{
data.tutorialCheckpoint = _run.CaptureCheckpoint(_combat);
data.tutorialLesson = 2;
data.tutorialLesson = _lesson + 1;
}
else TutorialCampaign.Complete(data);
_save.Save(data);
_error = null;
if (_lesson == 2) { _leaving = true; _returnToMenu(); return; }
_lesson = 2; SetGuide(2);
if (!_combat.ContinueTutorialWave()) throw new InvalidOperationException("Wave two could not start. Restart to resume the saved shop.");
if (_lesson == TutorialCampaign.LessonCount) { _leaving = true; _returnToMenu(); return; }
_lesson++; SetGuide(_lesson);
if (!_combat.ContinueTutorialWave()) throw new InvalidOperationException("Training could not continue. Restart to resume the saved wave.");
Redraw();
}
catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is InvalidOperationException || ex is OverflowException)
+1 -1
View File
@@ -50,7 +50,7 @@ namespace KernelPanic.UI
_guide = guide; _overlay.style.display = DisplayStyle.Flex;
_root.EnableInClassList("tutorial-card-focus", guide.Step.Anchor == "card");
_anchor = ResolveAnchor();
_progress.text = $"Wave {combat.RunConfig.TutorialLesson}/2 / step {guide.Index + 1} of {guide.Count}";
_progress.text = $"Wave {combat.RunConfig.TutorialLesson}/{TutorialCampaign.LessonCount} / step {guide.Index + 1} of {guide.Count}";
_title.text = guide.Step.Title; _copy.text = guide.Step.Copy;
_next.style.display = guide.Reading ? DisplayStyle.Flex : DisplayStyle.None;
_next.SetEnabled(combat.TutorialInputReady);
+18 -2
View File
@@ -13,6 +13,18 @@ namespace KernelPanic.UI
private static bool _reducedMotion;
private static UITextSize _textSize;
private static UILayoutDensity _density;
private static int _soundVolume = 75;
public static int SoundVolume
{
get => _soundVolume;
set
{
value = Mathf.Clamp(value, 0, 100);
if (_soundVolume == value) return;
_soundVolume = value;
Changed?.Invoke();
}
}
public static event Action Changed;
@@ -73,7 +85,9 @@ namespace KernelPanic.UI
bool motion = stored.reducedMotion;
var size = stored.textSize == (int)UITextSize.Large ? UITextSize.Large : UITextSize.Standard;
var density = stored.density == (int)UILayoutDensity.Comfortable ? UILayoutDensity.Comfortable : UILayoutDensity.Compact;
bool changed = motion != _reducedMotion || size != _textSize || density != _density;
int volume = Mathf.Clamp(stored.soundVolume, 0, 100);
bool changed = motion != _reducedMotion || size != _textSize || density != _density || volume != _soundVolume;
_soundVolume = volume;
_reducedMotion = motion;
_textSize = size;
_density = density;
@@ -86,7 +100,8 @@ namespace KernelPanic.UI
{
reducedMotion = _reducedMotion,
textSize = (int)_textSize,
density = (int)_density
density = (int)_density,
soundVolume = _soundVolume
}));
PlayerPrefs.Save();
}
@@ -98,6 +113,7 @@ namespace KernelPanic.UI
public bool reducedMotion;
public int textSize;
public int density;
public int soundVolume = 75;
}
}
}