Rebalance most languages and revamp main game loop

This commit is contained in:
2026-10-25 23:50:04 +01:00
parent 53f831d91e
commit a4109f5be0
76 changed files with 4198 additions and 573 deletions
+34 -22
View File
@@ -16,7 +16,7 @@ namespace KernelPanic.Combat
Cleanse, ShuffleToken, UpgradeHandCards, GenerateCard, NoOp, UpdateManager,
ShieldRepeatDamage, Timeshift, DnfAutoremove, FirstToPackage, Rawhide,
IncomingAttackHalve, ConsultWiki, RandomCommonLanguageCard, MinimalInstall, SizeofDamage,
RepairCorruptedCards, AskUbuntu
RepairCorruptedCards, AskUbuntu, FixedDraw, Python
}
/// <summary>
@@ -58,6 +58,8 @@ namespace KernelPanic.Combat
CardEffectKind.Damage => new DealDamageEffect(Amount, MaxAmount, Language, TrueDamage, CanCrit, AllEnemies),
CardEffectKind.Shield => new ShieldEffect(Amount),
CardEffectKind.Draw => new DrawEffect(Amount),
CardEffectKind.FixedDraw => new FixedDrawEffect(Amount),
CardEffectKind.Python => new PythonEffect((PythonOperation)SecondaryAmount, Amount),
CardEffectKind.AskUbuntu => new AskUbuntuEffect(),
CardEffectKind.ChanceDamage => new ChanceDamageEffect(Amount, SecondaryAmount, Language),
CardEffectKind.PreviousLanguageDamage => new PreviousLanguageDamageEffect(Amount, SecondaryAmount, Language),
@@ -126,6 +128,9 @@ namespace KernelPanic.Combat
/// Queue growth is resolved from the card without changing any combat state.
/// </summary>
public string GetRulesText(CardInstance card)
=> GetRulesText(card, null, 1);
public string GetRulesText(CardInstance card, string distroId, int distroVersion)
{
if (_rules == null)
{
@@ -133,7 +138,10 @@ namespace KernelPanic.Combat
? "effect not authored."
: card.Definition.Description + (card.UpgradeLevel > 0 ? " [upgraded]" : string.Empty);
}
string text = _rules;
int inspectCount = PythonPipeline.InspectCount(distroId, distroVersion);
int btwMultiplier = string.Equals(distroId, "arch", StringComparison.OrdinalIgnoreCase) && distroVersion >= 3 ? 4 : 3;
string text = _rules.Replace("{inspectCount}", inspectCount.ToString(CultureInfo.InvariantCulture))
.Replace("{btwMultiplier}", btwMultiplier.ToString(CultureInfo.InvariantCulture));
for (int i = 0; i < Effects.Count; i++)
{
CardEffectSpec effect = Effects[i];
@@ -148,6 +156,9 @@ namespace KernelPanic.Combat
text = Replace(text, "rawSecondary", i, effect.SecondaryAmount);
text = Replace(text, "failure", i, 100 - effect.SecondaryAmount);
text = Replace(text, "growth", i, UpgradeMath.ScaleAmount(effect.Amount + UnityEngine.Mathf.Max(0, (card?.QueuePlayCount ?? 0) - 1), card));
text = Replace(text, "listGrowth", i, CardScaling.Add(UpgradeMath.ScaleAmount(effect.Amount, card),
(int)Math.Min(int.MaxValue, 2L * Math.Max(0, (card?.QueuePlayCount ?? 0) - 1))));
text = Replace(text, "pythonBonus", i, UpgradeMath.ScaleAmount(5, card));
}
return text + (card?.UpgradeLevel > 0 ? " [upgraded]" : string.Empty);
}
@@ -168,7 +179,7 @@ namespace KernelPanic.Combat
private const CardTargeting Single = CardTargeting.SingleEnemy;
private const CardTargeting All = CardTargeting.AllEnemies;
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 const string Jit = " overkill spills. JIT: -1 Cycle per 2 Java plays, capped at -3; discount cools by 1 after each wave.";
private static readonly IReadOnlyDictionary<string, CardCatalogEntry> ById;
public static IReadOnlyList<CardCatalogEntry> Entries { get; }
@@ -200,30 +211,29 @@ namespace KernelPanic.Combat
Add("shop_hs_foldmap", All, false, "stack: deal {amount:0} to all living enemies.", Damage(4, Language.Haskell, all: true));
Add("shop_hs_deepseq", Single, false, "stack: deal {amount:0}.", Damage(9, Language.Haskell));
Add("shop_hs_dollar_bang", Single, false, "stack: deal {amount:0}. gain {shield:1} Shield.", Damage(5, Language.Haskell), Shield(2));
Add("lang_py_print", None, false, "queue: deal {amount:0}.", Damage(3, Language.Python));
Add("lang_py_import_antigravity", None, false, "queue: draw {amount:0}.", Draw(2));
Add("lang_py_for_loop", All, false, "queue: deal {amount:0} to all enemies.", Damage(2, Language.Python, all: true));
Add("lang_py_print", Single, false, "payload: deal {amount:0} to a chosen enemy.", Py(PythonOperation.Print, 4));
Add("lang_py_import_antigravity", None, false, "preparation: immediately draw 2 (fixed).", Py(PythonOperation.Draw, 2));
Add("lang_py_for_loop", None, false, "modifier: gain {shield:0} Shield. repeat the next payload once. unused repeat expires after next round.", Py(PythonOperation.Loop, 2));
Add("lang_js_console_log", Single, true, "deal {amount:0}-{max:0}.", Damage(3, Language.JavaScript, 9));
Add("lang_js_fetch", Single, true, "deal {amount:0}-{max:0}.", Damage(5, Language.JavaScript, 13));
Add("lang_rs_fn_main", Single, true, "deal {amount:0}. overkill becomes shield.", Damage(6, Language.Rust));
Add("lang_rs_unwrap", Single, true, "deal {amount:0}. overkill becomes shield. draw {amount:1}.", Damage(9, Language.Rust), Draw(1));
Add("lang_rs_unwrap", Single, true, "deal {amount:0}. overkill becomes shield. draw {raw:1} (fixed).", Damage(5, Language.Rust), Fx(CardEffectKind.FixedDraw, 1));
Add("lang_rs_borrow", None, false, "gain {shield:0} shield.", Shield(5));
Add("lang_c_malloc", Single, true, "deal {amount:0}." + CRecoil, Damage(12, Language.C));
Add("lang_c_printf", Single, true, "deal {amount:0}." + CRecoil + " then repair up to {amount:1} corrupted card{plural:1} in your active deck.",
Damage(7, Language.C), Fx(CardEffectKind.RepairCorruptedCards, 1));
Damage(4, Language.C), Fx(CardEffectKind.RepairCorruptedCards, 1));
Add("lang_c_pointer", Single, true, "deal {amount:0}; {secondary:0} if the previous card was C." + CRecoil,
Fx(CardEffectKind.PreviousLanguageDamage, 9, secondary: 15, language: Language.C));
Add("lang_java_public_static_main", Single, true, "uses 2 RAM. deal {amount:0}. overkill spills. JIT: Java cards cost 1 less this combat each time you play a Java card; discount decays by 1 after each wave.", Damage(7, Language.Java));
Add("lang_java_public_static_main", Single, true, "uses 2 RAM. deal {amount:0}." + Jit, Damage(7, Language.Java));
Add("lang_java_system_out_println", Single, true, "uses 2 RAM. deal {amount:0}." + Jit, Damage(5, Language.Java));
Add("lang_java_new_object", Single, true, "uses 2 RAM. deal {amount:0}." + Jit, Damage(3, Language.Java));
Add("ubuntu_ask_ubuntu", None, false, "queue: draw {amount:0}.", Fx(CardEffectKind.AskUbuntu, AskUbuntuEffect.BaseDrawCount));
Add("ubuntu_unattended_upgrades", None, false, "queue: gain {shield:0} shield now and next {rawSecondary:1} turns.",
Shield(4), Fx(CardEffectKind.UnattendedUpgrades, 4, secondary: 2));
Add("ubuntu_ask_ubuntu", None, false, "preparation: inspect the top {inspectCount} cards. take one; others keep their order.", Py(PythonOperation.Inspect));
Add("ubuntu_unattended_upgrades", None, false, "automation: gain {shield:0} Shield now and before the queue on each of the next 2 rounds. uses 1 of 2 script slots.", Py(PythonOperation.Unattended, 3));
Add("mint_fix_broken", Single, true, "deal {amount:0}. cleanse harmful statuses.", Damage(8, Language.JavaScript), Fx(CardEffectKind.Cleanse));
Add("lang_js_typeof", Single, true, "{rawSecondary:0}%: deal {amount:0}. {failure:0}%: deal 0.", Fx(CardEffectKind.ChanceDamage, 8, secondary: 75, language: Language.JavaScript));
Add("shop_py_list_append", Single, false, "queue: deal {growth:0}; +1 each time re-queued.", Fx(CardEffectKind.QueuedGrowthDamage, 4, language: Language.Python));
Add("shop_py_async_def", None, false, "queue: draw {amount:0}. gain {amount:1} cycle next turn.", Draw(2), Fx(CardEffectKind.NextTurnCycle, 1));
Add("shop_py_zip", None, false, "next {amount:0} queued cards resolve twice.", Fx(CardEffectKind.QueueRepeat, 2));
Add("lang_js_typeof", Single, true, "{rawSecondary:0}%: deal {amount:0}. {failure:0}%: deal 0.", Fx(CardEffectKind.ChanceDamage, 14, secondary: 75, language: Language.JavaScript));
Add("shop_py_list_append", Single, false, "payload: deal {listGrowth:0}. +2 per subsequent hand play this wave; replays do not grow it.", Py(PythonOperation.List, 6));
Add("shop_py_async_def", None, false, "automation: draw 1 immediately on play (fixed). capture the next payload without modifiers; replay it before the queue on each of the next 2 rounds. uses 1 of 2 script slots.", Py(PythonOperation.Async));
Add("shop_py_zip", Single, false, "modifier: deal {amount:0}. the next single-target damage payload hits all enemies. unused conversion expires after next round.", Py(PythonOperation.Zip, 2));
Add("shop_js_math_random", Single, true, "deal {amount:0}-{max:0}.", Damage(2, Language.JavaScript, 20));
CardEffectSpec promiseHit = Damage(4, Language.JavaScript, 10);
Add("shop_js_promise_all", Single, true, "deal {amount:0}-{max:0} three times.", promiseHit, promiseHit, promiseHit);
@@ -231,22 +241,22 @@ namespace KernelPanic.Combat
Add("ubuntu_snap_install", Single, true, "deal {amount:0}-{max:0}. shuffle an ubuntu pro trial into your draw pile.", Damage(6, Language.JavaScript, 14),
new CardEffectSpec(CardEffectKind.ShuffleToken, referenceId: "ubuntu_pro_trial"));
Add("ubuntu_do_release_upgrade", None, false, "upgrade {amount:0}-{max:0} random hand cards.", Fx(CardEffectKind.UpgradeHandCards, 1, 3));
Add("ubuntu_apt_install", None, false, "queue: generate a random common Python card at 0c.", Fx(CardEffectKind.GenerateCard, language: Language.Python));
Add("ubuntu_apt_install", None, false, "preparation: choose one of 3 Python cards. temporary copy costs 0 this turn and exhausts after play.", Py(PythonOperation.Install));
Add("ubuntu_pro_trial", None, false, null, new CardEffectSpec(CardEffectKind.NoOp, referenceId: "ubuntu pro trial is unplayable"));
// UpdateManager expands its own targets at execution, and historically asks for no target.
Add("mint_update_manager", None, false, "queue: deal {amount:0} to all enemies. repeats at the end of your next turn.", Fx(CardEffectKind.UpdateManager, 5, language: Language.Python, all: true));
Add("mint_cinnamon", None, false, "queue: gain {shield:0} shield. draw {amount:1}.", Shield(3), Draw(1));
Add("mint_update_manager", All, false, "payload: deal {amount:0} to all enemies; {pythonBonus:0} if an automation ran earlier this phase.", Py(PythonOperation.Update, 3, true));
Add("mint_cinnamon", None, false, "payload: gain {shield:0} Shield; {pythonBonus:0} if an earlier Python payload dealt damage this phase.", Py(PythonOperation.Cinnamon, 3));
Add("mint_nemo", Single, true, "deal {amount:0}. if you have shield, deal it again.", Fx(CardEffectKind.ShieldRepeatDamage, 6, language: Language.JavaScript));
Add("mint_timeshift", None, false, "queue: record uptime now. at end of your next turn, restore to it if lower.", Fx(CardEffectKind.Timeshift));
Add("mint_timeshift", None, false, "automation: save your Uptime when this resolves. after enemies act in each of the next 2 rounds, heal up to 6 Uptime, without exceeding the saved value. no healing this round or if defeated. healing does not scale with upgrades. uses 1 of 2 script slots until both rounds finish; ends when the wave ends.", Py(PythonOperation.Timeshift));
Add("fedora_dnf_autoremove", Single, true, "deal {amount:0}. exhaust a junk/NOP/broken card from hand; if you do, gain {secondary:0} cycle. if not, do nothing.", Fx(CardEffectKind.DnfAutoremove, 7, secondary: 1, language: Language.Rust));
Add("fedora_first_to_package", Single, true, "deal {amount:0}. Java cards cost 1 less this turn.", Fx(CardEffectKind.FirstToPackage, 7, language: Language.Java));
Add("fedora_dnf_update", Single, true, "deal {amount:0}. overkill spills. costs 1 less per Java card played this combat.", Damage(9, Language.Java));
Add("fedora_dnf_update", Single, true, "deal {amount:0}." + Jit, Damage(9, Language.Java));
Add("fedora_rawhide", None, false, "draw {amount:0}. next card this turn gains bleeding edge.", Fx(CardEffectKind.Rawhide, RawhideEffect.DrawCount));
Add("fedora_selinux", None, false, "next {amount:0} enemy attacks deal half damage.", Fx(CardEffectKind.IncomingAttackHalve, 2));
Add("arch_pacman_syu", Single, true, "deal {amount:0}." + CRecoil, Damage(14, Language.C));
Add("arch_consult_wiki", Single, true, "fix a broken card and draw {secondary:0}; if none, deal {amount:0}.",
Fx(CardEffectKind.ConsultWiki, ConsultWikiEffect.FallbackDamage, secondary: ConsultWikiEffect.DrawCount, language: Language.Rust));
Add("arch_makepkg", Single, true, "deal {amount:0} + btw x{rawSecondary:0}; x4 at Arch v3+." + CRecoil, Fx(CardEffectKind.BtwScaledDamage, 7, secondary: 3, language: Language.C));
Add("arch_makepkg", Single, true, "deal {amount:0} + btw x{btwMultiplier}." + CRecoil, Fx(CardEffectKind.BtwScaledDamage, 7, secondary: 3, language: Language.C));
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));
@@ -275,6 +285,8 @@ namespace KernelPanic.Combat
=> new(CardEffectKind.Damage, amount, max, language: language, allEnemies: all, trueDamage: trueDamage);
private static CardEffectSpec Shield(int amount) => new(CardEffectKind.Shield, amount);
private static CardEffectSpec Draw(int amount) => new(CardEffectKind.Draw, amount);
private static CardEffectSpec Py(PythonOperation operation, int amount = 0, bool all = false) =>
new(CardEffectKind.Python, amount, secondaryAmount: (int)operation, language: Language.Python, allEnemies: all);
private static CardEffectSpec Fx(CardEffectKind kind, int amount = 0, int max = -1, int secondary = 0, Language language = default, bool all = false)
=> new(kind, amount, max, secondary, language, all);
}
+30 -1
View File
@@ -375,6 +375,28 @@ namespace KernelPanic.Combat
}
}
/// <summary>A fixed replacement draw; magnitude and source effect bonuses do not increase it.</summary>
public sealed class FixedDrawEffect : ICardEffect
{
private readonly int _count;
public FixedDrawEffect(int count)
{
_count = count;
}
public void Execute(CombatContext context)
{
int added = 0;
// Use the same ordered, RAM-aware draw operation as ordinary draw effects.
while (added < _count && context.DeckController.TryDrawToHand(context.HandController, out _))
added++;
string capped = added < _count && context.DeckController.AvailableToDrawCount > 0
? " (not enough RAM)" : string.Empty;
context.CombatManager.ReportEffectResult($"drew {added}{capped}");
}
}
public sealed class AskUbuntuEffect : ICardEffect
{
internal const int BaseDrawCount = 2;
@@ -892,6 +914,12 @@ namespace KernelPanic.Combat
}
public static string GetRulesText(CardInstance card)
=> GetRulesText(card, null, 1);
public static string GetRulesText(CardInstance card, KernelPanic.Run.RunConfig config)
=> GetRulesText(card, config?.Distro?.Id, config?.DistroVersion ?? 1);
public static string GetRulesText(CardInstance card, string distroId, int distroVersion)
{
if (card?.Definition == null)
{
@@ -910,7 +938,8 @@ namespace KernelPanic.Combat
if (CardCatalog.TryGet(card.Definition.Id, out CardCatalogEntry entry))
{
return entry.GetRulesText(card);
return entry.GetRulesText(card, distroId, distroVersion)
+ (card.ExhaustOnPlay ? " Temporary copy: exhaust after play." : string.Empty);
}
return string.IsNullOrWhiteSpace(card.Definition.Description)
+2
View File
@@ -25,6 +25,7 @@ namespace KernelPanic.Combat
public int PermanentCostDelta { get; private set; }
public int MagnitudeBonus { get; private set; }
public int DrawRider { get; private set; }
public bool ExhaustOnPlay { get; set; }
public int UpgradeLevel { get; private set; }
public int QueuePlayCount { get; private set; }
public bool WasFirstCardThisTurn { get; private set; }
@@ -157,6 +158,7 @@ namespace KernelPanic.Combat
IsBroken = IsBroken,
IsLocked = IsLocked
};
copy.ExhaustOnPlay = ExhaustOnPlay;
copy.PermanentCostDelta = PermanentCostDelta;
copy.MagnitudeBonus = MagnitudeBonus;
+30 -2
View File
@@ -68,6 +68,8 @@ namespace KernelPanic.Combat
int cardDamageFlat = CardScaling.Add(source.FlatCardDamageBonus,
prospective && deferred ? combat.PreviewNextDnfDamageStack() : 0);
bool allEnemies = entry.TargetsAllEnemies || entry.Effects.Any(effect => effect.AllEnemies);
var python = combat.Python.PreviewState(card);
if (PythonPipeline.IsPayload(card.Definition) && python.area) allEnemies = true;
var targets = PreviewTargets(combat, card, target, queued, allEnemies);
bool hasSelectedTarget = target != null || queued && card.TargetSnapshot.Any(t => t != null && !t.IsDefeated)
|| combat.SelectedEnemyIndex >= 0 && combat.SelectedEnemyIndex < combat.Enemies.Count;
@@ -79,7 +81,7 @@ namespace KernelPanic.Combat
result.IsConditional = true;
}
if (lazy != 100 || card.Definition.Language == Language.Haskell)
notes.Add($"Haskell {(lazyEntry == null ? "next stack" : "captured")}: x{lazy / 100m:0.0} damage and explicit Shield.");
notes.Add($"Haskell {(lazyEntry == null ? "next stack" : "captured")}: x{(lazy / 100m).ToString("0.0#", System.Globalization.CultureInfo.InvariantCulture)} damage and explicit Shield.");
if (combat.Compilation.Active)
notes.Add($"Compilation {combat.Compilation.Level}/{combat.Compilation.Maximum}: {combat.Compilation.DamagePercent}% damage, {combat.Compilation.ShieldPercent}% explicit Shield.");
if (magnitude > 0) notes.Add($"Card magnitude: +{magnitude}" + (growth > 0 ? $" (includes +{growth} non-crash growth)" : string.Empty) + ".");
@@ -116,6 +118,29 @@ namespace KernelPanic.Combat
int repeats = 1;
switch (effect.Kind)
{
case CardEffectKind.Python:
var operation = (PythonOperation)effect.SecondaryAmount;
AddNote(notes, CardEffectFactory.GetRulesText(card, combat.RunConfig));
if (operation is PythonOperation.Print or PythonOperation.List or PythonOperation.Update or PythonOperation.Zip)
{
damage = true;
low = high = effect.Amount;
if (operation == PythonOperation.List)
low = high = CardScaling.Add(effect.Amount, (int)Math.Min(int.MaxValue, 2L * Math.Max(0, card.QueuePlayCount + (prospective ? 1 : 0) - 1)));
if (operation == PythonOperation.Update && python.automation) low = high = 5;
if (operation != PythonOperation.Zip) repeats = python.repeats;
}
if (operation is PythonOperation.Loop or PythonOperation.Cinnamon or PythonOperation.Unattended)
{
int shieldBase = operation == PythonOperation.Cinnamon && python.damageBefore ? 5 : effect.Amount;
int shieldRepeats = operation == PythonOperation.Cinnamon ? python.repeats : 1;
hasShield = true;
int shieldValue = ScaledShield(shieldBase, sourceFlat, magnitude, lazy, combat);
for (int i = 0; i < shieldRepeats; i++) targetShield = CardScaling.Add(targetShield, shieldValue);
}
if (PythonPipeline.IsPayload(card.Definition))
AddNote(notes, $"Pipeline: {python.repeats} execution(s){(python.area ? ", all enemies" : "")}. Earlier payloads may change conditions; replays never repeat draw or installation.");
break;
case CardEffectKind.Damage:
damage = true;
break;
@@ -185,6 +210,9 @@ namespace KernelPanic.Combat
hasShield = true;
targetShield = CardScaling.Add(targetShield, ScaledShield(effect.Amount, sourceFlat, magnitude, lazy, combat));
break;
case CardEffectKind.FixedDraw:
AddNote(notes, $"Draw {effect.Amount} (fixed): magnitude and effect bonuses do not increase this draw; available RAM still limits it.");
break;
case CardEffectKind.HaskellMaybe:
if (source.CurrentUptime >= source.MaxUptime)
{
@@ -324,7 +352,7 @@ namespace KernelPanic.Combat
if (captured != null) return captured.MultiplierPercent;
if (card.Definition.ResolutionTrack != ResolutionTrack.LazyStack || card.Definition.Language != Language.Haskell) return 100;
int haskell = combat.LazyStack?.Entries.Count(item => item.Card.Definition?.Language == Language.Haskell) ?? 0;
return 100 + 50 * Math.Min(3, haskell);
return CombatTuning.HaskellStackMultiplierPercent(haskell);
}
private static IReadOnlyList<CombatantState> PreviewTargets(CombatManager combat, CardInstance card,
+42 -16
View File
@@ -87,6 +87,9 @@ namespace KernelPanic.Combat
private bool _evaluatingLazyStack;
private LazyStackEntry _activeLazyEntry;
public CompilationState Compilation { get; } = new();
public PythonPipeline Python { get; } = new();
public IReadOnlyList<CardDefinition> GeneratedCardPool => _generatedCardPool.AsReadOnly();
public void NotifyPythonChanged() => StateChanged?.Invoke();
public TurnPhase CurrentPhase => currentPhase;
public RunConfig RunConfig => _runConfig;
@@ -118,8 +121,10 @@ namespace KernelPanic.Combat
_selectedEnemyIndex = -1; _pendingTargetCard = null;
}
public int CurrentWaveNumber => _runManager == null ? 1 : _runManager.CurrentWaveNumber;
public int RoundNumber => _turnNumberThisWave;
public int ActiveKernelRamPenalty => _activeKernelRamPenalty;
public bool CanSurrenderRun => currentPhase == TurnPhase.Execute
&& !Python.HasChoice
&& !TutorialReading
&& !_waveTransitionActive
&& !_awaitingWaveContinue
@@ -135,6 +140,7 @@ namespace KernelPanic.Combat
private void Awake()
{
Python.Bind(this);
_runManager = GetComponent<RunManager>();
_damagePipeline.ResistanceResolver = ResolveDamageResistance;
_damagePipeline.PreviewResistanceResolver = ResolveDamageResistance;
@@ -208,6 +214,7 @@ namespace KernelPanic.Combat
public void RestoreBoundaryState(RunConfig config, CheckpointCombat snapshot)
{
Python.Clear();
RunCompleted = false;
_waveTransitionActive = false;
RunEndedBySurrender = false;
@@ -230,7 +237,7 @@ namespace KernelPanic.Combat
_fedoraCrashChance = snapshot.fedoraCrashChance;
_packageInterpreterQueueShieldTriggeredThisWave = snapshot.interpreterShieldUsed;
_packageNativeDamageTriggeredThisWave = snapshot.nativeDamageUsed;
_javaCardsPlayedThisCombat = snapshot.javaCardsPlayed;
_javaCardsPlayedThisCombat = Mathf.Clamp(snapshot.javaCardsPlayed, 0, CombatTuning.JavaMaximumWarmup);
_rawhideBonusCharges = snapshot.rawhideCharges;
_queuedRepeatCharges = snapshot.repeatCharges;
_nextTurnCycleBonus = snapshot.nextTurnCycles;
@@ -297,13 +304,15 @@ namespace KernelPanic.Combat
{
if (_runConfig?.IsTutorial == true) return;
if (!_awaitingWaveContinue || RunFinished || _waveTransitionActive
|| _runManager?.IsSuspended == true || _runManager?.CampaignChoicePending == true || _runManager?.BuildRewardPending == true)
|| _runManager?.IsSuspended == true || _runManager?.CampaignChoicePending == true || _runManager?.BuildRewardPending == true
|| _runManager?.RouteEventPending == true)
{
return;
}
_waveTransitionActive = true;
_runManager?.PrepareNextEncounter(_playerState);
if (_runManager?.RepositoryVisitActive == true) { _waveTransitionActive = false; return; }
_awaitingWaveContinue = false;
DecayJavaWarmupForNextWave();
StartCoroutine(ContinueToNextWaveSequenced());
@@ -452,7 +461,7 @@ namespace KernelPanic.Combat
_playerState.HasLastPlayedCardLanguage = true;
if (card.Definition.Language == Language.Java)
{
_javaCardsPlayedThisCombat++;
_javaCardsPlayedThisCombat = Mathf.Min(CombatTuning.JavaMaximumWarmup, _javaCardsPlayedThisCombat + 1);
}
GameEvents.RaiseCardPlayed(new CardPlayedEvent(card, track));
@@ -507,6 +516,7 @@ namespace KernelPanic.Combat
case ResolutionTrack.InterpreterQueue:
card.MarkQueued();
_interpreterQueue.Enqueue(card);
if (PythonPipeline.IsAsync(card.Definition)) new FixedDrawEffect(1).Execute(BuildContext(card, Array.Empty<CombatantState>()));
break;
case ResolutionTrack.LazyStack:
_lazyStack.Enqueue(card);
@@ -514,9 +524,12 @@ namespace KernelPanic.Combat
default:
GameEvents.RaiseCardResolving(new CardResolvedEvent(card, ResolutionTrack.Native));
ExecuteCardEffects(card, ResolveTargets(card));
ResolveCardRiders(card);
_deckController.Discard(card);
GameEvents.RaiseCardResolved(new CardResolvedEvent(card, ResolutionTrack.Native));
Python.AfterChoice(() =>
{
ResolveCardRiders(card);
_deckController.Discard(card);
GameEvents.RaiseCardResolved(new CardResolvedEvent(card, ResolutionTrack.Native));
});
_selectedEnemyIndex = -1;
break;
}
@@ -528,10 +541,12 @@ namespace KernelPanic.Combat
_cCardsPlayedThisTurn++;
}
ApplyPackageCardPlayedEffects(card);
_pendingTargetCard = null;
TryApplyUbuntuEmptyHandRefill();
Python.AfterChoice(() =>
{
ApplyPackageCardPlayedEffects(card);
TryApplyUbuntuEmptyHandRefill();
});
StateChanged?.Invoke();
return true;
}
@@ -551,7 +566,7 @@ namespace KernelPanic.Combat
int cost = GetCardCost(card);
if (card?.Definition != null && card.Definition.Language == Language.Java)
{
cost -= _javaCardsPlayedThisCombat + _javaCardsDiscountThisTurn;
cost -= CombatTuning.JavaWarmupDiscount(_javaCardsPlayedThisCombat) + _javaCardsDiscountThisTurn;
}
cost = ApplyPackageCostRules(card, cost);
@@ -604,7 +619,7 @@ namespace KernelPanic.Combat
int cost = GetCardCost(card);
if (card.Definition.Language == Language.Java)
{
int reduction = _javaCardsPlayedThisCombat + _javaCardsDiscountThisTurn;
int reduction = CombatTuning.JavaWarmupDiscount(_javaCardsPlayedThisCombat) + _javaCardsDiscountThisTurn;
if (reduction > 0) lines.Add($"Java warmup: -{reduction}");
cost -= reduction;
}
@@ -1290,13 +1305,18 @@ namespace KernelPanic.Combat
private IEnumerator InterpretQueueSequenced()
{
Python.BeginPhase(_turnNumberThisWave);
while (VisualResolutionPending && !_runLost && !_awaitingWaveContinue) yield return null;
if (CheckWinOrLoss()) yield break;
while (_interpreterQueue.TryDequeue(out CardInstance card))
{
LogPlayIntent(card);
int resolutionCount = ConsumeQueuedResolutionCount(card);
// Legacy repeat charges must never duplicate Python installation/preparation effects.
int resolutionCount = PythonPipeline.IsPythonCard(card.Definition) ? 1 : ConsumeQueuedResolutionCount(card);
for (int repeatIndex = 0; repeatIndex < resolutionCount; repeatIndex++)
{
ExecuteCardEffects(card, ResolveQueuedTargets(card));
while (Python.HasChoice && !_runLost && !_awaitingWaveContinue) yield return null;
if (CheckWinOrLoss())
{
yield break;
@@ -1373,6 +1393,7 @@ namespace KernelPanic.Combat
private void ClearDeferredCards()
{
Python.Clear();
foreach (var card in _lazyStack.Cards.Concat(_interpreterQueue.Cards).Distinct())
{
card.ClearTargetSnapshot();
@@ -1444,6 +1465,7 @@ namespace KernelPanic.Combat
return;
}
Python.EndRound();
ResolveDelayedEndOfTurnEffects();
if (CheckWinOrLoss())
{
@@ -1487,6 +1509,7 @@ namespace KernelPanic.Combat
private IEnumerator DrawCardsToHandSequenced(int requestedCount, string label)
{
while (Python.HasChoice) yield return null;
if (_handController == null || _playerState == null || requestedCount <= 0)
{
yield break;
@@ -1506,6 +1529,7 @@ namespace KernelPanic.Combat
int added = 0;
for (int i = 0; i < drawn.Count; i++)
{
while (Python.HasChoice) yield return null;
if (!_handController.Add(drawn[i]))
{
blockedByRam = true;
@@ -1632,8 +1656,9 @@ namespace KernelPanic.Combat
return;
}
_javaCardsPlayedThisCombat = Mathf.Max(0, _javaCardsPlayedThisCombat - 1);
Log($"Java JIT cooled: discount now -{_javaCardsPlayedThisCombat}");
_javaCardsPlayedThisCombat = Mathf.Max(0,
Mathf.Min(CombatTuning.JavaMaximumWarmup, _javaCardsPlayedThisCombat) - CombatTuning.JavaPlaysPerDiscount);
Log($"Java JIT cooled: discount now -{CombatTuning.JavaWarmupDiscount(_javaCardsPlayedThisCombat)}");
}
private bool CanApplyFedoraPassiveBonus()
@@ -2848,7 +2873,8 @@ namespace KernelPanic.Combat
{
EnemyArchetypeDescriptor archetype = EnemyArchetypeCatalog.Get(archetypeId);
int baseUptime = RandomRoll.RollRange(archetype.BaseUptimeMin, archetype.BaseUptimeMax, RollContext.None);
if (_runConfig?.IsTutorial == true && CurrentWaveNumber == 1 && archetypeId == "zombie_process") baseUptime = 6;
// The guided first hit must kill even when the starter unwrap() does not crit.
if (_runConfig?.IsTutorial == true && CurrentWaveNumber == 1 && archetypeId == "zombie_process") baseUptime = 5;
EnemyInstance enemy = new(archetype, baseUptime + Mathf.Max(0, uptimeBonus));
_enemies.Add(enemy);
return enemy;
@@ -3286,7 +3312,7 @@ namespace KernelPanic.Combat
|| _enemyExitAwaitingVisual != null
|| _deathSpawnSequencesActive > 0;
private bool IsCombatPaused => _awaitingWaveContinue || _waveTransitionActive || RunFinished || VisualResolutionPending;
private bool IsCombatPaused => Python.HasChoice || _awaitingWaveContinue || _waveTransitionActive || RunFinished || VisualResolutionPending;
private enum DelayedCombatEffectKind
{
+9
View File
@@ -13,6 +13,15 @@ namespace KernelPanic.Combat
public const int CCriticalChancePercent = 35;
public const int COverkillSpillPercent = 50;
public const int OrphanSpawnChancePercent = 25;
public const int JavaPlaysPerDiscount = 2;
public const int JavaMaximumWarmup = 6;
public static int JavaWarmupDiscount(int plays) =>
System.Math.Clamp(plays, 0, JavaMaximumWarmup) / JavaPlaysPerDiscount;
// Lift small stacks while preserving the third position and the x2.5 ceiling.
public static int HaskellStackMultiplierPercent(int pendingHaskellCards) =>
pendingHaskellCards <= 0 ? 150 : pendingHaskellCards == 1 ? 175 : pendingHaskellCards == 2 ? 200 : 250;
public const int BaseEnemyUptimeMin = 5;
public const int BaseEnemyUptimeMax = 10;
+14
View File
@@ -186,10 +186,24 @@ namespace KernelPanic.Combat
{
if (card != null)
{
if (card.ExhaustOnPlay) { Exhaust(card); return; }
_discardPile.Add(card);
}
}
public IReadOnlyList<CardInstance> PeekTop(int count)
{
if (_drawPile.Count == 0) ReshuffleDiscardIntoDraw();
return _drawPile.AsEnumerable().Reverse().Take(System.Math.Max(0, count)).ToArray();
}
public bool TakeToHand(CardInstance card, HandController hand)
{
if (!_drawPile.Contains(card) || hand == null || !hand.Add(card)) return false;
_drawPile.Remove(card);
return true;
}
public void AddToDrawPile(CardInstance card, bool shuffle)
{
if (card == null)
+46 -2
View File
@@ -22,6 +22,7 @@ namespace KernelPanic.Combat
// A stable integer mixer, independent of both gameplay random streams and runtime hash codes.
public static EncounterPlan Plan(int wave, WaveRoute route, int seed, int revision)
{
if (revision >= 2) return CampaignPlan(wave, route, seed);
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;
@@ -56,7 +57,7 @@ namespace KernelPanic.Combat
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:
case RunJourney.LegacyBossWave:
title = variant == 1 ? "Kernel Overseer / scheduled interrupt" : "Kernel Overseer / memory pressure";
enemies = new[] { "kernel_overseer", variant == 1 ? "cron_job" : "memory_leak" };
advice = baseline.Advice;
@@ -99,7 +100,7 @@ namespace KernelPanic.Combat
title = "Concurrency fault";
advice = "Race partners attack in uncertain order; killing one enrages the survivor. Segfault has a death payload.";
enemies = new[] { "race_condition", "race_condition", "segfault" }; break;
case RunJourney.BossWave:
case RunJourney.LegacyBossWave:
title = "Kernel Overseer";
advice = "Boss cycle: shield, probe, heavy interrupt. At half uptime its NEXT announced attacks become stronger.";
enemies = new[] { "kernel_overseer", "firewalld" }; break;
@@ -123,5 +124,48 @@ namespace KernelPanic.Combat
}
return new EncounterPlan(title, advice, Math.Max(0, wave - 1) * CombatTuning.EnemyUptimeGrowthPerWave, enemies);
}
private static EncounterPlan CampaignPlan(int wave, WaveRoute route, int seed)
{
// Keep introductory encounters familiar; introduce the heavier systems before the final boss.
int legacyStage = wave <= 4 ? wave : wave == RunJourney.BossWave ? RunJourney.LegacyBossWave
: wave > RunJourney.BossWave ? wave - 5 : 3;
var baseline = Plan(legacyStage, route, seed, 1);
string title = baseline.Title, advice = baseline.Advice;
var enemies = new List<string>(baseline.Enemies);
string support = unchecked((uint)seed + (uint)wave) % 2 == 0 ? "firewalld" : "cron_job";
switch (wave)
{
case 5:
title = "Privilege escalation";
advice = "Rootkit resists damage while allies remain. Remove its support first.";
enemies = new() { "rootkit", "zombie_process", support }; break;
case 6:
title = "Telemetry breach";
advice = "Telemetry Collector interferes with your resources. Contain the growing Memory Leak.";
enemies = new() { "telemetry_collector", "memory_leak", support }; break;
case 7:
title = "Protected subsystem";
advice = "DRM Guardian protects the subsystem. Plan your damage around its defenses.";
enemies = new() { "drm_guardian", "segfault", support }; break;
case 8:
title = "Critical concurrency";
advice = "Race partners act in uncertain order; defeating one enrages the survivor. Remove their support deliberately.";
enemies = new() { "race_condition", "race_condition", support }; break;
case 9:
title = "Kernel perimeter";
advice = "Kernel Panic pressures your RAM. Clear this last perimeter before the Overseer.";
enemies = new() { "kernel_panic", "daemon", support }; break;
}
if (wave >= 5 && wave < RunJourney.BossWave && route == WaveRoute.Challenge)
{
enemies.Add("daemon"); title += " / challenge";
advice += baseline.EscortShield > 0 ? " Extra Daemon: 6 starting Shield, hidden intent."
: baseline.EscortUptime > 0 ? " Extra Daemon: +4 Uptime, hidden intent." : " Extra Daemon: hidden intent.";
}
if (wave > RunJourney.BossWave) title = "Survival / " + wave;
return new EncounterPlan(title, advice, Math.Max(0, wave - 1) * CombatTuning.EnemyUptimeGrowthPerWave, enemies.ToArray())
{ EscortShield = baseline.EscortShield, EscortUptime = baseline.EscortUptime };
}
}
}
+4 -2
View File
@@ -10,13 +10,15 @@ namespace KernelPanic.Combat
{
var lines = new List<string>();
if (combat?.PlayerState == null) return lines;
lines.Add("Native cards already executed. End turn resolves Python FIFO, then Haskell LIFO, then surviving enemies, then cleanup.");
lines.Add("Native cards and Python preparation already executed. End turn runs ready Python automation, then Python FIFO, Haskell LIFO, surviving enemies, and cleanup.");
if (combat.Python.AutomationCount > 0 || combat.Python.RepeatCount > 0 || combat.Python.AreaCount > 0)
foreach (string script in combat.Python.Readout) lines.Add(script);
int order = 0;
foreach (var card in combat.InterpreterQueue.Cards)
lines.Add(CardLine(combat, card, ++order, "FIFO", card.TargetSnapshot));
foreach (var entry in combat.LazyStack.Entries)
lines.Add(CardLine(combat, entry.Card, ++order, "LIFO " + entry.MultiplierLabel, entry.Targets));
if (order == 0) lines.Add("No deferred cards: surviving enemies act next.");
if (order == 0) lines.Add("No deferred cards: ready automation runs before surviving enemies act.");
lines.Add("ENEMIES / current announced intents (after deferred cards; each enemy's start-of-turn status ticks before its action)");
foreach (var enemy in combat.Enemies)
{
+2 -2
View File
@@ -11,7 +11,7 @@ namespace KernelPanic.Combat
public CardInstance Card { get; }
public int MultiplierPercent { get; }
public IReadOnlyList<CombatantState> Targets { get; }
public string MultiplierLabel => $"x{MultiplierPercent / 100}.{MultiplierPercent % 100 / 10}";
public string MultiplierLabel => "x" + (MultiplierPercent / 100m).ToString("0.0#", System.Globalization.CultureInfo.InvariantCulture);
internal LazyStackEntry(CardInstance card, int multiplierPercent)
{
Card = card;
@@ -34,7 +34,7 @@ namespace KernelPanic.Combat
if (card == null || _cards.Contains(card)) return;
int multiplier = 100;
if (card.Definition != null && card.Definition.Language == Language.Haskell)
multiplier = 100 + 50 * Math.Min(3, _entries.Count(e => e.Card.Definition != null && e.Card.Definition.Language == Language.Haskell));
multiplier = CombatTuning.HaskellStackMultiplierPercent(_entries.Count(e => e.Card.Definition != null && e.Card.Definition.Language == Language.Haskell));
_entries.Insert(0, new LazyStackEntry(card, multiplier));
_cards.Insert(0, card);
}
+275
View File
@@ -0,0 +1,275 @@
using System;
using System.Collections.Generic;
using System.Linq;
using KernelPanic.Core;
using KernelPanic.Data;
namespace KernelPanic.Combat
{
public enum PythonOperation { Print, Loop, Draw, List, Zip, Async, Inspect, Install, Unattended, Cinnamon, Update, Timeshift }
public sealed class PythonEffect : ICardEffect
{
private readonly PythonOperation _operation;
private readonly int _amount;
public PythonEffect(PythonOperation operation, int amount) { _operation = operation; _amount = amount; }
public void Execute(CombatContext context) => context.CombatManager.Python.Execute(context, _operation, _amount);
}
public sealed class PythonChoiceOption
{
public string Label { get; }
public bool Enabled { get; }
public PythonChoiceOption(string label, bool enabled = true) { Label = label; Enabled = enabled; }
public CardInstance Card { get; }
public int Cost { get; }
public string ActionLabel { get; }
public PythonChoiceOption(CardInstance card, int cost, string actionLabel, bool enabled = true)
{
Card = card; Cost = cost; ActionLabel = actionLabel;
Label = card.Definition.DisplayName; Enabled = enabled;
}
}
/// <summary>Wave-local FIFO transformations, immutable payload snapshots and bounded background tasks.</summary>
public sealed class PythonPipeline
{
private sealed class Payload
{
public CardInstance Card;
public int Damage, Shield;
public bool All;
public CombatantState Target;
}
private sealed class Script
{
public string Name;
public CardInstance Owner;
public Payload Payload;
public bool Waiting, Restore;
public int FirstRound, Remaining = 2, Uptime, LastRunRound = -1;
}
private readonly List<int> _loops = new(), _areas = new();
private readonly List<Script> _scripts = new();
private readonly Dictionary<CardInstance, int> _temporaryDiscounts = new();
private Action<int> _choose;
private Action _afterChoice;
private CombatManager _combat;
private int _round;
public bool DamageThisPhase { get; private set; }
public bool AutomationRan { get; private set; }
public string ChoiceTitle { get; private set; }
public IReadOnlyList<PythonChoiceOption> Choices { get; private set; } = Array.Empty<PythonChoiceOption>();
public bool HasChoice => _choose != null;
public int AutomationCount => _scripts.Count;
public int RepeatCount => _loops.Count;
public int AreaCount => _areas.Count;
public (int repeats, bool area, bool damageBefore, bool automation) PreviewState(CardInstance card)
{
int round = _combat.RoundNumber;
int loops = _loops.Count(r => round <= r + 1), areas = _areas.Count(r => round <= r + 1);
var ready = _scripts.Where(s => !s.Waiting && !s.Restore && round >= s.FirstRound && round > s.LastRunRound).ToArray();
bool damage = (_round == round && DamageThisPhase) || ready.Any(s => s.Payload.Damage > 0);
bool automated = (_round == round && AutomationRan) || ready.Length > 0;
foreach (var previous in _combat.InterpreterQueue.Cards)
{
if (previous == card) break;
if (!IsPythonCard(previous.Definition)) continue;
string id = previous.Definition.Id;
if (id == "lang_py_for_loop") loops++;
else if (id == "shop_py_zip") areas++;
else if (IsPayload(previous.Definition))
{
if (loops > 0) loops--;
if (id is "lang_py_print" or "shop_py_list_append") { if (areas > 0) areas--; }
if (id != "mint_cinnamon") damage = true;
}
}
return (loops > 0 ? 2 : 1, areas > 0 && card.Definition.Id is "lang_py_print" or "shop_py_list_append", damage, automated);
}
public IEnumerable<string> Readout => new[] { $"Python: repeat {_loops.Count} | area {_areas.Count} | scripts {_scripts.Count}/2" }
.Concat(_scripts.Select(s => s.Waiting ? $"{s.Name}: waiting for payload"
: $"{s.Name}{(s.Name == "async def" ? " / " + s.Payload.Card.Definition.DisplayName : "")}: {s.Remaining} runs remaining"));
public void Bind(CombatManager combat) => _combat = combat;
public void Clear()
{
ExpireDiscounts();
_loops.Clear(); _areas.Clear(); _scripts.Clear(); _choose = null; _afterChoice = null;
Choices = Array.Empty<PythonChoiceOption>(); ChoiceTitle = null;
DamageThisPhase = AutomationRan = false; _round = 0;
}
private void ExpireDiscounts()
{
foreach (var entry in _temporaryDiscounts) entry.Key.TemporaryCostDelta = entry.Value;
_temporaryDiscounts.Clear();
}
public bool Choose(int index)
{
if (!HasChoice || index < 0 || index >= Choices.Count || !Choices[index].Enabled) return false;
var action = _choose;
var afterChoice = _afterChoice;
_afterChoice = null;
_choose = null; Choices = Array.Empty<PythonChoiceOption>(); ChoiceTitle = null;
action(index);
afterChoice?.Invoke();
_combat.NotifyPythonChanged();
return true;
}
public void AfterChoice(Action action)
{
if (HasChoice) _afterChoice += action;
else action();
}
private void Offer(string title, IEnumerable<PythonChoiceOption> options, Action<int> choose)
{
if (HasChoice) throw new InvalidOperationException("Resolve the current Python choice first.");
ChoiceTitle = title; Choices = Array.AsReadOnly(options.ToArray()); _choose = choose;
_combat.NotifyPythonChanged();
}
public static bool IsPythonCard(CardDefinition card) => card != null && card.Language == Language.Python
&& !card.Effects.Any(e => e != null) && CardCatalog.TryGet(card.Id, out var entry)
&& entry.Effects.Any(e => e.Kind == CardEffectKind.Python);
public static bool IsPayload(CardDefinition card) => IsPythonCard(card)
&& card.Id is "lang_py_print" or "shop_py_list_append" or "mint_cinnamon" or "mint_update_manager";
public static bool IsAsync(CardDefinition card) => IsPythonCard(card) && card.Id == "shop_py_async_def";
public static int InspectCount(string distroId, int version) =>
string.Equals(distroId, "ubuntu", StringComparison.OrdinalIgnoreCase) && version >= 3 ? 5 : 3;
public void BeginPhase(int round)
{
_round = round;
ExpireDiscounts();
_loops.RemoveAll(r => round > r + 1); _areas.RemoveAll(r => round > r + 1);
DamageThisPhase = AutomationRan = false;
foreach (var script in _scripts.ToArray())
{
if (script.Waiting || script.Restore || round < script.FirstRound || round <= script.LastRunRound) continue;
script.LastRunRound = round;
AutomationRan = true;
Run(script.Payload, script.Payload.All);
if (--script.Remaining == 0) _scripts.Remove(script);
if (_combat.RunFinished || _combat.AwaitingWaveContinue || _combat.PlayerState.IsDefeated) break;
}
}
public void EndRound()
{
if (_combat.PlayerState.IsDefeated || _combat.RunFinished || _combat.AwaitingWaveContinue) return;
foreach (var script in _scripts.ToArray())
{
if (!script.Restore || _round < script.FirstRound || _round <= script.LastRunRound) continue;
script.LastRunRound = _round;
if (_combat.CanPlayerReceiveCardHeal(script.Owner))
{
int heal = Math.Min(6, Math.Max(0, Math.Min(script.Uptime, _combat.PlayerState.MaxUptime) - _combat.PlayerState.CurrentUptime));
_combat.PlayerState.CurrentUptime += heal;
_combat.ReportEffectResult($"timeshift restored {heal} Uptime");
}
if (--script.Remaining == 0) _scripts.Remove(script);
}
}
private CombatContext Context(CardInstance card, CombatantState target = null) => new(card, _combat.PlayerState,
target == null ? Array.Empty<CombatantState>() : new[] { target }, _combat, _combat.DamagePipeline,
new StatusEffectController(), _combat.DeckController, _combat.HandController, _combat.Enemies);
public void Execute(CombatContext context, PythonOperation operation, int amount)
{
Bind(context.CombatManager);
if (operation is PythonOperation.Print or PythonOperation.List or PythonOperation.Cinnamon or PythonOperation.Update)
{
int value = amount;
if (operation == PythonOperation.List) value = CardScaling.Add(value, (int)Math.Min(int.MaxValue, 2L * Math.Max(0, context.Card.QueuePlayCount - 1)));
if (operation == PythonOperation.Cinnamon && DamageThisPhase) value = 5;
if (operation == PythonOperation.Update && AutomationRan) value = 5;
var payload = new Payload { Card = context.Card.CopyForCombat(), Target = context.Targets.FirstOrDefault(), All = operation == PythonOperation.Update };
if (operation == PythonOperation.Cinnamon) payload.Shield = CardShieldExecutor.ScaleAmount(value, context);
else payload.Damage = CardDamageExecutor.ScaleAmount(value, context);
// Capture the operation once, before applying any temporary repeat/area transformations.
foreach (var script in _scripts.Where(s => s.Waiting))
{ script.Payload = payload; script.Waiting = false; script.FirstRound = _round + 1; }
bool all = payload.All;
if (!all && payload.Damage > 0 && _areas.Count > 0) { all = true; _areas.RemoveAt(0); }
int repeats = 1;
if (_loops.Count > 0) { repeats = 2; _loops.RemoveAt(0); }
for (int i = 0; i < repeats; i++)
{
Run(payload, all);
if (_combat.RunFinished || _combat.AwaitingWaveContinue || context.Source.IsDefeated) break;
}
return;
}
switch (operation)
{
case PythonOperation.Loop:
CardShieldExecutor.Execute(context, CardShieldExecutor.ScaleAmount(amount, context), "for loop");
_loops.Add(_round); break;
case PythonOperation.Zip:
CardDamageExecutor.Execute(context, () => CardDamageExecutor.ScaleAmount(amount, context), Language.Python);
_areas.Add(_round); break;
case PythonOperation.Draw: new FixedDrawEffect(amount).Execute(context); break;
case PythonOperation.Inspect: Inspect(context); break;
case PythonOperation.Install: Install(context); break;
case PythonOperation.Async:
AddScript(new Script { Name = "async def", Owner = context.Card.CopyForCombat(), Waiting = true }); break;
case PythonOperation.Unattended:
int shield = CardShieldExecutor.ScaleAmount(amount, context);
CardShieldExecutor.Execute(context, shield, "unattended-upgrades");
AddScript(new Script { Name = "unattended-upgrades", Owner = context.Card.CopyForCombat(), FirstRound = _round + 1,
Payload = new Payload { Card = context.Card.CopyForCombat(), Shield = shield } }); break;
case PythonOperation.Timeshift:
AddScript(new Script { Name = "timeshift snapshot", Owner = context.Card.CopyForCombat(), Restore = true,
Uptime = context.Source.CurrentUptime, FirstRound = _round + 1 }); break;
}
}
private void Run(Payload payload, bool all)
{
var target = payload.Target;
if (target == null || target.IsDefeated)
target = _combat.Enemies.Where(e => !e.State.IsDefeated).OrderBy(e => e.State.CurrentUptime).Select(e => e.State).FirstOrDefault();
var context = Context(payload.Card, target);
var before = _combat.Enemies.Select(e => (state: e.State, health: (long)e.State.CurrentUptime + e.State.Shield)).ToArray();
if (payload.Damage > 0) CardDamageExecutor.Execute(context, () => payload.Damage, Language.Python, allEnemies: all);
if (before.Any(e => (long)e.state.CurrentUptime + e.state.Shield < e.health)) DamageThisPhase = true;
if (payload.Shield > 0 && !_combat.PlayerState.IsDefeated) CardShieldExecutor.Execute(context, payload.Shield, "Python payload");
}
private void AddScript(Script script)
{
if (_scripts.Count < 2) { _scripts.Add(script); return; }
var existing = _scripts.ToArray();
Offer($"Install {script.Name}: replace a script (2/2 slots)", existing.Select((s, slot) => new PythonChoiceOption($"Slot {slot + 1}: {s.Name}"
+ (s.Name == "async def" && !s.Waiting ? " / " + s.Payload.Card.Definition.DisplayName : "")
+ (s.Waiting ? " — waiting for payload" : $" — {s.Remaining} runs left"))), index =>
{ _scripts.Remove(existing[index]); _scripts.Add(script); });
}
private void Inspect(CombatContext context)
{
var cards = context.DeckController.PeekTop(InspectCount(_combat.RunConfig?.Distro?.Id, _combat.RunConfig?.DistroVersion ?? 1)).ToArray();
if (cards.Length == 0) { _combat.ReportEffectResult("ask ubuntu: draw pile empty"); return; }
if (!cards.Any(context.HandController.CanAdd)) { _combat.ReportEffectResult("ask ubuntu: not enough RAM"); return; }
Offer("ask ubuntu: choose one card; the others keep their order", cards.Select(c =>
new PythonChoiceOption(c, _combat.GetDisplayedPlayCost(c),
context.HandController.CanAdd(c) ? $"> take card / {HandController.GetRamCost(c)} RAM" : $"needs {HandController.GetRamCost(c)} free RAM",
context.HandController.CanAdd(c))),
index => context.DeckController.TakeToHand(cards[index], context.HandController));
}
private void Install(CombatContext context)
{
if (context.HandController.RemainingRam < 1) { _combat.ReportEffectResult("apt install: not enough RAM"); return; }
var pool = _combat.GeneratedCardPool.Where(c => IsPythonCard(c) && !c.DistroExclusive && !c.IsToken && !c.IsJunk)
.GroupBy(c => c.Id).Select(g => g.First()).OrderBy(c => c.Id, StringComparer.Ordinal).ToList();
var offers = new List<CardDefinition>();
while (offers.Count < 3 && pool.Count > 0)
{ int index = RandomRoll.RollRange(0, pool.Count - 1, RollContext.None); offers.Add(pool[index]); pool.RemoveAt(index); }
if (offers.Count == 0) { _combat.ReportEffectResult("apt install: no Python packages available"); return; }
Offer("apt install: choose a temporary card (0 Cycles this turn; exhausts after play)", offers.Select(c =>
new PythonChoiceOption(new CardInstance(c) { ExhaustOnPlay = true }, 0, "> install / 1 RAM")), index =>
{
var card = new CardInstance(offers[index]) { ExhaustOnPlay = true };
if (!context.HandController.Add(card)) return;
_temporaryDiscounts[card] = card.TemporaryCostDelta;
card.TemporaryCostDelta = -card.Definition.CycleCost;
});
}
}
}
+3 -3
View File
@@ -15,12 +15,12 @@ namespace KernelPanic.Data
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")),
new(Language.Python, "Python", "pipelines and automation", ResolutionTrack.InterpreterQueue, "Preparation acts immediately. Payloads and modifiers resolve FIFO before enemies: for loop repeats the next payload, zip spreads a single-target payload to all enemies. Unused modifiers expire after the following round. Two automation slots run captured operations for two future rounds. Replays copy damage and Shield only, never draw, growth or installation. Scripts and modifiers clear each wave.", null, Distro("ubuntu", "Ubuntu"), Distro("kali", "Kali"), Distro("mint", "Mint")),
new(Language.JavaScript, "JavaScript", "runtime chaos", ResolutionTrack.Native, "JavaScript resolves immediately and is intentionally swingy: wide damage ranges, chance-based outcomes, and conditional repeat effects. It rewards embracing variance.", null, Distro("ubuntu", "Ubuntu"), Distro("endeavouros", "EndeavourOS"), Distro("mint", "Mint")),
new(Language.TypeScript, "TypeScript", "typed runtime", ResolutionTrack.Native, "TypeScript is planned as the steadier JavaScript branch: Native timing with less chaos and more controlled setup/payoff patterns.", "unlock: upgrade a JavaScript card during a run"),
new(Language.Haskell, "Haskell", "lazy proofs", ResolutionTrack.LazyStack, "Lazy proofs. Build a stack of delayed operations. Later cards gain stronger effects when evaluated. Snapshot x1.0 / x1.5 / x2.0 / x2.5 at play; LIFO after Python. Only damage and explicit Shield multiply.", null, Distro("gentoo", "Gentoo"), Distro("nixos", "NixOS")),
new(Language.Haskell, "Haskell", "lazy proofs", ResolutionTrack.LazyStack, "Lazy proofs. Build a stack of delayed operations. Later cards gain stronger effects when evaluated. Snapshot x1.5 / x1.75 / x2.0 / x2.5 at play; LIFO after Python. Only damage and explicit Shield multiply.", null, Distro("gentoo", "Gentoo"), Distro("nixos", "NixOS")),
new(Language.Assembly, "Assembly", "raw opcodes", ResolutionTrack.Native, "Assembly is planned as the most direct Native language: low-level, high-commitment effects that should trade flexibility for extreme precision or shield-bypass pressure.", null, Distro("templeos", "TempleOS")),
new(Language.Java, "Java", "warming vm", ResolutionTrack.Native, "Java cards are heavy but scale over the run: each Java card uses 2 RAM, Java damage spills overkill into other enemies, and JIT makes Java cards cheaper as you keep playing them. The discount cools after each wave.", null, Distro("debian", "Debian"), Distro("fedora", "Fedora")),
new(Language.Java, "Java", "warming vm", ResolutionTrack.Native, "Each Java card uses 2 RAM and spills overkill into other enemies. JIT gives -1 Cycle per 2 Java plays, capped at -3. Store at most 6 warmup plays; lose 2 after each wave, cooling the discount by 1.", null, Distro("debian", "Debian"), Distro("fedora", "Fedora")),
new(Language.Go, "Go", "small services", ResolutionTrack.Native, "Go is planned as a straightforward Native language for small, dependable actions. Its identity should be simple scaling, services, and concurrency-style utility without much randomness.", null, Distro("cachyos", "CachyOS"), Distro("nixos", "NixOS")),
new(Language.Ruby, "Ruby", "sharp scripts", ResolutionTrack.InterpreterQueue, "Ruby is planned as an interpreter-queue combo language: delayed scripting with expressive effects that should get better when sequenced with other queued cards.", null, Distro("kali", "Kali"), Distro("endeavouros", "EndeavourOS")),
new(Language.Php, "PHP", "legacy glue", ResolutionTrack.InterpreterQueue, "PHP is planned as a queued utility language that benefits from messy boards and legacy leftovers: practical, delayed effects that turn clutter into value.", null, Distro("debian", "Debian"), Distro("cachyos", "CachyOS")),
+100
View File
@@ -0,0 +1,100 @@
using System;
using System.Collections.Generic;
using System.IO;
using KernelPanic.Combat;
using KernelPanic.Core;
namespace KernelPanic.Meta
{
/// <summary>Records real gameplay immediately, independently of run rewards and checkpoints.</summary>
public sealed class DailyQuestTracker : IDisposable
{
private readonly SaveService _save;
private readonly Func<bool> _eligible;
private readonly Func<CombatantState> _player;
private readonly Func<DateTime> _utcNow;
private readonly List<(DailyQuestKind kind, int amount, DateTime time)> _pending = new();
public string SaveError { get; private set; }
public DailyQuestTracker(SaveService save, Func<bool> eligible, Func<CombatantState> player,
Func<DateTime> utcNow = null)
{
_save = save;
_eligible = eligible;
_player = player;
_utcNow = utcNow ?? (() => DateTime.UtcNow);
GameEvents.WaveCleared += OnWaveCleared;
GameEvents.CardPlayed += OnCardPlayed;
GameEvents.DamageDealt += OnDamageDealt;
GameEvents.PhaseChanged += OnPhaseChanged;
}
private void OnWaveCleared(WaveClearedEvent evt)
{
Record(DailyQuestKind.Waves, 1);
if (evt.WaveNumber == 5) Record(DailyQuestKind.WaveFive, 1);
}
private void OnCardPlayed(CardPlayedEvent evt)
{
Record(DailyQuestKind.Cards, 1);
if (evt.Track == ResolutionTrack.Native) Record(DailyQuestKind.NativeCards, 1);
}
private void OnPhaseChanged(PhaseChangedEvent evt)
{
if (evt.PreviousPhase == TurnPhase.EnemyProcess && evt.NextPhase == TurnPhase.GarbageCollection
&& _player()?.CurrentUptime > 0) Record(DailyQuestKind.SurviveRounds, 1);
}
private void OnDamageDealt(DamageDealtEvent evt)
{
var player = _player();
if (player != null && ReferenceEquals(evt.Source, player) && !ReferenceEquals(evt.Target, player))
{
Record(DailyQuestKind.Damage, evt.UptimeDamage);
Record(DailyQuestKind.ShieldDamage, evt.ShieldDamage);
}
else if (player != null && ReferenceEquals(evt.Target, player) && !ReferenceEquals(evt.Source, player))
Record(DailyQuestKind.BlockDamage, evt.ShieldDamage);
}
private void Record(DailyQuestKind kind, int amount)
{
if (!_eligible() || amount <= 0) return;
_pending.Add((kind, amount, _utcNow()));
Flush();
}
public bool Flush()
{
if (_pending.Count == 0) return true;
try
{
// Reload before every transaction so checkpoint and run settlement writes are preserved.
var data = _save.Load();
bool changed = false;
foreach (var entry in _pending)
changed |= DailyQuests.Record(data.dailyQuests, entry.kind, entry.amount, entry.time);
changed |= DailyQuests.Refresh(data.dailyQuests, _utcNow());
if (changed) _save.Save(data);
_pending.Clear();
SaveError = null;
return true;
}
catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException)
{
SaveError = ex.Message;
return false;
}
}
public void Dispose()
{
GameEvents.WaveCleared -= OnWaveCleared;
GameEvents.CardPlayed -= OnCardPlayed;
GameEvents.DamageDealt -= OnDamageDealt;
GameEvents.PhaseChanged -= OnPhaseChanged;
Flush();
}
}
}
+198
View File
@@ -0,0 +1,198 @@
using System;
using System.Collections.Generic;
namespace KernelPanic.Meta
{
// Keep values stable: selections and claim bits are persisted in player saves.
public enum DailyQuestKind { Waves, Cards, Damage, BlockDamage, NativeCards, ShieldDamage, SurviveRounds, WaveFive }
[Serializable]
public sealed class DailyQuestState
{
public long refreshAtUtcTicks;
public int waves;
public int cards;
public int damage;
public int claimedMask;
public DailyQuestKind[] selectedQuests;
public int selectionSeed;
public int blockedDamage;
public int nativeCards;
public int shieldDamage;
public int survivedRounds;
public int waveFive;
}
/// <summary>One persistent, rolling 24-hour window. All time comes from the caller for deterministic tests.</summary>
public static class DailyQuests
{
public const int Count = 3;
public const long PeriodTicks = TimeSpan.TicksPerDay;
public static readonly IReadOnlyList<DailyQuestKind> Pool = Array.AsReadOnly((DailyQuestKind[])Enum.GetValues(typeof(DailyQuestKind)));
private static readonly DailyQuestKind[] LegacySelection = { DailyQuestKind.Waves, DailyQuestKind.Cards, DailyQuestKind.Damage };
public static IReadOnlyList<DailyQuestKind> Active(DailyQuestState state) =>
ValidSelection(state.selectedQuests) ? state.selectedQuests : LegacySelection;
public static bool IsActive(DailyQuestState state, DailyQuestKind kind)
{
foreach (var selected in Active(state)) if (selected == kind) return true;
return false;
}
private static bool ValidSelection(DailyQuestKind[] selection)
{
if (selection == null || selection.Length != Count) return false;
for (int i = 0; i < selection.Length; i++)
{
if (!Enum.IsDefined(typeof(DailyQuestKind), selection[i])) return false;
for (int j = 0; j < i; j++) if (selection[i] == selection[j]) return false;
}
return true;
}
private static void PickQuests(DailyQuestState state)
{
if (state.selectionSeed == 0)
{
state.selectionSeed = Guid.NewGuid().GetHashCode();
if (state.selectionSeed == 0) state.selectionSeed = 1;
}
// Local randomness never consumes the combat, shop, or Unity RNG streams.
var random = new Random(unchecked(state.selectionSeed ^ (int)state.refreshAtUtcTicks ^ (int)(state.refreshAtUtcTicks >> 32)));
var candidates = (DailyQuestKind[])Enum.GetValues(typeof(DailyQuestKind));
for (int i = candidates.Length - 1; i > 0; i--)
{
int swap = random.Next(i + 1);
(candidates[i], candidates[swap]) = (candidates[swap], candidates[i]);
}
bool sameSet = ValidSelection(state.selectedQuests);
for (int i = 0; i < Count; i++) sameSet &= IsActive(state, candidates[i]);
if (sameSet) (candidates[Count - 1], candidates[Count]) = (candidates[Count], candidates[Count - 1]);
state.selectedQuests = new DailyQuestKind[Count];
Array.Copy(candidates, state.selectedQuests, Count);
}
public static int Target(DailyQuestKind kind) => kind switch
{
DailyQuestKind.Waves => 3,
DailyQuestKind.Cards => 25,
DailyQuestKind.Damage => 200,
DailyQuestKind.BlockDamage => 40,
DailyQuestKind.NativeCards => 15,
DailyQuestKind.ShieldDamage => 60,
DailyQuestKind.SurviveRounds => 8,
DailyQuestKind.WaveFive => 1,
_ => throw new ArgumentOutOfRangeException(nameof(kind))
};
// Routine actions < focused combat objectives < sustained/encounter-dependent play < wave-5 milestone.
// Display and settlement share this table; rewards are not persisted separately from claim flags.
public static (int Bandwidth, int Entropy) Reward(DailyQuestKind kind) => kind switch
{
DailyQuestKind.Cards => (75, 25),
DailyQuestKind.NativeCards => (75, 25),
DailyQuestKind.Damage => (100, 50),
DailyQuestKind.BlockDamage => (100, 50),
DailyQuestKind.Waves => (150, 75),
DailyQuestKind.ShieldDamage => (150, 75),
DailyQuestKind.SurviveRounds => (150, 75),
DailyQuestKind.WaveFive => (250, 125),
_ => throw new ArgumentOutOfRangeException(nameof(kind))
};
public static string Description(DailyQuestKind kind) => kind switch
{
DailyQuestKind.Waves => "Clear 3 waves",
DailyQuestKind.Cards => "Play 25 cards",
DailyQuestKind.Damage => "Deal 200 Uptime damage",
DailyQuestKind.BlockDamage => "Block 40 damage with Shield",
DailyQuestKind.NativeCards => "Play 15 Native cards",
DailyQuestKind.ShieldDamage => "Deal 60 damage to enemy Shields",
DailyQuestKind.SurviveRounds => "Survive 8 enemy rounds",
DailyQuestKind.WaveFive => "Clear wave 5",
_ => throw new ArgumentOutOfRangeException(nameof(kind))
};
public static int Progress(DailyQuestState state, DailyQuestKind kind) => Math.Clamp(kind switch
{
DailyQuestKind.Waves => state.waves,
DailyQuestKind.Cards => state.cards,
DailyQuestKind.Damage => state.damage,
DailyQuestKind.BlockDamage => state.blockedDamage,
DailyQuestKind.NativeCards => state.nativeCards,
DailyQuestKind.ShieldDamage => state.shieldDamage,
DailyQuestKind.SurviveRounds => state.survivedRounds,
DailyQuestKind.WaveFive => state.waveFive,
_ => throw new ArgumentOutOfRangeException(nameof(kind))
}, 0, Target(kind));
public static bool Claimed(DailyQuestState state, DailyQuestKind kind) =>
(state.claimedMask & (1 << (int)kind)) != 0;
public static bool Refresh(DailyQuestState state, DateTime utcNow)
{
long now = utcNow.ToUniversalTime().Ticks;
if (state.refreshAtUtcTicks > now && state.refreshAtUtcTicks <= DateTime.MaxValue.Ticks)
{
if (ValidSelection(state.selectedQuests)) return false;
// Schema 7 had three fixed quests. Preserve that day's progress and rewards.
state.selectedQuests = (DailyQuestKind[])LegacySelection.Clone();
return true;
}
// Advance by whole periods, retaining the original reset time even after days away.
if (state.refreshAtUtcTicks > 0 && !ValidSelection(state.selectedQuests))
state.selectedQuests = (DailyQuestKind[])LegacySelection.Clone();
state.refreshAtUtcTicks = state.refreshAtUtcTicks > 0 && state.refreshAtUtcTicks <= now
? state.refreshAtUtcTicks + ((now - state.refreshAtUtcTicks) / PeriodTicks + 1) * PeriodTicks
: now + PeriodTicks;
state.waves = state.cards = state.damage = state.claimedMask = 0;
state.blockedDamage = state.nativeCards = state.shieldDamage = state.survivedRounds = state.waveFive = 0;
PickQuests(state);
return true;
}
public static bool Record(DailyQuestState state, DailyQuestKind kind, int amount, DateTime utcNow)
{
if (amount <= 0 || !Enum.IsDefined(typeof(DailyQuestKind), kind)) return false;
bool changed = Refresh(state, utcNow);
// Delayed retries from an expired period must not count toward today's quests.
if (utcNow.ToUniversalTime().Ticks < state.refreshAtUtcTicks - PeriodTicks || !IsActive(state, kind)) return changed;
int previous = Progress(state, kind);
int next = (int)Math.Min(Target(kind), (long)previous + amount);
switch (kind)
{
case DailyQuestKind.Waves: state.waves = next; break;
case DailyQuestKind.Cards: state.cards = next; break;
case DailyQuestKind.Damage: state.damage = next; break;
case DailyQuestKind.BlockDamage: state.blockedDamage = next; break;
case DailyQuestKind.NativeCards: state.nativeCards = next; break;
case DailyQuestKind.ShieldDamage: state.shieldDamage = next; break;
case DailyQuestKind.SurviveRounds: state.survivedRounds = next; break;
case DailyQuestKind.WaveFive: state.waveFive = next; break;
}
return changed || next != previous;
}
public static bool Claim(SaveData data, DailyQuestKind kind, long expectedRefresh, DateTime utcNow)
{
data.dailyQuests ??= new DailyQuestState();
Refresh(data.dailyQuests, utcNow);
if (!Enum.IsDefined(typeof(DailyQuestKind), kind) || !IsActive(data.dailyQuests, kind) || data.dailyQuests.refreshAtUtcTicks != expectedRefresh
|| Claimed(data.dailyQuests, kind) || Progress(data.dailyQuests, kind) < Target(kind)) return false;
var reward = Reward(kind);
if (data.bandwidthBalance > int.MaxValue - reward.Bandwidth
|| data.entropyBalance > int.MaxValue - reward.Entropy) return false;
data.dailyQuests.claimedMask |= 1 << (int)kind;
data.bandwidthBalance += reward.Bandwidth;
data.entropyBalance += reward.Entropy;
return true;
}
public static string Countdown(DailyQuestState state, DateTime utcNow)
{
var remaining = TimeSpan.FromTicks(Math.Max(0, state.refreshAtUtcTicks - utcNow.ToUniversalTime().Ticks));
return $"refresh in {(int)remaining.TotalHours:00}:{remaining.Minutes:00}:{remaining.Seconds:00}";
}
}
}
+1 -1
View File
@@ -43,7 +43,7 @@ namespace KernelPanic.Meta
{
1 => "start of turn: apt update chooses the cheaper of top 2 draw cards",
2 => "apt update looks at top 3 instead of top 2",
3 => "ask ubuntu draws 3 instead of 2",
3 => "ask ubuntu inspects 5 cards instead of 3; take one",
4 => "apt update card costs 1 less this turn",
5 => "once per combat, empty hand refills up to RAM",
_ => "--"
+229 -5
View File
@@ -38,6 +38,13 @@ 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-python-ui-smoke") || args.Contains("--kernel-panic-route-ui-smoke"))
{
var fixture = SaveData.CreateDefault();
fixture.starterChosen = true;
fixture.ownedUnits.Add(new OwnedUnitSaveEntry { id = "ubuntu", version = 3 });
new SaveService().Save(fixture);
}
if (args.Contains("--kernel-panic-quest-ui-smoke"))
{
// The unused, isolated save-path guard above also applies to this UI fixture.
@@ -77,6 +84,18 @@ namespace KernelPanic.Run
try
{
if (_failure != null) throw new InvalidOperationException(_failure);
var choosingCombat = FindFirstObjectByType<CombatManager>();
if (choosingCombat?.Python.HasChoice == true && !Environment.GetCommandLineArgs().Contains("--kernel-panic-python-ui-smoke"))
{
var document = FindFirstObjectByType<CombatSceneController>()?.GetComponent<UIDocument>();
for (int i = 0; i < choosingCombat.Python.Choices.Count; i++)
{
var button = document?.rootVisualElement.Q<Button>($"PythonChoice{i}");
if (button?.enabledInHierarchy != true) continue;
Submit(button);
break;
}
}
if (Time.realtimeSinceStartup > _deadline) throw new TimeoutException("Smoke check timed out at " + _stage);
next = scenario.MoveNext();
if (next) yielded = scenario.Current;
@@ -107,6 +126,18 @@ 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-route-ui-smoke"))
{
var routeScenario = RouteUiScenario(menu);
while (routeScenario.MoveNext()) yield return routeScenario.Current;
yield break;
}
if (Environment.GetCommandLineArgs().Contains("--kernel-panic-python-ui-smoke"))
{
var pythonScenario = PythonUiScenario(menu);
while (pythonScenario.MoveNext()) yield return pythonScenario.Current;
yield break;
}
if (Environment.GetCommandLineArgs().Contains("--kernel-panic-quest-ui-smoke"))
{
var questScenario = QuestUiScenario(menu);
@@ -576,6 +607,186 @@ namespace KernelPanic.Run
commandInput.SendEvent(enter);
}
private IEnumerator RouteUiScenario(MainMenuController menu)
{
_stage = "route map UI fixture";
Call(menu, "CompleteBootIntro"); ConfigureMenu(menu); Call(menu, "BootSelectedPackage");
CombatManager combat = null;
while (combat == null || !combat.CanSurrenderRun)
{ yield return null; combat = FindFirstObjectByType<CombatManager>(); }
var view = FindFirstObjectByType<CombatSceneController>();
var run = combat.GetComponent<RunManager>();
var document = view.GetComponent<UIDocument>();
// UI fixture only: remove enemies to exercise real repository transitions without a combat bot.
Field<System.Collections.Generic.List<EnemyInstance>>(combat, "_enemies").Clear();
Call(combat, "CheckWin");
yield return null;
Submit(document.rootVisualElement.Q<Button>("BootNextWaveButton"));
var capture = CapturePanel(document, "route-map");
while (capture.MoveNext()) yield return capture.Current;
var back = document.rootVisualElement.Q<Button>("BackToRepositoryButton");
var next = document.rootVisualElement.Q<Button>("ConfirmRouteButton");
Require(Mathf.Abs(back.worldBound.width - next.worldBound.width) < 2, "Route footer buttons must have equal widths.");
Require(Mathf.Abs(back.worldBound.height - next.worldBound.height) < 2, "Route footer buttons must have equal heights.");
Require(next.worldBound.xMax <= document.rootVisualElement.worldBound.xMax, "Continue button exceeds the screen.");
var position = document.rootVisualElement.Q("CurrentMapPosition");
Require(position != null, "Map is missing the player's current position.");
if (Screen.height >= 720)
{
var viewport = document.rootVisualElement.Q<ScrollView>(className: "repository-body").contentViewport;
Require(position.Q<Label>(className: "route-map-here").worldBound.yMax <= viewport.worldBound.yMax + 1,
"Current-position marker should be visible together with the upcoming route.");
}
Submit(document.rootVisualElement.Q<Button>("RouteSacrifice"));
Require(document.rootVisualElement.Q("RouteEvent") == null, "Map must not contain event controls.");
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
Require(document.rootVisualElement.Q("RunMap") == null && document.rootVisualElement.Q("RouteEventScreen") != null,
"Entering a stop must open its own screen.");
string untouched = DeckSignature(run);
Submit(document.rootVisualElement.Q<Button>("BackToRouteButton"));
Require(document.rootVisualElement.Q("RunMap") != null && DeckSignature(run) == untouched, "Backing out of an event changed the deck.");
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
capture = CapturePanel(document, "route-sacrifice");
while (capture.MoveNext()) yield return capture.Current;
int count = run.RunDeck.Count, magnitude = run.RunDeck.Sum(c => c.MagnitudeBonus);
Require(document.rootVisualElement.Q<Button>("ConfirmRouteButton") == null, "Unresolved events must not offer departure.");
var commit = document.rootVisualElement.Q<Button>("ResolveRouteEventButton");
capture = CapturePanel(document, "route-sacrifice-confirm");
while (capture.MoveNext()) yield return capture.Current;
Submit(commit);
Require(run.RunDeck.Count == count - 1 && run.RunDeck.Sum(c => c.MagnitudeBonus) == magnitude + 4, "Sacrifice did not remove one card and grant +4 effect.");
string deck = DeckSignature(run);
Require(!document.rootVisualElement.Q<Button>("BackToRouteButton").enabledInHierarchy, "Committed stop must not allow undoing the path.");
Submit(document.rootVisualElement.Q<Button>("SaveAndExitRunButton"));
menu = null;
while (menu == null) { yield return null; menu = FindFirstObjectByType<MainMenuController>(); }
Call(menu, "ResumeSavedRun"); combat = null;
while (combat == null || !combat.AwaitingWaveContinue)
{ yield return null; combat = FindFirstObjectByType<CombatManager>(); }
view = FindFirstObjectByType<CombatSceneController>(); run = combat.GetComponent<RunManager>(); document = view.GetComponent<UIDocument>();
Require(DeckSignature(run) == deck && !run.RouteEventPending && !run.ResolveRouteEvent(skip: true), "Resume replayed or lost the route event.");
Submit(document.rootVisualElement.Q<Button>("BootNextWaveButton"));
capture = CapturePanel(document, "route-resumed");
while (capture.MoveNext()) yield return capture.Current;
for (int wave = 2; wave <= 3; wave++)
{
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
while (!combat.CanSurrenderRun) yield return null;
Require(run.CurrentWaveNumber == wave, "Map departure skipped a wave.");
Field<System.Collections.Generic.List<EnemyInstance>>(combat, "_enemies").Clear(); Call(combat, "CheckWin");
yield return null;
Submit(document.rootVisualElement.Q<Button>("BootNextWaveButton"));
if (run.BuildRewardPending)
{
Require(document.rootVisualElement.Q("RunMap") == null && document.rootVisualElement.Q("BuildRewardScreen") != null,
"Build reward must have its own screen.");
capture = CapturePanel(document, "build-reward");
while (capture.MoveNext()) yield return capture.Current;
Submit(document.rootVisualElement.Q<Button>("RewardBits"));
Require(document.rootVisualElement.Q("BuildRewardScreen") == null && document.rootVisualElement.Q("RunMap") != null,
"Claiming a reward must open the map.");
}
if (run.RouteEventPending)
{
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
Submit(document.rootVisualElement.Q<Button>("SkipRouteEventButton"));
}
capture = CapturePanel(document, "route-history-" + wave);
while (capture.MoveNext()) yield return capture.Current;
}
Require(run.AvailableRouteNodes.Count >= 2 && run.Journey.visits.Count == 2, "Expected branching routes and two past choices.");
var journal = document.rootVisualElement.Q<Foldout>("RouteHistory"); journal.value = true;
document.rootVisualElement.Q<ScrollView>(className: "repository-body").ScrollTo(journal);
capture = CapturePanel(document, "route-journal");
while (capture.MoveNext()) yield return capture.Current;
journal.value = false;
for (int wave = 4; wave <= RunJourney.BossWave; wave++)
{
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
while (!combat.CanSurrenderRun) yield return null;
Require(run.CurrentWaveNumber == wave && !run.CampaignChoicePending, "Extended route ended before its final boss.");
if (wave == RunJourney.BossWave)
Require(combat.Enemies.Count(e => e.ArchetypeId == "kernel_overseer") == 1, "Final tier did not lead to the boss.");
Field<System.Collections.Generic.List<EnemyInstance>>(combat, "_enemies").Clear(); Call(combat, "CheckWin");
yield return null;
Submit(document.rootVisualElement.Q<Button>("BootNextWaveButton"));
if (run.BuildRewardPending) Submit(document.rootVisualElement.Q<Button>("RewardBits"));
capture = CapturePanel(document, "route-stage-" + run.CurrentWaveNumber);
while (capture.MoveNext()) yield return capture.Current;
if (run.CampaignChoicePending) break;
if (run.RouteEventPending)
{
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
Submit(document.rootVisualElement.Q<Button>("SkipRouteEventButton"));
}
}
Require(run.CampaignChoicePending && run.Journey.visits.Count == 9, "Normal route must finish after nine route departures and ten battles.");
string completedDeck = DeckSignature(run), completedRun = run.RunId;
Submit(document.rootVisualElement.Q<Button>("ContinueEndlessButton"));
Require(run.Journey.endless && run.RunId == completedRun && DeckSignature(run) == completedDeck, "Survival transition lost the completed build.");
if (run.RouteEventPending)
{
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
Submit(document.rootVisualElement.Q<Button>("SkipRouteEventButton"));
}
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
while (!combat.CanSurrenderRun) yield return null;
Require(run.CurrentWaveNumber == 11, "Survival must start at wave eleven.");
capture = CapturePanel(document, "route-survival");
while (capture.MoveNext()) yield return capture.Current;
_campaignSuccess = "PASS: ten-wave route UI, separate rewards/events, sacrifice, exact save/resume, full travelled history, boss convergence and wave-eleven survival with the same build.";
}
private IEnumerator PythonUiScenario(MainMenuController menu)
{
_stage = "Python selection UI";
Call(menu, "CompleteBootIntro");
ConfigureMenu(menu);
Call(menu, "BootSelectedPackage");
CombatManager combat = null;
while (combat == null || !combat.CanSurrenderRun)
{
yield return null;
combat = FindFirstObjectByType<CombatManager>();
}
var view = FindFirstObjectByType<CombatSceneController>();
var document = view.GetComponent<UIDocument>();
var database = Field<CardDatabase>(view, "cardDatabase");
combat.HandController.Clear();
combat.HandController.SetRamCapacity(10);
foreach (string id in new[] { "ubuntu_apt_install", "ubuntu_ask_ubuntu", "ubuntu_unattended_upgrades" })
{
if (id == "ubuntu_ask_ubuntu")
foreach (string offer in new[] { "mint_timeshift", "ubuntu_ask_ubuntu", "lang_py_print", "shop_py_async_def", "shop_py_zip" })
combat.DeckController.AddToDrawPile(new CardInstance(database.FindById(offer)), false);
var card = new CardInstance(database.FindById(id));
var context = new CombatContext(card, combat.PlayerState, Array.Empty<CombatantState>(), combat,
combat.DamagePipeline, new StatusEffectController(), combat.DeckController, combat.HandController, combat.Enemies);
int repeats = id == "ubuntu_unattended_upgrades" ? 3 : 1;
for (int i = 0; i < repeats; i++)
foreach (var effect in CardEffectFactory.CreateEffects(card.Definition)) effect.Execute(context);
Call(view, "RefreshOverlay");
yield return null;
Require(combat.Python.HasChoice, "Expected a Python choice for " + id);
var capture = CapturePanel(document, id);
while (capture.MoveNext()) yield return capture.Current;
var dialog = document.rootVisualElement.Q("PythonChoiceDialog");
Require(dialog != null && dialog.worldBound.yMin >= -1
&& dialog.worldBound.yMax <= document.rootVisualElement.worldBound.yMax + 1, "Choice dialog exceeds viewport.");
if (id == "ubuntu_ask_ubuntu")
{
Require(combat.Python.Choices.Count == 5, "Ubuntu V3 must offer five cards.");
var last = dialog.Q<Button>("PythonChoice4");
last.Focus();
capture = CapturePanel(document, "inspect-last-card");
while (capture.MoveNext()) yield return capture.Current;
}
Submit(dialog.Query<Button>().ToList().First(button => button.enabledInHierarchy));
Require(!combat.Python.HasChoice, "Submitting a card must resolve the choice.");
}
_campaignSuccess = "PASS: install, Ubuntu V3 five-card inspection, Timeshift description, script replacement, keyboard selection and runtime panel captures.";
}
private IEnumerator QuestUiScenario(MainMenuController menu)
{
_stage = "daily quest widget";
@@ -659,7 +870,8 @@ namespace KernelPanic.Run
{
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,
Require(combat.AwaitingWaveContinue && (document.rootVisualElement.Q("RouteSelectionScreen") != null
|| document.rootVisualElement.Q("BuildRewardScreen") != null),
"Boot must open route selection before starting combat.");
if (run.BuildRewardPending)
{
@@ -679,7 +891,13 @@ namespace KernelPanic.Run
: 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"));
var repair = document.rootVisualElement.Q<Button>("RouteRepair");
if (repair?.enabledInHierarchy == true) Submit(repair);
if (run.RouteEventPending)
{
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
Submit(document.rootVisualElement.Q<Button>("SkipRouteEventButton"));
}
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
}
else if (combat.CanSurrenderRun)
@@ -716,7 +934,7 @@ namespace KernelPanic.Run
}
yield return null;
}
Require(!combat.RunLost && run.WavesCleared == 5 && capturedBoss, "Seeded campaign bot did not clear the boss.");
Require(!combat.RunLost && run.WavesCleared == RunJourney.BossWave && capturedBoss, "Seeded campaign bot did not clear the boss.");
_stage = "campaign milestone";
Submit(document.rootVisualElement.Q<Button>("BootNextWaveButton"));
var milestone = CapturePanel(document, "campaign-milestone");
@@ -728,8 +946,14 @@ namespace KernelPanic.Run
if (endless)
{
Submit(document.rootVisualElement.Q<Button>("ContinueEndlessButton"));
if (run.RouteEventPending)
{
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
Submit(document.rootVisualElement.Q<Button>("SkipRouteEventButton"));
}
Submit(document.rootVisualElement.Q<Button>("ConfirmRouteButton"));
while (!combat.CanSurrenderRun) yield return null;
Require(run.Journey.endless && run.CurrentWaveNumber == 6 && run.RunId == runId && !run.RewardsSettled,
Require(run.Journey.endless && run.CurrentWaveNumber == RunJourney.BossWave + 1 && run.RunId == runId && !run.RewardsSettled,
"Endless continuation reset the build/run or settled rewards early.");
var capture = CapturePanel(document, "endless-encounter");
while (capture.MoveNext()) yield return capture.Current;
@@ -747,7 +971,7 @@ namespace KernelPanic.Run
while (FindFirstObjectByType<MainMenuController>() == null) yield return null;
saved = new SaveService().Load();
Require(saved.recentRuns.Count == 1 && saved.bandwidthBalance == expectedBandwidth, "Scene unload duplicated campaign rewards.");
_campaignSuccess = "PASS: real five-wave campaign, repair route, purchases, boss, "
_campaignSuccess = "PASS: real ten-wave campaign, repair route, purchases, boss, "
+ (endless ? "endless continuation, surrender" : "victory") + ", saved rewards/history exactly once, menu return.";
}
+2 -1
View File
@@ -43,9 +43,10 @@ namespace KernelPanic.Run
public ResolvedRunCheckpoint Resolve(DistroDatabase distros, CardDatabase cards,
LanguageDeckDatabase languages, PackageDatabase packageDatabase)
{
Require(version >= 1 && version <= 3, "This checkpoint needs a different game version.");
Require(version >= 1 && version <= 4, "This checkpoint needs a different game version.");
Require(version < 2 || journey != null, "Missing saved route decisions.");
journey?.Validate(wave);
journey?.ValidateMap(seed, wave);
Require(Guid.TryParseExact(runId, "N", out _), "Invalid run identity.");
Require(wave >= 2 && wave <= 100000 && wavesCleared == wave - 1, "Invalid checkpoint wave.");
Require(bits >= 0 && bandwidth >= 0 && entropy >= 0 && rerolls >= 0, "Invalid checkpoint balances.");
+57 -11
View File
@@ -1,14 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace KernelPanic.Run
{
public enum WaveRoute { Repair, Challenge }
public enum WaveRoute { Repair, Challenge, Encounter, Cache, Forge, Sacrifice, Recycle }
/// <summary>Serializable route decisions, independent of combat and repository presentation.</summary>
[Serializable]
public sealed class RunJourney
{
public const int BossWave = 5;
public const int BossWave = 10;
public const int LegacyBossWave = 5;
public const int RepairUptime = 6;
public const int ChallengeBits = 4;
public bool campaign;
@@ -19,23 +22,66 @@ namespace KernelPanic.Run
public int encounterRevision;
public int pendingRewardWave;
public int claimedRewardWave;
public int mapRevision;
public int mapStartWave = 2;
public int selectedNodeId;
public int resolvedEventWave;
public string eventOutcome;
public List<RouteVisit> visits = new();
public bool AtMilestone(int wavesCleared) => campaign && !endless && wavesCleared >= BossWave;
public static RunJourney NewCampaign() => new() { campaign = true, encounterRevision = 1 };
public RunJourney Copy() => (RunJourney)MemberwiseClone();
// Revisions are persisted: an existing route must never change underneath its saved decisions.
public int FinalWave => encounterRevision >= 2 ? BossWave : LegacyBossWave;
public bool IsRewardWave(int wave) => encounterRevision > 0 && wave >= 2 && wave < FinalWave && wave % 2 == 0;
public bool AtMilestone(int wavesCleared) => campaign && !endless && wavesCleared >= FinalWave;
public static RunJourney NewCampaign() => new() { campaign = true, encounterRevision = 2, mapRevision = 2 };
public RunJourney Copy()
{
var copy = (RunJourney)MemberwiseClone();
copy.visits = (visits ?? new List<RouteVisit>()).Select(v => v.Copy()).ToList();
return copy;
}
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)
RunCheckpoint.Require(encounterRevision >= 0 && encounterRevision <= 2, "Unsupported encounter revision.");
RunCheckpoint.Require((pendingRewardWave == 0 || IsRewardWave(pendingRewardWave))
&& (claimedRewardWave == 0 || IsRewardWave(claimedRewardWave))
&& claimedRewardWave < wave
&& (pendingRewardWave == 0 || (campaign && encounterRevision == 1
&& (pendingRewardWave == 0 || (campaign && encounterRevision > 0
&& 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.");
RunCheckpoint.Require(!campaign || endless || wave <= BossWave + 1, "Missing campaign completion choice.");
RunCheckpoint.Require(!endless || (campaign && wave > FinalWave), "Invalid endless-mode checkpoint.");
RunCheckpoint.Require(!campaign || endless || wave <= FinalWave + 1, "Missing campaign completion choice.");
RunCheckpoint.Require(mapRevision >= 0 && mapRevision <= 2, "Unsupported route map.");
if (mapRevision == 0) return;
RunCheckpoint.Require(campaign && mapStartWave >= 2 && mapStartWave <= wave,
"Invalid route map start.");
RunCheckpoint.Require(visits != null && visits.Count <= wave && visits.All(v => v != null
&& v.wave >= mapStartWave && v.wave < wave && v.nodeId / 10 == v.wave
&& Enum.IsDefined(typeof(WaveRoute), v.route) && v.cleared), "Invalid route history.");
RunCheckpoint.Require(visits.Select(v => v.wave).Distinct().Count() == visits.Count,
"Duplicate route history.");
RunCheckpoint.Require(resolvedEventWave == 0 || resolvedEventWave == wave,
"Invalid route event claim.");
}
public void ValidateMap(int seed, int wave)
{
if (mapRevision == 0) return;
RouteNode previous = null;
foreach (var visit in visits)
{
var node = RunRouteMap.Row(seed, visit.wave, mapStartWave, mapRevision).FirstOrDefault(n => n.Id == visit.nodeId);
RunCheckpoint.Require(node != null && node.Route == visit.route
&& (previous == null ? visit.wave == mapStartWave : RunRouteMap.Connected(seed, previous, node, mapStartWave, mapRevision)),
"Disconnected route history.");
previous = node;
}
RunCheckpoint.Require(visits.Count == Math.Max(0, wave - mapStartWave), "Incomplete route history.");
var selected = RunRouteMap.Available(seed, wave, this).FirstOrDefault(n => n.Id == selectedNodeId);
RunCheckpoint.Require(selected != null && selected.Route == selectedRoute, "Unavailable saved route.");
RunCheckpoint.Require(resolvedEventWave == 0 || RunRouteMap.IsEvent(selectedRoute), "Unexpected event claim.");
}
}
}
+114 -3
View File
@@ -59,6 +59,80 @@ namespace KernelPanic.Run
public bool CampaignChoicePending => Journey.AtMilestone(_wavesCleared);
public bool BuildRewardPending => Journey.pendingRewardWave > 0;
public const int BuildRewardBits = 8;
public bool RouteEventPending => Journey.mapRevision > 0 && RunRouteMap.IsEvent(Journey.selectedRoute)
&& Journey.resolvedEventWave != currentWaveNumber;
public IReadOnlyList<RouteNode> AvailableRouteNodes => CurrentConfig == null ? Array.Empty<RouteNode>()
: RunRouteMap.Available(CurrentConfig.RunSeed, currentWaveNumber, Journey);
private void EnsureRouteSelection()
{
if (Journey.mapRevision == 0) return;
var available = AvailableRouteNodes;
if (available.Any(n => n.Id == Journey.selectedNodeId)) return;
var node = available.FirstOrDefault(n => n.Route == WaveRoute.Repair)
?? available.FirstOrDefault(n => !RunRouteMap.IsEvent(n.Route)) ?? available.FirstOrDefault();
if (node == null) return;
Journey.selectedNodeId = node.Id;
Journey.selectedRoute = node.Route;
}
public bool SelectRouteNode(int nodeId)
{
if (!isRunActive || IsSuspended || !_repositoryVisitActive || CampaignChoicePending
|| Journey.mapRevision == 0 || Journey.resolvedEventWave == currentWaveNumber) return false;
var node = AvailableRouteNodes.FirstOrDefault(n => n.Id == nodeId);
if (node == null) return false;
Journey.selectedNodeId = node.Id;
Journey.selectedRoute = node.Route;
RepositoryChanged?.Invoke();
return true;
}
public bool CanImproveRouteCard(CardInstance card)
{
if (card?.Definition == null || !_runDeck.Contains(card) || card.Definition.IsToken || card.Definition.IsJunk
|| card.MagnitudeBonus > int.MaxValue - 4 || card.UpgradeLevel == int.MaxValue) return false;
var preview = card.CopyForCombat();
preview.ApplyMagnitudeUpgrade(2);
return CardEffectFactory.GetRulesText(preview, CurrentConfig).Replace(" [upgraded]", "")
!= CardEffectFactory.GetRulesText(card, CurrentConfig).Replace(" [upgraded]", "");
}
public bool ResolveRouteEvent(CardInstance donor = null, CardInstance target = null, bool skip = false)
{
if (!isRunActive || IsSuspended || !_repositoryVisitActive || CampaignChoicePending || BuildRewardPending
|| !RouteEventPending || !AvailableRouteNodes.Any(n => n.Id == Journey.selectedNodeId)) return false;
string outcome;
if (skip) outcome = "Passed without changing the deck.";
else
{
bool remove = Journey.selectedRoute is WaveRoute.Sacrifice or WaveRoute.Recycle;
bool upgrade = Journey.selectedRoute is WaveRoute.Sacrifice or WaveRoute.Forge;
if (remove && (donor?.Definition == null || !_runDeck.Contains(donor) || donor.Definition.IsToken
|| _runDeck.Count <= 1 || (Journey.selectedRoute == WaveRoute.Sacrifice && donor.Definition.IsJunk))) return false;
if (upgrade && (ReferenceEquals(donor, target) || !CanImproveRouteCard(target))) return false;
if (Journey.selectedRoute == WaveRoute.Recycle && _bits > int.MaxValue - 4) return false;
int bonus = Journey.selectedRoute == WaveRoute.Sacrifice ? 4 : 2;
if (upgrade) target.ApplyMagnitudeUpgrade(bonus);
if (remove)
{
_runDeck.Remove(donor);
_repositoryOffers.RemoveAll(o => !o.Sold && o.Kind == RepositoryOfferKind.CardUpgrade && o.TargetCard == donor);
}
if (Journey.selectedRoute == WaveRoute.Recycle) _bits += 4;
outcome = Journey.selectedRoute switch
{
WaveRoute.Sacrifice => $"Sacrificed {donor.Definition.DisplayName}; {target.Definition.DisplayName} gained +4 effect.",
WaveRoute.Forge => $"Patched {target.Definition.DisplayName}: +2 effect.",
_ => $"Recycled {donor.Definition.DisplayName}: +4 Bits."
};
}
Journey.resolvedEventWave = currentWaveNumber;
Journey.eventOutcome = outcome;
Journey.lastReward = outcome;
RepositoryChanged?.Invoke();
return true;
}
public bool ClaimBuildReward(CardInstance card, CardUpgradeKind kind, bool takeBits = false)
{
@@ -82,6 +156,11 @@ namespace KernelPanic.Run
{
if (!isRunActive || IsSuspended || !_repositoryVisitActive || CampaignChoicePending
|| !Enum.IsDefined(typeof(WaveRoute), route)) return false;
if (Journey.mapRevision > 0)
{
var node = AvailableRouteNodes.FirstOrDefault(n => n.Route == route);
return node != null && SelectRouteNode(node.Id);
}
Journey.selectedRoute = route;
RepositoryChanged?.Invoke();
return true;
@@ -98,10 +177,25 @@ 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 || BuildRewardPending) return;
if (!_repositoryVisitActive || !isRunActive || IsSuspended || CampaignChoicePending || BuildRewardPending || RouteEventPending) return;
if (Journey.mapRevision > 0 && !AvailableRouteNodes.Any(n => n.Id == Journey.selectedNodeId)) return;
Journey.activeRoute = Journey.selectedRoute;
string outcome = Journey.eventOutcome;
if (Journey.campaign && Journey.activeRoute == WaveRoute.Repair && player != null)
{
int before = player.CurrentUptime;
player.CurrentUptime = Mathf.Min(player.MaxUptime, player.CurrentUptime + RunJourney.RepairUptime);
outcome = $"Restored {player.CurrentUptime - before} Uptime.";
}
if (Journey.activeRoute == WaveRoute.Cache)
{
int reward = Math.Min(6, int.MaxValue - _bits);
_bits += reward;
outcome = $"Recovered {reward} Bits.";
}
if (Journey.mapRevision > 0)
Journey.visits.Add(new RouteVisit { wave = currentWaveNumber, nodeId = Journey.selectedNodeId,
route = Journey.activeRoute, outcome = outcome ?? RunRouteMap.Title(Journey.activeRoute) });
_repositoryVisitActive = false;
}
@@ -170,7 +264,7 @@ namespace KernelPanic.Run
bandwidth = _accruedBandwidth, entropy = _accruedEntropy,
maxUptimeBonus = _maxUptimeBonus, maxCyclesBonus = _maxCyclesBonus, ramBonus = _ramBonus,
rerolls = _rerollsThisVisit, shopRandomDraws = _repositoryRandom.Draws,
version = 3, journey = Journey.Copy(),
version = 4, journey = Journey.Copy(),
combat = combat.CaptureBoundaryState()
};
foreach (PackageInstance package in CurrentConfig.EquippedPackages)
@@ -217,6 +311,15 @@ namespace KernelPanic.Run
_soldOfferKeys.Clear();
foreach (string key in snapshot.soldKeys) _soldOfferKeys.Add(key);
_repositoryVisitActive = true;
// Old saves begin a map here; do not invent decisions for earlier waves.
if (Journey.campaign && Journey.mapRevision == 0)
{
Journey.mapRevision = 1;
Journey.mapStartWave = currentWaveNumber;
Journey.selectedNodeId = RunRouteMap.Row(CurrentConfig.RunSeed, currentWaveNumber, currentWaveNumber, 1)
.FirstOrDefault(n => n.Route == Journey.selectedRoute)?.Id ?? 0;
}
EnsureRouteSelection();
}
public void AddBits(int amount)
@@ -237,6 +340,7 @@ namespace KernelPanic.Run
_soldOfferKeys.Clear();
FillRepositoryOffers(cardDatabase, languageDeckDatabase);
_repositoryVisitActive = true;
EnsureRouteSelection();
RepositoryChanged?.Invoke();
}
@@ -389,6 +493,8 @@ namespace KernelPanic.Run
{
int clearedWave = Mathf.Max(1, payload.WaveNumber);
if (!isRunActive || clearedWave <= _wavesCleared) return;
var visit = Journey.visits?.LastOrDefault(v => v.wave == clearedWave);
if (visit != null) visit.cleared = true;
Journey.lastReward = null;
if (Journey.campaign && clearedWave > 1 && Journey.activeRoute == WaveRoute.Challenge)
{
@@ -405,9 +511,13 @@ namespace KernelPanic.Run
_bits += RunJourney.ChallengeBits;
Journey.lastReward = $"Challenge cleared: +{RunJourney.ChallengeBits * 2} Bits (all cards already have draw riders).";
}
if (visit != null) visit.outcome = Journey.lastReward;
}
Journey.selectedRoute = WaveRoute.Repair;
if (Journey.campaign && Journey.encounterRevision > 0 && (clearedWave == 2 || clearedWave == 4))
Journey.selectedNodeId = 0;
Journey.resolvedEventWave = 0;
Journey.eventOutcome = null;
if (Journey.campaign && Journey.IsRewardWave(clearedWave))
Journey.pendingRewardWave = clearedWave;
_wavesCleared = Mathf.Max(_wavesCleared, clearedWave);
if (CurrentConfig?.IsTutorial != true)
@@ -416,6 +526,7 @@ namespace KernelPanic.Run
_accruedEntropy += CalculateEntropyReward(clearedWave);
}
currentWaveNumber = Mathf.Max(currentWaveNumber + 1, payload.WaveNumber + 1);
EnsureRouteSelection();
_repositoryOffers.Clear();
_rerollsThisVisit = 0;
_soldOfferKeys.Clear();
+137
View File
@@ -0,0 +1,137 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace KernelPanic.Run
{
public sealed class RouteNode
{
public int Wave { get; }
public int Lane { get; }
public int Id => Wave * 10 + Lane;
public WaveRoute Route { get; }
public RouteNode(int wave, int lane, WaveRoute route) { Wave = wave; Lane = lane; Route = route; }
}
[Serializable]
public sealed class RouteVisit
{
public int wave, nodeId;
public WaveRoute route;
public string outcome;
public bool cleared;
public RouteVisit Copy() => (RouteVisit)MemberwiseClone();
}
/// <summary>Stable topology and public event previews. Never consumes combat or shop randomness.</summary>
public static class RunRouteMap
{
private static uint Hash(int seed, int wave)
{
uint value = unchecked((uint)seed ^ (uint)wave * 0x9E3779B9u ^ 0xA37151E7u);
value ^= value >> 16; value = unchecked(value * 0x7FEB352Du);
value ^= value >> 15; return value;
}
public static IReadOnlyList<RouteNode> Row(int seed, int wave, int startWave = 2)
=> Row(seed, wave, startWave, 2);
public static IReadOnlyList<RouteNode> Row(int seed, int wave, int startWave, int revision)
{
if (wave < startWave) return Array.Empty<RouteNode>();
if (revision >= 2)
{
if (wave == RunJourney.BossWave)
return new[] { new RouteNode(wave, 1, WaveRoute.Encounter) };
if (wave == startWave)
return new[] { new RouteNode(wave, 0, WaveRoute.Repair), new RouteNode(wave, 1, WaveRoute.Challenge), new RouteNode(wave, 2, WaveRoute.Sacrifice) };
uint roll = Hash(seed, wave);
// Three lanes keep two alternatives reachable even at the outer edge.
// Occasional four-lane tiers widen the route, then merge back on even waves.
int width = wave % 2 == 1 && (roll & 1) != 0 ? 4 : 3;
// Every tier has recovery and a useful alternative; at most one optional elite.
var utility = new[] { WaveRoute.Forge, WaveRoute.Cache, WaveRoute.Recycle, WaveRoute.Sacrifice };
var routes = new List<WaveRoute> { WaveRoute.Repair, utility[(roll >> 4) % 4] };
bool elite = wave >= 7 || (wave >= 4 && (roll & 8) != 0);
if (width > 2) routes.Add(elite ? WaveRoute.Challenge : utility[((roll >> 4) + 1) % 4]);
if (width > 3) routes.Add(utility[((roll >> 4) + 2) % 4]);
// Keep recovery near the middle, instead of isolating it on an edge path.
(routes[0], routes[1]) = (routes[1], routes[0]);
return routes.Select((route, lane) => new RouteNode(wave, lane, route)).ToArray();
}
if (wave == startWave)
return new[] { new RouteNode(wave, 0, WaveRoute.Repair), new RouteNode(wave, 1, WaveRoute.Challenge), new RouteNode(wave, 2, WaveRoute.Sacrifice) };
if (wave == RunJourney.LegacyBossWave || (wave - startWave) % 3 == 2)
return new[] { new RouteNode(wave, 1, WaveRoute.Encounter) };
uint hash = Hash(seed, wave);
var pool = new[] { WaveRoute.Cache, WaveRoute.Forge, WaveRoute.Recycle, WaveRoute.Repair, WaveRoute.Challenge, WaveRoute.Sacrifice };
int count = (hash & 1) == 0 ? 2 : 3;
int offset = (int)((hash >> 4) % (uint)pool.Length);
return Enumerable.Range(0, count).Select(i => new RouteNode(wave, count == 2 ? i * 2 : i,
pool[(offset + i) % pool.Length])).ToArray();
}
public static bool Connected(int seed, RouteNode from, RouteNode to, int startWave = 2)
=> Connected(seed, from, to, startWave, 2);
public static bool Connected(int seed, RouteNode from, RouteNode to, int startWave, int revision)
{
if (from == null || to == null || to.Wave != from.Wave + 1) return false;
var before = Row(seed, from.Wave, startWave, revision).ToList();
var after = Row(seed, to.Wave, startWave, revision).ToList();
int a = before.FindIndex(n => n.Id == from.Id), b = after.FindIndex(n => n.Id == to.Id);
if (a < 0 || b < 0) return false;
if (before.Count == 1 || after.Count == 1) return true;
if (revision >= 2)
{
// Neighbouring lanes branch and merge, never jump across the whole map.
// Normalized positions keep every lane connected when tier widths change.
float x = (float)a / (before.Count - 1), y = (float)b / (after.Count - 1);
if (before.Count == 3 && after.Count == 4 && a == 1)
return b != ((Hash(seed, from.Wave) & 1) == 0 ? 3 : 0);
return Math.Abs(x - y) <= .51f;
}
uint hash = Hash(seed, from.Wave);
int target = (hash & 2) == 0 ? a % after.Count : after.Count - 1 - a % after.Count;
// A spanning set gives every node an entrance and exit; optional side paths add forks.
if (b == target) return true;
bool hasEntrance = Enumerable.Range(0, before.Count).Any(i =>
((hash & 2) == 0 ? i % after.Count : after.Count - 1 - i % after.Count) == b);
if (!hasEntrance && a == 0) return true;
return ((hash >> (a + 3)) & 1) != 0 && b == (target + 1) % after.Count;
}
public static IReadOnlyList<RouteNode> Available(int seed, int wave, RunJourney journey)
{
var row = Row(seed, wave, journey.mapStartWave, journey.mapRevision);
var previous = journey.visits?.LastOrDefault(v => v.wave == wave - 1);
if (previous == null) return row;
var from = Row(seed, wave - 1, journey.mapStartWave, journey.mapRevision).FirstOrDefault(n => n.Id == previous.nodeId);
return row.Where(to => Connected(seed, from, to, journey.mapStartWave, journey.mapRevision)).ToArray();
}
public static bool IsEvent(WaveRoute route) => route is WaveRoute.Forge or WaveRoute.Sacrifice or WaveRoute.Recycle;
public static string Title(WaveRoute route) => route switch
{
WaveRoute.Repair => "Repair stop", WaveRoute.Challenge => "Elite detour",
WaveRoute.Cache => "Lost cache", WaveRoute.Forge => "Patch workshop",
WaveRoute.Sacrifice => "Sacrifice altar", WaveRoute.Recycle => "Recycler",
_ => "Direct route"
};
public static string Symbol(WaveRoute route) => route switch
{
WaveRoute.Repair => "+", WaveRoute.Challenge => "!", WaveRoute.Cache => "$",
WaveRoute.Forge => "^", WaveRoute.Sacrifice => "X", WaveRoute.Recycle => "-", _ => ">"
};
public static string Detail(WaveRoute route) => route switch
{
WaveRoute.Repair => "Restore up to 6 Uptime on departure.",
WaveRoute.Challenge => "Fight an extra Daemon. On clear: +4 Bits and a draw rider on the first eligible card; +4 more Bits if none is eligible.",
WaveRoute.Cache => "Recover 6 Bits on departure. No extra enemy.",
WaveRoute.Forge => "Choose a card to gain +2 effect magnitude for this run. You may pass.",
WaveRoute.Sacrifice => "Remove one card from this run's deck. Give a different card +4 effect magnitude for this run. You may pass.",
WaveRoute.Recycle => "Remove one card from this run's deck and recover 4 Bits. You may pass.",
_ => "A direct continuation to the next battle. No extra reward or enemy."
};
}
}
+2 -2
View File
@@ -152,8 +152,8 @@ namespace KernelPanic.Run
return new[] {
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("queue-intro", "Python builds a pipeline", "Preparation acts immediately. Payloads and modifiers wait until End turn, oldest first (FIFO). Scripts run before the queue.", "TutorialQueue"),
new TutorialStep("select-python", "Select the Python card", "Click print(), then choose the highlighted enemy. This payload can later be repeated by for loop or spread by zip.", "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", "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"),
+6 -1
View File
@@ -53,6 +53,11 @@ namespace KernelPanic.UI
public static VisualElement BuildBrowser(string initialPile,
IReadOnlyDictionary<string, IReadOnlyList<CardInstance>> inventories, Action close,
Func<CardInstance, string> costDetails = null)
=> BuildBrowser(initialPile, inventories, close, costDetails, CardEffectFactory.GetRulesText);
public static VisualElement BuildBrowser(string initialPile,
IReadOnlyDictionary<string, IReadOnlyList<CardInstance>> inventories, Action close,
Func<CardInstance, string> costDetails, Func<CardInstance, string> rulesText)
{
var piles = inventories.ToDictionary(pair => pair.Key,
pair => (pair.Value ?? Array.Empty<CardInstance>()).Where(card => card?.Definition != null).ToArray());
@@ -180,7 +185,7 @@ namespace KernelPanic.UI
var card = copies[0];
var face = new VisualElement { name = "PileCard", userData = copies.Length };
face.AddToClassList("pile-card");
SoftwareCardView.Populate(face, card, CombatManager.GetCardCost(card));
SoftwareCardView.Populate(face, card, CombatManager.GetCardCost(card), rulesText(card));
face.Q<Label>(className: "software-cost").text = $"{CombatManager.GetCardCost(card)}c stored";
// The full rules remain inline; no hover is required for keyboard or touch readers.
face.tooltip = string.Empty;
@@ -1795,7 +1795,7 @@ namespace KernelPanic.UI
summary.Add(meta);
row.Add(summary);
Label description = new(GetCardCollectionDescription(entry.Card));
Label description = new(GetOwnedCardRules(entry.Card));
description.AddToClassList("package-description");
row.Add(description);
return row;
@@ -1810,7 +1810,7 @@ namespace KernelPanic.UI
if (card == null) return;
var manifest = new VisualElement();
manifest.AddToClassList("collection-manifest");
SoftwareCardView.Populate(manifest, new CardInstance(card), card.CycleCost);
SoftwareCardView.Populate(manifest, new CardInstance(card), card.CycleCost, GetOwnedCardRules(card));
_detail.Add(manifest);
if (!string.IsNullOrWhiteSpace(card.FlavorText))
{
@@ -1820,6 +1820,13 @@ namespace KernelPanic.UI
}
}
private string GetOwnedCardRules(CardDefinition card)
{
var distro = _units.FirstOrDefault(unit => unit.ExclusiveCards.Contains(card));
return distro == null ? GetCardCollectionDescription(card)
: CardEffectFactory.GetRulesText(new CardInstance(card), distro.Id, GetUnitVersion(distro));
}
private static string GetCardCollectionDescription(CardDefinition card)
{
if (card == null)
@@ -1827,11 +1834,6 @@ namespace KernelPanic.UI
return "--";
}
if (!string.IsNullOrWhiteSpace(card.Description))
{
return card.Description;
}
string rulesText = CardEffectFactory.GetRulesText(new CardInstance(card));
return string.IsNullOrWhiteSpace(rulesText) || rulesText == "effect not authored." ? "--" : rulesText;
}
+189 -25
View File
@@ -117,6 +117,7 @@ namespace KernelPanic.UI
private string _saveError;
private string _checkpointError;
private bool _routeSelectionOpen;
private bool _routeEventOpen;
private DailyQuestTracker _dailyQuestTracker;
private IVisualElementScheduledItem _dailyQuestSaveSchedule;
private CombatRunTelemetry _runTelemetry;
@@ -500,7 +501,11 @@ namespace KernelPanic.UI
_lazyStackPile.name = "TutorialStack";
_queueView = new ExecutionTrackView(_interpreterStrip, false);
_stackView = new ExecutionTrackView(_lazyStackPile, true);
_tokenArea = AddTrackZone(scheduler, "|| goroutines", "no active runtime", "track-zone-token");
_tokenArea = AddTrackZone(scheduler, "py automation", "2 script slots / expires at wave end", "track-zone-token");
_tokenArea.name = "PythonAutomationReadout";
_tokenArea.style.flexDirection = FlexDirection.Column;
_tokenArea.style.alignItems = Align.Stretch;
_tokenArea.style.width = Length.Percent(100);
_root.Add(scheduler);
VisualElement bottom = new();
@@ -648,7 +653,7 @@ namespace KernelPanic.UI
header.Add(subtitleLabel);
zone.Add(header);
var scroll = new ScrollView(className == "track-zone-stack" ? ScrollViewMode.Vertical : ScrollViewMode.Horizontal);
var scroll = new ScrollView(className == "track-zone-queue" ? ScrollViewMode.Horizontal : ScrollViewMode.Vertical);
scroll.AddToClassList("track-scroll");
VisualElement contents = new();
contents.AddToClassList("track-contents");
@@ -747,10 +752,10 @@ namespace KernelPanic.UI
}
RunConfig config = _runManager.CurrentConfig;
_waveLabel.text = _runManager.Journey.campaign && !_runManager.Journey.endless
? $"{Math.Min(RunJourney.BossWave, _runManager.CurrentWaveNumber)}/{RunJourney.BossWave}"
? $"{Math.Min(_runManager.Journey.FinalWave, _runManager.CurrentWaveNumber)}/{_runManager.Journey.FinalWave}"
: _runManager.CurrentWaveNumber.ToString();
_waveLabel.tooltip = _runManager.Journey.campaign && !_runManager.Journey.endless
? "Clear five waves, defeat the Kernel Overseer, then finish or continue into endless mode."
? $"Clear {_runManager.Journey.FinalWave} waves, defeat the Kernel Overseer, then finish or continue into endless mode."
: "Endless mode";
if (config?.IsTutorial == true)
{
@@ -866,10 +871,19 @@ namespace KernelPanic.UI
_stackView.EndExecution();
}
_tokenArea.Clear();
_tokenArea.Add(EmptyState("inactive"));
((VisualElement)_tokenArea.userData).EnableInClassList("track-idle", true);
bool pythonIdle = _combatManager.Python.AutomationCount == 0
&& _combatManager.Python.RepeatCount == 0 && _combatManager.Python.AreaCount == 0;
IEnumerable<string> pythonReadout = pythonIdle ? new[] { "0 / 2 slots" } : _combatManager.Python.Readout;
foreach (string line in pythonReadout)
{
var label = new Label(line);
label.style.whiteSpace = WhiteSpace.Normal;
_tokenArea.Add(label);
}
((VisualElement)_tokenArea.userData).EnableInClassList("track-idle", _combatManager.Python.AutomationCount == 0);
_root.Q(className: "scheduler").EnableInClassList("scheduler-idle",
_combatManager.InterpreterQueue.Count == 0 && _combatManager.LazyStack.Count == 0);
_combatManager.InterpreterQueue.Count == 0 && _combatManager.LazyStack.Count == 0
&& _combatManager.Python.AutomationCount == 0 && _combatManager.Python.RepeatCount == 0 && _combatManager.Python.AreaCount == 0);
((VisualElement)_interpreterStrip.userData).EnableInClassList("track-resolving", _combatManager.CurrentPhase == TurnPhase.Interpret);
}
@@ -1163,7 +1177,8 @@ namespace KernelPanic.UI
["exhaust"] = new List<CardInstance>(_combatManager.DeckController.ExhaustPile)
};
inventories[pile] = new List<CardInstance>(cards);
_overlay.Add(CardPileView.BuildBrowser(pile, inventories, ClosePileInspector, _combatManager.GetPileCostDetails));
_overlay.Add(CardPileView.BuildBrowser(pile, inventories, ClosePileInspector, _combatManager.GetPileCostDetails,
card => CardEffectFactory.GetRulesText(card, _combatManager.RunConfig)));
_overlay.style.display = DisplayStyle.Flex;
_overlay.Q<TextField>("PileSearch")?.Focus();
}
@@ -1204,7 +1219,7 @@ namespace KernelPanic.UI
victory = _combatManager.RunCompleted
};
_runTelemetry?.FillReport(entry);
if (entry.victory) entry.cause = "Kernel Overseer defeated. Five-wave campaign complete.";
if (entry.victory) entry.cause = $"Kernel Overseer defeated. {_runManager.Journey.FinalWave}-wave campaign complete.";
entry.cause ??= entry.surrendered ? "Shutdown signal accepted." : "Uptime reached 0; no damaging action recorded.";
_runHistoryEntry = entry;
return entry;
@@ -1287,6 +1302,75 @@ namespace KernelPanic.UI
return;
}
if (_combatManager.Python.HasChoice && !_combatManager.RunFinished)
{
_pileInspectorOpen = false;
_overlay.RemoveFromClassList("pile-overlay");
TerminalTheme.PreserveFocus(_overlay);
_overlay.Clear();
_overlay.style.display = DisplayStyle.Flex;
_overlay.AddToClassList("python-choice-overlay");
var dialog = new VisualElement { name = "PythonChoiceDialog" };
dialog.AddToClassList("python-choice-dialog");
dialog.Add(SoftwareCardView.Text("[ python / select one ]", "python-choice-eyebrow"));
string heading = _combatManager.Python.ChoiceTitle;
int separator = heading.IndexOf(':');
dialog.Add(SoftwareCardView.Text(separator < 0 ? heading : heading.Substring(0, separator), "python-choice-title"));
if (separator >= 0)
dialog.Add(SoftwareCardView.Text(heading.Substring(separator + 1).Trim(), "python-choice-description"));
var choices = new ScrollView(ScrollViewMode.Vertical) { name = "PythonChoiceScroll" };
choices.AddToClassList("python-choice-scroll");
choices.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
choices.contentContainer.AddToClassList("python-choice-grid");
for (int i = 0; i < _combatManager.Python.Choices.Count; i++)
{
int index = i;
var option = _combatManager.Python.Choices[i];
var button = new Button(() => _combatManager.Python.Choose(index)) { name = $"PythonChoice{index}" };
if (option.Card != null)
SoftwareCardView.Populate(button, option.Card, option.Cost,
CardEffectFactory.GetRulesText(option.Card, _combatManager.RunConfig));
else
button.Add(SoftwareCardView.Text(option.Label, "python-choice-description"));
button.AddToClassList("python-choice-option");
// These choices already show the complete rules; a repeated tooltip
// would cover the dialog header on small screens.
button.tooltip = null;
button.Add(SoftwareCardView.Text(option.ActionLabel ?? "> replace script", "python-choice-action"));
button.SetEnabled(option.Enabled);
choices.Add(button);
}
dialog.Add(choices);
dialog.Add(SoftwareCardView.Text("Tab / Shift+Tab to browse · Enter to select", "python-choice-hint"));
// Intercept focus before ScrollView tracks it: its automatic scrolling
// aligns oversized cards to their bottom, hiding the card's name.
dialog.RegisterCallback<FocusInEvent>(evt =>
{
if (evt.target is not Button focused || !focused.ClassListContains("python-choice-option")) return;
evt.StopPropagation();
void RevealChoice()
{
if (focused.worldBound.height > choices.contentViewport.worldBound.height)
choices.scrollOffset = new Vector2(0, Mathf.Max(0,
focused.worldBound.yMin - choices.contentContainer.worldBound.yMin));
else choices.ScrollTo(focused);
}
RevealChoice();
// Repeat after layout for newly attached cards, but never scroll back
// to a stale selection after the player has moved focus again.
choices.schedule.Execute(() =>
{
if (dialog.focusController?.focusedElement == focused) RevealChoice();
});
}, TrickleDown.TrickleDown);
TerminalTheme.ConstrainModalFocus(dialog);
_overlay.Add(dialog);
choices.Query<Button>().ToList().Find(b => b.enabledSelf)?.Focus();
return;
}
_overlay.RemoveFromClassList("python-choice-overlay");
if (_pileInspectorOpen && !_combatManager.RunFinished && !_combatManager.AwaitingWaveContinue
&& _combatManager.CurrentPhase == TurnPhase.Execute) return;
_pileInspectorOpen = false;
@@ -1298,6 +1382,7 @@ namespace KernelPanic.UI
if (_combatManager.RunFinished)
{
_routeSelectionOpen = false;
_routeEventOpen = false;
SettleRunRewardsIfNeeded();
_overlay.style.display = DisplayStyle.Flex;
_overlay.Add(BuildRunEndOverlay());
@@ -1322,6 +1407,7 @@ namespace KernelPanic.UI
}
_routeSelectionOpen = false;
_routeEventOpen = false;
_overlay.style.display = DisplayStyle.None;
}
@@ -1528,25 +1614,33 @@ namespace KernelPanic.UI
private void SetRouteSelectionOpen(bool open)
{
_routeSelectionOpen = open;
_routeEventOpen = false;
RefreshOverlay();
_overlay.Q<Button>(open ? "BackToRepositoryButton" : "BootNextWaveButton")?.Focus();
}
private VisualElement BuildRouteSelectionView()
{
var screen = new VisualElement { name = "RouteSelectionScreen" };
bool reward = _runManager.BuildRewardPending;
bool eventScreen = !reward && _routeEventOpen && !_runManager.CampaignChoicePending;
bool committed = eventScreen && !_runManager.RouteEventPending;
var screen = new VisualElement { name = reward ? "BuildRewardScreen" : eventScreen ? "RouteEventScreen" : "RouteSelectionScreen" };
screen.AddToClassList("repository");
screen.AddToClassList("screen-frame");
screen.AddToClassList("route-map-screen");
var header = new VisualElement();
header.AddToClassList("repository-header");
header.AddToClassList("screen-frame-header");
var copy = new VisualElement();
copy.AddToClassList("repository-header-copy");
var title = new Label(_runManager.CampaignChoicePending ? "campaign complete" : "choose your route");
var title = new Label(_runManager.CampaignChoicePending ? "campaign complete" : reward ? "claim your build reward"
: eventScreen ? RunRouteMap.Title(_runManager.Journey.selectedRoute) : "choose your route");
title.AddToClassList("screen-frame-title");
copy.Add(title);
var subtitle = new Label(_runManager.CampaignChoicePending
? "bank your rewards or continue into endless"
: reward ? "1 / claim reward > 2 / choose route > 3 / enter stop"
: eventScreen ? committed ? "stop complete / ready for battle" : "choose your cards / nothing changes until you confirm"
: $"preparing wave {_runManager.CurrentWaveNumber} / {_runManager.Bits} bits remaining");
subtitle.AddToClassList("repository-subtitle");
copy.Add(subtitle);
@@ -1556,29 +1650,99 @@ namespace KernelPanic.UI
var body = new ScrollView(ScrollViewMode.Vertical);
body.AddToClassList("repository-body");
body.AddToClassList("screen-frame-content");
body.Add(RunRouteView.Build(_runManager, _combatManager));
body.Add(reward ? RunRouteView.BuildReward(_runManager)
: eventScreen ? RunMapView.BuildEvent(_runManager) : RunRouteView.Build(_runManager, _combatManager));
if (!reward && !eventScreen && !_runManager.CampaignChoicePending)
{
body.AddToClassList("route-map-body");
body.contentViewport.RegisterCallback<GeometryChangedEvent>(evt =>
{
var mapScroll = body.Q<ScrollView>("RouteMapScroll");
if (mapScroll != null)
mapScroll.style.height = Mathf.Max(260, evt.newRect.height - 20);
});
}
if (committed)
{
var save = new Button(SaveAndExitRun) { name = "SaveAndExitRunButton", text = "save and exit / keep this result" };
save.AddToClassList("secondary-action"); body.Add(save);
}
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)
footer.AddToClassList("route-map-footer");
var back = new Button(() =>
{
var confirm = new Button(() => _combatManager.ContinueToNextWave())
if (!eventScreen) SetRouteSelectionOpen(false);
else if (_runManager.RouteEventPending)
{
_routeEventOpen = false; RefreshOverlay();
_overlay.Q<Button>("ConfirmRouteButton")?.Focus();
}
})
{ name = eventScreen ? "BackToRouteButton" : "BackToRepositoryButton",
text = committed ? "stop committed" : eventScreen ? "< back to map" : "< back to repository" };
back.SetEnabled(!committed);
back.AddToClassList("primary-action");
back.AddToClassList("route-map-back");
footer.Add(back);
screen.RegisterCallback<KeyDownEvent>(evt =>
{
if (evt.keyCode != KeyCode.Escape || !back.enabledSelf) return;
using var submit = NavigationSubmitEvent.GetPooled();
submit.target = back; back.SendEvent(submit); evt.StopPropagation();
});
void MoveAction(string name, string caption = null)
{
var button = body.Q<Button>(name);
if (button == null) return;
button.RemoveFromHierarchy();
if (caption != null) button.text = caption;
if (name == "ResolveRouteEventButton")
{
string fullCaption = button.text;
button.RegisterCallback<GeometryChangedEvent>(evt => button.text = evt.newRect.width < 160 ? "apply" : fullCaption);
}
button.AddToClassList("primary-action");
button.AddToClassList(name is "ClaimBuildRewardButton" or "ResolveRouteEventButton" ? "route-map-continue" : "route-map-back");
footer.Add(button);
}
if (reward)
{
back.text = "< back"; back.tooltip = "Back to repository";
MoveAction("RewardBits", $"{RunManager.BuildRewardBits} Bits");
MoveAction("ClaimBuildRewardButton", "claim");
}
else if (eventScreen && !committed)
{
back.text = "< map";
MoveAction("SkipRouteEventButton", "pass");
MoveAction("ResolveRouteEventButton");
}
else if (!_runManager.CampaignChoicePending)
{
var confirm = new Button(() =>
{
if (_runManager.RouteEventPending && !eventScreen)
{
_routeEventOpen = true; RefreshOverlay();
_overlay.Q<Button>("BackToRouteButton")?.Focus();
}
else _combatManager.ContinueToNextWave();
})
{
name = "ConfirmRouteButton",
text = _runManager.BuildRewardPending ? "choose a build reward to continue" : "> depart / boot next-wave"
text = eventScreen ? committed ? "> continue to battle" : "confirm or pass above"
: _runManager.RouteEventPending ? "> enter stop" : "> continue to battle"
};
confirm.AddToClassList("primary-action");
confirm.SetEnabled(!_runManager.BuildRewardPending && !_runManager.IsSuspended);
confirm.AddToClassList("route-map-continue");
confirm.SetEnabled((!eventScreen || committed) && !_runManager.IsSuspended);
footer.Add(confirm);
}
screen.Add(footer);
if (committed) screen.schedule.Execute(() => screen.Q<Button>("ConfirmRouteButton")?.Focus());
return screen;
}
@@ -1810,13 +1974,13 @@ namespace KernelPanic.UI
{
VisualElement face = new();
face.AddToClassList("hand-card");
SoftwareCardView.Populate(face, card, GetDisplayCardCost(card));
SoftwareCardView.Populate(face, card, GetDisplayCardCost(card), CardEffectFactory.GetRulesText(card, _combatManager.RunConfig));
return face;
}
private void PopulateCardFace(VisualElement target, CardInstance card)
{
SoftwareCardView.Populate(target, card, GetDisplayCardCost(card));
SoftwareCardView.Populate(target, card, GetDisplayCardCost(card), CardEffectFactory.GetRulesText(card, _combatManager.RunConfig));
var preview = CardPreviewService.Build(_combatManager, card);
if (!string.IsNullOrEmpty(preview.Summary) && !preview.Summary.StartsWith("Utility", StringComparison.Ordinal))
{
@@ -2158,7 +2322,7 @@ namespace KernelPanic.UI
{
VisualElement chip = CardChip(cards[i]);
chip.Insert(0, SoftwareCardView.Text($"{i + 1:00} >", "execution-order"));
chip.tooltip = CardEffectFactory.GetRulesText(cards[i]);
chip.tooltip = CardEffectFactory.GetRulesText(cards[i], _combatManager.RunConfig);
if (target == _interpreterStrip)
{
_queueChipElements[cards[i]] = chip;
+174
View File
@@ -0,0 +1,174 @@
using System;
using KernelPanic.Meta;
using UnityEngine;
using UnityEngine.UIElements;
namespace KernelPanic.UI
{
public static class DailyQuestView
{
public static Button BuildWidget(DailyQuestState state, DateTime utcNow, Action open)
{
var widget = new Button(open) { name = "DailyQuestWidget", tooltip = "Open daily quests (Enter)" };
widget.AddToClassList("daily-quest-widget");
var counts = Counts(state);
var heading = new VisualElement();
heading.AddToClassList("daily-service-summary");
heading.Add(TerminalLayout.Heading("[ cron.daily ]", className: "daily-service-title"));
var reward = TerminalLayout.BodyText(counts.Ready == 1 ? "1 reward ready" : $"{counts.Ready} rewards ready",
"DailyQuestRewardReady", "daily-reward-ready");
reward.style.display = counts.Ready > 0 ? DisplayStyle.Flex : DisplayStyle.None;
heading.Add(reward);
widget.Add(heading);
widget.Add(TerminalLayout.BodyText(DailyQuests.Countdown(state, utcNow), "DailyQuestCountdown", "daily-service-meta"));
var summary = new VisualElement();
summary.AddToClassList("daily-service-summary");
summary.Add(TerminalLayout.BodyText($"{counts.Completed}/{DailyQuests.Count} completed", "DailyQuestCompleted", "daily-service-meta"));
summary.Add(TerminalLayout.BodyText($"{counts.Claimed} claimed", "DailyQuestClaimed", "daily-service-meta"));
widget.Add(summary);
foreach (var kind in DailyQuests.Active(state))
{
var row = new VisualElement();
row.AddToClassList("daily-service-entry");
row.EnableInClassList("daily-service-ready", !DailyQuests.Claimed(state, kind)
&& DailyQuests.Progress(state, kind) >= DailyQuests.Target(kind));
row.EnableInClassList("daily-service-claimed", DailyQuests.Claimed(state, kind));
row.Add(TerminalLayout.BodyText(ShortName(kind), className: "daily-service-name"));
row.Add(TerminalLayout.BodyText($"{DailyQuests.Progress(state, kind)}/{DailyQuests.Target(kind)}", className: "daily-service-progress"));
widget.Add(row);
}
widget.Add(TerminalLayout.BodyText(counts.Ready > 0 ? "> claim available rewards" : "> inspect tasks",
"DailyQuestInspect", "daily-service-command"));
widget.EnableInClassList("daily-has-rewards", counts.Ready > 0);
// Child copy is part of one button, not additional focus targets.
widget.Query<VisualElement>().ForEach(child => { if (child != widget) child.pickingMode = PickingMode.Ignore; });
widget.RegisterCallback<KeyDownEvent>(evt =>
{
if (evt.keyCode == KeyCode.Escape)
{
widget.Blur();
widget.panel?.focusController.IgnoreEvent(evt);
evt.StopImmediatePropagation();
return;
}
if (evt.keyCode != KeyCode.Return && evt.keyCode != KeyCode.KeypadEnter) return;
open();
widget.panel?.focusController.IgnoreEvent(evt);
evt.StopImmediatePropagation();
});
return widget;
}
private static (int Completed, int Claimed, int Ready) Counts(DailyQuestState state)
{
int completed = 0, claimed = 0, ready = 0;
foreach (var kind in DailyQuests.Active(state))
{
bool complete = DailyQuests.Progress(state, kind) >= DailyQuests.Target(kind);
if (complete) completed++;
if (DailyQuests.Claimed(state, kind)) claimed++;
else if (complete) ready++;
}
return (completed, claimed, ready);
}
public static void RefreshHeader(VisualElement overlay, DailyQuestState state, DateTime utcNow)
{
overlay.Q<Label>("DailyQuestDetailCountdown").text = DailyQuests.Countdown(state, utcNow).Replace("refresh in ", "reset ");
overlay.Q<Label>("DailyQuestDetailSummary").text = $"{DailyQuests.Count} tasks / {Counts(state).Completed} completed";
}
private static string ShortName(DailyQuestKind kind) => kind switch
{
DailyQuestKind.Waves => "Waves cleared",
DailyQuestKind.Cards => "Cards played",
DailyQuestKind.Damage => "Uptime damage",
DailyQuestKind.BlockDamage => "Damage blocked",
DailyQuestKind.NativeCards => "Native cards",
DailyQuestKind.ShieldDamage => "Enemy Shield damage",
DailyQuestKind.SurviveRounds => "Rounds survived",
DailyQuestKind.WaveFive => "Wave 5 cleared",
_ => DailyQuests.Description(kind)
};
public static VisualElement BuildOverlay(DailyQuestState state, DateTime utcNow,
Action<DailyQuestKind, long> claim, Action close)
{
var overlay = new VisualElement { name = "DailyQuestOverlay" };
overlay.AddToClassList("modal-overlay");
overlay.AddToClassList("modal-open");
overlay.AddToClassList("daily-quest-overlay");
var dialog = new VisualElement { name = "DailyQuestDialog" };
dialog.AddToClassList("daily-quest-dialog");
var header = new VisualElement { name = "DailyQuestHeader" };
header.AddToClassList("daily-detail-header");
header.Add(TerminalLayout.BodyText("$ cat /etc/cron.daily/quests", className: "daily-detail-command"));
var titleRow = new VisualElement();
titleRow.AddToClassList("daily-service-summary");
titleRow.Add(TerminalLayout.Heading("DAILY TASKS", className: "daily-service-title"));
titleRow.Add(TerminalLayout.BodyText("", "DailyQuestDetailCountdown", "daily-service-meta"));
header.Add(titleRow);
header.Add(TerminalLayout.BodyText("", "DailyQuestDetailSummary", "daily-service-meta"));
dialog.Add(header);
var scroll = new ScrollView(ScrollViewMode.Vertical) { name = "DailyQuestDetailScroll" };
scroll.AddToClassList("daily-quest-detail-scroll");
scroll.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
scroll.Add(Build(state, utcNow, claim));
dialog.Add(scroll);
var feedback = TerminalLayout.BodyText("", "DailyQuestFeedback", "daily-quest-feedback");
feedback.style.display = DisplayStyle.None;
dialog.Add(feedback);
var dismiss = new Button(close) { name = "CloseDailyQuests", text = "[ Esc ] close" };
dismiss.AddToClassList("terminal-button");
dialog.Add(dismiss);
overlay.Add(dialog);
RefreshHeader(overlay, state, utcNow);
overlay.RegisterCallback<KeyDownEvent>(evt =>
{
if (evt.keyCode == KeyCode.Escape) { close(); evt.StopImmediatePropagation(); }
});
TerminalTheme.ConstrainModalFocus(overlay);
return overlay;
}
public static VisualElement Build(DailyQuestState state, DateTime utcNow, Action<DailyQuestKind, long> claim)
{
var panel = new VisualElement { name = "DailyQuestsPanel" };
panel.AddToClassList("daily-quests");
var quests = new VisualElement();
quests.AddToClassList("daily-quest-list");
panel.Add(quests);
long period = state.refreshAtUtcTicks;
foreach (var kind in DailyQuests.Active(state))
{
var row = new VisualElement { name = "DailyQuest" + kind };
row.AddToClassList("daily-quest");
int progress = DailyQuests.Progress(state, kind);
bool claimed = DailyQuests.Claimed(state, kind);
bool complete = progress >= DailyQuests.Target(kind);
row.EnableInClassList("daily-quest-complete", complete);
row.EnableInClassList("daily-quest-claimed", claimed);
row.Add(TerminalLayout.BodyText(DailyQuests.Description(kind), className: "daily-quest-name"));
int filled = progress * 10 / DailyQuests.Target(kind);
var progressRow = new VisualElement();
progressRow.AddToClassList("daily-detail-progress-row");
progressRow.Add(TerminalLayout.BodyText($"[{new string('#', filled)}{new string('.', 10 - filled)}]",
className: "daily-detail-progress"));
progressRow.Add(TerminalLayout.BodyText($"{progress}/{DailyQuests.Target(kind)}", className: "daily-detail-values"));
row.Add(progressRow);
var reward = DailyQuests.Reward(kind);
row.Add(TerminalLayout.BodyText($"+{reward.Bandwidth} Bandwidth / +{reward.Entropy} Entropy"));
var button = new Button(() => claim(kind, period))
{ name = "ClaimDailyQuest" + kind, text = claimed ? "[ CLAIMED ]" : complete ? "> CLAIM REWARD" : "[ in progress ]" };
button.AddToClassList("terminal-button");
button.AddToClassList("daily-claim-action");
button.EnableInClassList("daily-claim-ready", !claimed && complete);
button.EnableInClassList("daily-claim-done", claimed);
button.SetEnabled(!claimed && complete);
row.Add(button);
quests.Add(row);
}
return panel;
}
}
}
+1 -1
View File
@@ -81,7 +81,7 @@ namespace KernelPanic.UI
{
if (_disposed) return;
foreach (var card in pending)
Chip(card).tooltip = CardEffectFactory.GetRulesText(card) + "\n\n" + CardPreviewService.Build(combat, card).Details;
Chip(card).tooltip = CardEffectFactory.GetRulesText(card, combat.RunConfig) + "\n\n" + CardPreviewService.Build(combat, card).Details;
}
public void Resolving(CardInstance card)
+1 -1
View File
@@ -71,7 +71,7 @@ namespace KernelPanic.UI
_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.");
AddTrack("1 / Python pipeline", "Preparation acts immediately. End turn: scripts run, then FIFO modifiers and payloads. Loops repeat; zip spreads damage. Two script slots, cleared each wave.");
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.");
+4 -5
View File
@@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using KernelPanic.Combat;
using KernelPanic.Core;
using KernelPanic.Data;
using KernelPanic.Meta;
@@ -2123,11 +2124,9 @@ namespace KernelPanic.UI
summary.ElementAt(2).AddToClassList("package-meta");
row.Add(summary);
if (!string.IsNullOrWhiteSpace(card.Description))
{
row.Add(new Label(card.Description) { name = "RunSetupCardDescription" });
row.ElementAt(1).AddToClassList("package-description");
}
row.Add(new Label(CardEffectFactory.GetRulesText(new CardInstance(card), unit.Id,
_playerCollection?.GetVersion(unit.Id) ?? 1)) { name = "RunSetupCardDescription" });
row.ElementAt(1).AddToClassList("package-description");
if (!string.IsNullOrWhiteSpace(card.FlavorText))
{
+362
View File
@@ -0,0 +1,362 @@
using System;
using System.Collections.Generic;
using System.Linq;
using KernelPanic.Combat;
using KernelPanic.Run;
using UnityEngine;
using UnityEngine.UIElements;
namespace KernelPanic.UI
{
internal static class RunMapView
{
public static VisualElement Build(RunManager run)
{
var layout = new VisualElement { name = "RunMap" };
layout.AddToClassList("route-map-layout");
var map = new VisualElement { name = "RouteGraph" };
map.AddToClassList("route-map-graph");
if (run.Journey.mapStartWave > 2)
map.Add(Text("Earlier decisions are unavailable for this older save. Your map starts here.", "route-map-legend"));
int current = run.CurrentWaveNumber, seed = run.CurrentConfig.RunSeed;
int revision = run.Journey.mapRevision, startWave = run.Journey.mapStartWave;
int first = run.Journey.endless ? Math.Max(startWave, current - 3) : startWave;
int last = run.Journey.endless ? current + 5 : run.Journey.FinalWave;
IReadOnlyList<RouteNode> Row(int wave) => RunRouteMap.Row(seed, wave, startWave, revision);
bool Connected(RouteNode a, RouteNode b) => RunRouteMap.Connected(seed, a, b, startWave, revision);
var detail = new VisualElement { name = "RouteDetails" };
detail.AddToClassList("route-map-detail");
var preview = new VisualElement { name = "RoutePreview" };
detail.Add(preview);
void Preview(RouteNode node)
{
if (node == null) return;
preview.Clear();
bool boss = node.Wave == run.Journey.FinalWave && !run.Journey.endless;
string phase = run.Journey.endless ? "SURVIVAL" : node.Wave <= 3 ? "BOOT SECTOR"
: node.Wave <= 6 ? "ESCALATION" : boss ? "FINAL ENCOUNTER" : "KERNEL PERIMETER";
preview.Add(Text($"{node.Wave:00} / {(run.Journey.endless ? "ENDLESS" : run.Journey.FinalWave.ToString("00"))} {phase}", "route-map-eyebrow"));
string state = node.Wave < current ? run.Journey.visits.Any(v => v.nodeId == node.Id) ? "CLEARED" : "NOT TAKEN"
: node.Wave > current ? "FUTURE STOP" : node.Id == run.Journey.selectedNodeId ? "SELECTED DESTINATION"
: run.AvailableRouteNodes.Any(n => n.Id == node.Id) ? "AVAILABLE / select to take this path" : "UNREACHABLE FROM HERE";
preview.Add(Text(state, "route-preview-state"));
preview.Add(Text(boss ? "Kernel Overseer" : RunRouteMap.Title(node.Route), "route-detail-title"));
preview.Add(Text(boss ? "Defeat the Overseer to complete the route. Bank your rewards, or continue this build in endless survival."
: RunRouteMap.Detail(node.Route), "route-detail-copy"));
var encounter = EncounterDirector.Plan(node.Wave, node.Route, seed, run.Journey.encounterRevision);
preview.Add(Text("BATTLE / " + encounter.Title, "route-map-eyebrow"));
preview.Add(Text(encounter.Advice, "route-detail-copy"));
if (node.Wave == current && run.Journey.resolvedEventWave == current && node.Id == run.Journey.selectedNodeId)
preview.Add(Text("[ resolved ]\n" + run.Journey.eventOutcome, "route-map-history"));
}
void SelectedPreview() => Preview(Row(current).FirstOrDefault(n => n.Id == run.Journey.selectedNodeId));
var available = run.AvailableRouteNodes.Select(n => n.Id).ToHashSet();
var chosen = run.Journey.visits.ToDictionary(v => v.wave, v => v.nodeId);
chosen[current] = run.Journey.selectedNodeId;
var potential = new HashSet<int> { run.Journey.selectedNodeId };
var lit = new HashSet<int>(potential);
for (int wave = current + 1; wave <= last; wave++)
{
var before = Row(wave - 1);
var after = Row(wave);
potential = after.Where(to => before.Any(from => potential.Contains(from.Id)
&& Connected(from, to))).Select(n => n.Id).ToHashSet();
lit.UnionWith(potential);
}
// One coordinate space for both nodes and trails. Future is up; travelled ground is below.
bool origin = first == startWave;
int bottom = origin ? first - 1 : first;
const float pitch = 96, radius = 30, top = 48;
var scroll = new ScrollView(ScrollViewMode.Vertical) { name = "RouteMapScroll" };
scroll.AddToClassList("route-map-scroll");
scroll.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
var canvas = new VisualElement { name = "RouteCanvas" };
canvas.AddToClassList("route-map-canvas");
canvas.style.height = top + (last - bottom) * pitch + 62;
var nodesById = new Dictionary<int, VisualElement>();
var points = new Dictionary<int, Vector2>();
var rows = new Dictionary<int, IReadOnlyList<RouteNode>>();
void AddMarker(int id, int wave, float position, VisualElement marker)
{
marker.style.position = Position.Absolute;
marker.style.top = top + (last - wave) * pitch - radius;
marker.style.left = new Length(12 + position * 76, LengthUnit.Percent);
marker.style.marginLeft = -radius;
marker.userData = id;
nodesById.Add(id, marker); canvas.Add(marker);
}
for (int wave = first; wave <= last; wave++)
{
var nodes = Row(wave);
rows.Add(wave, nodes);
var waveLabel = Text(wave.ToString("00"), "route-map-wave");
waveLabel.style.top = top + (last - wave) * pitch - 42;
canvas.Add(waveLabel);
foreach (var node in nodes)
{
bool selected = chosen.TryGetValue(wave, out int id) && id == node.Id;
bool reachable = wave == current ? available.Contains(node.Id) : wave > current && lit.Contains(node.Id);
VisualElement tile;
if (wave == current)
{
var button = new Button(() => run.SelectRouteNode(node.Id)) { name = "Route" + node.Route };
button.SetEnabled(reachable && run.Journey.resolvedEventWave != current);
tile = button;
}
else tile = new VisualElement { name = "MapNode" + node.Id };
tile.AddToClassList("route-map-node");
tile.EnableInClassList("map-choice", wave == current && reachable);
tile.EnableInClassList("map-selected", wave == current && selected);
tile.EnableInClassList("map-taken", wave < current && selected);
tile.EnableInClassList("map-muted", !selected && !reachable);
tile.EnableInClassList("map-future", wave > current);
tile.EnableInClassList("map-boss", wave == run.Journey.FinalWave && !run.Journey.endless);
tile.Add(Glyph(node.Route));
tile.Add(Text(wave == run.Journey.FinalWave && !run.Journey.endless ? "BOSS" : CompactTitle(node.Route), "route-map-name"));
tile.tooltip = $"Wave {wave} / {RunRouteMap.Title(node.Route)}\n{RunRouteMap.Detail(node.Route)}";
tile.RegisterCallback<MouseEnterEvent>(_ => Preview(node));
tile.RegisterCallback<MouseLeaveEvent>(_ => SelectedPreview());
tile.RegisterCallback<FocusInEvent>(_ => Preview(node));
tile.RegisterCallback<FocusOutEvent>(_ => SelectedPreview());
AddMarker(node.Id, wave, nodes.Count == 1 ? .5f : (float)nodes.ToList().IndexOf(node) / (nodes.Count - 1), tile);
if (selected && wave == current - 1)
{
tile.name = "CurrentMapPosition";
var here = Text("YOU ARE HERE", "route-map-here"); tile.Add(here);
}
}
}
if (origin)
{
var start = new VisualElement { name = current == startWave ? "CurrentMapPosition" : "RouteStart" };
start.AddToClassList("route-map-node"); start.AddToClassList("map-taken");
start.Add(Text("OK", "route-map-symbol")); start.Add(Text("Cleared", "route-map-name"));
if (current == startWave) start.Add(Text("YOU ARE HERE", "route-map-here"));
start.tooltip = $"Wave {startWave - 1} cleared. The route begins here.";
AddMarker(-1, bottom, .5f, start);
}
var edges = new List<(int from, int to, bool taken, bool active, bool future)>();
foreach (var row in rows)
{
if (!rows.TryGetValue(row.Key + 1, out var next)) continue;
foreach (var a in row.Value)
foreach (var b in next)
{
if (!Connected(a, b)) continue;
bool taken = b.Wave < current && chosen.TryGetValue(a.Wave, out int aId) && aId == a.Id
&& chosen.TryGetValue(b.Wave, out int bId) && bId == b.Id;
bool active = a.Wave == current - 1 ? chosen.GetValueOrDefault(a.Wave) == a.Id && b.Id == run.Journey.selectedNodeId
: a.Wave >= current && lit.Contains(a.Id);
edges.Add((a.Id, b.Id, taken, active, a.Wave >= current));
}
}
if (origin) foreach (var node in rows[first])
edges.Add((-1, node.Id, first < current && chosen.GetValueOrDefault(first) == node.Id,
first == current && node.Id == run.Journey.selectedNodeId, false));
canvas.generateVisualContent += context =>
{
points.Clear();
foreach (var entry in nodesById)
points[entry.Key] = entry.Value.layout.center;
var painter = context.painter2D;
// Muted trails first, then the player's path. At crossings the active trail stays legible.
foreach (var edge in edges.OrderBy(e => e.taken || e.active))
{
Vector2 a = points[edge.from], b = points[edge.to];
var direction = (b - a).normalized;
a += direction * radius; b -= direction * radius;
Color color = edge.taken ? new Color(.48f, .76f, .59f) : edge.active ? new Color(.91f, .72f, .43f) : new Color(.24f, .33f, .28f);
// A dark under-stroke separates real crossings without inventing junctions.
Trail(painter, a, b, new Color(.055f, .085f, .067f), 7, false);
Trail(painter, a, b, color, edge.active || edge.taken ? 2.5f : 1.5f, edge.future);
}
};
canvas.RegisterCallback<GeometryChangedEvent>(_ => canvas.MarkDirtyRepaint());
scroll.Add(canvas); map.Add(scroll);
bool positioned = false;
scroll.RegisterCallback<GeometryChangedEvent>(_ =>
{
if (positioned || scroll.contentViewport.layout.height < 20) return;
positioned = true;
scroll.schedule.Execute(() =>
{
var here = canvas.Q("CurrentMapPosition");
if (here != null)
scroll.scrollOffset = new Vector2(0, Mathf.Max(0, here.layout.yMax + 36 - scroll.contentViewport.layout.height));
});
});
var choices = nodesById.Values.OfType<Button>().Where(b => b.enabledSelf).OrderBy(b => (int)b.userData).ToList();
void MoveFocus(int direction)
{
if (choices.Count == 0) return;
int index = choices.FindIndex(b => b == layout.focusController?.focusedElement);
var next = choices[(index + direction + choices.Count) % choices.Count];
next.Focus(); scroll.ScrollTo(next);
}
canvas.RegisterCallback<NavigationMoveEvent>(evt =>
{
if (evt.direction is not (NavigationMoveEvent.Direction.Left or NavigationMoveEvent.Direction.Right
or NavigationMoveEvent.Direction.Up or NavigationMoveEvent.Direction.Down)) return;
MoveFocus(evt.direction is NavigationMoveEvent.Direction.Left or NavigationMoveEvent.Direction.Up ? -1 : 1);
evt.StopPropagation(); evt.PreventDefault();
});
canvas.RegisterCallback<KeyDownEvent>(evt =>
{
if (evt.keyCode is not (KeyCode.W or KeyCode.A or KeyCode.S or KeyCode.D)) return;
MoveFocus(evt.keyCode is KeyCode.W or KeyCode.A ? -1 : 1);
evt.StopPropagation();
});
if (run.Journey.visits.Count > 0)
{
var history = new Foldout { text = "Travel journal / " + run.Journey.visits.Count + " decisions", value = false, name = "RouteHistory" };
history.AddToClassList("route-map-journal");
foreach (var visit in run.Journey.visits)
history.Add(Text($"Wave {visit.wave} / {RunRouteMap.Title(visit.route)}\n{visit.outcome}", "route-map-history"));
detail.Add(history);
}
layout.Add(map);
SelectedPreview();
layout.Add(detail);
return layout;
}
private static void Trail(Painter2D painter, Vector2 a, Vector2 b, Color color, float width, bool dotted)
{
painter.strokeColor = color; painter.lineWidth = width;
if (!dotted)
{
painter.BeginPath(); painter.MoveTo(a); painter.LineTo(b); painter.Stroke();
return;
}
float length = Vector2.Distance(a, b);
for (float offset = 0; offset < length; offset += 10)
{
painter.BeginPath(); painter.MoveTo(Vector2.Lerp(a, b, offset / length));
painter.LineTo(Vector2.Lerp(a, b, Mathf.Min(offset + 4, length) / length)); painter.Stroke();
}
}
private static VisualElement Glyph(WaveRoute route)
{
var glyph = new VisualElement { pickingMode = PickingMode.Ignore };
glyph.AddToClassList("route-map-glyph");
glyph.generateVisualContent += context =>
{
var p = context.painter2D; p.strokeColor = glyph.resolvedStyle.color; p.lineWidth = 1.8f;
void Line(params Vector2[] points)
{
p.BeginPath(); p.MoveTo(points[0]); foreach (var point in points.Skip(1)) p.LineTo(point); p.Stroke();
}
switch (route)
{
case WaveRoute.Repair:
Line(new(12, 3), new(12, 21)); Line(new(3, 12), new(21, 12)); break;
case WaveRoute.Challenge:
Line(new(4, 3), new(20, 3), new(20, 13), new(12, 22), new(4, 13), new(4, 3));
Line(new(12, 7), new(12, 13)); Line(new(12, 16), new(12, 17)); break;
case WaveRoute.Cache:
Line(new(3, 8), new(12, 3), new(21, 8), new(21, 20), new(3, 20), new(3, 8), new(21, 8));
Line(new(12, 9), new(12, 14)); break;
case WaveRoute.Forge:
Line(new(5, 19), new(16, 8)); Line(new(10, 4), new(14, 2), new(22, 10), new(19, 14), new(10, 4)); break;
case WaveRoute.Sacrifice:
Line(new(12, 2), new(18, 9), new(12, 16), new(6, 9), new(12, 2));
Line(new(3, 21), new(5, 17), new(19, 17), new(21, 21), new(3, 21)); break;
case WaveRoute.Recycle:
Line(new(4, 8), new(9, 3), new(19, 3), new(21, 8)); Line(new(16, 8), new(21, 8), new(21, 2));
Line(new(20, 16), new(15, 21), new(5, 21), new(3, 16)); Line(new(8, 16), new(3, 16), new(3, 22)); break;
default:
Line(new(6, 14), new(12, 8), new(18, 14)); Line(new(6, 21), new(12, 15), new(18, 21)); break;
}
};
return glyph;
}
public static VisualElement BuildEvent(RunManager run)
{
var content = new VisualElement { name = "RouteEventContent" };
content.AddToClassList("departure-content");
content.Add(Text(RunRouteMap.Detail(run.Journey.selectedRoute), "route-detail-copy"));
if (run.RouteEventPending) content.Add(Event(run));
else content.Add(Text("STOP COMPLETE\n" + run.Journey.eventOutcome, "route-event-result"));
return content;
}
private static VisualElement Event(RunManager run)
{
var panel = new VisualElement { name = "RouteEvent" }; panel.AddToClassList("route-event");
var selectors = new VisualElement(); selectors.AddToClassList("departure-selectors"); panel.Add(selectors);
bool remove = run.Journey.selectedRoute is WaveRoute.Sacrifice or WaveRoute.Recycle;
bool upgrade = run.Journey.selectedRoute is WaveRoute.Sacrifice or WaveRoute.Forge;
int amount = run.Journey.selectedRoute == WaveRoute.Sacrifice ? 4 : 2;
var donors = run.RunDeck.Where(c => c.Definition != null && !c.Definition.IsToken
&& (run.Journey.selectedRoute != WaveRoute.Sacrifice || !c.Definition.IsJunk)).ToList();
var targets = run.RunDeck.Where(run.CanImproveRouteCard).ToList();
int donorIndex = 0, targetIndex = Math.Max(0, targets.FindIndex(c => !remove || donors.Count == 0 || c != donors[0]));
var previews = new VisualElement(); previews.AddToClassList("departure-previews");
var result = Text("", "route-event-result");
var commit = new Button { name = "ResolveRouteEventButton", text = run.Journey.selectedRoute switch
{ WaveRoute.Sacrifice => "sacrifice & empower", WaveRoute.Forge => "apply patch", _ => "recycle card" } };
commit.AddToClassList("primary-action");
CardInstance Donor() => remove && donors.Count > 0 ? donors[donorIndex] : null;
CardInstance Target() => upgrade && targets.Count > 0 ? targets[targetIndex] : null;
void Refresh()
{
previews.Clear();
var donor = Donor(); var target = Target();
if (donor != null) previews.Add(Preview(donor, run, "REMOVE FROM THIS RUN"));
if (target != null)
{
previews.Add(Preview(target, run, "BEFORE UPGRADE"));
var after = target.CopyForCombat(); after.ApplyMagnitudeUpgrade(amount);
previews.Add(Preview(after, run, $"AFTER / +{amount} EFFECT"));
}
bool valid = (!remove || (donor != null && run.RunDeck.Count > 1)) && (!upgrade || target != null)
&& (!remove || !upgrade || donor != target);
result.text = !valid ? run.Journey.selectedRoute == WaveRoute.Sacrifice
? "Choose two different cards, or pass if there are no eligible cards. Your deck must keep at least one card."
: "No eligible card is selected. You may pass; your deck must keep at least one card."
: remove ? $"{donor.Definition.DisplayName} will leave this run's deck. " + (upgrade ? $"{target.Definition.DisplayName}: +{target.MagnitudeBonus} -> +{target.MagnitudeBonus + amount} effect." : "Receive 4 Bits.")
: $"{target.Definition.DisplayName}: +{target.MagnitudeBonus} -> +{target.MagnitudeBonus + amount} effect.";
if (run.BuildRewardPending) result.text = "Choose your build reward first, then resolve this stop.";
commit.SetEnabled(valid && !run.BuildRewardPending);
}
if (remove && donors.Count > 0)
{
var picker = new DropdownField("Card to remove", donors.Select((c, i) => $"{i + 1}. {c.Definition.DisplayName}").ToList(), donorIndex) { name = "RouteDonor" };
picker.RegisterValueChangedCallback(_ => { donorIndex = picker.index; Refresh(); }); selectors.Add(picker);
}
if (upgrade && targets.Count > 0)
{
var picker = new DropdownField("Card to empower", targets.Select((c, i) => $"{i + 1}. {c.Definition.DisplayName}").ToList(), targetIndex) { name = "RouteTarget" };
picker.RegisterValueChangedCallback(_ => { targetIndex = picker.index; Refresh(); }); selectors.Add(picker);
}
panel.Add(Text("Run only; your collection is unaffected. Confirm or pass to commit this path.", "route-detail-copy"));
panel.Add(previews); panel.Add(result);
commit.clicked += () => run.ResolveRouteEvent(Donor(), Target());
panel.Add(commit);
var skip = new Button(() => run.ResolveRouteEvent(skip: true)) { text = "pass / keep my deck", name = "SkipRouteEventButton" };
skip.AddToClassList("secondary-action"); skip.SetEnabled(!run.BuildRewardPending); panel.Add(skip);
Refresh();
return panel;
}
private static VisualElement Preview(CardInstance card, RunManager run, string heading)
{
var holder = new VisualElement(); holder.AddToClassList("route-event-card"); holder.AddToClassList("departure-card");
holder.Add(Text(heading, "route-map-eyebrow"));
var face = new VisualElement();
SoftwareCardView.Populate(face, card, CombatManager.GetCardCost(card), CardEffectFactory.GetRulesText(card, run.CurrentConfig));
holder.Add(face); return holder;
}
private static Label Text(string text, string style) => SoftwareCardView.Text(text, style);
private static string CompactTitle(WaveRoute route) => route switch
{
WaveRoute.Repair => "Repair", WaveRoute.Challenge => "Elite", WaveRoute.Cache => "Cache",
WaveRoute.Forge => "Patch", WaveRoute.Sacrifice => "Altar", WaveRoute.Recycle => "Scrap", _ => "Path"
};
}
}
+76 -35
View File
@@ -11,45 +11,21 @@ namespace KernelPanic.UI
{
public static VisualElement Build(RunManager run, CombatManager combat)
{
var section = TerminalLayout.Section(run.CampaignChoicePending ? "KERNEL SECURED" : "Route", "RunRouteChoices");
var section = run.Journey.mapRevision > 0 && !run.CampaignChoicePending
? new VisualElement { name = "RunRouteChoices" }
: 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.BuildRewardPending) return BuildReward(run);
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."));
section.Add(TerminalLayout.BodyText($"All {run.Journey.FinalWave} waves cleared. Kernel Overseer defeated. Finish and bank your rewards, or carry this deck and remaining Uptime into endless survival. Rewards are saved when the run ends."));
section.Add(Action("Finish campaign", "FinishCampaignButton", () => combat.CompleteCampaign()));
section.Add(Action("Continue into endless", "ContinueEndlessButton", () => combat.ContinueEndless()));
section.Add(Action("Continue into endless", "ContinueEndlessButton", () => run.EnterEndless()));
return section;
}
if (run.Journey.mapRevision > 0)
{
section.Add(RunMapView.Build(run));
return section;
}
var plan = EncounterDirector.Plan(run.CurrentWaveNumber, run.Journey.selectedRoute,
@@ -66,6 +42,71 @@ namespace KernelPanic.UI
return section;
}
public static VisualElement BuildReward(RunManager run)
{
var content = new VisualElement { name = "BuildRewardChoices" };
content.AddToClassList("departure-content");
content.Add(TerminalLayout.BodyText($"Upgrade one card, or take {RunManager.BuildRewardBits} Bits."));
var cards = run.RunDeck.Where(c => c.Definition != null && !c.Definition.IsToken && !c.Definition.IsJunk).ToList();
if (cards.Count > 0)
{
int index = 0;
CardUpgradeKind kind = run.CanImproveRouteCard(cards[0]) ? CardUpgradeKind.MagnitudeUp : CardUpgradeKind.DrawRider;
var picker = new DropdownField("Card to upgrade", cards.Select((c, i) => $"{i + 1}. {c.Definition.DisplayName}").ToList(), 0)
{ name = "BuildRewardCard" };
content.Add(picker);
var target = TerminalLayout.BodyText("", "BuildRewardTarget");
var modes = new VisualElement(); modes.AddToClassList("departure-actions"); content.Add(modes);
var beforeAfter = new VisualElement { name = "BuildRewardPreviews" };
beforeAfter.AddToClassList("departure-previews"); content.Add(beforeAfter);
var effect = new Button { name = "RewardMagnitude", text = $"Effect +{CombatTuning.UpgradeMagnitudeBonus}" };
var draw = new Button { name = "RewardDraw", text = "Draw +1 on resolution" };
effect.AddToClassList("primary-action"); draw.AddToClassList("primary-action");
modes.Add(effect); modes.Add(draw);
var claim = Action("claim upgrade / open map", "ClaimBuildRewardButton", () => run.ClaimBuildReward(cards[index], kind));
content.Add(claim);
void Refresh()
{
var card = cards[index];
bool canEffect = run.CanImproveRouteCard(card);
bool canDraw = card.DrawRider == 0 && card.UpgradeLevel < int.MaxValue;
effect.SetEnabled(canEffect); draw.SetEnabled(canDraw);
if (kind == CardUpgradeKind.MagnitudeUp && !canEffect && canDraw) kind = CardUpgradeKind.DrawRider;
if (kind == CardUpgradeKind.DrawRider && !canDraw && canEffect) kind = CardUpgradeKind.MagnitudeUp;
bool valid = kind == CardUpgradeKind.MagnitudeUp ? canEffect : canDraw;
target.text = valid ? "" : "No eligible upgrade. Choose another card or take Bits.";
effect.EnableInClassList("departure-selected", kind == CardUpgradeKind.MagnitudeUp);
draw.EnableInClassList("departure-selected", kind == CardUpgradeKind.DrawRider);
beforeAfter.Clear(); beforeAfter.Add(CardPreview(card, run, "BEFORE"));
var after = card.CopyForCombat();
if (valid)
{
if (kind == CardUpgradeKind.MagnitudeUp) after.ApplyMagnitudeUpgrade(CombatTuning.UpgradeMagnitudeBonus);
else after.ApplyDrawRider(1);
}
beforeAfter.Add(CardPreview(after, run, valid ? "AFTER UPGRADE" : "UNCHANGED"));
claim.SetEnabled(valid);
}
picker.RegisterValueChangedCallback(_ => { index = picker.index; Refresh(); });
effect.clicked += () => { kind = CardUpgradeKind.MagnitudeUp; Refresh(); };
draw.clicked += () => { kind = CardUpgradeKind.DrawRider; Refresh(); };
Refresh();
content.Add(target);
}
content.Add(Action($"take {RunManager.BuildRewardBits} Bits instead / open map", "RewardBits",
() => run.ClaimBuildReward(null, CardUpgradeKind.MagnitudeUp, true)));
return content;
}
private static VisualElement CardPreview(CardInstance card, RunManager run, string title)
{
var panel = new VisualElement(); panel.AddToClassList("departure-card");
panel.Add(SoftwareCardView.Text(title, "route-map-eyebrow"));
var face = new VisualElement();
SoftwareCardView.Populate(face, card, CombatManager.GetCardCost(card), CardEffectFactory.GetRulesText(card, run.CurrentConfig));
panel.Add(face); return panel;
}
private static void AddChoice(VisualElement parent, RunManager run, WaveRoute route, string title, string detail)
{
var card = new VisualElement();
+3 -1
View File
@@ -15,6 +15,9 @@ namespace KernelPanic.UI
};
public static void Populate(VisualElement target, CardInstance card, int cost)
=> Populate(target, card, cost, CardEffectFactory.GetRulesText(card));
public static void Populate(VisualElement target, CardInstance card, int cost, string rules)
{
if (card?.Definition == null) return;
var definition = card.Definition;
@@ -33,7 +36,6 @@ namespace KernelPanic.UI
target.Add(Text(string.IsNullOrWhiteSpace(definition.DisplayName) ? definition.name : definition.DisplayName, "software-name"));
target.Add(Text(TrackName(definition.ResolutionTrack), "software-track"));
string rules = CardEffectFactory.GetRulesText(card);
if (card.DrawRider > 0) rules += $" Draw {card.DrawRider}.";
target.tooltip = rules;
if (card.IsBroken) target.tooltip += "\n\n" + CardPreviewService.CorruptionDetails(card);