add missing files
This commit is contained in:
@@ -0,0 +1,281 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Globalization;
|
||||
using KernelPanic.Core;
|
||||
|
||||
namespace KernelPanic.Combat
|
||||
{
|
||||
public enum CardTargeting { None, SingleEnemy, AllEnemies }
|
||||
|
||||
public enum CardEffectKind
|
||||
{
|
||||
Damage, Shield, Draw, ChanceDamage, PreviousLanguageDamage, QueuedGrowthDamage,
|
||||
BtwScaledDamage, CompilationDraw, MakeJ4, HaskellFilter, HaskellMaybe,
|
||||
NextTurnCycle, QueueRepeat, CopyLowestCostHandCard, UnattendedUpgrades,
|
||||
Cleanse, ShuffleToken, UpgradeHandCards, GenerateCard, NoOp, UpdateManager,
|
||||
ShieldRepeatDamage, Timeshift, DnfAutoremove, FirstToPackage, Rawhide,
|
||||
IncomingAttackHalve, ConsultWiki, RandomCommonLanguageCard, MinimalInstall, SizeofDamage,
|
||||
RepairCorruptedCards, AskUbuntu
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Immutable, unscaled effect data shared by execution, rules and read-only previews.
|
||||
/// SecondaryAmount describes the conditional amount, threshold or rider for its Kind.
|
||||
/// Preview readers must interpret the Kind; a custom effect is never implicitly plain damage.
|
||||
/// </summary>
|
||||
public sealed class CardEffectSpec
|
||||
{
|
||||
public CardEffectKind Kind { get; }
|
||||
public int Amount { get; }
|
||||
public int MaxAmount { get; }
|
||||
public int SecondaryAmount { get; }
|
||||
public Language Language { get; }
|
||||
public bool AllEnemies { get; }
|
||||
public bool TrueDamage { get; }
|
||||
public bool CanCrit { get; }
|
||||
public string ReferenceId { get; }
|
||||
|
||||
internal CardEffectSpec(CardEffectKind kind, int amount = 0, int maxAmount = -1,
|
||||
int secondaryAmount = 0, Language language = default, bool allEnemies = false,
|
||||
bool trueDamage = false, bool canCrit = true, string referenceId = null)
|
||||
{
|
||||
Kind = kind;
|
||||
Amount = amount;
|
||||
MaxAmount = maxAmount < 0 ? amount : maxAmount;
|
||||
SecondaryAmount = secondaryAmount;
|
||||
Language = language;
|
||||
AllEnemies = allEnemies;
|
||||
TrueDamage = trueDamage;
|
||||
CanCrit = canCrit;
|
||||
ReferenceId = referenceId;
|
||||
}
|
||||
|
||||
public ICardEffect CreateRuntimeEffect()
|
||||
{
|
||||
return Kind switch
|
||||
{
|
||||
CardEffectKind.Damage => new DealDamageEffect(Amount, MaxAmount, Language, TrueDamage, CanCrit, AllEnemies),
|
||||
CardEffectKind.Shield => new ShieldEffect(Amount),
|
||||
CardEffectKind.Draw => new DrawEffect(Amount),
|
||||
CardEffectKind.AskUbuntu => new AskUbuntuEffect(),
|
||||
CardEffectKind.ChanceDamage => new ChanceDamageEffect(Amount, SecondaryAmount, Language),
|
||||
CardEffectKind.PreviousLanguageDamage => new PreviousLanguageDamageEffect(Amount, SecondaryAmount, Language),
|
||||
CardEffectKind.QueuedGrowthDamage => new QueuedGrowthDamageEffect(Amount, Language),
|
||||
CardEffectKind.BtwScaledDamage => new BtwScaledDamageEffect(Amount, SecondaryAmount, Language),
|
||||
CardEffectKind.CompilationDraw => new CompilationDrawEffect(),
|
||||
CardEffectKind.MakeJ4 => new MakeJ4Effect(),
|
||||
CardEffectKind.HaskellFilter => new HaskellFilterEffect(),
|
||||
CardEffectKind.HaskellMaybe => new HaskellMaybeEffect(),
|
||||
CardEffectKind.NextTurnCycle => new NextTurnCycleEffect(Amount),
|
||||
CardEffectKind.QueueRepeat => new QueueRepeatEffect(Amount),
|
||||
CardEffectKind.CopyLowestCostHandCard => new CopyLowestCostHandCardEffect(),
|
||||
CardEffectKind.UnattendedUpgrades => new ApplyStatusEffect(StatusType.UnattendedUpgrades, Amount, SecondaryAmount, targetSelf: true, skipNextTick: true),
|
||||
CardEffectKind.Cleanse => new CleanseEffect(harmfulOnly: true),
|
||||
CardEffectKind.ShuffleToken => new ShuffleTokenIntoDrawPileEffect(ReferenceId),
|
||||
CardEffectKind.UpgradeHandCards => new UpgradeHandCardsEffect(Amount, MaxAmount),
|
||||
CardEffectKind.GenerateCard => new GenerateCardEffect(Language, Rarity.Common),
|
||||
CardEffectKind.NoOp => new NoOpCardEffect(ReferenceId),
|
||||
CardEffectKind.UpdateManager => new UpdateManagerEffect(Amount),
|
||||
CardEffectKind.ShieldRepeatDamage => new ConditionalShieldRepeatDamageEffect(Amount, Language),
|
||||
CardEffectKind.Timeshift => new TimeshiftSnapshotEffect(),
|
||||
CardEffectKind.DnfAutoremove => new DnfAutoremoveEffect(Amount, SecondaryAmount),
|
||||
CardEffectKind.FirstToPackage => new FirstToPackageEffect(Amount),
|
||||
CardEffectKind.Rawhide => new RawhideEffect(),
|
||||
CardEffectKind.IncomingAttackHalve => new IncomingAttackHalveEffect(Amount),
|
||||
CardEffectKind.ConsultWiki => new ConsultWikiEffect(),
|
||||
CardEffectKind.RandomCommonLanguageCard => new RandomCommonLanguageCardEffect(),
|
||||
CardEffectKind.MinimalInstall => new MinimalInstallEffect(),
|
||||
CardEffectKind.SizeofDamage => new SizeofDamageEffect(),
|
||||
CardEffectKind.RepairCorruptedCards => new RepairCorruptedCardsEffect(Amount),
|
||||
_ => throw new InvalidOperationException($"Unsupported authored effect {Kind}.")
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CardCatalogEntry
|
||||
{
|
||||
private readonly string _rules;
|
||||
public string Id { get; }
|
||||
public CardTargeting Targeting { get; }
|
||||
public bool RequiresSingleTarget => Targeting == CardTargeting.SingleEnemy;
|
||||
public bool TargetsAllEnemies => Targeting == CardTargeting.AllEnemies;
|
||||
public bool BleedingEdgeEligible { get; }
|
||||
public IReadOnlyList<CardEffectSpec> Effects { get; }
|
||||
|
||||
internal CardCatalogEntry(string id, CardTargeting targeting, bool bleedingEdgeEligible,
|
||||
string rules, params CardEffectSpec[] effects)
|
||||
{
|
||||
Id = id;
|
||||
Targeting = targeting;
|
||||
BleedingEdgeEligible = bleedingEdgeEligible;
|
||||
_rules = rules;
|
||||
Effects = Array.AsReadOnly((CardEffectSpec[])effects.Clone());
|
||||
}
|
||||
|
||||
public IReadOnlyList<ICardEffect> CreateEffects()
|
||||
{
|
||||
ICardEffect[] result = new ICardEffect[Effects.Count];
|
||||
for (int i = 0; i < result.Length; i++) result[i] = Effects[i].CreateRuntimeEffect();
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rules reference descriptor values by index: amount/shield/max/secondary scale with
|
||||
/// card magnitude, while raw/rawSecondary/rawMax deliberately remain unscaled.
|
||||
/// Queue growth is resolved from the card without changing any combat state.
|
||||
/// </summary>
|
||||
public string GetRulesText(CardInstance card)
|
||||
{
|
||||
if (_rules == null)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(card?.Definition?.Description)
|
||||
? "effect not authored."
|
||||
: card.Definition.Description + (card.UpgradeLevel > 0 ? " [upgraded]" : string.Empty);
|
||||
}
|
||||
string text = _rules;
|
||||
for (int i = 0; i < Effects.Count; i++)
|
||||
{
|
||||
CardEffectSpec effect = Effects[i];
|
||||
text = text.Replace("{plural:" + i + "}", UpgradeMath.ScaleAmount(effect.Amount, card) == 1 ? string.Empty : "s");
|
||||
text = Replace(text, "amount", i, UpgradeMath.ScaleAmount(effect.Amount, card));
|
||||
text = Replace(text, "shield", i, UpgradeMath.ScaleShield(effect.Amount, card));
|
||||
text = Replace(text, "max", i, UpgradeMath.ScaleAmount(effect.MaxAmount, card));
|
||||
text = Replace(text, "secondary", i, UpgradeMath.ScaleAmount(effect.SecondaryAmount, card));
|
||||
text = Replace(text, "secondaryShield", i, UpgradeMath.ScaleShield(effect.SecondaryAmount, card));
|
||||
text = Replace(text, "raw", i, effect.Amount);
|
||||
text = Replace(text, "rawMax", i, effect.MaxAmount);
|
||||
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));
|
||||
}
|
||||
return text + (card?.UpgradeLevel > 0 ? " [upgraded]" : string.Empty);
|
||||
}
|
||||
|
||||
private static string Replace(string text, string name, int index, int value)
|
||||
{
|
||||
return text.Replace("{" + name + ":" + index + "}", value.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Each built-in card ID is authored once here. Asset IDs and serialized effect overrides
|
||||
/// stay unchanged; adding a card no longer requires parallel effect, targeting and rules switches.
|
||||
/// </summary>
|
||||
public static class CardCatalog
|
||||
{
|
||||
private const CardTargeting None = CardTargeting.None;
|
||||
private const CardTargeting Single = CardTargeting.SingleEnemy;
|
||||
private const CardTargeting All = CardTargeting.AllEnemies;
|
||||
private const string CRecoil = " overkill spills. 25%: segfault, uptime -3 and corrupt a hand card.";
|
||||
private const string Jit = " overkill spills. JIT applies; discount decays by 1 after each wave.";
|
||||
private static readonly IReadOnlyDictionary<string, CardCatalogEntry> ById;
|
||||
public static IReadOnlyList<CardCatalogEntry> Entries { get; }
|
||||
|
||||
static CardCatalog()
|
||||
{
|
||||
var entries = new List<CardCatalogEntry>();
|
||||
void Add(string id, CardTargeting target, bool bleeding, string rules, params CardEffectSpec[] effects)
|
||||
=> entries.Add(new CardCatalogEntry(id, target, bleeding, rules, effects));
|
||||
|
||||
Add("gentoo_emerge_sync", None, false, "stack: gain {shield:0} Shield. draw {amount:1}.", Shield(2), Draw(1));
|
||||
Add("gentoo_ebuild", Single, false, "stack: deal {amount:0}.", Damage(4, Language.Haskell));
|
||||
Add("gentoo_use_flags", None, false, "gain {shield:0} Shield. if Compilation >= {rawSecondary:1}, draw {amount:1}.",
|
||||
Shield(4), Fx(CardEffectKind.CompilationDraw, CompilationDrawEffect.DrawCount, secondary: CompilationDrawEffect.RequiredCompilation));
|
||||
Add("gentoo_make_j4", Single, true, "deal {amount:0}; {secondary:0} if Compilation >= {rawMax:0}. one C hit; overkill spills; 25%: segfault, uptime -3 and corrupt a hand card.",
|
||||
Fx(CardEffectKind.MakeJ4, MakeJ4Effect.BaseDamage, MakeJ4Effect.RequiredCompilation, MakeJ4Effect.CompiledDamage, Language.C));
|
||||
Add("gentoo_emerge_world", All, false, "stack: deal {amount:0} to all living enemies. gain {shield:1} Shield.", Damage(3, Language.Haskell, all: true), Shield(2));
|
||||
Add("lang_hs_map", Single, false, "stack: deal {amount:0}.", Damage(2, Language.Haskell));
|
||||
Add("lang_hs_foldr", None, false, "stack: gain {shield:0} Shield. draw {amount:1}.", Shield(3), Draw(1));
|
||||
Add("lang_hs_thunk", Single, false, "stack: deal {amount:0}.", Damage(4, Language.Haskell));
|
||||
Add("shop_hs_filter", Single, false, "stack: deal {amount:0}; {secondary:0} if target has a harmful status. one hit.",
|
||||
Fx(CardEffectKind.HaskellFilter, HaskellFilterEffect.BaseDamage, secondary: HaskellFilterEffect.ConditionalDamage, language: Language.Haskell));
|
||||
Add("shop_hs_fmap", None, false, "stack: gain {shield:0} Shield.", Shield(2));
|
||||
Add("shop_hs_zipwith", All, false, "stack: deal {amount:0} to all living enemies.", Damage(2, Language.Haskell, all: true));
|
||||
Add("shop_hs_maybe", None, false, "stack: if below maximum Uptime, restore {amount:0} Uptime. otherwise gain {secondaryShield:0} Shield.",
|
||||
Fx(CardEffectKind.HaskellMaybe, HaskellMaybeEffect.HealAmount, secondary: HaskellMaybeEffect.ShieldAmount));
|
||||
Add("shop_hs_sequence", None, false, "stack: draw {amount:0}.", Draw(2));
|
||||
Add("shop_hs_const", Single, false, "stack: deal {amount:0}.", Damage(2, Language.Haskell));
|
||||
Add("shop_hs_scanl", None, false, "stack: gain {shield:0} Shield. draw {amount:1}.", Shield(4), Draw(1));
|
||||
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_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_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));
|
||||
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_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("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("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);
|
||||
Add("shop_js_spread", None, false, "copy the lowest-cost card in hand.", Fx(CardEffectKind.CopyLowestCostHandCard));
|
||||
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_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_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("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_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_aur_helper", None, false, "add a random C/Rust common card to hand; it costs 0 this turn.", Fx(CardEffectKind.RandomCommonLanguageCard));
|
||||
Add("arch_minimal_install", None, false, "exhaust up to {raw:0} hand cards. per card: gain {rawSecondary:0} Shield and {rawMax:0} Cycle.",
|
||||
Fx(CardEffectKind.MinimalInstall, MinimalInstallEffect.MaxExhaust, MinimalInstallEffect.CyclesPerCard, MinimalInstallEffect.ShieldPerCard));
|
||||
Add("shop_c_free", Single, true, "deal {amount:0}. overkill spills. 25%: segfault, uptime -3, corrupt a hand card, and draw 2. then repair up to {amount:1} corrupted card{plural:1} in your active deck.",
|
||||
Damage(18, Language.C), Fx(CardEffectKind.RepairCorruptedCards, 1));
|
||||
Add("shop_c_sizeof", Single, true, "deal {raw:0} x C cards in hand." + CRecoil, Fx(CardEffectKind.SizeofDamage, SizeofDamageEffect.DamagePerCard, language: Language.C));
|
||||
Add("shop_c_kernel_exploit", Single, true, "deal {amount:0} ignoring Shield. overkill spills. 50%: segfault, uptime -8 and corrupt a hand card.", Damage(36, Language.C, trueDamage: true));
|
||||
Add("shop_c_gdb", None, false, "repair up to {amount:0} corrupted cards in your active deck. draw {amount:1}.",
|
||||
Fx(CardEffectKind.RepairCorruptedCards, 2), Draw(1));
|
||||
Add("shop_c_valgrind", None, false, "repair up to {amount:0} corrupted cards in your active deck. gain {shield:1} Shield.",
|
||||
Fx(CardEffectKind.RepairCorruptedCards, 3), Shield(6));
|
||||
|
||||
var byId = new Dictionary<string, CardCatalogEntry>(StringComparer.Ordinal);
|
||||
foreach (CardCatalogEntry entry in entries) byId.Add(entry.Id, entry);
|
||||
Entries = entries.AsReadOnly();
|
||||
ById = new ReadOnlyDictionary<string, CardCatalogEntry>(byId);
|
||||
}
|
||||
|
||||
public static bool TryGet(string id, out CardCatalogEntry entry)
|
||||
{
|
||||
entry = null;
|
||||
return id != null && ById.TryGetValue(id, out entry);
|
||||
}
|
||||
|
||||
private static CardEffectSpec Damage(int amount, Language language, int max = -1, bool all = false, bool trueDamage = false)
|
||||
=> 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 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 64c67631f8c94fbf96527bc0d79588cd
|
||||
@@ -0,0 +1,75 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using KernelPanic.Core;
|
||||
|
||||
namespace KernelPanic.Combat
|
||||
{
|
||||
/// <summary>
|
||||
/// Shared card-hit lifecycle. Amount producers apply card magnitude and source flat bonuses
|
||||
/// once; this executor passes that amount through the damage pipeline without scaling it again.
|
||||
/// </summary>
|
||||
internal static class CardDamageExecutor
|
||||
{
|
||||
internal static int ScaleAmount(int baseAmount, CombatContext context) =>
|
||||
UpgradeMath.ScaleAmount(CardScaling.Add(UpgradeMath.ApplySourceFlatBonus(baseAmount, context),
|
||||
context?.Source?.FlatCardDamageBonus ?? 0), context.Card);
|
||||
|
||||
internal static void Execute(CombatContext context, Func<int> rollAmount, Language language,
|
||||
bool trueDamage = false, bool canCrit = true, bool allEnemies = false,
|
||||
bool overkillToShield = false, Action<int> reportHit = null)
|
||||
{
|
||||
IReadOnlyList<CombatantState> targets = ResolveTargets(context, allEnemies);
|
||||
bool dealtDamage = false;
|
||||
for (int i = 0; i < targets.Count; i++)
|
||||
{
|
||||
CombatantState target = targets[i];
|
||||
if (target == null || target.IsDefeated) continue;
|
||||
|
||||
int amount = rollAmount();
|
||||
bool rustOverflow = CardDamageLanguageRules.TryRollRustOverflow(context, language);
|
||||
if (rustOverflow) amount = int.MaxValue;
|
||||
|
||||
int capacity = CardDamageLanguageRules.GetDamageCapacity(target, trueDamage);
|
||||
DamageResult result = ApplyHit(context,
|
||||
DamageRequest.FromCard(context, target, amount, language, trueDamage, canCrit && !rustOverflow), overkillToShield);
|
||||
dealtDamage |= result.IncomingAmount > 0;
|
||||
dealtDamage |= CardDamageLanguageRules.TrySpillOverkill(context, target, result, capacity,
|
||||
language, trueDamage);
|
||||
reportHit?.Invoke(amount);
|
||||
}
|
||||
|
||||
SegfaultRecoil.TryApply(context, language, dealtDamage);
|
||||
}
|
||||
|
||||
internal static DamageResult ApplyHit(CombatContext context, DamageRequest request, bool overkillToShield = false)
|
||||
{
|
||||
int capacity = request.Target == null ? 0 : CardDamageLanguageRules.GetDamageCapacity(request.Target, request.TrueDamage);
|
||||
DamageResult result = context.DamagePipeline.DealDamage(request);
|
||||
// Preserve ordering: shield conversion precedes enemy death payloads, then spill follows removal queuing.
|
||||
if (request.IsCardDamage)
|
||||
CardDamageLanguageRules.ApplyOverkillShield(context, result, capacity, request.Language, overkillToShield);
|
||||
if (result.TargetDefeated)
|
||||
context.CombatManager.QueueDefeatedCombatantForRemoval(request.Target);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static IReadOnlyList<CombatantState> ResolveTargets(CombatContext context, bool allEnemies)
|
||||
{
|
||||
IReadOnlyList<CombatantState> targets = allEnemies
|
||||
? context.Enemies.Where(enemy => enemy?.State != null && !enemy.State.IsDefeated)
|
||||
.Select(enemy => enemy.State).ToList()
|
||||
: context.Targets;
|
||||
if (!StatusEffectController.Has(context.Source, StatusType.RaceCondition) || targets.Count < 2)
|
||||
return targets;
|
||||
|
||||
List<CombatantState> shuffled = targets.ToList();
|
||||
for (int i = shuffled.Count - 1; i > 0; i--)
|
||||
{
|
||||
int swapIndex = RandomRoll.RollRange(0, i, new RollContext(context.Source));
|
||||
(shuffled[i], shuffled[swapIndex]) = (shuffled[swapIndex], shuffled[i]);
|
||||
}
|
||||
return shuffled;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: cba4bb43d50c5232046ff3ffbe0ab9b3
|
||||
@@ -0,0 +1,88 @@
|
||||
using KernelPanic.Core;
|
||||
using UnityEngine;
|
||||
|
||||
namespace KernelPanic.Combat
|
||||
{
|
||||
/// <summary>Language riders for card damage. Spill hits never reapply source or card bonuses.</summary>
|
||||
internal static class CardDamageLanguageRules
|
||||
{
|
||||
private const int RustOverflowRollMax = 10000000;
|
||||
private const string RustUnsigned64LimitText = "18446744073709551615";
|
||||
|
||||
internal static bool TryRollRustOverflow(CombatContext context, Language language)
|
||||
{
|
||||
if (!IsRustDamage(context, language)
|
||||
|| RandomRoll.RollRange(1, RustOverflowRollMax, new RollContext(context.Source)) != 1)
|
||||
return false;
|
||||
|
||||
context.CombatManager.ReportEffectResult($"rust unsigned overflow: {RustUnsigned64LimitText}");
|
||||
return true;
|
||||
}
|
||||
|
||||
internal static int GetDamageCapacity(CombatantState target, bool trueDamage) =>
|
||||
trueDamage ? Mathf.Max(0, target.CurrentUptime) : CardScaling.Add(target.CurrentUptime, target.Shield);
|
||||
|
||||
internal static void ApplyOverkillShield(CombatContext context, DamageResult result,
|
||||
int capacity, Language language, bool explicitOverkillShield)
|
||||
{
|
||||
int overkill = Mathf.Max(0, result.IncomingAmount - capacity);
|
||||
if (overkill == 0) return;
|
||||
|
||||
bool rust = IsRustDamage(context, language);
|
||||
// Explicit conversion and Rust's implicit conversion describe the same excess hit.
|
||||
if (rust || explicitOverkillShield)
|
||||
GrantOverkillShield(context, overkill, rust ? "rust overkill" : "overkill");
|
||||
}
|
||||
|
||||
internal static bool TrySpillOverkill(CombatContext context, CombatantState target, DamageResult result,
|
||||
int capacity, Language language, bool trueDamage)
|
||||
{
|
||||
int overkill = Mathf.Max(0, result.IncomingAmount - capacity);
|
||||
return overkill > 0 && IsSpillDamage(context, language)
|
||||
&& SpillOverkillDamage(context, target, overkill, language, trueDamage);
|
||||
}
|
||||
|
||||
private static bool IsRustDamage(CombatContext context, Language language) =>
|
||||
language == Language.Rust || context.Card?.Definition?.Language == Language.Rust;
|
||||
|
||||
private static bool IsSpillDamage(CombatContext context, Language language)
|
||||
{
|
||||
Language cardLanguage = context.Card?.Definition?.Language ?? language;
|
||||
return language == Language.C || language == Language.Java
|
||||
|| cardLanguage == Language.C || cardLanguage == Language.Java;
|
||||
}
|
||||
|
||||
private static bool SpillOverkillDamage(CombatContext context, CombatantState firstTarget,
|
||||
int remaining, Language language, bool trueDamage)
|
||||
{
|
||||
bool dealtDamage = false;
|
||||
// Keep the original target excluded even if a lethal-hit save left it alive.
|
||||
CombatantState originalTarget = firstTarget;
|
||||
for (int i = 0; i < context.Enemies.Count && remaining > 0; i++)
|
||||
{
|
||||
CombatantState target = context.Enemies[i]?.State;
|
||||
if (target == null || target == originalTarget || target == firstTarget || target.IsDefeated)
|
||||
continue;
|
||||
|
||||
int capacity = GetDamageCapacity(target, trueDamage);
|
||||
GameEvents.RaiseOverflowDamageTravel(new OverflowDamageTravelEvent(context.Source, firstTarget, target, remaining, language));
|
||||
DamageResult result = CardDamageExecutor.ApplyHit(context,
|
||||
new DamageRequest(context.Source, target, remaining, language, trueDamage, false, applySourceModifiers: false));
|
||||
dealtDamage |= result.IncomingAmount > 0;
|
||||
firstTarget = target;
|
||||
remaining = Mathf.Max(0, result.IncomingAmount - capacity);
|
||||
}
|
||||
return dealtDamage;
|
||||
}
|
||||
|
||||
private static void GrantOverkillShield(CombatContext context, int overkill, string reason)
|
||||
{
|
||||
if (!context.CombatManager.CanPlayerReceiveCardShield(context.Card))
|
||||
{
|
||||
context.CombatManager.ReportEffectResult($"overkill shield blocked: {overkill}");
|
||||
return;
|
||||
}
|
||||
context.CombatManager.GrantPlayerShield(overkill, reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6e4803e6caaa61538aa798afd397af94
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b1100000000000000000000000000006
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,34 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace KernelPanic.Combat
|
||||
{
|
||||
/// <summary>
|
||||
/// Shared card eligibility rules for previews, playability checks, and effect execution.
|
||||
/// </summary>
|
||||
public static class CardEligibility
|
||||
{
|
||||
public static bool IsJunkForAutoremove(CardInstance card)
|
||||
{
|
||||
return card != null && (card.IsBroken || card.Definition != null && card.Definition.IsJunk);
|
||||
}
|
||||
|
||||
public static CardInstance FindAutoremoveTarget(IReadOnlyList<CardInstance> hand, CardInstance playedCard)
|
||||
{
|
||||
if (hand == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
for (int i = 0; i < hand.Count; i++)
|
||||
{
|
||||
CardInstance card = hand[i];
|
||||
if (card != playedCard && IsJunkForAutoremove(card))
|
||||
{
|
||||
return card;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 92f5633fd6d249aca9a491d7a774492d
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c05e61a09404ee046a6771f8ac75803c
|
||||
@@ -0,0 +1,349 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using KernelPanic.Core;
|
||||
|
||||
namespace KernelPanic.Combat
|
||||
{
|
||||
/// <summary>Potential incoming damage and explicit Shield, never a prediction of RNG or kills.</summary>
|
||||
public sealed class CardPreview
|
||||
{
|
||||
public string Summary { get; internal set; } = string.Empty;
|
||||
public string Details { get; internal set; } = string.Empty;
|
||||
public int MinimumDamage { get; internal set; }
|
||||
public int MaximumDamage { get; internal set; }
|
||||
public int Shield { get; internal set; }
|
||||
public int Heal { get; internal set; }
|
||||
public int RepairCapacity { get; internal set; }
|
||||
public int Repairs { get; internal set; }
|
||||
public int Cost { get; internal set; }
|
||||
public bool HasDamage { get; internal set; }
|
||||
public bool IsConditional { get; internal set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads catalog values and current authoritative combat state. This never creates or
|
||||
/// executes effects, mutates a card, calls gameplay hooks, or reads a random number.
|
||||
/// Deferred cards show their captured stack multiplier and current resolution conditions.
|
||||
/// </summary>
|
||||
public static class CardPreviewService
|
||||
{
|
||||
public static CardPreview Build(CombatManager combat, CardInstance card, CombatantState target = null)
|
||||
{
|
||||
var result = new CardPreview();
|
||||
if (combat?.PlayerState == null || card?.Definition == null) return result;
|
||||
result.Cost = combat.GetDisplayedPlayCost(card);
|
||||
if (card.Definition.IsToken || card.IsBroken || card.IsLocked)
|
||||
{
|
||||
result.Summary = card.Definition.IsToken ? "Unplayable" : card.IsBroken ? CorruptionSummary(card) : "Locked";
|
||||
result.Details = result.Summary;
|
||||
if (card.IsBroken) result.Details += "\n" + CorruptionDetails(card);
|
||||
return result;
|
||||
}
|
||||
if (card.Definition.Effects.Any(effect => effect != null)
|
||||
|| !CardCatalog.TryGet(card.Definition.Id, out var entry))
|
||||
{
|
||||
result.Summary = "Conditional effect";
|
||||
result.Details = "Custom effect: no numeric preview is available. See card rules.";
|
||||
result.IsConditional = true;
|
||||
return result;
|
||||
}
|
||||
|
||||
var notes = new List<string>();
|
||||
var source = combat.PlayerState;
|
||||
var lazyEntry = combat.LazyStack?.Entries.FirstOrDefault(item => item.Card == card);
|
||||
bool queued = lazyEntry != null || combat.InterpreterQueue?.Cards.Contains(card) == true;
|
||||
bool prospective = !queued;
|
||||
bool deferred = card.Definition.ResolutionTrack != ResolutionTrack.Native;
|
||||
bool fedora = prospective && combat.WouldApplyFedoraBonus(card);
|
||||
int growth = prospective ? combat.PreviewFedoraGrowth(card) : 0;
|
||||
int magnitude = CardScaling.Add(card.MagnitudeBonus, growth);
|
||||
int lazy = GetLazyMultiplier(combat, card, lazyEntry);
|
||||
int archStacks = source.ArchBtwStacks + (prospective && IsDistro(combat, "arch") ? 1 : 0);
|
||||
int damageMultiplier = deferred ? 100 : fedora ? (combat.RunConfig.DistroVersion >= 2 ? 175 : 150) : source.DamageMultiplierPercent;
|
||||
int cardMultiplier = deferred ? 100 : combat.PreviewFirstCCardMultiplier(card);
|
||||
int sourceFlat = source.FlatEffectBonus;
|
||||
// DNF's play hook runs after Native execution but before deferred resolution.
|
||||
// Already queued cards include their accepted play's stack in authoritative state.
|
||||
int cardDamageFlat = CardScaling.Add(source.FlatCardDamageBonus,
|
||||
prospective && deferred ? combat.PreviewNextDnfDamageStack() : 0);
|
||||
bool allEnemies = entry.TargetsAllEnemies || entry.Effects.Any(effect => effect.AllEnemies);
|
||||
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;
|
||||
|
||||
notes.Add(queued ? "Already played; its Cycles were paid on acceptance." : combat.GetCardCostBreakdown(card));
|
||||
if (deferred)
|
||||
{
|
||||
notes.Add("At resolution, using current state. Earlier cards, queue repeats and later buffs can change the outcome.");
|
||||
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.");
|
||||
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) + ".");
|
||||
if (sourceFlat > 0) notes.Add($"Source effect bonus: +{sourceFlat} before scaling.");
|
||||
if (cardDamageFlat > 0) notes.Add($"Card damage bonus: +{cardDamageFlat} before scaling; does not increase draw, Shield, healing or status stacks.");
|
||||
if (archStacks > 0) notes.Add($"BTW: {archStacks} stacks, +{archStacks * Math.Max(1, source.ArchBtwDamagePerStack)} to C/Rust damage" + (prospective && IsDistro(combat, "arch") ? " (includes this play)" : string.Empty) + ".");
|
||||
if (source.JavaScriptFlatDamageBonus > 0) notes.Add($"JavaScript flat damage: +{source.JavaScriptFlatDamageBonus}.");
|
||||
if (fedora)
|
||||
{
|
||||
notes.Add(combat.IsCardCrashImmune(card)
|
||||
? "Bleeding Edge: this card is crash-immune."
|
||||
: $"On a successful play; Bleeding Edge can crash ({combat.FedoraCrashChance:0.#}%).");
|
||||
result.IsConditional |= !combat.IsCardCrashImmune(card);
|
||||
}
|
||||
if (source.IgnoreDamageMultipliers) notes.Add("Mint ignores damage multipliers and uses maximum rolls; crits are disabled.");
|
||||
else
|
||||
{
|
||||
if (damageMultiplier != 100) notes.Add($"Damage multiplier: {damageMultiplier}%.");
|
||||
if (cardMultiplier != 100) notes.Add($"First C-card package multiplier: {cardMultiplier}%.");
|
||||
}
|
||||
|
||||
int minAcrossTargets = int.MaxValue, maxAcrossTargets = 0;
|
||||
int explicitShield = 0, heal = 0, repairCapacity = 0;
|
||||
bool hasShield = false, hasDamage = false, rust = false, critical = false, random = false, trueDamage = false;
|
||||
int hitCount = 0;
|
||||
foreach (var previewTarget in targets)
|
||||
{
|
||||
int targetMin = 0, targetMax = 0;
|
||||
int targetShield = 0, targetHeal = 0, targetHits = 0, targetRepairCapacity = 0;
|
||||
foreach (var effect in entry.Effects)
|
||||
{
|
||||
int low = effect.Amount, high = effect.MaxAmount;
|
||||
bool damage = false, chance = false;
|
||||
int repeats = 1;
|
||||
switch (effect.Kind)
|
||||
{
|
||||
case CardEffectKind.Damage:
|
||||
damage = true;
|
||||
break;
|
||||
case CardEffectKind.ChanceDamage:
|
||||
damage = true;
|
||||
chance = !source.ForceMaxRolls && effect.SecondaryAmount < 100;
|
||||
low = high = effect.Amount;
|
||||
AddNote(notes, $"Hit chance: {(source.ForceMaxRolls ? 100 : effect.SecondaryAmount)}%; failure still receives applicable flat damage bonuses.");
|
||||
break;
|
||||
case CardEffectKind.PreviousLanguageDamage:
|
||||
bool matches = prospective
|
||||
? source.HasLastPlayedCardLanguage && source.LastPlayedCardLanguage == effect.Language
|
||||
: source.HasPreviousPlayedCardLanguage && source.PreviousPlayedCardLanguage == effect.Language;
|
||||
low = high = matches ? effect.SecondaryAmount : effect.Amount;
|
||||
damage = true;
|
||||
break;
|
||||
case CardEffectKind.QueuedGrowthDamage:
|
||||
low = high = effect.Amount + Math.Max(0, card.QueuePlayCount + (prospective ? 1 : 0) - 1);
|
||||
damage = true;
|
||||
break;
|
||||
case CardEffectKind.BtwScaledDamage:
|
||||
low = high = effect.Amount + archStacks * Math.Max(effect.SecondaryAmount, source.ArchMakepkgBtwMultiplier);
|
||||
damage = true;
|
||||
break;
|
||||
case CardEffectKind.MakeJ4:
|
||||
low = high = combat.Compilation.Level >= effect.MaxAmount ? effect.SecondaryAmount : effect.Amount;
|
||||
damage = true;
|
||||
break;
|
||||
case CardEffectKind.HaskellFilter:
|
||||
bool harmful = previewTarget != null && previewTarget.Statuses.Any(status => !StatusEffectController.GetDescriptor(status.Type).IsBeneficial);
|
||||
low = high = harmful ? effect.SecondaryAmount : effect.Amount;
|
||||
damage = true;
|
||||
break;
|
||||
case CardEffectKind.SizeofDamage:
|
||||
low = high = effect.Amount * HandAfterPlay(combat, card).Count(c => c.Definition?.Language == Language.C);
|
||||
damage = true;
|
||||
break;
|
||||
case CardEffectKind.ShieldRepeatDamage:
|
||||
low = high = effect.Amount;
|
||||
repeats = source.Shield > 0 ? 2 : 1;
|
||||
damage = true;
|
||||
break;
|
||||
case CardEffectKind.FirstToPackage:
|
||||
case CardEffectKind.UpdateManager:
|
||||
low = high = effect.Amount;
|
||||
damage = true;
|
||||
if (effect.Kind == CardEffectKind.UpdateManager)
|
||||
AddNote(notes, "Update Manager captures the source effect bonus and card magnitude for its delayed repeat. The repeat uses current damage modifiers, Compilation and enemy defenses, with no Haskell stack multiplier.");
|
||||
break;
|
||||
case CardEffectKind.DnfAutoremove:
|
||||
if (!combat.HasJunkForPreview(card))
|
||||
{
|
||||
AddNote(notes, "No junk in hand: no damage or Cycle gain.");
|
||||
break;
|
||||
}
|
||||
low = high = effect.Amount;
|
||||
damage = true;
|
||||
AddNote(notes, "Damage requires junk in hand at resolution; otherwise no damage or Cycle gain.");
|
||||
result.IsConditional = true;
|
||||
break;
|
||||
case CardEffectKind.ConsultWiki:
|
||||
if (HandAfterPlay(combat, card).Any(c => c.IsBroken))
|
||||
AddNote(notes, "Repairs a broken card and draws; no damage with the current hand.");
|
||||
else { low = high = effect.Amount; damage = true; }
|
||||
break;
|
||||
case CardEffectKind.Shield:
|
||||
hasShield = true;
|
||||
targetShield = CardScaling.Add(targetShield, ScaledShield(effect.Amount, sourceFlat, magnitude, lazy, combat));
|
||||
break;
|
||||
case CardEffectKind.HaskellMaybe:
|
||||
if (source.CurrentUptime >= source.MaxUptime)
|
||||
{
|
||||
hasShield = true;
|
||||
targetShield = CardScaling.Add(targetShield, ScaledShield(effect.SecondaryAmount, sourceFlat, magnitude, lazy, combat));
|
||||
}
|
||||
else if (combat.CanPlayerReceiveCardHeal(card))
|
||||
targetHeal = CardScaling.Add(targetHeal, Math.Min(source.MaxUptime - source.CurrentUptime, ScaledBase(effect.Amount, sourceFlat, magnitude)));
|
||||
else AddNote(notes, "Healing blocked by Mint.");
|
||||
break;
|
||||
case CardEffectKind.MinimalInstall:
|
||||
hasShield = true;
|
||||
int exhausted = Math.Min(effect.Amount, HandAfterPlay(combat, card).Count());
|
||||
targetShield = CardScaling.Add(targetShield, CardScaling.Scale(exhausted * effect.SecondaryAmount, lazy, combat.Compilation.ShieldPercent));
|
||||
AddNote(notes, $"Exhausts {exhausted} cards with the current hand; grants {exhausted * effect.MaxAmount} Cycles. Exhaust package hooks may add benefits.");
|
||||
break;
|
||||
case CardEffectKind.Timeshift:
|
||||
AddNote(notes, $"Snapshots {source.CurrentUptime} Uptime; future restoration depends on later damage.");
|
||||
result.IsConditional = true;
|
||||
break;
|
||||
case CardEffectKind.RepairCorruptedCards:
|
||||
targetRepairCapacity = CardScaling.Add(targetRepairCapacity, CardScaling.Add(effect.Amount, magnitude));
|
||||
if (targetHits > 0 && !source.ForceMaxRolls && card.Definition.Language == Language.C)
|
||||
AddNote(notes, "Repair resolves after damage and any segfault from this card, so it can repair a newly corrupted card.");
|
||||
break;
|
||||
}
|
||||
if (!damage) continue;
|
||||
hasDamage = true;
|
||||
targetHits += repeats;
|
||||
low = ScaledBase(low, CardScaling.Add(sourceFlat, cardDamageFlat), magnitude);
|
||||
high = ScaledBase(high, CardScaling.Add(sourceFlat, cardDamageFlat), magnitude);
|
||||
if (source.ForceMaxRolls) low = high;
|
||||
if (chance) low = 0; // Runtime chance failure passes zero through flat/multiplier stages.
|
||||
random |= low != high;
|
||||
critical |= effect.CanCrit && !source.ForceMaxRolls;
|
||||
rust |= effect.Language == Language.Rust || card.Definition.Language == Language.Rust;
|
||||
trueDamage |= effect.TrueDamage;
|
||||
var minimum = DamageRequest.PreviewCard(source, previewTarget, low, effect.Language, effect.TrueDamage, effect.CanCrit, lazy, combat.Compilation.DamagePercent);
|
||||
var maximum = DamageRequest.PreviewCard(source, previewTarget, high, effect.Language, effect.TrueDamage, effect.CanCrit, lazy, combat.Compilation.DamagePercent);
|
||||
int minHit = combat.DamagePipeline.PreviewIncomingDamage(minimum, false, archStacks, damageMultiplier, cardMultiplier);
|
||||
int maxHit = combat.DamagePipeline.PreviewIncomingDamage(maximum, true, archStacks, damageMultiplier, cardMultiplier);
|
||||
for (int hit = 0; hit < repeats; hit++)
|
||||
{
|
||||
targetMin = CardScaling.Add(targetMin, minHit);
|
||||
targetMax = CardScaling.Add(targetMax, maxHit);
|
||||
}
|
||||
}
|
||||
minAcrossTargets = Math.Min(minAcrossTargets, targetMin);
|
||||
maxAcrossTargets = Math.Max(maxAcrossTargets, targetMax);
|
||||
explicitShield = Math.Max(explicitShield, targetShield);
|
||||
heal = Math.Max(heal, targetHeal);
|
||||
repairCapacity = Math.Max(repairCapacity, targetRepairCapacity);
|
||||
hitCount = Math.Max(hitCount, targetHits);
|
||||
}
|
||||
|
||||
if (hasShield && !combat.CanPlayerReceiveCardShield(card))
|
||||
{
|
||||
explicitShield = 0;
|
||||
notes.Add("Explicit card Shield is blocked by Mint.");
|
||||
}
|
||||
// Package play hooks run once for an accepted play, including deferred cards.
|
||||
int playShield = prospective ? combat.PreviewCardPlayShield(card) : 0;
|
||||
result.Shield = CardScaling.Add(explicitShield, playShield);
|
||||
if (result.Shield > 0 && combat.PreviewFirstShieldBonus() > 0)
|
||||
{
|
||||
result.Shield = CardScaling.Add(result.Shield, combat.PreviewFirstShieldBonus());
|
||||
notes.Add($"First-Shield package bonus: +{combat.PreviewFirstShieldBonus()} once, if still ready.");
|
||||
}
|
||||
if (playShield > 0) notes.Add($"Successful play package Shield: +{playShield} once (not multiplied by Compilation or Haskell).");
|
||||
result.Heal = heal;
|
||||
result.RepairCapacity = repairCapacity;
|
||||
result.Repairs = Math.Min(repairCapacity, combat.CorruptedCardCount);
|
||||
if (repairCapacity > 0)
|
||||
notes.Add($"Repair up to {repairCapacity} corrupted {(repairCapacity == 1 ? "card" : "cards")} across your run deck; {combat.CorruptedCardCount} currently corrupted. Repairs prioritize your hand. Repair count scales with card magnitude only.");
|
||||
result.MinimumDamage = hasDamage ? minAcrossTargets : 0;
|
||||
result.MaximumDamage = hasDamage ? maxAcrossTargets : 0;
|
||||
result.HasDamage = hasDamage;
|
||||
if (hasDamage)
|
||||
{
|
||||
notes.Add("Damage is incoming damage before target Shield and remaining Uptime; critical hits are included in the range.");
|
||||
if (!hasSelectedTarget && !allEnemies && entry.RequiresSingleTarget)
|
||||
notes.Add("Select a target; the range currently covers living targets.");
|
||||
if (allEnemies) notes.Add("Damage shown per target; defenses can differ between enemies.");
|
||||
if (hitCount > 1) notes.Add($"{hitCount} hits in total; later hits can stop when a target dies or combat ends.");
|
||||
if (trueDamage) notes.Add("True damage bypasses Shield.");
|
||||
if (random) notes.Add("Random amounts show the full normal range.");
|
||||
if (critical) notes.Add("Critical chance: C 50%, other languages 25%; each hit rolls independently.");
|
||||
if (rust) notes.Add(source.ForceMaxRolls
|
||||
? "Rust overkill can grant Shield; max-roll mode prevents unsigned overflow."
|
||||
: "Rare Rust unsigned overflow is not included in the normal range. Overkill can grant additional Shield.");
|
||||
if (card.Definition.Language == Language.C && !source.ForceMaxRolls) notes.Add("C damage can trigger segfault recoil and corrupt a hand card. Segfault corruption recovers automatically after 3 rounds, or earlier with repair; recoil is not included.");
|
||||
if (!combat.DamagePipeline.CanPreviewResistance)
|
||||
{
|
||||
notes.Add("A custom resistance hook has no pure preview; damage shown before that hook.");
|
||||
result.IsConditional = true;
|
||||
}
|
||||
}
|
||||
var parts = new List<string>();
|
||||
if (hasDamage) parts.Add($"{Range(result.MinimumDamage, result.MaximumDamage)} damage" + (allEnemies ? "/target" : string.Empty));
|
||||
if (hasShield || result.Shield > 0) parts.Add($"+{result.Shield} Shield");
|
||||
if (heal > 0) parts.Add($"+{heal} Uptime");
|
||||
if (repairCapacity > 0) parts.Add($"repair up to {repairCapacity}");
|
||||
if (parts.Count == 0) parts.Add("Utility · see rules");
|
||||
result.Summary = string.Join(" · ", parts);
|
||||
result.Details = result.Summary + "\n" + string.Join("\n", notes);
|
||||
return result;
|
||||
}
|
||||
|
||||
public static string CorruptionSummary(CardInstance card) => card?.CorruptionRoundsRemaining > 0
|
||||
? $"Corrupted · recovers in {card.CorruptionRoundsRemaining} {(card.CorruptionRoundsRemaining == 1 ? "round" : "rounds")}"
|
||||
: "Corrupted · repair required";
|
||||
|
||||
public static string CorruptionDetails(CardInstance card) => card?.CorruptionRoundsRemaining > 0
|
||||
? $"Unplayable until repaired. Automatic recovery in {card.CorruptionRoundsRemaining} {(card.CorruptionRoundsRemaining == 1 ? "round" : "rounds")}; a repair card can restore it sooner."
|
||||
: "Unplayable until repaired. This corruption has no automatic recovery timer.";
|
||||
|
||||
private static int ScaledBase(int amount, int sourceFlat, int magnitude) =>
|
||||
CardScaling.Add(CardScaling.Add(amount, sourceFlat), magnitude);
|
||||
|
||||
private static int ScaledShield(int amount, int sourceFlat, int magnitude, int lazy, CombatManager combat) =>
|
||||
CardScaling.Scale(ScaledBase(amount, sourceFlat, magnitude), lazy, combat.Compilation.ShieldPercent);
|
||||
|
||||
private static string Range(int minimum, int maximum) => minimum == maximum ? minimum.ToString() : $"{minimum}–{maximum}";
|
||||
|
||||
private static void AddNote(List<string> notes, string note) { if (!notes.Contains(note)) notes.Add(note); }
|
||||
|
||||
private static bool IsDistro(CombatManager combat, string id) =>
|
||||
string.Equals(combat.RunConfig?.Distro?.Id, id, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private static IEnumerable<CardInstance> HandAfterPlay(CombatManager combat, CardInstance card) =>
|
||||
combat.HandController == null ? Enumerable.Empty<CardInstance>() : combat.HandController.Cards.Where(item => item != null && item != card);
|
||||
|
||||
private static int GetLazyMultiplier(CombatManager combat, CardInstance card, LazyStackEntry captured)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<CombatantState> PreviewTargets(CombatManager combat, CardInstance card,
|
||||
CombatantState target, bool queued, bool allEnemies)
|
||||
{
|
||||
if (!allEnemies)
|
||||
{
|
||||
if (target != null && !target.IsDefeated) return new[] { target };
|
||||
if (queued)
|
||||
{
|
||||
var captured = card.TargetSnapshot.Where(item => item != null && !item.IsDefeated).ToArray();
|
||||
if (captured.Length > 0) return captured;
|
||||
}
|
||||
else if (combat.SelectedEnemyIndex >= 0 && combat.SelectedEnemyIndex < combat.Enemies.Count)
|
||||
{
|
||||
var selected = combat.Enemies[combat.SelectedEnemyIndex].State;
|
||||
if (selected != null && !selected.IsDefeated) return new[] { selected };
|
||||
}
|
||||
}
|
||||
var living = combat.Enemies.Where(enemy => enemy.State != null && !enemy.State.IsDefeated).Select(enemy => enemy.State).ToArray();
|
||||
return living.Length == 0 ? new CombatantState[] { null } : living;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: acd50a890a1542b5b6d45e52e0444d11
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,23 @@
|
||||
namespace KernelPanic.Combat
|
||||
{
|
||||
/// <summary>
|
||||
/// Shared explicit card-Shield resolution. Effects choose whether their base reward receives
|
||||
/// source and magnitude bonuses; eligibility and explicit multipliers are applied here once.
|
||||
/// </summary>
|
||||
internal static class CardShieldExecutor
|
||||
{
|
||||
internal static int ScaleAmount(int baseAmount, CombatContext context) =>
|
||||
UpgradeMath.ScaleShield(UpgradeMath.ApplySourceFlatBonus(baseAmount, context), context.Card);
|
||||
|
||||
internal static void Execute(CombatContext context, int amount, string label = "card")
|
||||
{
|
||||
if (!context.CombatManager.CanPlayerReceiveCardShield(context.Card))
|
||||
{
|
||||
context.CombatManager.ReportEffectResult($"shield blocked: {amount}");
|
||||
return;
|
||||
}
|
||||
|
||||
context.CombatManager.GrantPlayerShield(context.ScaleExplicitShield(amount), label);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 364946246fb54c2895c0f8fa0d3bb4ef
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2eed81ad20b42a447858691a49666804
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9f87432412de1ee46bf7d4c9c530d4c6
|
||||
@@ -0,0 +1,106 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Meta;
|
||||
|
||||
namespace KernelPanic.Combat
|
||||
{
|
||||
/// <summary>Observation only. Never consumes randomness or changes combat state.</summary>
|
||||
public sealed class CombatRunTelemetry : IDisposable
|
||||
{
|
||||
private readonly Func<CombatantState> _player;
|
||||
private readonly Func<CombatantState, string> _describeSource;
|
||||
private readonly Queue<string> _hits = new();
|
||||
private bool _surrendering;
|
||||
private int _lastCompletedRound;
|
||||
public int Round { get; private set; }
|
||||
public int DamageDealt { get; private set; }
|
||||
public int DamageTaken { get; private set; }
|
||||
public int ShieldBlocked { get; private set; }
|
||||
public string KillingAction { get; private set; }
|
||||
public Func<bool> SurrenderRequested { get; set; }
|
||||
public IReadOnlyCollection<string> IncomingHits => _hits;
|
||||
|
||||
public CombatRunTelemetry(Func<CombatantState> player, Func<CombatantState, string> describeSource)
|
||||
{
|
||||
_player = player;
|
||||
_describeSource = describeSource;
|
||||
GameEvents.PhaseChanged += OnPhaseChanged;
|
||||
GameEvents.DamageDealt += ObserveDamage;
|
||||
GameEvents.WaveAdvanced += OnWaveAdvanced;
|
||||
}
|
||||
|
||||
public void BeginRound()
|
||||
{
|
||||
if (!string.IsNullOrEmpty(KillingAction)) return;
|
||||
Round++;
|
||||
DamageDealt = 0;
|
||||
DamageTaken = 0;
|
||||
ShieldBlocked = 0;
|
||||
_hits.Clear();
|
||||
}
|
||||
|
||||
private void OnPhaseChanged(PhaseChangedEvent payload)
|
||||
{
|
||||
if (payload.NextPhase == TurnPhase.Boot)
|
||||
{
|
||||
Round = 0;
|
||||
_lastCompletedRound = 0;
|
||||
KillingAction = null;
|
||||
_surrendering = false;
|
||||
DamageDealt = DamageTaken = ShieldBlocked = 0;
|
||||
_hits.Clear();
|
||||
}
|
||||
else if (payload.NextPhase == TurnPhase.Allocate) BeginRound();
|
||||
}
|
||||
|
||||
public void MarkSurrender() => _surrendering = true;
|
||||
|
||||
private void OnWaveAdvanced(WaveAdvancedEvent payload)
|
||||
{
|
||||
_lastCompletedRound = Round;
|
||||
Round = 0;
|
||||
}
|
||||
|
||||
public void ObserveDamage(DamageDealtEvent payload)
|
||||
{
|
||||
var player = _player?.Invoke();
|
||||
if (player == null || _surrendering || SurrenderRequested?.Invoke() == true) return;
|
||||
if (ReferenceEquals(payload.Target, player))
|
||||
{
|
||||
DamageTaken += Math.Max(0, payload.UptimeDamage);
|
||||
ShieldBlocked += Math.Max(0, payload.ShieldDamage);
|
||||
string cause = !string.IsNullOrWhiteSpace(payload.Cause) ? payload.Cause
|
||||
: _describeSource?.Invoke(payload.Source) ?? "Unattributed system damage";
|
||||
string hit = $"{cause}: {payload.UptimeDamage} uptime / {payload.ShieldDamage} shield" +
|
||||
(payload.TrueDamage ? " (bypasses shield)" : string.Empty);
|
||||
if (payload.IncomingAmount > 0)
|
||||
{
|
||||
_hits.Enqueue(hit);
|
||||
while (_hits.Count > 8) _hits.Dequeue();
|
||||
}
|
||||
if (player.CurrentUptime <= 0 && !payload.ArchRollingReleaseSaveTriggered && string.IsNullOrEmpty(KillingAction))
|
||||
KillingAction = hit;
|
||||
}
|
||||
else if (ReferenceEquals(payload.Source, player))
|
||||
DamageDealt += Math.Max(0, payload.UptimeDamage);
|
||||
}
|
||||
|
||||
public void FillReport(RunHistoryEntry entry)
|
||||
{
|
||||
entry.finalRound = Round > 0 ? Round : _lastCompletedRound;
|
||||
entry.damageDealt = DamageDealt;
|
||||
entry.damageTaken = DamageTaken;
|
||||
entry.shieldBlocked = ShieldBlocked;
|
||||
entry.cause = entry.surrendered ? "Shutdown signal accepted." : KillingAction ?? "Uptime reached 0; no damaging action recorded.";
|
||||
entry.finalHits = new List<string>(_hits);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
GameEvents.PhaseChanged -= OnPhaseChanged;
|
||||
GameEvents.DamageDealt -= ObserveDamage;
|
||||
GameEvents.WaveAdvanced -= OnWaveAdvanced;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: dd64bf26935869431215eef4de870c55
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b1100000000000000000000000000009
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 93b1080022652b542903e204d36a64f8
|
||||
@@ -0,0 +1,64 @@
|
||||
using System;
|
||||
|
||||
namespace KernelPanic.Combat
|
||||
{
|
||||
/// <summary>Wave-scoped Gentoo progression. Round IDs make completion idempotent.</summary>
|
||||
public sealed class CompilationState
|
||||
{
|
||||
private int _version;
|
||||
private int _lastCompletedRound;
|
||||
public int LastAdvancedRound { get; private set; }
|
||||
public bool Active => _version > 0;
|
||||
public int Level { get; private set; }
|
||||
public int Maximum => !Active ? 0 : _version >= 5 ? 6 : 4;
|
||||
public int DamagePercent => !Active ? 100 : Level == 0 ? (_version >= 2 ? 95 : 85) : 100 + (Level - 1) * 10;
|
||||
public int ShieldPercent => _version >= 4 ? 100 + Level * 5 : 100;
|
||||
|
||||
public void BeginWave(int version)
|
||||
{
|
||||
_version = Math.Max(0, Math.Min(5, version));
|
||||
Level = _version >= 3 ? 1 : 0;
|
||||
_lastCompletedRound = 0;
|
||||
LastAdvancedRound = 0;
|
||||
}
|
||||
|
||||
public bool CompleteRound(int round)
|
||||
{
|
||||
if (!Active || round <= _lastCompletedRound) return false;
|
||||
_lastCompletedRound = round;
|
||||
if (Level >= Maximum) return false;
|
||||
Level++;
|
||||
LastAdvancedRound = round;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Silent equipment advancement: no completion or compilation-increase hooks.
|
||||
public void AdvanceFromEquipment(int amount, int round)
|
||||
{
|
||||
if (!Active || amount <= 0 || Level >= Maximum) return;
|
||||
Level = (int)Math.Min(Maximum, (long)Level + amount);
|
||||
LastAdvancedRound = round;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// New card multipliers use exact decimal arithmetic and one final nearest-even rounding,
|
||||
/// matching Mathf.RoundToInt's tie policy. Saturate before conversion; never wrap negative.
|
||||
/// Crit/resistance retain their existing, later rounding stages.
|
||||
/// </summary>
|
||||
public static class CardScaling
|
||||
{
|
||||
public static int Scale(int amount, params int[] percentages)
|
||||
{
|
||||
decimal value = Math.Max(0, amount);
|
||||
try
|
||||
{
|
||||
foreach (int percent in percentages) value = value * Math.Max(0, percent) / 100m;
|
||||
}
|
||||
catch (OverflowException) { return int.MaxValue; }
|
||||
return (int)Math.Min(int.MaxValue, decimal.Round(value, 0, MidpointRounding.ToEven));
|
||||
}
|
||||
|
||||
public static int Add(int amount, int bonus) => (int)Math.Min(int.MaxValue, (long)Math.Max(0, amount) + Math.Max(0, bonus));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b821fa56a5034b9bbd3a000000000201
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b1100000000000000000000000000005
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6683933e853af334ba19e658b13c878d
|
||||
@@ -0,0 +1,67 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using KernelPanic.Run;
|
||||
|
||||
namespace KernelPanic.Combat
|
||||
{
|
||||
public sealed class EncounterPlan
|
||||
{
|
||||
public string Title { get; }
|
||||
public string Advice { get; }
|
||||
public IReadOnlyList<string> Enemies { get; }
|
||||
public int UptimeBonus { get; }
|
||||
public EncounterPlan(string title, string advice, int uptimeBonus, params string[] enemies)
|
||||
{ Title = title; Advice = advice; UptimeBonus = uptimeBonus; Enemies = Array.AsReadOnly(enemies); }
|
||||
}
|
||||
|
||||
/// <summary>Authored encounter composition. Reads no random state; spawning owns stat rolls.</summary>
|
||||
public static class EncounterDirector
|
||||
{
|
||||
public static EncounterPlan Plan(int wave, WaveRoute route)
|
||||
{
|
||||
string title, advice;
|
||||
string[] enemies;
|
||||
switch (wave)
|
||||
{
|
||||
case 1:
|
||||
title = "Boot diagnostics";
|
||||
advice = "Memory Leak grows each round. A Zombie can revive once: finish weakened zombies decisively.";
|
||||
enemies = new[] { "zombie_process", "memory_leak" }; break;
|
||||
case 2:
|
||||
title = "Firewall maintenance";
|
||||
advice = "firewalld shields its neighbours. Cron Job counts down to a heavy attack.";
|
||||
enemies = new[] { "firewalld", "cron_job" }; break;
|
||||
case 3:
|
||||
title = "Process explosion";
|
||||
advice = "Fork Bomb copies itself after acting. Stop it before the process table fills.";
|
||||
enemies = new[] { "fork_bomb", "memory_leak", "firewalld" }; break;
|
||||
case 4:
|
||||
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:
|
||||
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;
|
||||
default:
|
||||
title = "Endless / " + wave;
|
||||
advice = "Threats return in stronger combinations. Race partners remain paired.";
|
||||
enemies = (wave % 4) switch
|
||||
{
|
||||
0 => new[] { "race_condition", "race_condition", "drm_guardian", "segfault" },
|
||||
1 => new[] { "kernel_overseer", "telemetry_collector", "firewalld" },
|
||||
2 => new[] { "rootkit", "fork_bomb", "cron_job", "memory_leak" },
|
||||
_ => new[] { "kernel_panic", "daemon", "firewalld", "zombie_process" }
|
||||
}; break;
|
||||
}
|
||||
if (wave > 1 && route == WaveRoute.Challenge)
|
||||
{
|
||||
var harder = new List<string>(enemies) { "daemon" };
|
||||
enemies = harder.ToArray();
|
||||
title += " / challenge";
|
||||
advice += " An elite Daemon escorts this route; damage it to expose its intent.";
|
||||
}
|
||||
return new EncounterPlan(title, advice, Math.Max(0, wave - 1) * CombatTuning.EnemyUptimeGrowthPerWave, enemies);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 319cac6a8938459eb14f3495c88f647c
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 051af243e3ee3d644b8d3cdb7f11b57d
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b1100000000000000000000000000001
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b1100000000000000000000000000007
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,42 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace KernelPanic.Combat
|
||||
{
|
||||
/// <summary>Snapshot of public intentions, never a speculative execution or random roll.</summary>
|
||||
public static class ExecutionPreview
|
||||
{
|
||||
public static IReadOnlyList<string> Build(CombatManager 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.");
|
||||
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.");
|
||||
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)
|
||||
{
|
||||
if (enemy.PendingRevive) { lines.Add(enemy.Name + ": revival pending; blocks wave completion."); continue; }
|
||||
if (enemy.State.IsDefeated) continue;
|
||||
string uncertainty = enemy.HasBehavior(EnemyBehaviorFlags.RacePair) ? " / race pair order can swap; partner bonuses apply" : "";
|
||||
lines.Add(enemy.Name + " > " + enemy.DisplayIntent.DisplayText + uncertainty);
|
||||
}
|
||||
lines.Add("CLEANUP / status ticks, delayed effects and next-round resources. Estimates use current state independently: earlier cards, deaths, retargeting, new spawns, random rolls and buffs can change later results. No guaranteed damage total.");
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static string CardLine(CombatManager combat, CardInstance card, int order, string track,
|
||||
IReadOnlyList<CombatantState> targets)
|
||||
{
|
||||
var names = targets.Select(target => ReferenceEquals(target, combat.PlayerState) ? "self"
|
||||
: combat.Enemies.FirstOrDefault(enemy => ReferenceEquals(enemy.State, target))?.Name ?? "departed target");
|
||||
string targetText = targets.Count == 0 ? "card-defined targets" : string.Join(", ", names);
|
||||
string preview = CardPreviewService.Build(combat, card).Summary;
|
||||
return $"{order:00} / {track} / {card.Definition.DisplayName} > {targetText}\nCurrent estimate: {preview}";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7dc726705cda4b21b9841e429b9b7f4a
|
||||
@@ -0,0 +1,67 @@
|
||||
using System.Linq;
|
||||
using KernelPanic.Core;
|
||||
|
||||
namespace KernelPanic.Combat
|
||||
{
|
||||
public sealed class CompilationDrawEffect : ICardEffect
|
||||
{
|
||||
internal const int RequiredCompilation = 2;
|
||||
internal const int DrawCount = 1;
|
||||
|
||||
public void Execute(CombatContext context)
|
||||
{
|
||||
if (context.CombatManager.Compilation.Level >= RequiredCompilation) new DrawEffect(DrawCount).Execute(context);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class MakeJ4Effect : ICardEffect
|
||||
{
|
||||
internal const int RequiredCompilation = 3;
|
||||
internal const int BaseDamage = 8;
|
||||
internal const int CompiledDamage = 11;
|
||||
|
||||
public void Execute(CombatContext context)
|
||||
{
|
||||
int amount = context.CombatManager.Compilation.Level >= RequiredCompilation ? CompiledDamage : BaseDamage;
|
||||
new DealDamageEffect(amount, amount, Language.C).Execute(context);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class HaskellFilterEffect : ICardEffect
|
||||
{
|
||||
internal const int BaseDamage = 4;
|
||||
internal const int ConditionalDamage = 6;
|
||||
|
||||
public void Execute(CombatContext context)
|
||||
{
|
||||
bool harmful = context.Targets.Any(target => target != null && !target.IsDefeated
|
||||
&& target.Statuses.Any(status => !StatusEffectController.GetDescriptor(status.Type).IsBeneficial));
|
||||
int amount = harmful ? ConditionalDamage : BaseDamage;
|
||||
new DealDamageEffect(amount, amount, Language.Haskell).Execute(context);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class HaskellMaybeEffect : ICardEffect
|
||||
{
|
||||
internal const int HealAmount = 3;
|
||||
internal const int ShieldAmount = 4;
|
||||
|
||||
public void Execute(CombatContext context)
|
||||
{
|
||||
if (context.Source.CurrentUptime >= context.Source.MaxUptime)
|
||||
{
|
||||
new ShieldEffect(ShieldAmount).Execute(context);
|
||||
return;
|
||||
}
|
||||
if (!context.CombatManager.CanPlayerReceiveCardHeal(context.Card))
|
||||
{
|
||||
context.CombatManager.ReportEffectResult("heal blocked");
|
||||
return;
|
||||
}
|
||||
int amount = UpgradeMath.ScaleAmount(UpgradeMath.ApplySourceFlatBonus(HealAmount, context), context.Card);
|
||||
int before = context.Source.CurrentUptime;
|
||||
context.Source.CurrentUptime = System.Math.Min(context.Source.MaxUptime, CardScaling.Add(before, amount));
|
||||
context.CombatManager.ReportEffectResult($"maybe: restored {context.Source.CurrentUptime - before} Uptime");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b821fa56a5034b9bbd3a000000000202
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bece1c6fddc2c63489bf129bf6295a31
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 886be8d59396e5e488eea3ea58445fb4
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5d296d1160df6d747adaeec9ef68c710
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 13c99cf765e7e8b48a58afbacc8a5440
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 556859e6fac10a24bb4a60165fd82157
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b662e4e1a38b1554084a063fd3d415e2
|
||||
@@ -0,0 +1,32 @@
|
||||
using KernelPanic.Data;
|
||||
|
||||
namespace KernelPanic.Combat
|
||||
{
|
||||
/// <summary>A read-only view of an equipped package, derived from authoritative combat state.</summary>
|
||||
public readonly struct PackageCombatReadout
|
||||
{
|
||||
public PackageCombatReadout(PackageDefinition definition, string state, string details)
|
||||
{
|
||||
Definition = definition;
|
||||
State = state;
|
||||
Details = details;
|
||||
}
|
||||
|
||||
public PackageDefinition Definition { get; }
|
||||
public string State { get; }
|
||||
public string Details { get; }
|
||||
}
|
||||
|
||||
public readonly struct PackageActivation
|
||||
{
|
||||
public PackageActivation(string packageId, string name, string message)
|
||||
{
|
||||
PackageId = packageId;
|
||||
Name = name;
|
||||
Message = message;
|
||||
}
|
||||
public string PackageId { get; }
|
||||
public string Name { get; }
|
||||
public string Message { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c52fa5b733144fdb8f098323be070501
|
||||
@@ -0,0 +1,45 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Meta;
|
||||
|
||||
namespace KernelPanic.Combat
|
||||
{
|
||||
/// <summary>Pure package pricing shared by actual plays and hypothetical card previews.</summary>
|
||||
public static class PackageCostRules
|
||||
{
|
||||
public static int Apply(int cost, IReadOnlyList<PackageInstance> packages, string distroId,
|
||||
int cardsPlayedThisTurn, int cardsPlayedThisWave, List<string> breakdown = null)
|
||||
{
|
||||
if (cost <= 0 || packages == null) return cost;
|
||||
int nextTurnCard = cardsPlayedThisTurn + 1;
|
||||
int nextWaveCard = cardsPlayedThisWave + 1;
|
||||
foreach (var package in packages)
|
||||
{
|
||||
if (package?.Definition == null) continue;
|
||||
int before = Math.Max(0, cost);
|
||||
foreach (var effect in package.EffectsFor(distroId))
|
||||
{
|
||||
switch (effect.Kind)
|
||||
{
|
||||
case PackageEffectKind.FirstCardEachRoundDiscountAndShield:
|
||||
if (nextTurnCard == 1) cost -= 1;
|
||||
break;
|
||||
case PackageEffectKind.FirstCardEachWaveCostReduction:
|
||||
if (nextWaveCard == 1) cost -= Math.Max(0, effect.Amount);
|
||||
break;
|
||||
case PackageEffectKind.EveryNthCardEachWaveFree:
|
||||
if (effect.Threshold > 0 && nextWaveCard % effect.Threshold == 0) cost = 0;
|
||||
break;
|
||||
case PackageEffectKind.FirstCardsEachTurnCostReduction:
|
||||
if (nextTurnCard <= Math.Max(0, effect.Threshold)) cost -= Math.Max(0, effect.Amount);
|
||||
break;
|
||||
}
|
||||
}
|
||||
int reduction = before - Math.Max(0, cost);
|
||||
if (reduction > 0) breakdown?.Add($"{package.Definition.DisplayName}: -{reduction}");
|
||||
}
|
||||
return cost;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3f9e27ef06ab42d6b58f7d5ff6cc5f20
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b1100000000000000000000000000004
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5f91b8d9171889f4996bb3106d97f1f6
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b1100000000000000000000000000008
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
|
||||
namespace KernelPanic.Data
|
||||
{
|
||||
/// <summary>Shared gacha and collection rarity; does not alter serialized distro schemas.</summary>
|
||||
public static class DistroRarity
|
||||
{
|
||||
public static int Stars(DistroDefinition distro) => distro != null &&
|
||||
(string.Equals(distro.Id, "arch", StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(distro.Id, "gentoo", StringComparison.OrdinalIgnoreCase)) ? 5 : 4;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
|
||||
namespace KernelPanic.Meta
|
||||
{
|
||||
/// <summary>Unfinished run setup; package slots are stored in the existing per-distro package loadouts.</summary>
|
||||
[Serializable]
|
||||
public sealed class RunBuildDraftSaveEntry
|
||||
{
|
||||
public string distroId;
|
||||
public List<string> cardIds = new();
|
||||
public List<Language> languages = new();
|
||||
|
||||
public void EnsureLists()
|
||||
{
|
||||
cardIds ??= new List<string>();
|
||||
languages ??= new List<Language>();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Frozen package identity and upgrade level for reproducing the previous build.</summary>
|
||||
[Serializable]
|
||||
public sealed class RunBuildPackageSaveEntry
|
||||
{
|
||||
public string packageId;
|
||||
public PackageSlot slot;
|
||||
public int upgradeLevel;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Run;
|
||||
|
||||
namespace KernelPanic.Meta
|
||||
{
|
||||
[Serializable]
|
||||
public sealed class RunHistoryEntry
|
||||
{
|
||||
public string runId;
|
||||
public string endedUtc;
|
||||
public string distroId;
|
||||
public string distroName;
|
||||
public int distroVersion;
|
||||
public string languages;
|
||||
public int seed;
|
||||
public int waveReached;
|
||||
public int wavesCleared;
|
||||
public bool surrendered;
|
||||
public bool victory;
|
||||
public string cause;
|
||||
public int finalRound;
|
||||
public int damageDealt;
|
||||
public int damageTaken;
|
||||
public int shieldBlocked;
|
||||
public List<string> finalHits = new();
|
||||
public RunHistoryBuildSnapshot build;
|
||||
}
|
||||
|
||||
/// <summary>The original starting build, not the deck after repository upgrades.</summary>
|
||||
[Serializable]
|
||||
public sealed class RunHistoryBuildSnapshot
|
||||
{
|
||||
// Keep the default zero: JsonUtility may create an empty object for old saves.
|
||||
public int schemaVersion;
|
||||
public string distroId;
|
||||
public int distroVersion;
|
||||
public int seed;
|
||||
public List<string> exclusiveCardIds = new();
|
||||
public List<string> startingDeckCardIds = new();
|
||||
public List<Language> languages = new();
|
||||
public List<RunBuildPackageSaveEntry> packages = new();
|
||||
}
|
||||
|
||||
public sealed class ResolvedHistoryBuild
|
||||
{
|
||||
public DistroDefinition Distro { get; internal set; }
|
||||
public List<string> CardIds { get; } = new();
|
||||
public List<Language> Languages { get; } = new();
|
||||
public List<PackageLoadoutSlotSaveEntry> PackageSlots { get; } = new();
|
||||
public int Seed { get; internal set; }
|
||||
public string Notice { get; internal set; }
|
||||
}
|
||||
|
||||
public static class RunHistory
|
||||
{
|
||||
public const int Capacity = 20;
|
||||
|
||||
public static bool HasBuildSnapshot(RunHistoryEntry entry) => entry?.build?.schemaVersion == 1;
|
||||
|
||||
public static RunHistoryBuildSnapshot CaptureBuild(RunConfig config)
|
||||
{
|
||||
if (config?.Distro == null) return null;
|
||||
var snapshot = new RunHistoryBuildSnapshot
|
||||
{
|
||||
schemaVersion = 1, distroId = config.Distro.Id,
|
||||
distroVersion = config.DistroVersion, seed = config.RunSeed,
|
||||
languages = new List<Language> { config.PrimaryLanguage, config.SecondaryLanguage }
|
||||
};
|
||||
var exclusiveIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var card in config.Distro.ExclusiveCards)
|
||||
if (card != null && !card.IsRunOnly && !card.IsToken) exclusiveIds.Add(card.Id);
|
||||
foreach (var card in config.StartingDeck ?? Array.Empty<CardDefinition>())
|
||||
{
|
||||
if (card == null) continue;
|
||||
snapshot.startingDeckCardIds.Add(card.Id);
|
||||
if (exclusiveIds.Contains(card.Id)) snapshot.exclusiveCardIds.Add(card.Id);
|
||||
}
|
||||
foreach (var package in config.EquippedPackages)
|
||||
if (package?.Definition != null)
|
||||
snapshot.packages.Add(new RunBuildPackageSaveEntry
|
||||
{
|
||||
packageId = package.Definition.Id, slot = package.Definition.Slot,
|
||||
upgradeLevel = package.UpgradeLevel
|
||||
});
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/// <summary>Resolve without changing drafts. Setup deliberately uses current owned upgrades.</summary>
|
||||
public static bool TryResolveBuild(RunHistoryEntry entry, PlayerCollection collection,
|
||||
DistroDatabase distros, CardDatabase cards, PackageDatabase packages, LanguageDeckDatabase languageDecks,
|
||||
out ResolvedHistoryBuild resolved, out string reason)
|
||||
{
|
||||
resolved = null;
|
||||
reason = "Build snapshot unavailable for this older run.";
|
||||
if (!HasBuildSnapshot(entry)) return false;
|
||||
var build = entry.build;
|
||||
reason = "This build snapshot is incomplete or uses an unsupported version.";
|
||||
if (build.distroVersion < 1 || build.distroVersion > GachaTuning.MaxVersion
|
||||
|| build.exclusiveCardIds?.Count != CardLoadout.MaxEquippedCards
|
||||
|| build.languages?.Count != 2 || build.languages[0] == build.languages[1]
|
||||
|| build.packages == null || build.startingDeckCardIds == null
|
||||
|| build.startingDeckCardIds.Count < CardLoadout.MaxEquippedCards) return false;
|
||||
var distro = distros == null ? null : distros.FindById(build.distroId);
|
||||
reason = $"Distro '{build.distroId}' is missing or is not currently owned.";
|
||||
if (distro == null || collection == null || !collection.IsOwned(distro.Id)) return false;
|
||||
var candidate = new ResolvedHistoryBuild { Distro = distro, Seed = build.seed };
|
||||
var changes = new List<string>();
|
||||
int currentVersion = collection.GetVersion(distro.Id);
|
||||
if (currentVersion != build.distroVersion)
|
||||
changes.Add($"{distro.DisplayName}: archived V{build.distroVersion} -> owned V{currentVersion}");
|
||||
var uniqueCards = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (string id in build.exclusiveCardIds)
|
||||
{
|
||||
CardDefinition card = null;
|
||||
foreach (var exclusive in distro.ExclusiveCards)
|
||||
if (exclusive != null && string.Equals(exclusive.Id, id, StringComparison.OrdinalIgnoreCase)) { card = exclusive; break; }
|
||||
reason = $"Exclusive card '{id}' is missing or no longer available in this distro's setup.";
|
||||
if (card == null || card.IsRunOnly || card.IsToken || !uniqueCards.Add(card.Id)) return false;
|
||||
candidate.CardIds.Add(card.Id);
|
||||
if (!build.startingDeckCardIds.Exists(savedId => string.Equals(savedId, card.Id, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
reason = "This build snapshot is incomplete: a selected card is missing from its starting deck.";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
foreach (var language in build.languages)
|
||||
{
|
||||
reason = $"Language '{language}' is missing or is not currently unlocked.";
|
||||
if (!Enum.IsDefined(typeof(Language), language) || !LanguageUnlock.IsUnlocked(language, collection)
|
||||
|| languageDecks == null || languageDecks.FindByLanguage(language) == null) return false;
|
||||
candidate.Languages.Add(language);
|
||||
}
|
||||
foreach (string id in build.startingDeckCardIds)
|
||||
{
|
||||
reason = $"Starting-deck card '{id}' is missing from the current content.";
|
||||
if (string.IsNullOrWhiteSpace(id) || (cards?.FindById(id) == null && !uniqueCards.Contains(id))) return false;
|
||||
}
|
||||
var slots = new HashSet<PackageSlot>();
|
||||
foreach (var saved in build.packages)
|
||||
{
|
||||
var definition = saved == null || packages == null ? null : packages.FindById(saved.packageId);
|
||||
var owned = definition == null ? null : collection.GetOwnedPackage(definition.Id);
|
||||
reason = $"Package '{saved?.packageId ?? "unknown"}' is missing, not owned, or has an invalid saved slot.";
|
||||
if (definition == null || owned == null || !Enum.IsDefined(typeof(PackageSlot), saved.slot)
|
||||
|| definition.Slot != saved.slot || !slots.Add(saved.slot)
|
||||
|| saved.upgradeLevel < 0 || saved.upgradeLevel > PackageTuning.MaxPackageLevel) return false;
|
||||
candidate.PackageSlots.Add(new PackageLoadoutSlotSaveEntry { packageId = definition.Id, slot = definition.Slot });
|
||||
if (owned.UpgradeLevel != saved.upgradeLevel)
|
||||
changes.Add($"{definition.DisplayName}: archived +{saved.upgradeLevel} -> owned +{owned.UpgradeLevel}");
|
||||
}
|
||||
candidate.Notice = "Archive build loaded into setup with its original seed. Nothing has launched. Setup uses current owned distro and package upgrades."
|
||||
+ (changes.Count == 0 ? "" : " Changed: " + string.Join("; ", changes) + ".")
|
||||
+ " Card and language rules use the currently installed content.";
|
||||
resolved = candidate;
|
||||
reason = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void Record(List<RunHistoryEntry> entries, RunHistoryEntry entry)
|
||||
{
|
||||
if (entries == null || entry == null || string.IsNullOrWhiteSpace(entry.runId)) return;
|
||||
entries.RemoveAll(old => old == null || string.Equals(old.runId, entry.runId, StringComparison.Ordinal));
|
||||
entries.Insert(0, entry);
|
||||
Normalize(entries);
|
||||
}
|
||||
|
||||
public static void Normalize(List<RunHistoryEntry> entries)
|
||||
{
|
||||
if (entries == null) return;
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
entries.RemoveAll(entry => entry == null || string.IsNullOrWhiteSpace(entry.runId) || !seen.Add(entry.runId));
|
||||
if (entries.Count > Capacity) entries.RemoveRange(Capacity, entries.Count - Capacity);
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
entry.waveReached = Math.Max(0, entry.waveReached);
|
||||
entry.wavesCleared = Math.Max(0, entry.wavesCleared);
|
||||
entry.damageDealt = Math.Max(0, entry.damageDealt);
|
||||
entry.damageTaken = Math.Max(0, entry.damageTaken);
|
||||
entry.shieldBlocked = Math.Max(0, entry.shieldBlocked);
|
||||
entry.finalHits ??= new List<string>();
|
||||
if (entry.finalHits.Count > 8) entry.finalHits.RemoveRange(0, entry.finalHits.Count - 8);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,788 @@
|
||||
#if UNITY_EDITOR || DEVELOPMENT_BUILD
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Meta;
|
||||
using KernelPanic.UI;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace KernelPanic.Run
|
||||
{
|
||||
/// <summary>Opt-in standalone development-build integration check with an isolated save.</summary>
|
||||
public sealed class PlayerSmokeRunner : MonoBehaviour
|
||||
{
|
||||
private string _output;
|
||||
private string _failure;
|
||||
private string _campaignSuccess;
|
||||
private string _stage = "startup";
|
||||
private float _deadline;
|
||||
|
||||
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
|
||||
private static void Install()
|
||||
{
|
||||
string[] args = Environment.GetCommandLineArgs();
|
||||
int flag = Array.IndexOf(args, "--kernel-panic-smoke");
|
||||
if (flag < 0) return;
|
||||
int saveFlag = Array.IndexOf(args, "--kernel-panic-save-path");
|
||||
if (saveFlag < 0 || saveFlag + 1 >= args.Length || !Path.IsPathRooted(args[saveFlag + 1]) || File.Exists(args[saveFlag + 1]) || File.Exists(args[saveFlag + 1] + ".bak"))
|
||||
{
|
||||
Debug.LogError("Smoke check requires an absolute, unused --kernel-panic-save-path.");
|
||||
Application.Quit(2);
|
||||
return;
|
||||
}
|
||||
// Install before the menu's OnEnable can schedule the animated boot sequence.
|
||||
UIPreferences.ReducedMotion = true; // Session only; never writes preferences.
|
||||
var owner = new GameObject("Player smoke verification");
|
||||
Application.runInBackground = true;
|
||||
DontDestroyOnLoad(owner);
|
||||
var runner = owner.AddComponent<PlayerSmokeRunner>();
|
||||
runner._output = Path.GetDirectoryName(args[saveFlag + 1]);
|
||||
Directory.CreateDirectory(runner._output);
|
||||
runner._deadline = Time.realtimeSinceStartup + 900;
|
||||
Application.logMessageReceived += runner.ObserveLog;
|
||||
}
|
||||
|
||||
private void ObserveLog(string message, string trace, LogType type)
|
||||
{
|
||||
if (type == LogType.Exception || type == LogType.Error || type == LogType.Assert)
|
||||
_failure ??= message + "\n" + trace;
|
||||
}
|
||||
|
||||
private IEnumerator Start()
|
||||
{
|
||||
// Pump manually so an exception writes a useful result and exits instead of hanging CI.
|
||||
var scenario = Scenario();
|
||||
while (true)
|
||||
{
|
||||
bool next = false;
|
||||
object yielded = null;
|
||||
try
|
||||
{
|
||||
if (_failure != null) throw new InvalidOperationException(_failure);
|
||||
if (Time.realtimeSinceStartup > _deadline) throw new TimeoutException("Smoke check timed out at " + _stage);
|
||||
next = scenario.MoveNext();
|
||||
if (next) yielded = scenario.Current;
|
||||
}
|
||||
catch (Exception ex) { _failure = ex.ToString(); }
|
||||
if (_failure != null || !next) break;
|
||||
yield return yielded;
|
||||
}
|
||||
Application.logMessageReceived -= ObserveLog;
|
||||
if (_failure == null && _campaignSuccess != null)
|
||||
{
|
||||
File.WriteAllText(Path.Combine(_output, "player-smoke-result.txt"), _campaignSuccess);
|
||||
Debug.Log("PLAYER_SMOKE_PASS");
|
||||
Application.Quit(0);
|
||||
yield break;
|
||||
}
|
||||
File.WriteAllText(Path.Combine(_output, "player-smoke-result.txt"), _failure == null ? "PASS: starter selection -> configured run -> pile tabs/search/grouping/cost details/keyboard focus -> combat -> repository purchase -> save and exit without payout -> exact repository resume -> next wave -> shutdown -> run archive command/navigation -> original build details/copy seed/load setup -> saved rewards/history -> same-seed retry -> new-seed retry -> natural defeat with attributed damage" : "FAIL at " + _stage + "\n" + _failure);
|
||||
Debug.Log(_failure == null ? "PLAYER_SMOKE_PASS" : "PLAYER_SMOKE_FAIL: " + _failure);
|
||||
Application.Quit(_failure == null ? 0 : 1);
|
||||
}
|
||||
|
||||
private IEnumerator Scenario()
|
||||
{
|
||||
// Preference loading is also a BeforeSceneLoad callback; reapply the session
|
||||
// override after all such callbacks, regardless of their registration order.
|
||||
UIPreferences.ReducedMotion = true;
|
||||
_stage = "starter selection";
|
||||
yield return new WaitForSecondsRealtime(2);
|
||||
var menu = FindFirstObjectByType<MainMenuController>();
|
||||
Require(menu != null, "Main menu scene did not initialize.");
|
||||
var starter = Field<StarterSelectionController>(menu, "starterSelection");
|
||||
if (!starter.IsActive)
|
||||
{
|
||||
// Exercise the normal "any key" boot skip; hidden windows need not run
|
||||
// the animated panel scheduler at the same cadence as a visible window.
|
||||
var startupRoot = menu.GetComponent<UIDocument>().rootVisualElement;
|
||||
using var skipIntro = KeyDownEvent.GetPooled(' ', KeyCode.Space, EventModifiers.None);
|
||||
skipIntro.target = startupRoot;
|
||||
startupRoot.SendEvent(skipIntro);
|
||||
}
|
||||
float starterDeadline = Time.realtimeSinceStartup + 30;
|
||||
while (!starter.IsActive && Time.realtimeSinceStartup < starterDeadline) yield return null;
|
||||
Require(starter.IsActive, $"Fresh profile did not show starter selection; boot elapsed={Field<float>(menu, "_bootIntroElapsed")}, starterChosen={new SaveService().Load().starterChosen}.");
|
||||
var choices = Field<System.Collections.Generic.IReadOnlyList<DistroDefinition>>(starter, "_activeStarters");
|
||||
int ubuntuIndex = choices.ToList().FindIndex(distro => distro.Id == "ubuntu");
|
||||
Require(ubuntuIndex >= 0, "Ubuntu starter not available.");
|
||||
Call(starter, "Select", ubuntuIndex);
|
||||
using (var key = KeyDownEvent.GetPooled('\n', KeyCode.Return, EventModifiers.None)) starter.HandleKeyDown(key);
|
||||
using (var key = KeyDownEvent.GetPooled('y', KeyCode.Y, EventModifiers.None)) starter.HandleKeyDown(key);
|
||||
yield return null;
|
||||
Require(new SaveService().Load().IsUnitOwned("ubuntu"), "Starter choice was not persisted.");
|
||||
var training = TutorialScenario();
|
||||
while (training.MoveNext()) yield return training.Current;
|
||||
if (Environment.GetCommandLineArgs().Contains("--kernel-panic-tutorial-smoke"))
|
||||
{
|
||||
_campaignSuccess = "PASS: two-wave guided tutorial, real targeting/revival/queue/stack, full clears, shop purchase, same-run resume, one-time 1000 Bandwidth + 1000 Entropy, clean normal-run workspace.";
|
||||
yield break;
|
||||
}
|
||||
menu = FindFirstObjectByType<MainMenuController>();
|
||||
_stage = "run setup";
|
||||
ConfigureMenu(menu);
|
||||
yield return null;
|
||||
Call(menu, "BootSelectedPackage");
|
||||
CombatManager combat = null;
|
||||
while (combat == null || !combat.CanSurrenderRun)
|
||||
{
|
||||
yield return null;
|
||||
combat = FindFirstObjectByType<CombatManager>();
|
||||
}
|
||||
Require(combat.RunConfig.RunSeed == 12345, "Run seed was not handed off.");
|
||||
string originalBuild = BuildSignature(combat.RunConfig);
|
||||
var view = FindFirstObjectByType<CombatSceneController>();
|
||||
var previewRoot = view.GetComponent<UIDocument>().rootVisualElement;
|
||||
var executionPreview = previewRoot.Q<Foldout>("ExecutionPreview");
|
||||
int drawsBeforePreview = RandomRoll.DrawCount;
|
||||
executionPreview.value = true;
|
||||
yield return null;
|
||||
var previewContents = previewRoot.Q("ExecutionPreviewPopup") ?? executionPreview;
|
||||
Require(RandomRoll.DrawCount == drawsBeforePreview && previewContents.Q<Label>(className: "terminal-body") != null,
|
||||
"Execution preview changed RNG or did not render its explanation.");
|
||||
executionPreview.value = false;
|
||||
if (Environment.GetCommandLineArgs().Contains("--kernel-panic-campaign-smoke"))
|
||||
{
|
||||
var campaign = CampaignScenario(combat, view);
|
||||
while (campaign.MoveNext()) yield return campaign.Current;
|
||||
yield break;
|
||||
}
|
||||
var guide = Field<FirstBattleGuide>(view, "_firstBattleGuide");
|
||||
guide.Begin(combat.RunConfig, true);
|
||||
var capture = CapturePanel(view.GetComponent<UIDocument>(), "first-battle");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
_stage = "pile inspection";
|
||||
var inspection = InspectPiles(view, combat);
|
||||
while (inspection.MoveNext()) yield return inspection.Current;
|
||||
_stage = "combat";
|
||||
int actions = 0;
|
||||
while (!combat.AwaitingWaveContinue && !combat.RunLost)
|
||||
{
|
||||
if (combat.CanSurrenderRun)
|
||||
{
|
||||
bool played = false;
|
||||
for (int i = 0; i < combat.Enemies.Count; i++)
|
||||
{
|
||||
if (!combat.Enemies[i].State.IsDefeated) { combat.SelectEnemy(i); break; }
|
||||
}
|
||||
foreach (var card in combat.HandController.Cards.ToArray())
|
||||
{
|
||||
if (combat.PlayCard(card)) { played = true; break; }
|
||||
}
|
||||
if (!played) combat.EndPlayerTurn();
|
||||
Require(++actions < 500, "Bot exceeded action budget before clearing wave one.");
|
||||
}
|
||||
yield return null;
|
||||
}
|
||||
Require(!combat.RunLost, "Seeded starter bot died before repository.");
|
||||
yield return null;
|
||||
_stage = "repository";
|
||||
var run = combat.GetComponent<RunManager>();
|
||||
Require(run.WavesCleared == 1 && run.RepositoryVisitActive, "Wave completion did not open repository.");
|
||||
Submit(view.GetComponent<UIDocument>().rootVisualElement.Q<Button>("RouteChallenge"));
|
||||
Require(run.Journey.selectedRoute == WaveRoute.Challenge, "Elite route selection did not reach the run model.");
|
||||
var offer = run.RepositoryOffers.FirstOrDefault(item => item.Price <= run.Bits);
|
||||
Require(offer != null, "No affordable repository offer.");
|
||||
int bits = run.Bits;
|
||||
Require(run.BuyOffer(offer, combat.PlayerState), "Repository purchase failed.");
|
||||
Require(run.Bits == bits - offer.Price, "Purchase charged incorrect Bits.");
|
||||
capture = CapturePanel(view.GetComponent<UIDocument>(), "repository");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
yield return null;
|
||||
|
||||
_stage = "repository checkpoint and suspension";
|
||||
string runId = run.RunId;
|
||||
string deckBefore = DeckSignature(run);
|
||||
string offersBefore = OfferSignature(run);
|
||||
RunCheckpoint beforeSuspend = run.CaptureCheckpoint(combat);
|
||||
string combatBefore = JsonUtility.ToJson(beforeSuspend.combat);
|
||||
int bankedBits = run.Bits;
|
||||
var beforeSave = new SaveService().Load();
|
||||
Call(view, "SaveAndExitRun");
|
||||
menu = null;
|
||||
while (menu == null) { yield return null; menu = FindFirstObjectByType<MainMenuController>(); }
|
||||
var suspended = new SaveService().Load();
|
||||
Require(suspended.activeRun != null && suspended.activeRun.runId == runId, "Repository checkpoint was not persisted.");
|
||||
Require(suspended.bandwidthBalance == beforeSave.bandwidthBalance && suspended.entropyBalance == beforeSave.entropyBalance,
|
||||
"Suspending the run paid out rewards.");
|
||||
Require(suspended.recentRuns.Count == beforeSave.recentRuns.Count, "Suspending created a completed-run history entry.");
|
||||
Require(JsonUtility.ToJson(suspended.activeRun.combat) == combatBefore, "Saved checkpoint changed carried combat state or RNG cursor.");
|
||||
_stage = "repository resume";
|
||||
Call(menu, "ResumeSavedRun");
|
||||
combat = null;
|
||||
while (combat == null || !combat.AwaitingWaveContinue)
|
||||
{
|
||||
yield return null;
|
||||
combat = FindFirstObjectByType<CombatManager>();
|
||||
}
|
||||
view = FindFirstObjectByType<CombatSceneController>();
|
||||
run = combat.GetComponent<RunManager>();
|
||||
Require(run.RepositoryVisitActive && run.RunId == runId && run.CurrentWaveNumber == beforeSuspend.wave
|
||||
&& run.WavesCleared == beforeSuspend.wavesCleared && run.Bits == bankedBits, "Resume changed run identity, wave or currency.");
|
||||
Require(DeckSignature(run) == deckBefore && OfferSignature(run) == offersBefore, "Resume changed cards, upgrades or repository offers.");
|
||||
Require(JsonUtility.ToJson(run.CaptureCheckpoint(combat).combat) == combatBefore, "Resume changed carried combat state or RNG cursor.");
|
||||
Require(BuildSignature(combat.RunConfig) == originalBuild, "Resume changed the original build.");
|
||||
Require(run.Journey.selectedRoute == WaveRoute.Challenge, "Resume lost the selected elite route.");
|
||||
Require(new SaveService().Load().activeRun == null, "Resumed checkpoint was not claimed exactly once.");
|
||||
capture = CapturePanel(view.GetComponent<UIDocument>(), "repository-resumed");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
combat.ContinueToNextWave();
|
||||
while (!combat.CanSurrenderRun) yield return null;
|
||||
Require(run.CurrentWaveNumber == 2, "Next wave failed to start.");
|
||||
_stage = "defeat and reward settlement";
|
||||
int reward = run.AccruedBandwidth + TutorialCampaign.BandwidthReward;
|
||||
Call(view, "ConfirmSurrender");
|
||||
yield return null;
|
||||
Require(combat.RunLost && run.RewardsSettled, "Defeat did not settle rewards.");
|
||||
var saved = new SaveService().Load();
|
||||
Require(saved.bandwidthBalance == reward && saved.GetBestWave("ubuntu") == 2, "Run rewards/stats were not persisted exactly once.");
|
||||
Require(saved.activeRun == null && saved.recentRuns.Count == 1 && saved.recentRuns[0].runId == runId
|
||||
&& saved.recentRuns[0].surrendered && !string.IsNullOrWhiteSpace(saved.recentRuns[0].cause), "Completed resumed run did not save a single useful history entry.");
|
||||
Require(saved.recentRuns[0].finalRound >= 1, "Next wave accepted shutdown before its first round was ready.");
|
||||
capture = CapturePanel(view.GetComponent<UIDocument>(), "run-report");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
yield return null;
|
||||
_stage = "return to menu and run archive";
|
||||
SceneLoader.LoadMainMenu(view.GetComponent<UIDocument>().rootVisualElement);
|
||||
menu = null;
|
||||
while (menu == null) { yield return null; menu = FindFirstObjectByType<MainMenuController>(); }
|
||||
Require(!Field<StarterSelectionController>(menu, "starterSelection").IsActive, "Returning profile unexpectedly needs a starter.");
|
||||
Require(new SaveService().Load().bandwidthBalance == reward, "Scene unload paid rewards twice.");
|
||||
var menuRoot = menu.GetComponent<UIDocument>().rootVisualElement;
|
||||
yield return null;
|
||||
var homePanel = menuRoot.Q("MainMenuPanel");
|
||||
Require(homePanel != null && homePanel.resolvedStyle.display != DisplayStyle.None, "Returning profile did not show the main menu.");
|
||||
Require(homePanel.Q("RetrySameSeedButton") == null && homePanel.Q("RetryNewSeedButton") == null
|
||||
&& homePanel.Q("RecentRunsButton") == null, "Archived run actions still appear on the main menu.");
|
||||
var archiveCommand = menuRoot.Q("CommandRunArchive");
|
||||
Require(archiveCommand != null && archiveCommand.parent.IndexOf(archiveCommand) == archiveCommand.parent.IndexOf(menuRoot.Q("CommandSettings")) + 1
|
||||
&& archiveCommand.parent.IndexOf(menuRoot.Q("CommandQuit")) == archiveCommand.parent.IndexOf(archiveCommand) + 1,
|
||||
"Run archive command is not between Settings and Quit.");
|
||||
capture = CapturePanel(menu.GetComponent<UIDocument>(), "home-menu");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
OpenRunArchive(menuRoot);
|
||||
yield return null;
|
||||
RequireArchiveVisible(menuRoot);
|
||||
capture = CapturePanel(menu.GetComponent<UIDocument>(), "run-archive");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
_stage = "recent runs within archive";
|
||||
Submit(menuRoot.Q<Button>("RecentRunsButton"));
|
||||
yield return null;
|
||||
Require(menuRoot.Q("RunHistoryOverlay") != null, "Recent runs did not open.");
|
||||
var archived = new SaveService().Load().recentRuns[0];
|
||||
Require(RunHistory.HasBuildSnapshot(archived) && archived.build.seed == 12345
|
||||
&& archived.build.startingDeckCardIds.Count > 4, "Run history did not preserve the original starting build.");
|
||||
menuRoot.Q<Foldout>("ArchivedBuildDetails_0").value = true;
|
||||
string previousClipboard = GUIUtility.systemCopyBuffer;
|
||||
try
|
||||
{
|
||||
Submit(menuRoot.Q<Button>("CopyRunSeed_0"));
|
||||
Require(GUIUtility.systemCopyBuffer == "12345", "Archive copy-seed action copied the wrong seed.");
|
||||
}
|
||||
finally { GUIUtility.systemCopyBuffer = previousClipboard; }
|
||||
capture = CapturePanel(menu.GetComponent<UIDocument>(), "run-history");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
string retryBeforeLoad = JsonUtility.ToJson(new SaveService().Load().lastRunLoadout);
|
||||
Submit(menuRoot.Q<Button>("LoadArchivedBuild_0"));
|
||||
yield return null;
|
||||
Require(menuRoot.Q("RunSetupPanel").resolvedStyle.display != DisplayStyle.None
|
||||
&& !Field<bool>(menu, "_runLaunchPending") && Field<string>(menu, "_runSeedText") == "12345",
|
||||
"Archive load did not open setup without launching a run.");
|
||||
Require(JsonUtility.ToJson(new SaveService().Load().lastRunLoadout) == retryBeforeLoad,
|
||||
"Loading an archived build changed the frozen retry build.");
|
||||
Submit(menuRoot.Q("RunSetupPanel").Q<Button>(className: "screen-back"));
|
||||
yield return null;
|
||||
OpenRunArchive(menuRoot);
|
||||
yield return null;
|
||||
Submit(menuRoot.Q<Button>("RecentRunsButton"));
|
||||
Submit(menuRoot.Q<Button>("CloseRunHistory"));
|
||||
Require(menuRoot.Q("RunHistoryOverlay") == null, "Recent runs did not close.");
|
||||
RequireArchiveVisible(menuRoot);
|
||||
_stage = "run archive back navigation";
|
||||
using (var escape = KeyDownEvent.GetPooled('\0', KeyCode.Escape, EventModifiers.None))
|
||||
{
|
||||
escape.target = menuRoot.Q("RunArchivePanel");
|
||||
menuRoot.Q("RunArchivePanel").SendEvent(escape);
|
||||
}
|
||||
yield return null;
|
||||
Require(homePanel.resolvedStyle.display != DisplayStyle.None && menuRoot.Q("RunArchivePanel").resolvedStyle.display == DisplayStyle.None,
|
||||
"Escape did not return from run archive to the main menu.");
|
||||
using (var click = ClickEvent.GetPooled())
|
||||
{
|
||||
click.target = archiveCommand;
|
||||
archiveCommand.SendEvent(click);
|
||||
}
|
||||
yield return null;
|
||||
RequireArchiveVisible(menuRoot);
|
||||
Submit(menuRoot.Q("RunArchivePanel").Q<Button>(className: "screen-back"));
|
||||
yield return null;
|
||||
Require(homePanel.resolvedStyle.display != DisplayStyle.None && menuRoot.Q("RunArchivePanel").resolvedStyle.display == DisplayStyle.None,
|
||||
"Archive Back button did not return to the main menu.");
|
||||
OpenRunArchive(menuRoot);
|
||||
yield return null;
|
||||
RequireArchiveVisible(menuRoot);
|
||||
_stage = "same-seed retry";
|
||||
Submit(menuRoot.Q<Button>("RetrySameSeedButton"));
|
||||
combat = null;
|
||||
while (combat == null || !combat.CanSurrenderRun) { yield return null; combat = FindFirstObjectByType<CombatManager>(); }
|
||||
Require(combat.CurrentWaveNumber == 1 && combat.RunConfig.RunSeed == 12345, "Restart did not produce a fresh seeded run.");
|
||||
Require(BuildSignature(combat.RunConfig) == originalBuild && combat.GetComponent<RunManager>().RunId != runId,
|
||||
"Same-seed retry lost the saved build or reused the completed run identity.");
|
||||
Call(FindFirstObjectByType<CombatSceneController>(), "ConfirmSurrender");
|
||||
yield return null;
|
||||
SceneLoader.LoadMainMenu(combat.GetComponent<UIDocument>().rootVisualElement);
|
||||
menu = null;
|
||||
while (menu == null) { yield return null; menu = FindFirstObjectByType<MainMenuController>(); }
|
||||
Require(new SaveService().Load().bandwidthBalance == reward, "Empty second run changed earned rewards.");
|
||||
_stage = "new-seed retry";
|
||||
menuRoot = menu.GetComponent<UIDocument>().rootVisualElement;
|
||||
OpenRunArchive(menuRoot);
|
||||
yield return null;
|
||||
RequireArchiveVisible(menuRoot);
|
||||
Submit(menuRoot.Q<Button>("RetryNewSeedButton"));
|
||||
combat = null;
|
||||
while (combat == null || !combat.CanSurrenderRun) { yield return null; combat = FindFirstObjectByType<CombatManager>(); }
|
||||
Require(combat.CurrentWaveNumber == 1 && combat.RunConfig.RunSeed != 12345 && BuildSignature(combat.RunConfig) == originalBuild,
|
||||
"New-seed retry did not preserve the build with a fresh seed.");
|
||||
Require(new SaveService().Load().lastRunLoadout.runSeed == combat.RunConfig.RunSeed, "New seed was not persisted for the next retry.");
|
||||
_stage = "natural defeat and damage attribution";
|
||||
string finalRunId = combat.GetComponent<RunManager>().RunId;
|
||||
int idleTurns = 0;
|
||||
while (!combat.RunLost)
|
||||
{
|
||||
if (combat.CanSurrenderRun)
|
||||
{
|
||||
combat.EndPlayerTurn();
|
||||
Require(++idleTurns < 200, "Enemies did not defeat the idle starter within 200 turns.");
|
||||
}
|
||||
yield return null;
|
||||
}
|
||||
yield return null;
|
||||
saved = new SaveService().Load();
|
||||
var naturalDefeat = saved.recentRuns.FirstOrDefault(entry => entry.runId == finalRunId);
|
||||
Require(naturalDefeat != null && !naturalDefeat.surrendered && naturalDefeat.finalRound >= 1
|
||||
&& naturalDefeat.damageTaken > 0 && naturalDefeat.finalHits.Count > 0, "Natural defeat did not persist incoming damage and final-round history.");
|
||||
Require(!string.IsNullOrWhiteSpace(naturalDefeat.cause)
|
||||
&& naturalDefeat.cause.IndexOf("Uptime reached 0", StringComparison.OrdinalIgnoreCase) < 0
|
||||
&& naturalDefeat.cause.IndexOf("Unattributed", StringComparison.OrdinalIgnoreCase) < 0
|
||||
&& naturalDefeat.cause.IndexOf("Shutdown", StringComparison.OrdinalIgnoreCase) < 0,
|
||||
"Natural defeat did not identify the killing action: " + naturalDefeat.cause);
|
||||
capture = CapturePanel(combat.GetComponent<UIDocument>(), "natural-defeat");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
// Exercise scene-unload settlement after both retry modes before reporting PASS.
|
||||
SceneLoader.LoadMainMenu(combat.GetComponent<UIDocument>().rootVisualElement);
|
||||
while (FindFirstObjectByType<MainMenuController>() == null) yield return null;
|
||||
saved = new SaveService().Load();
|
||||
Require(saved.bandwidthBalance == reward && saved.recentRuns.Count == 3 && saved.activeRun == null,
|
||||
"Retry settlement duplicated rewards/history or resurrected the consumed checkpoint.");
|
||||
}
|
||||
|
||||
private IEnumerator TutorialScenario()
|
||||
{
|
||||
var save = new SaveService();
|
||||
var initial = save.Load();
|
||||
Require(TutorialCampaign.Required(initial), "Starter did not enroll in required training.");
|
||||
CombatManager combat = null;
|
||||
while (combat == null || combat.CurrentPhase != TurnPhase.Execute)
|
||||
{ yield return null; combat = FindFirstObjectByType<CombatManager>(); }
|
||||
Require(combat.RunConfig.IsTutorial, "Fresh starter bypassed training.");
|
||||
var view = FindFirstObjectByType<CombatSceneController>();
|
||||
var flow = Field<TutorialFlow>(view, "_tutorial");
|
||||
var document = view.GetComponent<UIDocument>();
|
||||
var capture = CapturePanel(document, "tutorial-intro");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
int actions = 0;
|
||||
bool resumed = false;
|
||||
var capturedSteps = new System.Collections.Generic.HashSet<string>();
|
||||
while (TutorialCampaign.Required(save.Load()))
|
||||
{
|
||||
_stage = "training wave " + flow.Lesson + " / " + flow.Guide.Step?.Id;
|
||||
Require(!combat.RunLost, "Training bot lost: " + _stage);
|
||||
if (flow.Guide.Active)
|
||||
{
|
||||
if (!combat.TutorialInputReady) { yield return null; continue; }
|
||||
var step = flow.Guide.Step;
|
||||
if (capturedSteps.Add(flow.Lesson + step.Id) && step.Id is "select-attack" or "target-zombie" or "pending-revival" or "revived" or "queued-haskell")
|
||||
{
|
||||
capture = CapturePanel(document, "tutorial-" + step.Id);
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
}
|
||||
var root = document.rootVisualElement;
|
||||
if (flow.Reading)
|
||||
{
|
||||
var before = combat.CurrentPhase; combat.EndPlayerTurn();
|
||||
Require(combat.CurrentPhase == before, "Reading allowed combat input.");
|
||||
Submit(root.Q<Button>("TutorialNext"));
|
||||
}
|
||||
else if (step.Action is TutorialAction.SelectCard or TutorialAction.PlayShield)
|
||||
{
|
||||
int cycles = combat.PlayerState.Cycles;
|
||||
var button = root.Query<Button>(className: "hand-card").ToList().FirstOrDefault(b => b.userData == flow.Guide.Card);
|
||||
Require(button != null && button.enabledInHierarchy, "Guided card unavailable: " + step.Id);
|
||||
Submit(button);
|
||||
if (combat.PendingTargetCard != null) Require(combat.PlayerState.Cycles == cycles, "Selection spent Cycles before targeting.");
|
||||
}
|
||||
else if (step.Action == TutorialAction.TargetEnemy)
|
||||
{
|
||||
var button = root.Query<Button>(className: "enemy-card").ToList().FirstOrDefault(b => b.userData == flow.Guide.Enemy);
|
||||
Require(button != null && button.enabledInHierarchy, "Guided target unavailable: " + step.Id);
|
||||
Submit(button);
|
||||
}
|
||||
else if (step.Action == TutorialAction.EndTurn)
|
||||
Submit(root.Q<Button>("TutorialEndTurn"));
|
||||
}
|
||||
else if (combat.AwaitingWaveContinue)
|
||||
{
|
||||
Require(combat.Enemies.All(enemy => enemy.State.IsDefeated && !enemy.PendingRevive), "Shop opened with surviving enemies.");
|
||||
var root = document.rootVisualElement;
|
||||
var shopNext = root.Q<Button>("TutorialShopNext");
|
||||
var buy = root.Q<Button>("TutorialBuy");
|
||||
if (shopNext != null) Submit(shopNext);
|
||||
else if (buy?.enabledSelf == true)
|
||||
{
|
||||
capture = CapturePanel(document, "tutorial-shop");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
Submit(buy);
|
||||
}
|
||||
else
|
||||
{
|
||||
string runId = FindFirstObjectByType<RunManager>().RunId;
|
||||
int uptime = combat.PlayerState.CurrentUptime;
|
||||
var next = root.Q<Button>("TutorialContinue");
|
||||
Require(next != null && next.enabledSelf, "Tutorial progression blocked.");
|
||||
Submit(next);
|
||||
if (!resumed && save.Load().tutorialCheckpoint != null)
|
||||
{
|
||||
resumed = true;
|
||||
Require(save.Load().tutorialCheckpoint.offers.Any(offer => offer.sold), "Shop purchase was not saved.");
|
||||
SceneLoader.LoadMainMenu(document.rootVisualElement);
|
||||
while (FindFirstObjectByType<MainMenuController>() == null) yield return null;
|
||||
combat = null;
|
||||
while (combat == null || combat.CurrentPhase != TurnPhase.Execute)
|
||||
{ yield return null; combat = FindFirstObjectByType<CombatManager>(); }
|
||||
view = FindFirstObjectByType<CombatSceneController>();
|
||||
document = view.GetComponent<UIDocument>(); flow = Field<TutorialFlow>(view, "_tutorial");
|
||||
Require(flow.Lesson == 2 && flow.Reading && FindFirstObjectByType<RunManager>().RunId == runId,
|
||||
"Restart did not resume the same run at wave two.");
|
||||
Require(combat.PlayerState.CurrentUptime == uptime, "Resume reset remaining Uptime.");
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (combat.CanSurrenderRun)
|
||||
{
|
||||
int target = -1;
|
||||
for (int i = 0; i < combat.Enemies.Count; i++)
|
||||
if (!combat.Enemies[i].State.IsDefeated && !combat.Enemies[i].PendingRevive
|
||||
&& (target < 0 || combat.Enemies[i].CurrentUptime < combat.Enemies[target].CurrentUptime)) target = i;
|
||||
if (target >= 0) combat.SelectEnemy(target);
|
||||
var card = combat.HandController.Cards.Where(card => !card.Definition.IsToken && !card.IsBroken && !card.IsLocked
|
||||
&& combat.GetDisplayedPlayCost(card) <= combat.PlayerState.Cycles)
|
||||
.OrderByDescending(card =>
|
||||
{
|
||||
var p = CardPreviewService.Build(combat, card);
|
||||
return (p.MinimumDamage + p.MaximumDamage + p.Shield + p.Heal + 1f) / (p.Cost + 1);
|
||||
}).FirstOrDefault();
|
||||
if (card == null || combat.CardsPlayedThisRound >= 64 || !combat.PlayCard(card)) combat.EndPlayerTurn();
|
||||
}
|
||||
Require(++actions < 1500, "Tutorial exceeded action budget: " + _stage);
|
||||
yield return null;
|
||||
}
|
||||
while (FindFirstObjectByType<MainMenuController>() == null) yield return null;
|
||||
var final = save.Load();
|
||||
Require(final.recentRuns.Count == 0 && final.activeRun == null && final.tutorialCheckpoint == null && final.tutorialRewardClaimed
|
||||
&& final.bandwidthBalance == initial.bandwidthBalance + TutorialCampaign.BandwidthReward
|
||||
&& final.entropyBalance == initial.entropyBalance + TutorialCampaign.EntropyReward
|
||||
&& final.lastRunLoadout.cardIds.Count == initial.lastRunLoadout.cardIds.Count,
|
||||
"Training rewards or isolation are incorrect.");
|
||||
if (Environment.GetCommandLineArgs().Contains("--kernel-panic-tutorial-smoke"))
|
||||
{
|
||||
var menu = FindFirstObjectByType<MainMenuController>();
|
||||
ConfigureMenu(menu); Call(menu, "BootSelectedPackage");
|
||||
combat = null;
|
||||
while (combat == null || !combat.CanSurrenderRun) { yield return null; combat = FindFirstObjectByType<CombatManager>(); }
|
||||
view = FindFirstObjectByType<CombatSceneController>(); document = view.GetComponent<UIDocument>();
|
||||
Require(!combat.RunConfig.IsTutorial && document.rootVisualElement.Q("EncounterBrief").resolvedStyle.display == DisplayStyle.None
|
||||
&& !Field<FirstBattleGuide>(view, "_firstBattleGuide").Visible, "Normal run still has automatic instructional text.");
|
||||
capture = CapturePanel(document, "normal-run-clean");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
Require(save.Load().bandwidthBalance == final.bandwidthBalance && save.Load().entropyBalance == final.entropyBalance,
|
||||
"Scene change paid the tutorial reward again.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void OpenRunArchive(VisualElement root)
|
||||
{
|
||||
var commandInput = root.Q<TextField>("CommandInput");
|
||||
Require(commandInput != null && commandInput.enabledInHierarchy, "Main menu command prompt is unavailable.");
|
||||
commandInput.value = "history --runs";
|
||||
using var enter = KeyDownEvent.GetPooled('\n', KeyCode.Return, EventModifiers.None);
|
||||
enter.target = commandInput;
|
||||
commandInput.SendEvent(enter);
|
||||
}
|
||||
|
||||
private IEnumerator CampaignScenario(CombatManager combat, CombatSceneController view)
|
||||
{
|
||||
var run = combat.GetComponent<RunManager>();
|
||||
var document = view.GetComponent<UIDocument>();
|
||||
int actions = 0;
|
||||
bool capturedBoss = false;
|
||||
bool capturedPreview = false;
|
||||
while (!run.CampaignChoicePending && !combat.RunFinished)
|
||||
{
|
||||
_stage = "campaign wave " + run.CurrentWaveNumber;
|
||||
if (combat.AwaitingWaveContinue)
|
||||
{
|
||||
foreach (var offer in run.RepositoryOffers.Where(offer => !offer.Sold)
|
||||
.OrderByDescending(offer => offer.Kind == RepositoryOfferKind.StatUpgrade && offer.StatUpgradeKind == RunStatUpgradeKind.Heal
|
||||
&& combat.PlayerState.CurrentUptime < combat.PlayerState.MaxUptime / 2 ? 100
|
||||
: offer.Kind == RepositoryOfferKind.CardUpgrade && offer.CardUpgradeKind == CardUpgradeKind.DrawRider ? 90
|
||||
: offer.Kind == RepositoryOfferKind.CardUpgrade ? 80 : 10).ToArray())
|
||||
if (offer.Price <= run.Bits) run.BuyOffer(offer, combat.PlayerState);
|
||||
Submit(document.rootVisualElement.Q<Button>("RouteRepair"));
|
||||
combat.ContinueToNextWave();
|
||||
}
|
||||
else if (combat.CanSurrenderRun)
|
||||
{
|
||||
if (!capturedPreview && combat.InterpreterQueue.Count > 0)
|
||||
{
|
||||
capturedPreview = true;
|
||||
var preview = document.rootVisualElement.Q<Foldout>("ExecutionPreview");
|
||||
preview.value = true;
|
||||
var capture = CapturePanel(document, "execution-preview");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
preview.value = false;
|
||||
}
|
||||
if (run.CurrentWaveNumber == RunJourney.BossWave && !capturedBoss)
|
||||
{
|
||||
capturedBoss = true;
|
||||
Require(combat.Enemies.Any(enemy => enemy.Archetype.Tier == EnemyTier.Boss), "Boss encounter did not spawn.");
|
||||
var capture = CapturePanel(document, "boss-encounter");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
}
|
||||
int target = -1;
|
||||
for (int i = 0; i < combat.Enemies.Count; i++)
|
||||
if (!combat.Enemies[i].State.IsDefeated && (target < 0 || combat.Enemies[i].CurrentUptime < combat.Enemies[target].CurrentUptime)) target = i;
|
||||
if (target >= 0) combat.SelectEnemy(target);
|
||||
var card = combat.HandController.Cards.Where(card => card.Definition != null && !card.Definition.IsToken
|
||||
&& !card.IsBroken && !card.IsLocked && combat.GetDisplayedPlayCost(card) <= combat.PlayerState.Cycles)
|
||||
.OrderByDescending(card =>
|
||||
{
|
||||
var preview = CardPreviewService.Build(combat, card);
|
||||
return ((preview.MinimumDamage + preview.MaximumDamage) * 0.5 + preview.Shield * 0.7 + preview.Heal * 1.5 + 1) / (preview.Cost + 1);
|
||||
}).FirstOrDefault();
|
||||
if (card == null || combat.CardsPlayedThisRound >= 64 || !combat.PlayCard(card)) combat.EndPlayerTurn();
|
||||
Require(++actions < 2000, "Campaign bot exceeded action budget.");
|
||||
}
|
||||
yield return null;
|
||||
}
|
||||
Require(!combat.RunLost && run.WavesCleared == 5 && capturedBoss, "Seeded campaign bot did not clear the boss.");
|
||||
_stage = "campaign milestone";
|
||||
var milestone = CapturePanel(document, "campaign-milestone");
|
||||
while (milestone.MoveNext()) yield return milestone.Current;
|
||||
int expectedBandwidth = run.AccruedBandwidth + TutorialCampaign.BandwidthReward;
|
||||
int expectedEntropy = run.AccruedEntropy + TutorialCampaign.EntropyReward;
|
||||
string runId = run.RunId;
|
||||
bool endless = Environment.GetCommandLineArgs().Contains("--kernel-panic-endless-smoke");
|
||||
if (endless)
|
||||
{
|
||||
Submit(document.rootVisualElement.Q<Button>("ContinueEndlessButton"));
|
||||
while (!combat.CanSurrenderRun) yield return null;
|
||||
Require(run.Journey.endless && run.CurrentWaveNumber == 6 && 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;
|
||||
combat.SurrenderRun();
|
||||
}
|
||||
else Submit(document.rootVisualElement.Q<Button>("FinishCampaignButton"));
|
||||
yield return null;
|
||||
var saved = new SaveService().Load();
|
||||
Require(run.RewardsSettled && saved.recentRuns.Count == 1 && saved.recentRuns[0].victory == !endless,
|
||||
"Campaign outcome did not settle a single correct history record.");
|
||||
Require(saved.bandwidthBalance == expectedBandwidth && saved.entropyBalance == expectedEntropy, "Campaign reward settlement mismatch.");
|
||||
var report = CapturePanel(document, "campaign-report");
|
||||
while (report.MoveNext()) yield return report.Current;
|
||||
SceneLoader.LoadMainMenu(document.rootVisualElement);
|
||||
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, "
|
||||
+ (endless ? "endless continuation, surrender" : "victory") + ", saved rewards/history exactly once, menu return.";
|
||||
}
|
||||
|
||||
private static void RequireArchiveVisible(VisualElement root)
|
||||
{
|
||||
var archive = root.Q("RunArchivePanel");
|
||||
Require(archive != null && archive.resolvedStyle.display != DisplayStyle.None
|
||||
&& root.Q("MainMenuPanel").resolvedStyle.display == DisplayStyle.None, "Run archive did not become the active screen.");
|
||||
Require(archive.Q<Button>("RetrySameSeedButton") != null && archive.Q<Button>("RetryNewSeedButton") != null
|
||||
&& archive.Q<Button>("RecentRunsButton") != null, "Run archive does not contain all three run actions.");
|
||||
}
|
||||
|
||||
private static void ConfigureMenu(MainMenuController menu)
|
||||
{
|
||||
Call(menu, "HandleStartRunClicked");
|
||||
var distro = Field<DistroDatabase>(menu, "distroDatabase").FindById("ubuntu");
|
||||
var loadout = Field<CardLoadout>(menu, "_cardLoadout");
|
||||
foreach (var card in distro.ExclusiveCards.Take(4))
|
||||
if (!loadout.GetEquippedCardIds(distro.Id).Contains(card.Id)) Call(menu, "ToggleCardInSelectedLoadout", distro, card);
|
||||
var languages = Field<System.Collections.Generic.List<Language>>(menu, "_selectedRunLanguages");
|
||||
if (!languages.Contains(Language.Python)) Call(menu, "ToggleRunLanguage", Language.Python);
|
||||
if (!languages.Contains(Language.JavaScript)) Call(menu, "ToggleRunLanguage", Language.JavaScript);
|
||||
var root = menu.GetComponent<UIDocument>().rootVisualElement;
|
||||
var seed = root.Q<TextField>("RunSeedInput");
|
||||
Require(seed != null, "Seed input is missing.");
|
||||
seed.value = "12345";
|
||||
Require(root.Q<Button>("BootRunButton").enabledSelf, "Configured boot button is disabled.");
|
||||
}
|
||||
|
||||
private IEnumerator InspectPiles(CombatSceneController view, CombatManager combat)
|
||||
{
|
||||
var root = view.GetComponent<UIDocument>().rootVisualElement;
|
||||
var originalOrder = combat.DeckController.DrawPile.ToArray();
|
||||
Require(originalOrder.Length > 0, "Smoke setup needs a non-empty draw pile.");
|
||||
Submit(root.Q<Button>("InspectPile_draw"));
|
||||
yield return null;
|
||||
var inspector = root.Q("CardPileInspector");
|
||||
Require(inspector != null, "Draw pile inspector did not open.");
|
||||
var overlay = inspector.parent;
|
||||
Require(overlay.ClassListContains("pile-overlay"), "Pile inspector did not use its centered overlay layout.");
|
||||
var grid = inspector.Q("PileCardGrid");
|
||||
Require(grid != null, "Pile inspector card grid is missing.");
|
||||
var names = grid.Query<VisualElement>("PileCard").ToList()
|
||||
.Select(card => card.Q<Label>(className: "software-name").text).ToArray();
|
||||
Require(names.SequenceEqual(CardPileView.GroupIdenticalCopies(originalOrder, combat.GetPileCostDetails).Select(group => group[0].Definition.DisplayName)),
|
||||
"Draw pile inspector did not present an alphabetically sorted inventory.");
|
||||
Require(grid.Query<VisualElement>("PileCard").ToList().Sum(face => (int)face.userData) == originalOrder.Length,
|
||||
"Grouping did not preserve the actual card count.");
|
||||
inspector.Q<Toggle>("PileGroupCopies").value = false;
|
||||
var search = inspector.Q<TextField>("PileSearch");
|
||||
var clear = inspector.Q<Button>("ClearPileSearch");
|
||||
Require(clear != null && !clear.enabledSelf, "Empty pile search should have a disabled Clear button.");
|
||||
search.value = "__no_matching_card__";
|
||||
Require(grid.Query<VisualElement>("PileCard").ToList().Count == 0, "Pile search did not filter cards.");
|
||||
Require(grid.Q<Label>("PileEmptyState")?.text.StartsWith("No matching cards.", StringComparison.Ordinal) == true,
|
||||
"Nonmatching pile search did not explain how to recover.");
|
||||
Submit(clear);
|
||||
for (int frame = 0; frame < 3; frame++) yield return null;
|
||||
Require(search.value.Length == 0 && grid.Query<VisualElement>("PileCard").ToList().Count == originalOrder.Length
|
||||
&& grid.Q("PileEmptyState") == null && !clear.enabledSelf, "Clearing pile search did not restore every card.");
|
||||
var focused = root.focusController.focusedElement as VisualElement;
|
||||
Require(focused == search || (focused != null && search.Contains(focused)), "Clearing pile search did not restore search focus.");
|
||||
search.value = originalOrder[0].Definition.Id;
|
||||
Require(grid.Query<VisualElement>("PileCard").ToList().Count > 0, "Pile search could not find an existing card.");
|
||||
Submit(inspector.Q<Button>("PileTab_discard"));
|
||||
Require(search.value.Length == 0 && inspector.Q<Label>("PileEmptyState")?.text == "This pile is empty.",
|
||||
"Discard tab did not retain its own empty search and pile.");
|
||||
Submit(inspector.Q<Button>("PileTab_exhaust"));
|
||||
Require(inspector.Q<Button>("PileTab_exhaust").ClassListContains("selected"), "Exhaust tab did not become selected.");
|
||||
Submit(inspector.Q<Button>("PileTab_draw"));
|
||||
Require(search.value == originalOrder[0].Definition.Id && !inspector.Q<Toggle>("PileGroupCopies").value,
|
||||
"Returning to Draw did not preserve its search and grouping preference.");
|
||||
Submit(clear);
|
||||
inspector.Q<Toggle>("PileGroupCopies").value = true;
|
||||
var costDetails = grid.Q<Foldout>("PileCostDetails");
|
||||
Require(costDetails != null, "Current cost explanation is missing.");
|
||||
costDetails.value = true;
|
||||
var languageFilter = inspector.Q<DropdownField>("PileLanguageFilter");
|
||||
var costFilter = inspector.Q<DropdownField>("PileCostFilter");
|
||||
languageFilter.Focus();
|
||||
yield return null;
|
||||
using (var next = NavigationMoveEvent.GetPooled(NavigationMoveEvent.Direction.Next))
|
||||
{
|
||||
next.target = languageFilter;
|
||||
languageFilter.SendEvent(next);
|
||||
}
|
||||
yield return null;
|
||||
var filterFocus = root.focusController.focusedElement as VisualElement;
|
||||
Require(filterFocus == costFilter || costFilter.Contains(filterFocus), "Runtime modal navigation skipped the cost filter.");
|
||||
var capture = CapturePanel(view.GetComponent<UIDocument>(), "pile-inspector");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
Require(Mathf.Abs(inspector.worldBound.center.x - overlay.worldBound.center.x) <= 2
|
||||
&& Mathf.Abs(inspector.worldBound.center.y - overlay.worldBound.center.y) <= 2,
|
||||
"Pile inspector is not centered in the combat overlay.");
|
||||
var faces = grid.Query<VisualElement>("PileCard").ToList();
|
||||
if (Screen.width >= 1200)
|
||||
Require(faces.Count >= 2 && Mathf.Abs(faces[0].worldBound.yMin - faces[1].worldBound.yMin) <= 2
|
||||
&& faces[1].worldBound.xMin > faces[0].worldBound.xMax,
|
||||
"Wide-screen pile inspector did not display multiple card columns with a gutter.");
|
||||
Submit(inspector.Q<Button>("ClosePileInspector"));
|
||||
Require(root.Q("CardPileInspector") == null && !overlay.ClassListContains("pile-overlay")
|
||||
&& combat.DeckController.DrawPile.SequenceEqual(originalOrder),
|
||||
"Inspecting or closing the draw pile changed its live order.");
|
||||
foreach (string pile in new[] { "discard", "exhaust" })
|
||||
{
|
||||
Submit(root.Q<Button>("InspectPile_" + pile));
|
||||
yield return null;
|
||||
inspector = root.Q("CardPileInspector");
|
||||
Require(inspector != null, pile + " inspector did not open.");
|
||||
Require(inspector.Q("PileCardGrid").Query<VisualElement>("PileCard").ToList().Count == 0
|
||||
&& inspector.Q<Label>("PileEmptyState")?.text == "This pile is empty.",
|
||||
pile + " did not display its empty state before any cards were played.");
|
||||
capture = CapturePanel(view.GetComponent<UIDocument>(), "pile-" + pile + "-empty");
|
||||
while (capture.MoveNext()) yield return capture.Current;
|
||||
Submit(inspector.Q<Button>("ClosePileInspector"));
|
||||
Require(root.Q("CardPileInspector") == null && !overlay.ClassListContains("pile-overlay"),
|
||||
"Closing the " + pile + " inspector left its modal layout active.");
|
||||
}
|
||||
Require(combat.DeckController.DrawPile.SequenceEqual(originalOrder), "Pile inspection changed the original draw order.");
|
||||
}
|
||||
|
||||
private static string BuildSignature(RunConfig config) => $"{config.Distro.Id}|{config.DistroVersion}|{config.PrimaryLanguage}|{config.SecondaryLanguage}|"
|
||||
+ string.Join(",", config.StartingDeck.Select(card => card.Id)) + "|"
|
||||
+ string.Join(",", config.EquippedPackages.Select(package => package.Definition.Id + ":" + package.UpgradeLevel));
|
||||
|
||||
private static string DeckSignature(RunManager run) => string.Join("|", run.RunDeck.Select(card =>
|
||||
$"{card.InstanceId}:{card.Definition.Id}:{card.PermanentCostDelta}:{card.MagnitudeBonus}:{card.DrawRider}:{card.UpgradeLevel}"));
|
||||
|
||||
private static string OfferSignature(RunManager run) => string.Join("|", run.RepositoryOffers.Select(offer =>
|
||||
$"{offer.Kind}:{offer.CardDefinition?.Id}:{offer.TargetCard?.InstanceId}:{offer.CardUpgradeKind}:{offer.StatUpgradeKind}:{offer.Price}:{offer.Sold}"));
|
||||
|
||||
private static void Submit(Button button)
|
||||
{
|
||||
Require(button != null && button.enabledInHierarchy, "Expected enabled UI command is unavailable.");
|
||||
using var submit = NavigationSubmitEvent.GetPooled();
|
||||
submit.target = button;
|
||||
button.SendEvent(submit);
|
||||
}
|
||||
|
||||
private IEnumerator CapturePanel(UIDocument document, string name)
|
||||
{
|
||||
// A hidden Windows swap chain can return black screenshots. Render the actual
|
||||
// runtime panel to a texture for deterministic visual inspection of the same UI.
|
||||
var settings = document.panelSettings;
|
||||
var previous = settings.targetTexture;
|
||||
var target = new RenderTexture(Screen.width, Screen.height, 24);
|
||||
target.Create();
|
||||
settings.targetTexture = target;
|
||||
try
|
||||
{
|
||||
for (int frame = 0; frame < 8; frame++) yield return null;
|
||||
var root = document.rootVisualElement;
|
||||
File.WriteAllText(Path.Combine(_output, name + "-panel.txt"),
|
||||
$"panel={root.panel != null}; bounds={root.worldBound}; opacity={root.resolvedStyle.opacity}; display={root.resolvedStyle.display}; visibility={root.resolvedStyle.visibility}; children={root.childCount}; renderedFrames={Time.renderedFrameCount}; graphics={SystemInfo.graphicsDeviceType}; focused={Application.isFocused}");
|
||||
var previousActive = RenderTexture.active;
|
||||
var pixels = new Texture2D(target.width, target.height, TextureFormat.RGB24, false);
|
||||
try
|
||||
{
|
||||
RenderTexture.active = target;
|
||||
pixels.ReadPixels(new Rect(0, 0, target.width, target.height), 0, 0);
|
||||
pixels.Apply();
|
||||
File.WriteAllBytes(Path.Combine(_output, name + ".png"), pixels.EncodeToPNG());
|
||||
Require(pixels.GetPixels32().Any(pixel => pixel.r > 20 || pixel.g > 20 || pixel.b > 20), "Runtime panel rendered an empty image: " + name);
|
||||
}
|
||||
finally { RenderTexture.active = previousActive; Destroy(pixels); }
|
||||
}
|
||||
finally { settings.targetTexture = previous; target.Release(); Destroy(target); }
|
||||
}
|
||||
|
||||
private static T Field<T>(object owner, string name) => (T)owner.GetType().GetField(name, BindingFlags.NonPublic | BindingFlags.Instance).GetValue(owner);
|
||||
private static void Call(object owner, string name, params object[] args) => owner.GetType().GetMethod(name, BindingFlags.NonPublic | BindingFlags.Instance).Invoke(owner, args);
|
||||
private static void Require(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d7286c6e49724ab183243caac5f05945
|
||||
@@ -0,0 +1,29 @@
|
||||
using System;
|
||||
|
||||
namespace KernelPanic.Run
|
||||
{
|
||||
/// <summary>Retains System.Random's existing sequence, with a portable seed/cursor checkpoint.</summary>
|
||||
public sealed class ReplayableRandom
|
||||
{
|
||||
private Random _random;
|
||||
public int Seed { get; }
|
||||
public int Draws { get; private set; }
|
||||
|
||||
public ReplayableRandom(int seed, int draws = 0)
|
||||
{
|
||||
if (draws < 0 || draws > 10000000) throw new ArgumentOutOfRangeException(nameof(draws));
|
||||
Seed = seed;
|
||||
_random = new Random(seed);
|
||||
for (int i = 0; i < draws; i++) _random.Next();
|
||||
Draws = draws;
|
||||
}
|
||||
|
||||
public int Next(int min, int max)
|
||||
{
|
||||
// Large-range Next consumes two samples; combat/shop ranges use one.
|
||||
int value = _random.Next(min, max);
|
||||
Draws += (long)max - min > int.MaxValue ? 2 : 1;
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 41d0b7e13bb879d42944d340610f5b69
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b1200000000000000000000000000001
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a06eada6fbafd6e44ae1d21238a64750
|
||||
@@ -0,0 +1,224 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Meta;
|
||||
using UnityEngine;
|
||||
|
||||
namespace KernelPanic.Run
|
||||
{
|
||||
/// <summary>A repository-boundary snapshot, never an in-flight combat serialization.</summary>
|
||||
[Serializable]
|
||||
public sealed class RunCheckpoint
|
||||
{
|
||||
public int version = 1;
|
||||
public string runId;
|
||||
public string savedUtc;
|
||||
public string distroId;
|
||||
public int distroVersion;
|
||||
public Language primaryLanguage;
|
||||
public Language secondaryLanguage;
|
||||
public int seed;
|
||||
public List<string> startingCards = new();
|
||||
public List<RunBuildPackageSaveEntry> packages = new();
|
||||
public List<CheckpointCard> deck = new();
|
||||
public List<CheckpointOffer> offers = new();
|
||||
public List<string> soldKeys = new();
|
||||
public int wave;
|
||||
public int wavesCleared;
|
||||
public int bits;
|
||||
public int bandwidth;
|
||||
public int entropy;
|
||||
public int maxUptimeBonus;
|
||||
public int maxCyclesBonus;
|
||||
public int ramBonus;
|
||||
public int rerolls;
|
||||
public int shopRandomDraws;
|
||||
public CheckpointCombat combat;
|
||||
public RunJourney journey;
|
||||
|
||||
public ResolvedRunCheckpoint Resolve(DistroDatabase distros, CardDatabase cards,
|
||||
LanguageDeckDatabase languages, PackageDatabase packageDatabase)
|
||||
{
|
||||
Require(version == 1 || version == 2, "This checkpoint needs a different game version.");
|
||||
Require(version < 2 || journey != null, "Missing saved route decisions.");
|
||||
journey?.Validate(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.");
|
||||
Require(maxUptimeBonus >= 0 && maxCyclesBonus >= 0 && ramBonus >= 0, "Invalid run upgrades.");
|
||||
Require(shopRandomDraws >= 0 && shopRandomDraws <= 10000000, "Invalid shop random cursor.");
|
||||
Require(Enum.IsDefined(typeof(Language), primaryLanguage) && Enum.IsDefined(typeof(Language), secondaryLanguage)
|
||||
&& primaryLanguage != secondaryLanguage, "Invalid checkpoint languages.");
|
||||
Require(distroVersion >= 1 && distroVersion <= GachaTuning.MaxVersion, "Invalid distro version.");
|
||||
DistroDefinition distro = distros == null ? null : distros.FindById(distroId);
|
||||
Require(distro != null, $"Checkpoint distro '{distroId}' is unavailable. Save was left unchanged.");
|
||||
Require(deck != null && deck.Count > 0 && deck.Count <= 10000 && startingCards != null
|
||||
&& startingCards.Count > 0 && startingCards.Count <= 10000, "Invalid checkpoint deck.");
|
||||
Require(packages != null && packages.Count <= 3 && offers != null && offers.Count <= 100
|
||||
&& soldKeys != null && soldKeys.Count <= 10000, "Invalid repository snapshot.");
|
||||
Require(combat != null, "Missing combat checkpoint.");
|
||||
combat.Validate();
|
||||
|
||||
CardDefinition FindCard(string id)
|
||||
{
|
||||
CardDefinition result = cards == null ? null : cards.FindById(id);
|
||||
result ??= distro.ExclusiveCards.FirstOrDefault(card => card != null && string.Equals(card.Id, id, StringComparison.OrdinalIgnoreCase));
|
||||
foreach (Language language in new[] { primaryLanguage, secondaryLanguage })
|
||||
{
|
||||
LanguageDeckDefinition languageDeck = languages == null ? null : languages.FindByLanguage(language);
|
||||
if (result == null && languageDeck != null)
|
||||
result = languageDeck.Entries.Select(entry => entry.Card).FirstOrDefault(card => card != null && string.Equals(card.Id, id, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
Require(result != null, $"Checkpoint card '{id}' is unavailable. Save was left unchanged.");
|
||||
return result;
|
||||
}
|
||||
|
||||
List<PackageInstance> equipped = new();
|
||||
HashSet<PackageSlot> slots = new();
|
||||
foreach (RunBuildPackageSaveEntry entry in packages)
|
||||
{
|
||||
PackageDefinition package = entry == null || packageDatabase == null ? null : packageDatabase.FindById(entry.packageId);
|
||||
Require(package != null && package.Slot == entry.slot && slots.Add(entry.slot), "A checkpoint package is missing or invalid.");
|
||||
Require(entry.upgradeLevel >= 0 && entry.upgradeLevel <= 5, "Invalid package level.");
|
||||
equipped.Add(new PackageInstance(package, entry.upgradeLevel));
|
||||
}
|
||||
var config = new RunConfig(distro, primaryLanguage, secondaryLanguage, startingCards.Select(FindCard).ToList(), equipped, seed, distroVersion);
|
||||
List<CardInstance> restoredDeck = deck.Select(entry => RestoreCard(entry, FindCard)).ToList();
|
||||
Require(restoredDeck.Select(card => card.InstanceId).Distinct().Count() == restoredDeck.Count, "Duplicate run card identity.");
|
||||
List<RepositoryOffer> restoredOffers = new();
|
||||
foreach (CheckpointOffer entry in offers)
|
||||
{
|
||||
Require(entry != null && entry.price >= 0 && Enum.IsDefined(typeof(RepositoryOfferKind), entry.kind), "Invalid repository offer.");
|
||||
RepositoryOffer offer;
|
||||
switch (entry.kind)
|
||||
{
|
||||
case RepositoryOfferKind.NewCard:
|
||||
offer = RepositoryOffer.NewCard(FindCard(entry.cardId), entry.price);
|
||||
break;
|
||||
case RepositoryOfferKind.CardUpgrade:
|
||||
Require(Enum.IsDefined(typeof(CardUpgradeKind), entry.cardUpgrade), "Invalid card upgrade.");
|
||||
CardInstance target = restoredDeck.FirstOrDefault(card => card.InstanceId == entry.targetId)
|
||||
?? RestoreCard(entry.detachedTarget, FindCard);
|
||||
offer = RepositoryOffer.CardUpgrade(target, entry.cardUpgrade, entry.price);
|
||||
break;
|
||||
default:
|
||||
Require(Enum.IsDefined(typeof(RunStatUpgradeKind), entry.statUpgrade), "Invalid stat upgrade.");
|
||||
offer = RepositoryOffer.StatUpgrade(entry.statUpgrade, entry.price);
|
||||
break;
|
||||
}
|
||||
if (entry.sold) offer.MarkSold();
|
||||
restoredOffers.Add(offer);
|
||||
}
|
||||
return new ResolvedRunCheckpoint(this, config, restoredDeck, restoredOffers);
|
||||
}
|
||||
|
||||
private static CardInstance RestoreCard(CheckpointCard entry, Func<string, CardDefinition> find)
|
||||
{
|
||||
Require(entry != null && Guid.TryParseExact(entry.instanceId, "N", out _), "Invalid run card.");
|
||||
Require(entry.costDelta <= 0 && entry.magnitude >= 0 && entry.drawRider >= 0 && entry.upgradeLevel >= 0,
|
||||
"Invalid card upgrades.");
|
||||
CardInstance card = new(find(entry.cardId));
|
||||
card.RestoreRunState(entry.instanceId, entry.costDelta, entry.magnitude, entry.drawRider, entry.upgradeLevel);
|
||||
return card;
|
||||
}
|
||||
|
||||
internal static void Require(bool valid, string message)
|
||||
{
|
||||
if (!valid) throw new InvalidDataException(message);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ResolvedRunCheckpoint
|
||||
{
|
||||
public RunCheckpoint Snapshot { get; }
|
||||
public RunConfig Config { get; }
|
||||
public IReadOnlyList<CardInstance> Deck { get; }
|
||||
public IReadOnlyList<RepositoryOffer> Offers { get; }
|
||||
internal ResolvedRunCheckpoint(RunCheckpoint snapshot, RunConfig config, List<CardInstance> deck, List<RepositoryOffer> offers)
|
||||
{ Snapshot = snapshot; Config = config; Deck = deck; Offers = offers; }
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public sealed class CheckpointCard
|
||||
{
|
||||
public string cardId, instanceId;
|
||||
public int costDelta, magnitude, drawRider, upgradeLevel;
|
||||
public static CheckpointCard Capture(CardInstance card) => new()
|
||||
{
|
||||
cardId = card.Definition.Id, instanceId = card.InstanceId, costDelta = card.PermanentCostDelta,
|
||||
magnitude = card.MagnitudeBonus, drawRider = card.DrawRider, upgradeLevel = card.UpgradeLevel
|
||||
};
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public sealed class CheckpointOffer
|
||||
{
|
||||
public RepositoryOfferKind kind;
|
||||
public string cardId, targetId;
|
||||
public CheckpointCard detachedTarget;
|
||||
public CardUpgradeKind cardUpgrade;
|
||||
public RunStatUpgradeKind statUpgrade;
|
||||
public int price;
|
||||
public bool sold;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public sealed class CheckpointCombat
|
||||
{
|
||||
public int uptime, shield, cycles;
|
||||
public int randomSeed, randomDraws;
|
||||
public bool ubuntuRefillUsed, interpreterShieldUsed, nativeDamageUsed;
|
||||
public float fedoraCrashChance;
|
||||
public int javaCardsPlayed, rawhideCharges, repeatCharges, nextTurnCycles;
|
||||
public List<CheckpointDelayedEffect> delayed = new();
|
||||
|
||||
internal void Validate()
|
||||
{
|
||||
RunCheckpoint.Require(uptime > 0 && shield >= 0 && cycles >= 0 && randomDraws >= 0 && randomDraws <= 10000000,
|
||||
"Invalid combat boundary state.");
|
||||
RunCheckpoint.Require(!float.IsNaN(fedoraCrashChance) && !float.IsInfinity(fedoraCrashChance)
|
||||
&& fedoraCrashChance >= 0 && fedoraCrashChance <= 100 && javaCardsPlayed >= 0 && rawhideCharges >= 0
|
||||
&& repeatCharges >= 0 && nextTurnCycles >= 0 && delayed != null && delayed.Count <= 10000, "Invalid carried combat effects.");
|
||||
foreach (CheckpointDelayedEffect effect in delayed)
|
||||
RunCheckpoint.Require(effect != null && (effect.kind == 0 || effect.kind == 1) && effect.rounds > 0
|
||||
&& effect.amount >= 0, "Invalid delayed effect.");
|
||||
}
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public sealed class CheckpointDelayedEffect { public int kind, amount, rounds; }
|
||||
|
||||
public static class RunCheckpointService
|
||||
{
|
||||
public static void SaveAndSuspend(SaveService saves, RunManager run, CombatManager combat)
|
||||
{
|
||||
RunCheckpoint.Require(run.CurrentConfig?.IsTutorial != true, "Training uses its separate shop checkpoint.");
|
||||
RunCheckpoint snapshot = run.CaptureCheckpoint(combat);
|
||||
SaveData data = saves.Load();
|
||||
data.activeRun = snapshot;
|
||||
saves.Save(data);
|
||||
run.MarkSuspended(); // Never suppress settlement or leave the scene on a failed save.
|
||||
}
|
||||
|
||||
public static ResolvedRunCheckpoint PrepareResume(SaveService saves, DistroDatabase distros, CardDatabase cards,
|
||||
LanguageDeckDatabase languages, PackageDatabase packages)
|
||||
{
|
||||
RunCheckpoint snapshot = saves.Load().activeRun;
|
||||
RunCheckpoint.Require(snapshot != null, "No saved run is available.");
|
||||
return snapshot.Resolve(distros, cards, languages, packages);
|
||||
}
|
||||
|
||||
public static void Consume(SaveService saves, ResolvedRunCheckpoint resume)
|
||||
{
|
||||
SaveData data = saves.Load();
|
||||
RunCheckpoint.Require(data.activeRun != null && data.activeRun.runId == resume.Snapshot.runId
|
||||
&& data.activeRun.savedUtc == resume.Snapshot.savedUtc, "The saved run changed. Return to the menu and retry.");
|
||||
data.activeRun = null;
|
||||
saves.Save(data); // Claim once before play, preventing replaying the same banked rewards.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c74add9056068a2458a5f6c4b494fc6d
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0c3d34a2ce0e53b4b8f9a77feb60fb95
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b1100000000000000000000000000002
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,32 @@
|
||||
using System;
|
||||
|
||||
namespace KernelPanic.Run
|
||||
{
|
||||
public enum WaveRoute { Repair, Challenge }
|
||||
|
||||
/// <summary>Serializable route decisions, independent of combat and repository presentation.</summary>
|
||||
[Serializable]
|
||||
public sealed class RunJourney
|
||||
{
|
||||
public const int BossWave = 5;
|
||||
public const int RepairUptime = 6;
|
||||
public const int ChallengeBits = 4;
|
||||
public bool campaign;
|
||||
public bool endless;
|
||||
public WaveRoute selectedRoute;
|
||||
public WaveRoute activeRoute;
|
||||
public string lastReward;
|
||||
|
||||
public bool AtMilestone(int wavesCleared) => campaign && !endless && wavesCleared >= BossWave;
|
||||
public static RunJourney NewCampaign() => new() { campaign = true };
|
||||
public RunJourney Copy() => (RunJourney)MemberwiseClone();
|
||||
|
||||
public void Validate(int wave)
|
||||
{
|
||||
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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c0a22d93857c4b64a8b4bdc1c802250a
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 234cc6c5ca577b64ea44020f5514cebe
|
||||
@@ -0,0 +1,54 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Meta;
|
||||
|
||||
namespace KernelPanic.Run
|
||||
{
|
||||
public static class TutorialCampaign
|
||||
{
|
||||
public const int LessonCount = 2;
|
||||
public const int BandwidthReward = 1000;
|
||||
public const int EntropyReward = GachaService.StandardTenPullCost * GachaService.EntropyPerCommit;
|
||||
public static bool Required(SaveData save) => save != null && save.starterChosen && save.tutorialRequired;
|
||||
public static int Lesson(SaveData save) => save?.tutorialCheckpoint != null ? 2 : 1;
|
||||
|
||||
public static void Enroll(SaveData save, string distroId)
|
||||
{
|
||||
save.tutorialRequired = true; save.tutorialLesson = 1;
|
||||
save.tutorialDistroId = distroId; save.tutorialCheckpoint = null;
|
||||
}
|
||||
|
||||
// Commit balances and the claimed flag together. Re-enrollment never grants a second payout.
|
||||
public static void Complete(SaveData save)
|
||||
{
|
||||
if (!Required(save) || save.tutorialLesson != 2)
|
||||
throw new InvalidOperationException("Complete both training waves before claiming the reward.");
|
||||
if (!save.tutorialRewardClaimed)
|
||||
{
|
||||
save.bandwidthBalance = checked(Math.Max(0, save.bandwidthBalance) + BandwidthReward);
|
||||
save.entropyBalance = checked(Math.Max(0, save.entropyBalance) + EntropyReward);
|
||||
save.tutorialRewardClaimed = true;
|
||||
}
|
||||
save.tutorialRequired = false; save.tutorialCheckpoint = null;
|
||||
}
|
||||
|
||||
public static EncounterPlan Plan(int wave) => wave switch
|
||||
{
|
||||
1 => new("Targeting and revival", "", 0, "zombie_process", "orphan_process"),
|
||||
2 => new("Queue, stack and finish", "", 0, "memory_leak", "firewalld"),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(wave))
|
||||
};
|
||||
|
||||
public static RunConfig CreateConfig(DistroDefinition distro, CardDatabase cards, int lesson)
|
||||
{
|
||||
if (distro == null || cards == null) throw new InvalidOperationException("Tutorial content is unavailable.");
|
||||
_ = Plan(lesson);
|
||||
var deck = new List<CardDefinition>();
|
||||
foreach (string id in new[] { "lang_rs_unwrap", "lang_rs_fn_main", "lang_rs_borrow", "lang_py_print", "lang_hs_thunk" })
|
||||
deck.Add(cards.FindById(id) ?? throw new InvalidOperationException("Missing tutorial card: " + id));
|
||||
return RunConfig.ForTutorial(distro, deck, lesson);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: cb33ab352e4340c4b362209cf671d92b
|
||||
@@ -0,0 +1,151 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
|
||||
namespace KernelPanic.Run
|
||||
{
|
||||
public enum TutorialAction { Read, SelectCard, TargetEnemy, EndTurn, PlayShield, Free }
|
||||
|
||||
public sealed class TutorialStep
|
||||
{
|
||||
public readonly string Id, Title, Copy, Anchor;
|
||||
public readonly TutorialAction Action;
|
||||
public TutorialStep(string id, string title, string copy, string anchor, TutorialAction action = TutorialAction.Read)
|
||||
{ Id = id; Title = title; Copy = copy; Anchor = anchor; Action = action; }
|
||||
}
|
||||
|
||||
/// <summary>Advances from observed combat state, never from fabricated damage or a Next button on action steps.</summary>
|
||||
public sealed class TutorialGuide
|
||||
{
|
||||
private readonly int _lesson;
|
||||
private readonly IReadOnlyList<TutorialStep> _steps;
|
||||
private bool _played, _resolved, _ended;
|
||||
public int Index { get; private set; }
|
||||
public int Count => _steps.Count;
|
||||
public TutorialStep Step => Active ? _steps[Index] : null;
|
||||
public bool Active => Index < _steps.Count;
|
||||
public bool Reading => Active && Step.Action == TutorialAction.Read;
|
||||
public CardInstance Card { get; private set; }
|
||||
public EnemyInstance Enemy { get; private set; }
|
||||
public bool CanEndTurn => !Active || Step.Action == TutorialAction.EndTurn;
|
||||
private ResolutionTrack ExpectedTrack => _lesson == 1 ? ResolutionTrack.Native
|
||||
: Step?.Id.Contains("haskell") == true ? ResolutionTrack.LazyStack : ResolutionTrack.InterpreterQueue;
|
||||
|
||||
public TutorialGuide(int lesson) { _lesson = lesson; _steps = Build(lesson); }
|
||||
|
||||
public bool AllowsCard(CardInstance card) => !Active || !Reading && ReferenceEquals(card, Card)
|
||||
&& Step.Action is TutorialAction.SelectCard or TutorialAction.TargetEnemy or TutorialAction.PlayShield;
|
||||
public bool AllowsEnemy(EnemyInstance enemy) => !Active || Step.Action == TutorialAction.TargetEnemy && ReferenceEquals(enemy, Enemy);
|
||||
|
||||
public void Acknowledge(CombatManager combat)
|
||||
{
|
||||
if (!Reading || !combat.TutorialInputReady) return;
|
||||
Advance(combat);
|
||||
}
|
||||
|
||||
public void CardPlayed(ResolutionTrack track)
|
||||
{ if (Active && !Reading && track == ExpectedTrack) _played = true; }
|
||||
public void CardResolved(ResolutionTrack track)
|
||||
{ if (Active && !Reading && track == ExpectedTrack) _resolved = true; }
|
||||
public void PhaseChanged(TurnPhase phase) { if (Active && Step.Action == TutorialAction.EndTurn && phase == TurnPhase.Interpret) _ended = true; }
|
||||
|
||||
public void Update(CombatManager combat)
|
||||
{
|
||||
if (!Active || combat.PlayerState == null) return;
|
||||
PickReferences(combat);
|
||||
switch (Step.Action)
|
||||
{
|
||||
case TutorialAction.SelectCard:
|
||||
if (Card != null && combat.PendingTargetCard == Card) Advance(combat);
|
||||
else if (_played && (Queued(combat) || _resolved))
|
||||
{ Advance(combat); if (Step?.Action == TutorialAction.TargetEnemy) Advance(combat); }
|
||||
break;
|
||||
case TutorialAction.TargetEnemy:
|
||||
if (_lesson == 1)
|
||||
{
|
||||
if (Step.Id == "target-zombie" && Enemy?.PendingRevive == true) Advance(combat);
|
||||
else if (Step.Id == "finish-zombie" && Enemy?.HasRevived == true && Enemy.State.IsDefeated) Advance(combat);
|
||||
}
|
||||
else if (_played && (Queued(combat) || _resolved)) Advance(combat);
|
||||
break;
|
||||
case TutorialAction.PlayShield:
|
||||
if (_resolved && Card != null && !combat.HandController.Cards.Contains(Card)) Advance(combat);
|
||||
break;
|
||||
case TutorialAction.EndTurn:
|
||||
if (_ended && combat.TutorialInputReady
|
||||
&& (_lesson != 1 || Enemy?.HasRevived == true)) Advance(combat);
|
||||
break;
|
||||
}
|
||||
combat.TutorialReading = Reading;
|
||||
}
|
||||
|
||||
private bool Queued(CombatManager combat) => Card != null && (combat.InterpreterQueue.Cards.Contains(Card)
|
||||
|| combat.LazyStack.Entries.Any(entry => entry.Card == Card));
|
||||
|
||||
private void Advance(CombatManager combat)
|
||||
{
|
||||
Index++;
|
||||
if (Active && Step.Action is TutorialAction.SelectCard or TutorialAction.PlayShield)
|
||||
{
|
||||
Card = null; _played = _resolved = false;
|
||||
combat.ClearTutorialSelection();
|
||||
}
|
||||
if (Active && Step.Action == TutorialAction.EndTurn) _ended = false;
|
||||
PickReferences(combat);
|
||||
combat.TutorialReading = Reading;
|
||||
}
|
||||
|
||||
private void PickReferences(CombatManager combat)
|
||||
{
|
||||
if (!Active) return;
|
||||
if (Enemy == null)
|
||||
Enemy = combat.Enemies.FirstOrDefault(enemy => _lesson != 1 || enemy.ArchetypeId == "zombie_process");
|
||||
if (Card != null || combat.HandController == null) return;
|
||||
string id = _lesson == 1 ? Step.Id is "shield-card" or "shield-result" ? "lang_rs_borrow"
|
||||
: Index >= 13 ? "lang_rs_fn_main" : "lang_rs_unwrap" : null;
|
||||
Card = combat.HandController.Cards.FirstOrDefault(card => !card.IsBroken && !card.IsLocked
|
||||
&& (id != null ? card.Definition.Id == id : card.Definition.ResolutionTrack == ExpectedTrack)
|
||||
&& combat.GetDisplayedPlayCost(card) <= combat.PlayerState.Cycles);
|
||||
}
|
||||
|
||||
public static IReadOnlyList<TutorialStep> Build(int lesson)
|
||||
{
|
||||
if (lesson == 1) return new[] {
|
||||
new TutorialStep("uptime", "This is your Uptime", "Uptime is your health. At 0, a normal run ends. This practice uses loan cards, full health and no distro passive procs; your collection is safe.", "TutorialUptime"),
|
||||
new TutorialStep("shield", "Shield protects Uptime", "Shield absorbs ordinary incoming damage first. This number shows how much protection you currently have.", "TutorialShield"),
|
||||
new TutorialStep("cycles", "Cycles pay for cards", "This is your remaining card budget. The cost in a card's upper-right corner is paid when you play it. Cycles refresh each round.", "TutorialCycles"),
|
||||
new TutorialStep("ram", "RAM is hand capacity", "This shows used RAM / capacity. Most cards use 1 RAM; Java uses 2. More Cycles do not let extra cards fit in a full hand.", "TutorialRam"),
|
||||
new TutorialStep("attack-card", "Read your attack card", "unwrap() costs Cycles and deals damage immediately: it is Native. Its rules and current estimate are printed here. Rust overkill can also grant Shield.", "card"),
|
||||
new TutorialStep("intent", "Read the enemy's intent", "This is what Zombie Process plans to do when enemies act. Check the attack range before ending your turn.", "zombie-intent"),
|
||||
new TutorialStep("select-attack", "1 / Select the attack", "Click the highlighted unwrap() card first. Selecting a targeted card asks for an enemy; it does not spend Cycles yet.", "card", TutorialAction.SelectCard),
|
||||
new TutorialStep("target-zombie", "2 / Choose the zombie", "Now click Zombie Process to dispatch your selected card. Other targets and End turn are locked for this demonstration.", "zombie", TutorialAction.TargetEnemy),
|
||||
new TutorialStep("pending-revival", "Zero Uptime, but not gone", "Your attack reduced the zombie to 0. RESTART PENDING means it will revive next round. A fresh zombie can do this once; finishing it from 30% Uptime or less reaps it instead.", "zombie"),
|
||||
new TutorialStep("end-turn", "3 / End your turn", "Click End turn (or press E). The remaining enemy acts, then the next round begins and the zombie revives. Watch its Uptime.", "TutorialEndTurn", TutorialAction.EndTurn),
|
||||
new TutorialStep("revived", "The zombie has respawned", "It has returned at half Uptime. RESTART USED means it cannot revive again. Your Cycles also refreshed for this round.", "zombie"),
|
||||
new TutorialStep("shield-card", "4 / Add protection", "Click borrow() to gain Shield now. It needs no enemy target. Any Shield you already have from Rust overkill is kept.", "card", TutorialAction.PlayShield),
|
||||
new TutorialStep("shield-result", "Your Shield increased", "That card added protection to this number. Shield is not healing: it absorbs damage before your Uptime is reduced.", "TutorialShield"),
|
||||
new TutorialStep("select-finisher", "5 / Select a finisher", "Select the highlighted fn main() card. Then you will choose the revived zombie as its target.", "card", TutorialAction.SelectCard),
|
||||
new TutorialStep("finish-zombie", "6 / Finish the revived zombie", "Click the zombie again. Its revival is already spent, so this attack can terminate it permanently.", "zombie", TutorialAction.TargetEnemy),
|
||||
new TutorialStep("piles", "Track your cards", "Played cards go to discard; an empty draw pile reshuffles discard. Exhausted cards stay out for this wave. These counters open pile inspectors.", "TutorialPiles"),
|
||||
new TutorialStep("practice", "Finish the encounter", "You have practiced targeting, revival and Shield. Clear the remaining orphan processes on your own. Use card → enemy, and End turn when needed. A zombie can leave an orphan when permanently defeated.", "enemies")
|
||||
};
|
||||
return new[] {
|
||||
new TutorialStep("leak", "A new threat: Memory Leak", "This enemy grows stronger each round and applies damage-over-time stacks. Your health and purchased upgrade carried over from wave one.", "enemy:memory_leak"),
|
||||
new TutorialStep("firewall", "A protector: firewalld", "firewalld shields itself and adjacent processes. Read its intent before choosing which enemy to remove first.", "enemy:firewalld"),
|
||||
new TutorialStep("queue-intro", "Python uses the queue", "Python waits until End turn. Its cards resolve oldest first (FIFO). Let's put a real card into this queue.", "TutorialQueue"),
|
||||
new TutorialStep("select-python", "Select the Python card", "Click the highlighted Python card. print() chooses its target when it resolves, so it does not ask you to click an enemy.", "card", TutorialAction.SelectCard),
|
||||
new TutorialStep("target-python", "Select a target", "Click the highlighted enemy to complete this play.", "enemy", TutorialAction.TargetEnemy),
|
||||
new TutorialStep("queued-python", "Python is waiting here", "Your card is now queued, not resolved. With multiple entries, the oldest would execute first.", "TutorialQueue"),
|
||||
new TutorialStep("stack-intro", "Haskell uses the stack", "Haskell waits until after Python and resolves newest first (LIFO). Each entry captures a multiplier for damage and explicit Shield.", "TutorialStack"),
|
||||
new TutorialStep("select-haskell", "Select the Haskell card", "Click the highlighted thunk() card, then select the highlighted enemy.", "card", TutorialAction.SelectCard),
|
||||
new TutorialStep("target-haskell", "Choose its target", "Click this enemy. The attack will wait on the stack rather than dealing damage immediately.", "enemy", TutorialAction.TargetEnemy),
|
||||
new TutorialStep("queued-haskell", "Both tracks are ready", "Python will resolve first, then Haskell, then surviving enemies. A defeated target can cause deferred damage to retarget.", "TutorialStack"),
|
||||
new TutorialStep("end-round", "Run the queued actions", "Click End turn (or press E). Watch the queue resolve before the stack. We will continue when the exchange finishes.", "TutorialEndTurn", TutorialAction.EndTurn),
|
||||
new TutorialStep("resolved", "The waiting cards resolved", "The scheduler has executed the deferred cards. Check enemy Uptime, Shield and intents before choosing your next move.", "enemies"),
|
||||
new TutorialStep("practice", "Clear wave two", "Finish every remaining enemy on your own. Clearing this wave completes training and unlocks 1,000 Bandwidth plus 1,000 Entropy: enough for a standard 10-pull.", "enemies")
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 42f2d4b1f5fdc5246b1f5300f014f8a5
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6f677d4ac6de4dca8e92a3efa687ff1b
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 03ad9dd5bf1d46ee9cd2a6f54d17b5fa
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e05527a70e234c16af2f9089012721b8
|
||||
@@ -0,0 +1,260 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using KernelPanic.Combat;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace KernelPanic.UI
|
||||
{
|
||||
/// <summary>Read-only card inventory. Sorting a copy never exposes or changes draw order.</summary>
|
||||
public static class CardPileView
|
||||
{
|
||||
private sealed class TabState
|
||||
{
|
||||
public string Query = string.Empty;
|
||||
public string Language = "All languages";
|
||||
public string Cost = "Any stored cost";
|
||||
public bool GroupCopies = true;
|
||||
public float Scroll;
|
||||
}
|
||||
|
||||
public static IReadOnlyList<CardInstance> FilterAndSort(IEnumerable<CardInstance> cards, string query)
|
||||
{
|
||||
query = query?.Trim() ?? string.Empty;
|
||||
return (cards ?? Array.Empty<CardInstance>()).Where(card => card?.Definition != null)
|
||||
.Where(card => query.Length == 0 || SearchText(card).IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0)
|
||||
.OrderBy(card => card.Definition.DisplayName, StringComparer.OrdinalIgnoreCase)
|
||||
.ThenBy(card => card.Definition.Id, StringComparer.Ordinal)
|
||||
.ThenBy(card => card.UpgradeLevel).ThenBy(card => card.MagnitudeBonus)
|
||||
.ThenBy(card => card.PermanentCostDelta).ThenBy(card => card.DrawRider)
|
||||
.ThenBy(card => card.TemporaryCostDelta).ThenBy(card => card.IsBroken)
|
||||
.ThenBy(card => card.CorruptionRoundsRemaining).ThenBy(card => card.IsLocked).ToArray();
|
||||
}
|
||||
|
||||
private static string SearchText(CardInstance card) =>
|
||||
$"{card.Definition.DisplayName} {card.Definition.Id} {card.Definition.Language} {CardEffectFactory.GetRulesText(card)} " +
|
||||
(card.IsUpgraded ? $"upgraded patch {card.UpgradeLevel}" : string.Empty);
|
||||
|
||||
public static IReadOnlyList<CardInstance[]> GroupIdenticalCopies(IEnumerable<CardInstance> cards,
|
||||
Func<CardInstance, string> costDetails = null) => FilterAndSort(cards, string.Empty)
|
||||
.GroupBy(card => new
|
||||
{
|
||||
card.Definition, card.UpgradeLevel, card.MagnitudeBonus, card.DrawRider,
|
||||
card.PermanentCostDelta, card.TemporaryCostDelta, card.IsBroken,
|
||||
card.CorruptionRoundsRemaining, card.IsLocked, card.QueuePlayCount,
|
||||
card.WasFirstCardThisTurn, card.HadFedoraNonCrashBonus,
|
||||
CostContext = costDetails?.Invoke(card) ?? string.Empty
|
||||
}).Select(group => group.ToArray()).ToArray();
|
||||
|
||||
public static VisualElement Build(string title, IReadOnlyList<CardInstance> snapshot, Action close) =>
|
||||
BuildBrowser(title, new Dictionary<string, IReadOnlyList<CardInstance>> { [title] = snapshot }, close);
|
||||
|
||||
public static VisualElement BuildBrowser(string initialPile,
|
||||
IReadOnlyDictionary<string, IReadOnlyList<CardInstance>> inventories, Action close,
|
||||
Func<CardInstance, string> costDetails = null)
|
||||
{
|
||||
var piles = inventories.ToDictionary(pair => pair.Key,
|
||||
pair => (pair.Value ?? Array.Empty<CardInstance>()).Where(card => card?.Definition != null).ToArray());
|
||||
if (piles.Count == 0) piles[initialPile] = Array.Empty<CardInstance>();
|
||||
string selected = piles.ContainsKey(initialPile) ? initialPile : piles.Keys.First();
|
||||
var states = piles.Keys.ToDictionary(key => key, _ => new TabState());
|
||||
var tabs = new Dictionary<string, Button>();
|
||||
int revision = 0;
|
||||
var cards = piles[selected];
|
||||
var panel = new VisualElement { name = "CardPileInspector" };
|
||||
panel.AddToClassList("pile-inspector");
|
||||
var header = new VisualElement();
|
||||
header.AddToClassList("pile-header");
|
||||
var heading = SoftwareCardView.Text(selected.ToUpperInvariant() + " PILE", "pile-title");
|
||||
header.Add(heading);
|
||||
var count = SoftwareCardView.Text(string.Empty, "pile-count");
|
||||
count.name = "PileCount";
|
||||
header.Add(count);
|
||||
panel.Add(header);
|
||||
panel.Add(SoftwareCardView.Text("Sorted A-Z. Draw order stays hidden. Costs on cards are stored costs.", "pile-description"));
|
||||
var tabRow = new VisualElement { name = "PileTabs" };
|
||||
tabRow.AddToClassList("pile-tabs");
|
||||
if (piles.Count > 1) panel.Add(tabRow);
|
||||
var searchRow = new VisualElement();
|
||||
searchRow.AddToClassList("pile-search-row");
|
||||
var search = new TextField("Search") { name = "PileSearch", tooltip = "Filter by card name, language, rules or upgrades." };
|
||||
search.textEdition.placeholder = "Name, language or rules...";
|
||||
search.textEdition.hidePlaceholderOnFocus = false;
|
||||
search.AddToClassList("pile-search");
|
||||
searchRow.Add(search);
|
||||
var clear = new Button(() => { search.value = string.Empty; search.Focus(); })
|
||||
{
|
||||
name = "ClearPileSearch", text = "Clear", tooltip = "Clear the search text."
|
||||
};
|
||||
clear.AddToClassList("pile-clear");
|
||||
searchRow.Add(clear);
|
||||
panel.Add(searchRow);
|
||||
var filters = new VisualElement();
|
||||
filters.AddToClassList("pile-filters");
|
||||
var languages = new List<string> { "All languages" };
|
||||
languages.AddRange(piles.Values.SelectMany(pile => pile).Select(LanguageName).Distinct().OrderBy(name => name, StringComparer.Ordinal));
|
||||
var language = new DropdownField(languages, 0) { name = "PileLanguageFilter", tooltip = "Filter by card language." };
|
||||
var cost = new DropdownField(new List<string> { "Any stored cost", "0 cycles", "1 cycle", "2 cycles", "3+ cycles" }, 0)
|
||||
{ name = "PileCostFilter", tooltip = "Filter by stored Cycles, before current combat discounts." };
|
||||
var grouped = new Toggle("Group copies") { name = "PileGroupCopies", value = true };
|
||||
var scroll = new ScrollView(ScrollViewMode.Vertical) { name = "PileCards" };
|
||||
var grid = new VisualElement { name = "PileCardGrid" };
|
||||
var reset = new Button { name = "ResetPileFilters", text = "Reset filters" };
|
||||
reset.clicked += () =>
|
||||
{
|
||||
states[selected].Query = string.Empty;
|
||||
states[selected].Language = languages[0];
|
||||
states[selected].Cost = cost.choices[0];
|
||||
search.SetValueWithoutNotify(string.Empty);
|
||||
language.SetValueWithoutNotify(languages[0]);
|
||||
cost.SetValueWithoutNotify(cost.choices[0]);
|
||||
Refresh(string.Empty);
|
||||
search.Focus();
|
||||
};
|
||||
language.AddToClassList("pile-filter");
|
||||
cost.AddToClassList("pile-filter");
|
||||
grouped.AddToClassList("pile-group-toggle");
|
||||
reset.AddToClassList("pile-clear");
|
||||
filters.Add(language); filters.Add(cost); filters.Add(grouped); filters.Add(reset);
|
||||
panel.Add(filters);
|
||||
scroll.AddToClassList("pile-scroll");
|
||||
scroll.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
|
||||
grid.AddToClassList("pile-grid");
|
||||
scroll.Add(grid);
|
||||
panel.Add(scroll);
|
||||
void LayoutCards()
|
||||
{
|
||||
float width = scroll.contentViewport.contentRect.width;
|
||||
if (width <= 0 || float.IsNaN(width)) return;
|
||||
int columns = width >= 900 ? 3 : width >= 600 ? 2 : 1;
|
||||
float cardWidth = Mathf.Floor((width - (columns - 1) * 12) / columns);
|
||||
int index = 0;
|
||||
foreach (var face in grid.Children().Where(element => element.ClassListContains("pile-card")))
|
||||
{
|
||||
face.style.width = cardWidth;
|
||||
face.style.marginRight = ++index % columns == 0 ? 0 : 12;
|
||||
}
|
||||
}
|
||||
scroll.contentViewport.RegisterCallback<GeometryChangedEvent>(_ => LayoutCards());
|
||||
panel.RegisterCallback<KeyDownEvent>(evt =>
|
||||
{
|
||||
if (evt.keyCode == KeyCode.Escape)
|
||||
{
|
||||
close?.Invoke();
|
||||
evt.StopPropagation();
|
||||
}
|
||||
else if (evt.keyCode == KeyCode.PageUp || evt.keyCode == KeyCode.PageDown)
|
||||
{
|
||||
float delta = Mathf.Max(40, scroll.contentViewport.layout.height * 0.8f);
|
||||
scroll.scrollOffset += new Vector2(0, evt.keyCode == KeyCode.PageUp ? -delta : delta);
|
||||
evt.StopPropagation();
|
||||
}
|
||||
}, TrickleDown.TrickleDown);
|
||||
void Refresh(string query)
|
||||
{
|
||||
revision++;
|
||||
var state = states[selected];
|
||||
state.Query = query;
|
||||
grid.Clear();
|
||||
scroll.scrollOffset = Vector2.zero;
|
||||
var filtered = FilterAndSort(cards, query).Where(card =>
|
||||
(state.Language == languages[0] || LanguageName(card) == state.Language) &&
|
||||
(state.Cost == cost.choices[0] || (state.Cost == "3+ cycles"
|
||||
? CombatManager.GetCardCost(card) >= 3
|
||||
: CombatManager.GetCardCost(card) == state.Cost[0] - '0'))).ToArray();
|
||||
heading.text = selected.ToUpperInvariant() + " PILE";
|
||||
count.text = filtered.Length == cards.Length ? $"{cards.Length} {(cards.Length == 1 ? "card" : "cards")}" : $"{filtered.Length} of {cards.Length} cards";
|
||||
clear.SetEnabled(!string.IsNullOrEmpty(query));
|
||||
reset.SetEnabled(query.Length > 0 || state.Language != languages[0] || state.Cost != cost.choices[0]);
|
||||
foreach (var tab in tabs) tab.Value.EnableInClassList("selected", tab.Key == selected);
|
||||
if (filtered.Length == 0)
|
||||
{
|
||||
var empty = SoftwareCardView.Text(cards.Length == 0 ? "This pile is empty." : "No matching cards. Try another search or reset the filters.", "pile-empty");
|
||||
empty.name = "PileEmptyState";
|
||||
grid.Add(empty);
|
||||
}
|
||||
var groups = state.GroupCopies ? GroupIdenticalCopies(filtered, costDetails) : filtered.Select(card => new[] { card }).ToArray();
|
||||
foreach (var copies in groups)
|
||||
{
|
||||
var card = copies[0];
|
||||
var face = new VisualElement { name = "PileCard", userData = copies.Length };
|
||||
face.AddToClassList("pile-card");
|
||||
SoftwareCardView.Populate(face, card, CombatManager.GetCardCost(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;
|
||||
if (copies.Length > 1)
|
||||
{
|
||||
var badge = SoftwareCardView.Text($"×{copies.Length} identical copies", "pile-copy-count");
|
||||
badge.name = "PileCopyCount";
|
||||
face.Insert(0, badge);
|
||||
}
|
||||
string costs = costDetails?.Invoke(card);
|
||||
if (!string.IsNullOrEmpty(costs))
|
||||
{
|
||||
int split = costs.IndexOf('\n');
|
||||
face.Add(SoftwareCardView.Text(split < 0 ? costs : costs.Substring(0, split), "pile-cost-summary"));
|
||||
if (split >= 0)
|
||||
{
|
||||
var explanation = new Foldout { text = "Cost details", value = false, name = "PileCostDetails" };
|
||||
explanation.Add(SoftwareCardView.Text(costs.Substring(split + 1), "pile-cost-explanation"));
|
||||
face.Add(explanation);
|
||||
}
|
||||
}
|
||||
if (card.IsBroken)
|
||||
face.Add(SoftwareCardView.Text(CardPreviewService.CorruptionDetails(card), "pile-status-detail"));
|
||||
var details = new List<string> { $"RAM {HandController.GetRamCost(card)}" };
|
||||
if (card.UpgradeLevel > 0) details.Add($"Patch {card.UpgradeLevel}");
|
||||
if (card.PermanentCostDelta != 0) details.Add($"cost adjustment {card.PermanentCostDelta:+0;-0;0}");
|
||||
if (card.MagnitudeBonus != 0) details.Add($"magnitude {card.MagnitudeBonus:+0;-0;0}");
|
||||
if (card.DrawRider != 0) details.Add($"draw {card.DrawRider:+0;-0;0}");
|
||||
if (card.TemporaryCostDelta != 0) details.Add($"temporary cost {card.TemporaryCostDelta:+0;-0;0}");
|
||||
face.Add(SoftwareCardView.Text(string.Join(" / ", details), "pile-upgrades"));
|
||||
grid.Add(face);
|
||||
}
|
||||
LayoutCards();
|
||||
}
|
||||
foreach (string key in piles.Keys)
|
||||
{
|
||||
string pile = key;
|
||||
var tab = new Button(() =>
|
||||
{
|
||||
if (selected == pile) return;
|
||||
states[selected].Scroll = scroll.scrollOffset.y;
|
||||
selected = pile;
|
||||
cards = piles[pile];
|
||||
var state = states[pile];
|
||||
search.SetValueWithoutNotify(state.Query);
|
||||
language.SetValueWithoutNotify(state.Language);
|
||||
cost.SetValueWithoutNotify(state.Cost);
|
||||
grouped.SetValueWithoutNotify(state.GroupCopies);
|
||||
Refresh(state.Query);
|
||||
int rendering = revision;
|
||||
panel.schedule.Execute(() =>
|
||||
{
|
||||
if (rendering == revision) scroll.scrollOffset = new Vector2(0, state.Scroll);
|
||||
}).StartingIn(16);
|
||||
}) { name = "PileTab_" + pile, text = $"{char.ToUpperInvariant(pile[0])}{pile.Substring(1)} ({piles[pile].Length})" };
|
||||
tab.AddToClassList("pile-tab");
|
||||
tabs.Add(pile, tab);
|
||||
tabRow.Add(tab);
|
||||
}
|
||||
search.RegisterValueChangedCallback(evt => Refresh(evt.newValue));
|
||||
language.RegisterValueChangedCallback(evt => { states[selected].Language = evt.newValue; Refresh(search.value); });
|
||||
cost.RegisterValueChangedCallback(evt => { states[selected].Cost = evt.newValue; Refresh(search.value); });
|
||||
grouped.RegisterValueChangedCallback(evt => { states[selected].GroupCopies = evt.newValue; Refresh(search.value); });
|
||||
Refresh(string.Empty);
|
||||
var dismiss = new Button(close) { text = "Close [Esc]", name = "ClosePileInspector" };
|
||||
dismiss.AddToClassList("primary-action");
|
||||
var footer = new VisualElement();
|
||||
footer.AddToClassList("pile-footer");
|
||||
footer.Add(SoftwareCardView.Text("PgUp / PgDn: scroll", "pile-footer-hint"));
|
||||
footer.Add(dismiss);
|
||||
panel.Add(footer);
|
||||
return panel;
|
||||
}
|
||||
|
||||
private static string LanguageName(CardInstance card) => card.Definition.Language.ToString().Replace("CPlusPlus", "C++");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: cc8a03f56d32c661088f820d4f765a47
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c6c581de5a6bcbc73a451ce3906547bc
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b1100000000000000000000000000003
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 73880a4e893003d719622694aa5ffc02
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4bf334307f22465cad853cb6b3757468
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4b02ec0c6f7df1d3aa8211567c3ec2a3
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3fc0548ea57f35548834530e8a2ec091
|
||||
@@ -0,0 +1,100 @@
|
||||
using KernelPanic.Combat;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace KernelPanic.UI
|
||||
{
|
||||
internal sealed class ExecutionPreviewView
|
||||
{
|
||||
public Foldout Element { get; } = new() { text = "End-turn execution preview", name = "ExecutionPreview", value = false };
|
||||
private readonly ScrollView _rows = new(ScrollViewMode.Vertical);
|
||||
private CombatManager _combat;
|
||||
private VisualElement _popup;
|
||||
public bool IsOpen => _popup != null;
|
||||
|
||||
public ExecutionPreviewView()
|
||||
{
|
||||
Element.AddToClassList("execution-preview");
|
||||
_rows.style.maxHeight = 220;
|
||||
_rows.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
|
||||
Element.Add(_rows);
|
||||
Element.RegisterValueChangedCallback(evt =>
|
||||
{
|
||||
if (!evt.newValue) { Close(); return; }
|
||||
Refresh(_combat);
|
||||
Element.schedule.Execute(() =>
|
||||
{
|
||||
if (!Element.value) return;
|
||||
var workspace = Element.GetFirstAncestorOfType<ScrollView>();
|
||||
if (workspace == null) return;
|
||||
if (workspace.contentViewport.resolvedStyle.height < 180)
|
||||
{ OpenPopup(workspace.parent); return; }
|
||||
FitRows(workspace);
|
||||
Element.schedule.Execute(() => workspace.ScrollTo(Element));
|
||||
});
|
||||
});
|
||||
Element.RegisterCallback<GeometryChangedEvent>(_ =>
|
||||
{
|
||||
if (Element.value && !IsOpen && Element.GetFirstAncestorOfType<ScrollView>() is { } workspace)
|
||||
FitRows(workspace);
|
||||
});
|
||||
}
|
||||
|
||||
private void OpenPopup(VisualElement root)
|
||||
{
|
||||
if (IsOpen || root == null) return;
|
||||
_popup = new VisualElement { name = "ExecutionPreviewPopup", focusable = true };
|
||||
_popup.AddToClassList("execution-preview-shade");
|
||||
var panel = TerminalLayout.Section("End-turn execution preview", "ExecutionPreviewDialog");
|
||||
panel.AddToClassList("execution-preview-dialog");
|
||||
_rows.RemoveFromHierarchy();
|
||||
_rows.style.maxHeight = StyleKeyword.None;
|
||||
_rows.style.flexGrow = 1;
|
||||
_rows.style.minHeight = 0;
|
||||
panel.Add(_rows);
|
||||
var close = new Button(Close) { text = "Close / Escape", name = "CloseExecutionPreview" };
|
||||
close.AddToClassList("primary-action");
|
||||
panel.Add(close);
|
||||
_popup.Add(panel);
|
||||
_popup.RegisterCallback<KeyDownEvent>(evt =>
|
||||
{
|
||||
if (evt.keyCode == KeyCode.Escape) Close();
|
||||
evt.StopPropagation();
|
||||
});
|
||||
TerminalTheme.ConstrainModalFocus(_popup);
|
||||
root.Add(_popup);
|
||||
_popup.BringToFront();
|
||||
close.Focus();
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
bool hadPopup = IsOpen;
|
||||
_popup?.RemoveFromHierarchy();
|
||||
_popup = null;
|
||||
Element.SetValueWithoutNotify(false);
|
||||
_rows.style.maxHeight = 220;
|
||||
_rows.style.flexGrow = 0;
|
||||
if (_rows.parent != Element.contentContainer) Element.Add(_rows);
|
||||
if (hadPopup) Element.Q<Toggle>()?.Focus();
|
||||
}
|
||||
|
||||
private void FitRows(ScrollView workspace)
|
||||
{
|
||||
float height = workspace.contentViewport.resolvedStyle.height;
|
||||
if (!float.IsNaN(height) && height > 0)
|
||||
_rows.style.maxHeight = System.Math.Max(36, System.Math.Min(220, height - 42));
|
||||
}
|
||||
|
||||
public void Refresh(CombatManager combat)
|
||||
{
|
||||
_combat = combat;
|
||||
bool available = combat != null && !combat.RunFinished && !combat.AwaitingWaveContinue;
|
||||
Element.style.display = available ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
if (!available) Close();
|
||||
if (!available || !Element.value) return;
|
||||
_rows.Clear();
|
||||
foreach (string line in ExecutionPreview.Build(combat)) _rows.Add(TerminalLayout.BodyText(line));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: aa8f89d97d7143a6b735100d9dfc677b
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a850316506e1ce241a2e74281b4b9943
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c7f7ef4e16694ed9bd746278b0ddc4d8
|
||||
@@ -0,0 +1,148 @@
|
||||
using System;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Run;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace KernelPanic.UI
|
||||
{
|
||||
/// <summary>Observes a real battle; never changes cards, targeting or turn timing.</summary>
|
||||
public sealed class FirstBattleGuide
|
||||
{
|
||||
private const string PreferenceKey = "KernelPanic.FirstBattleGuide.v1";
|
||||
private readonly Action _remember;
|
||||
private readonly Label _title = new();
|
||||
private readonly Label _instruction = new();
|
||||
private readonly Label _receipt = new();
|
||||
private readonly Button _action;
|
||||
private readonly Button _skip;
|
||||
private RunConfig _config;
|
||||
private bool _played;
|
||||
private bool _endedTurn;
|
||||
private bool _completed;
|
||||
private bool _started;
|
||||
public VisualElement Element { get; } = new() { name = "FirstBattleGuide" };
|
||||
public bool Visible => Element.style.display.value != DisplayStyle.None;
|
||||
public string Instruction => _instruction.text;
|
||||
|
||||
public FirstBattleGuide(Action remember = null)
|
||||
{
|
||||
_remember = remember ?? Remember;
|
||||
Element.AddToClassList("first-battle-guide");
|
||||
_title.AddToClassList("guide-title");
|
||||
_instruction.AddToClassList("guide-copy");
|
||||
_receipt.AddToClassList("guide-copy");
|
||||
var header = new VisualElement();
|
||||
header.AddToClassList("guide-header");
|
||||
header.Add(_title);
|
||||
Element.Add(header);
|
||||
Element.Add(_instruction);
|
||||
Element.Add(_receipt);
|
||||
var actions = new VisualElement();
|
||||
actions.AddToClassList("guide-actions");
|
||||
_action = new Button(Advance) { text = "Ready: play a card" };
|
||||
_skip = new Button(Dismiss) { text = "Skip guide" };
|
||||
actions.Add(_action);
|
||||
actions.Add(_skip);
|
||||
header.Add(actions);
|
||||
Element.style.display = DisplayStyle.None;
|
||||
}
|
||||
|
||||
public void Begin(RunConfig config, bool replay = false)
|
||||
{
|
||||
_config = config;
|
||||
if (!replay && PlayerPrefs.GetInt(PreferenceKey, 0) != 0) return;
|
||||
_played = _endedTurn = _completed = _started = false;
|
||||
_receipt.text = "";
|
||||
Element.style.display = DisplayStyle.Flex;
|
||||
_action.style.display = DisplayStyle.Flex;
|
||||
_skip.style.display = DisplayStyle.Flex;
|
||||
_action.text = "Ready: play a card";
|
||||
_title.text = "First battle / 1 of 4 / read the process table";
|
||||
_instruction.text = "Uptime = health; Cycles = card budget; RAM = hand capacity. Read enemy intents, then select a card and its target. " + TrackLesson(config);
|
||||
}
|
||||
|
||||
public void Advance()
|
||||
{
|
||||
if (!Visible) return;
|
||||
if (_completed) { Dismiss(); return; }
|
||||
_started = true;
|
||||
_action.style.display = DisplayStyle.None;
|
||||
_title.text = "First battle / 2 of 4 / dispatch a card";
|
||||
_instruction.text = "Play any affordable card. Targeted cards need a living process selected. The preview explains its current effect. " + TrackLesson(_config);
|
||||
}
|
||||
|
||||
public void CardPlayed(ResolutionTrack track, string name)
|
||||
{
|
||||
if (!Visible || _completed) return;
|
||||
_played = _started = true;
|
||||
_action.style.display = DisplayStyle.None;
|
||||
_title.text = "First battle / 3 of 4 / finish your turn";
|
||||
_receipt.text = track switch
|
||||
{
|
||||
ResolutionTrack.InterpreterQueue => name + " entered the queue. It waits until end turn; the oldest queued card resolves first.",
|
||||
ResolutionTrack.LazyStack => name + " entered the stack. It waits until after the queue; the newest stacked card resolves first.",
|
||||
_ => name + " executes immediately on the Native track."
|
||||
};
|
||||
_instruction.text = "Play more cards if you have Cycles, then choose [E] end turn. Watch the scheduler: queue first, stack second, then enemies act. Shield helps absorb incoming damage.";
|
||||
}
|
||||
|
||||
public void CardResolved(string name, ResolutionTrack track)
|
||||
{
|
||||
if (!Visible || _completed) return;
|
||||
_receipt.text = name + " resolved" + (track == ResolutionTrack.Native ? " immediately." : track == ResolutionTrack.InterpreterQueue ? " from the front of the queue." : " from the top of the stack.");
|
||||
}
|
||||
|
||||
public void PhaseChanged(TurnPhase phase)
|
||||
{
|
||||
if (!Visible || _completed) return;
|
||||
if (phase == TurnPhase.Interpret)
|
||||
{
|
||||
_endedTurn = true;
|
||||
_instruction.text = "Resolving: queued cards execute oldest first, then stacked cards execute newest first. Enemy actions follow. You can inspect the journal for the result of each operation.";
|
||||
}
|
||||
if (phase == TurnPhase.Execute && _endedTurn) Complete(false);
|
||||
}
|
||||
|
||||
public void Refresh(bool waveCleared, bool runLost)
|
||||
{
|
||||
if (!Visible || _completed) return;
|
||||
if (waveCleared || runLost) Complete(waveCleared);
|
||||
}
|
||||
|
||||
private void Complete(bool waveCleared)
|
||||
{
|
||||
_completed = true;
|
||||
_title.text = "First battle / 4 of 4 / plan the next round";
|
||||
_instruction.text = waveCleared
|
||||
? "Wave cleared! Spend Bits in the repository on cards, upgrades or healing, then continue. Cleared waves earn rewards that are banked when the run ends."
|
||||
: "Check Uptime, Shield and the next enemy intents before your next move. Each completed round refreshes your turn resources. " + (_config?.Distro?.Id == "gentoo" ? "Gentoo's Compilation advances after a completed round, improving damage (and Shield at higher versions), and resets each wave. " : "") + "You can reopen this with '? guide' in dispatch.";
|
||||
if (!_played && _started) _receipt.text = "You can also end a turn without playing a card; the same execution order applies.";
|
||||
_action.text = "Got it";
|
||||
_action.style.display = DisplayStyle.Flex;
|
||||
_skip.style.display = DisplayStyle.None;
|
||||
}
|
||||
|
||||
public void Dismiss()
|
||||
{
|
||||
Element.style.display = DisplayStyle.None;
|
||||
_remember();
|
||||
}
|
||||
|
||||
public static string TrackLesson(RunConfig config)
|
||||
{
|
||||
string lesson = "Native cards execute now.";
|
||||
if (config?.PrimaryLanguage == Language.Python || config?.SecondaryLanguage == Language.Python)
|
||||
lesson += " Your Python cards queue until end turn (first in, first out).";
|
||||
if (config?.PrimaryLanguage == Language.Haskell || config?.SecondaryLanguage == Language.Haskell)
|
||||
lesson += " Your Haskell cards stack until end turn (last in, first out); the multiplier shown on entry scales damage and explicit Shield.";
|
||||
return lesson;
|
||||
}
|
||||
|
||||
private static void Remember()
|
||||
{
|
||||
PlayerPrefs.SetInt(PreferenceKey, 1);
|
||||
PlayerPrefs.Save();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2387eab1278b407bab0ab3c3af35d553
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 039fa8aea1685b643b3f109bf70ec2ff
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0915991bbd2d4fb08d438e4fdae30935
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d5b4ca12d26e4e54962ab9f6658e72d2
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 27a7f29e93cb4c55beac52f1e32a1bf5
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e3049cf231244bd09f80e0f76801ef3b
|
||||
@@ -0,0 +1,137 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Meta;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace KernelPanic.UI
|
||||
{
|
||||
public static class RunHistoryView
|
||||
{
|
||||
public static VisualElement Build(IReadOnlyList<RunHistoryEntry> entries, Action close)
|
||||
=> Build(entries, close, null, null, null, null);
|
||||
|
||||
public static VisualElement Build(IReadOnlyList<RunHistoryEntry> entries, Action close,
|
||||
CardDatabase cards, PackageDatabase packages, Action<RunHistoryEntry> loadBuild,
|
||||
Func<RunHistoryEntry, string> unavailableReason)
|
||||
{
|
||||
var overlay = new VisualElement { name = "RunHistoryOverlay" };
|
||||
overlay.AddToClassList("modal-overlay");
|
||||
overlay.AddToClassList("modal-open");
|
||||
var dialog = new VisualElement();
|
||||
dialog.AddToClassList("root-credit-dialog");
|
||||
dialog.AddToClassList("run-history-dialog");
|
||||
dialog.style.width = Length.Percent(94);
|
||||
dialog.style.maxWidth = 760;
|
||||
dialog.style.maxHeight = Length.Percent(92);
|
||||
overlay.Add(dialog);
|
||||
dialog.Add(SoftwareCardView.Text($"RECENT RUNS / last {RunHistory.Capacity}", "section-title"));
|
||||
dialog.Add(new Label { name = "RunHistoryNotice", enableRichText = false });
|
||||
dialog.Q<Label>("RunHistoryNotice").style.whiteSpace = WhiteSpace.Normal;
|
||||
var scroll = new ScrollView(ScrollViewMode.Vertical);
|
||||
scroll.style.flexShrink = 1;
|
||||
scroll.style.flexGrow = 1;
|
||||
scroll.style.minHeight = 0;
|
||||
scroll.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
|
||||
dialog.Add(scroll);
|
||||
if (entries == null || entries.Count == 0)
|
||||
scroll.Add(Text("No completed runs yet. Your next run report will appear here."));
|
||||
else for (int index = 0; index < entries.Count; index++)
|
||||
{
|
||||
var entry = entries[index];
|
||||
if (entry == null) continue;
|
||||
var item = new VisualElement();
|
||||
item.style.marginBottom = 16;
|
||||
item.Add(Text($"{entry.distroName ?? entry.distroId} V{entry.distroVersion} / {entry.languages}"));
|
||||
item.Add(Text($"Wave {entry.waveReached} reached / {entry.wavesCleared} cleared / seed {entry.seed}"));
|
||||
string when = DateTimeOffset.TryParse(entry.endedUtc, out var time) ? time.ToLocalTime().ToString("g") : entry.endedUtc;
|
||||
item.Add(Text($"{when} / {(entry.victory ? "Victory" : entry.surrendered ? "Shutdown" : "Defeat")}: {entry.cause}"));
|
||||
item.Add(Text(entry.victory && entry.finalRound == 0 ? "Combat recap unavailable after resuming the victory checkpoint."
|
||||
: $"Final round {entry.finalRound}: {entry.damageDealt} uptime dealt / {entry.damageTaken} lost / {entry.shieldBlocked} blocked by shield"));
|
||||
if (entry.finalHits?.Count > 0)
|
||||
{
|
||||
var details = new Foldout { text = "Last incoming hits", value = false };
|
||||
foreach (var hit in entry.finalHits) details.Add(Text(hit));
|
||||
item.Add(details);
|
||||
}
|
||||
var buildDetails = new Foldout { text = "Inspect original build", name = $"ArchivedBuildDetails_{index}", value = false };
|
||||
if (!RunHistory.HasBuildSnapshot(entry))
|
||||
buildDetails.Add(Text("Build snapshot unavailable for this older run. Its deck, packages and languages cannot be reconstructed."));
|
||||
else
|
||||
{
|
||||
var snapshot = entry.build;
|
||||
buildDetails.Add(Text($"Original distro: {entry.distroName ?? snapshot.distroId} V{snapshot.distroVersion}"));
|
||||
buildDetails.Add(Text("Languages: " + (snapshot.languages == null ? "unavailable" : string.Join(" + ", snapshot.languages))));
|
||||
buildDetails.Add(Text($"Original seed: {snapshot.seed.ToString(CultureInfo.InvariantCulture)}"));
|
||||
buildDetails.Add(Text("Selected exclusive cards:"));
|
||||
AddCards(buildDetails, snapshot.exclusiveCardIds, cards);
|
||||
var deck = new Foldout { text = $"Full starting deck ({snapshot.startingDeckCardIds?.Count ?? 0} cards)", value = false };
|
||||
AddCards(deck, snapshot.startingDeckCardIds, cards);
|
||||
buildDetails.Add(deck);
|
||||
buildDetails.Add(Text("Equipped packages (original levels):"));
|
||||
if (snapshot.packages == null || snapshot.packages.Count == 0) buildDetails.Add(Text("None equipped."));
|
||||
else foreach (var package in snapshot.packages)
|
||||
{
|
||||
if (package == null) { buildDetails.Add(Text("Unavailable package entry.")); continue; }
|
||||
var definition = packages == null ? null : packages.FindById(package.packageId);
|
||||
buildDetails.Add(Text($"{package.slot}: {definition?.DisplayName ?? package.packageId} +{package.upgradeLevel}"
|
||||
+ (definition == null ? " (content unavailable)" : "")));
|
||||
}
|
||||
buildDetails.Add(Text("This is the original build, before repository changes. Loading copies its selections and seed into setup using current owned versions and package levels; it does not start a run. Card rules use current content."));
|
||||
}
|
||||
string reason = unavailableReason?.Invoke(entry);
|
||||
if (!RunHistory.HasBuildSnapshot(entry)) reason = "Build snapshot unavailable for this older run.";
|
||||
if (!string.IsNullOrWhiteSpace(reason)) buildDetails.Add(Text(reason));
|
||||
var load = new Button(() => loadBuild?.Invoke(entry)) { text = "load build into setup", name = $"LoadArchivedBuild_{index}", tooltip = reason };
|
||||
load.SetEnabled(RunHistory.HasBuildSnapshot(entry) && loadBuild != null && string.IsNullOrWhiteSpace(reason));
|
||||
load.AddToClassList("terminal-button");
|
||||
buildDetails.Add(load);
|
||||
item.Add(buildDetails);
|
||||
var copySeed = new Button { text = "copy seed", name = $"CopyRunSeed_{index}" };
|
||||
copySeed.AddToClassList("terminal-button");
|
||||
copySeed.clicked += () =>
|
||||
{
|
||||
GUIUtility.systemCopyBuffer = (RunHistory.HasBuildSnapshot(entry) ? entry.build.seed : entry.seed).ToString(CultureInfo.InvariantCulture);
|
||||
copySeed.text = "seed copied";
|
||||
};
|
||||
item.Add(copySeed);
|
||||
scroll.Add(item);
|
||||
}
|
||||
var dismiss = new Button(close) { text = "Close [Esc]", name = "CloseRunHistory" };
|
||||
dismiss.AddToClassList("terminal-button");
|
||||
dismiss.style.flexShrink = 0;
|
||||
dialog.Add(dismiss);
|
||||
TerminalTheme.ConstrainModalFocus(overlay);
|
||||
return overlay;
|
||||
}
|
||||
|
||||
private static void AddCards(VisualElement parent, IReadOnlyList<string> ids, CardDatabase cards)
|
||||
{
|
||||
if (ids == null || ids.Count == 0) { parent.Add(Text("Card list unavailable.")); return; }
|
||||
var counts = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
|
||||
var order = new List<string>();
|
||||
foreach (string id in ids)
|
||||
{
|
||||
string key = string.IsNullOrWhiteSpace(id) ? "unknown card" : id;
|
||||
if (!counts.ContainsKey(key)) { counts[key] = 0; order.Add(key); }
|
||||
counts[key]++;
|
||||
}
|
||||
foreach (string id in order)
|
||||
{
|
||||
var card = cards == null ? null : cards.FindById(id);
|
||||
parent.Add(Text($"{card?.DisplayName ?? id} x{counts[id]}"
|
||||
+ (card == null ? " (content unavailable)" : $" / {card.Language} / {card.CycleCost} base Cycles")));
|
||||
}
|
||||
}
|
||||
|
||||
private static Label Text(string value)
|
||||
{
|
||||
var label = new Label(value) { enableRichText = false };
|
||||
label.style.whiteSpace = WhiteSpace.Normal;
|
||||
label.style.flexShrink = 0;
|
||||
return label;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2f440079df49b3ced275f4c60f6a9f0e
|
||||
@@ -0,0 +1,56 @@
|
||||
using System;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Run;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace KernelPanic.UI
|
||||
{
|
||||
/// <summary>Repository decisions; all rewards and transitions remain in the run/combat model.</summary>
|
||||
internal static class RunRouteView
|
||||
{
|
||||
public static VisualElement Build(RunManager run, CombatManager combat)
|
||||
{
|
||||
var section = TerminalLayout.Section(run.CampaignChoicePending ? "KERNEL SECURED" : "Next route", "RunRouteChoices");
|
||||
section.AddToClassList("run-route-section");
|
||||
if (!string.IsNullOrEmpty(run.Journey.lastReward)) section.Add(TerminalLayout.BodyText(run.Journey.lastReward));
|
||||
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(Action("Finish campaign", "FinishCampaignButton", () => combat.CompleteCampaign()));
|
||||
section.Add(Action("Continue into endless", "ContinueEndlessButton", () => combat.ContinueEndless()));
|
||||
return section;
|
||||
}
|
||||
var plan = EncounterDirector.Plan(run.CurrentWaveNumber, run.Journey.selectedRoute);
|
||||
section.Add(TerminalLayout.BodyText($"Wave {run.CurrentWaveNumber}: {plan.Title}"));
|
||||
section.Add(TerminalLayout.BodyText(plan.Advice));
|
||||
var choices = new VisualElement();
|
||||
choices.AddToClassList("route-choices");
|
||||
AddChoice(choices, run, WaveRoute.Repair, "Repair stop",
|
||||
$"Restore up to {RunJourney.RepairUptime} Uptime on departure. Fight the standard encounter.");
|
||||
AddChoice(choices, run, WaveRoute.Challenge, "Elite detour",
|
||||
$"An extra elite Daemon joins the encounter. On clear: +{RunJourney.ChallengeBits} Bits and +1 draw on the first eligible deck card without a draw rider; +{RunJourney.ChallengeBits} extra Bits if none qualify.");
|
||||
section.Add(choices);
|
||||
section.Add(TerminalLayout.BodyText("Choose freely before booting. Repairs and difficulty apply only when you leave; the elite reward requires clearing the wave."));
|
||||
return section;
|
||||
}
|
||||
|
||||
private static void AddChoice(VisualElement parent, RunManager run, WaveRoute route, string title, string detail)
|
||||
{
|
||||
var card = new VisualElement();
|
||||
card.AddToClassList("route-choice");
|
||||
bool selected = run.Journey.selectedRoute == route;
|
||||
card.EnableInClassList("route-selected", selected);
|
||||
card.Add(Action((selected ? "[selected] " : "") + title, "Route" + route,
|
||||
() => run.SelectRoute(route)));
|
||||
card.Add(TerminalLayout.BodyText(detail));
|
||||
parent.Add(card);
|
||||
}
|
||||
|
||||
private static Button Action(string title, string name, Action action)
|
||||
{
|
||||
var button = new Button(action) { text = title, name = name };
|
||||
button.AddToClassList("primary-action");
|
||||
return button;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 856aaec7209048718a4828fd240b9a8b
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6bfa65b8d497538499a5b84a4d7a4e9f
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b73ddac91da44a8fb6ba634517d01003
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 14c81f7c3ea7de425b5ba4adf237c460
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b73ddac91da44a8fb6ba634517d01002
|
||||
@@ -0,0 +1,57 @@
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace KernelPanic.UI
|
||||
{
|
||||
/// <summary>Shared, wrapping terminal copy. Callers retain their names and contextual classes.</summary>
|
||||
internal static class TerminalLayout
|
||||
{
|
||||
public static VisualElement Section(string title, string name = null, string sectionClass = null, string headingClass = null)
|
||||
{
|
||||
var section = new VisualElement { name = name };
|
||||
section.AddToClassList("terminal-section");
|
||||
AddClasses(section, sectionClass);
|
||||
section.Add(Heading(title, name == null ? null : name + "Heading", headingClass));
|
||||
return section;
|
||||
}
|
||||
|
||||
public static Label Heading(string text, string name = null, string className = null)
|
||||
{
|
||||
var label = new Label(text) { name = name };
|
||||
label.AddToClassList("terminal-heading");
|
||||
AddClasses(label, className);
|
||||
return label;
|
||||
}
|
||||
|
||||
public static VisualElement StatRow(string key, string value, string name = null, string rowClass = null,
|
||||
string keyClass = null, string valueClass = null)
|
||||
{
|
||||
var row = new VisualElement { name = name };
|
||||
row.AddToClassList("terminal-stat-row");
|
||||
AddClasses(row, rowClass);
|
||||
var keyLabel = new Label(key) { name = name == null ? null : name + "Key" };
|
||||
keyLabel.AddToClassList("terminal-stat-key");
|
||||
AddClasses(keyLabel, keyClass);
|
||||
var valueLabel = new Label(value) { name = name == null ? null : name + "Value" };
|
||||
valueLabel.AddToClassList("terminal-stat-value");
|
||||
AddClasses(valueLabel, valueClass);
|
||||
row.Add(keyLabel);
|
||||
row.Add(valueLabel);
|
||||
return row;
|
||||
}
|
||||
|
||||
public static Label BodyText(string text, string name = null, string className = null)
|
||||
{
|
||||
var label = new Label(text) { name = name };
|
||||
label.AddToClassList("terminal-body");
|
||||
AddClasses(label, className);
|
||||
return label;
|
||||
}
|
||||
|
||||
private static void AddClasses(VisualElement element, string classes)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(classes)) return;
|
||||
foreach (var className in classes.Split(' '))
|
||||
if (!string.IsNullOrEmpty(className)) element.AddToClassList(className);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 249e31573a794e2190b0a13e875114db
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b73ddac91da44a8fb6ba634517d01001
|
||||
@@ -0,0 +1,175 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using KernelPanic.Combat;
|
||||
using KernelPanic.Core;
|
||||
using KernelPanic.Data;
|
||||
using KernelPanic.Meta;
|
||||
using KernelPanic.Run;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace KernelPanic.UI
|
||||
{
|
||||
internal sealed class TutorialFlow : IDisposable
|
||||
{
|
||||
private readonly VisualElement _overlay;
|
||||
private readonly RunManager _run;
|
||||
private readonly CombatManager _combat;
|
||||
private readonly CardDatabase _cards;
|
||||
private readonly LanguageDeckDatabase _languages;
|
||||
private readonly SaveService _save;
|
||||
private readonly Action _returnToMenu;
|
||||
private TutorialSpotlight _spotlight;
|
||||
private Action _refresh;
|
||||
private int _lesson, _shopStep;
|
||||
private bool _leaving, _resuming;
|
||||
private string _renderKey, _error;
|
||||
public TutorialGuide Guide { get; private set; }
|
||||
public bool Reading => Guide.Reading;
|
||||
public int Lesson => _lesson;
|
||||
|
||||
public TutorialFlow(VisualElement overlay, RunManager run, CombatManager combat, CardDatabase cards,
|
||||
LanguageDeckDatabase languages, SaveService save, RunConfig config, Action returnToMenu)
|
||||
{
|
||||
_overlay = overlay; _run = run; _combat = combat; _cards = cards; _languages = languages;
|
||||
_save = save; _lesson = config.TutorialLesson; _returnToMenu = returnToMenu;
|
||||
_resuming = _lesson == 2;
|
||||
SetGuide(_lesson);
|
||||
}
|
||||
|
||||
public void SetRefresh(Action refresh) => _refresh = refresh;
|
||||
private void Redraw() { if (_refresh != null) _refresh(); else Refresh(); }
|
||||
private void SetGuide(int lesson)
|
||||
{
|
||||
_spotlight?.Dispose(); _spotlight = null;
|
||||
Guide = new TutorialGuide(lesson); _combat.TutorialGuide = Guide;
|
||||
_combat.TutorialReading = true; _renderKey = null;
|
||||
}
|
||||
public void ObserveCard(ResolutionTrack track) => Guide.CardPlayed(track);
|
||||
public void ObserveResolved(ResolutionTrack track) => Guide.CardResolved(track);
|
||||
public void ObservePhase(TurnPhase phase) => Guide.PhaseChanged(phase);
|
||||
public void UpdateState() { if (!_resuming) Guide.Update(_combat); }
|
||||
public void Review() => Redraw();
|
||||
public void AdvancePage() { if (_leaving || _resuming) return; Guide.Acknowledge(_combat); Redraw(); }
|
||||
|
||||
public void ResumeSecondWave()
|
||||
{
|
||||
if (!_resuming) return;
|
||||
_resuming = false;
|
||||
if (!_combat.ContinueTutorialWave()) throw new InvalidDataException("Training checkpoint is not a purchased first-wave shop.");
|
||||
}
|
||||
|
||||
public void Refresh()
|
||||
{
|
||||
if (_leaving || _resuming) return;
|
||||
UpdateState();
|
||||
if (Guide.Active && !_combat.RunFinished)
|
||||
{
|
||||
_overlay.RemoveFromClassList("tutorial-overlay");
|
||||
_spotlight ??= new TutorialSpotlight(_overlay, AdvancePage);
|
||||
_spotlight.Show(Guide, _combat);
|
||||
return;
|
||||
}
|
||||
_spotlight?.Dispose(); _spotlight = null;
|
||||
bool cleared = _combat.AwaitingWaveContinue, lost = _combat.RunFinished;
|
||||
if (!cleared && !lost)
|
||||
{
|
||||
_overlay.RemoveFromClassList("tutorial-overlay");
|
||||
_overlay.Clear(); _overlay.style.display = DisplayStyle.None; _renderKey = null;
|
||||
return;
|
||||
}
|
||||
if (cleared && _lesson == 1 && !_run.RepositoryVisitActive)
|
||||
_run.GenerateRepositoryOffers(_cards, _languages);
|
||||
bool purchased = _run.RepositoryOffers.Any(offer => offer.Sold);
|
||||
string key = $"{_lesson}:{cleared}:{lost}:{_shopStep}:{purchased}:{_error}";
|
||||
if (_renderKey == key) return;
|
||||
_renderKey = key;
|
||||
_overlay.Clear(); _overlay.AddToClassList("tutorial-overlay"); _overlay.style.display = DisplayStyle.Flex;
|
||||
var panel = TerminalLayout.Section(lost ? "Practice ended" : _lesson == 1 ? "Wave one cleared / repository" : "Training complete", "TutorialDialog");
|
||||
panel.AddToClassList("tutorial-dialog");
|
||||
var scroll = new ScrollView(ScrollViewMode.Vertical) { name = "TutorialCopy" };
|
||||
scroll.style.flexShrink = 1; scroll.style.minHeight = 0;
|
||||
scroll.horizontalScrollerVisibility = ScrollerVisibility.Hidden; panel.Add(scroll);
|
||||
Button action;
|
||||
if (lost)
|
||||
{
|
||||
scroll.Add(TerminalLayout.BodyText("Try again. Wave two restarts from your saved shop purchase; wave one restarts with full Uptime. Your collection is safe."));
|
||||
action = new Button(RestartLesson) { text = "Retry training", name = "TutorialRetry" };
|
||||
}
|
||||
else if (_lesson == 1)
|
||||
{
|
||||
var bits = TerminalLayout.Heading($"{_run.Bits} Bits available", "TutorialShopBits"); scroll.Add(bits);
|
||||
if (_shopStep == 0)
|
||||
{
|
||||
bits.AddToClassList("tutorial-shop-highlight");
|
||||
scroll.Add(TerminalLayout.BodyText("Every enemy is gone. Between waves, the repository is your shop. Spend Bits earned in combat to improve this run; Bits are separate from your permanent currencies."));
|
||||
action = new Button(() => { _shopStep = 1; Redraw(); }) { text = "Show an upgrade", name = "TutorialShopNext" };
|
||||
}
|
||||
else
|
||||
{
|
||||
// A real card patch keeps the five-card teaching hand intact for the scheduler lesson.
|
||||
var offer = _run.RepositoryOffers.FirstOrDefault(item => item.Kind == RepositoryOfferKind.CardUpgrade);
|
||||
if (offer == null) throw new InvalidOperationException("Training shop needs a card upgrade.");
|
||||
var item = new VisualElement(); item.AddToClassList("tutorial-shop-highlight"); scroll.Add(item);
|
||||
item.Add(TerminalLayout.Heading(offer.DisplayName));
|
||||
item.Add(TerminalLayout.BodyText(offer.Description));
|
||||
item.Add(TerminalLayout.BodyText($"Price: {offer.Price} Bits. This patch stays on the card for the rest of this run."));
|
||||
var buy = new Button(() => { _run.BuyOffer(offer, _combat.PlayerState); _renderKey = null; Redraw(); })
|
||||
{ text = purchased ? "Purchased" : $"Buy / {offer.Price} Bits", name = "TutorialBuy" };
|
||||
buy.SetEnabled(!purchased && _run.Bits >= offer.Price); item.Add(buy);
|
||||
scroll.Add(TerminalLayout.BodyText(purchased
|
||||
? "Upgrade installed. Your remaining Uptime, deck and purchase carry into wave two. Normal shops also sell new cards and stat upgrades."
|
||||
: "Buy this upgrade to practice spending Bits. Then start the next wave."));
|
||||
action = new Button(Continue) { text = "Start wave two", name = "TutorialContinue" };
|
||||
action.SetEnabled(purchased);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
scroll.Add(TerminalLayout.BodyText("Both waves are clear. You have completed the combat → shop → combat loop."));
|
||||
scroll.Add(TerminalLayout.Heading($"+{TutorialCampaign.BandwidthReward:N0} Bandwidth"));
|
||||
scroll.Add(TerminalLayout.Heading($"+{TutorialCampaign.EntropyReward:N0} Entropy"));
|
||||
scroll.Add(TerminalLayout.BodyText("Enough Entropy for one standard 10-pull. This training reward is granted once per profile."));
|
||||
action = new Button(Continue) { text = "Claim rewards & finish", name = "TutorialContinue" };
|
||||
}
|
||||
if (!string.IsNullOrEmpty(_error)) scroll.Add(TerminalLayout.BodyText("Could not save: " + _error + " Retry to continue.", "TutorialSaveError"));
|
||||
action.AddToClassList("primary-action"); panel.Add(action);
|
||||
panel.RegisterCallback<KeyDownEvent>(evt => evt.StopPropagation());
|
||||
TerminalTheme.ConstrainModalFocus(panel); _overlay.Add(panel);
|
||||
(panel.Q<Button>("TutorialBuy") is { enabledSelf: true } buyButton ? buyButton : action).Focus();
|
||||
}
|
||||
|
||||
public void Continue()
|
||||
{
|
||||
if (_leaving || Guide.Active || !_combat.AwaitingWaveContinue || _combat.RunFinished) return;
|
||||
if (_lesson == 1 && !_run.RepositoryOffers.Any(offer => offer.Sold)) return;
|
||||
if (_lesson == 2 && _run.WavesCleared < 2) return;
|
||||
try
|
||||
{
|
||||
var data = _save.Load();
|
||||
if (!TutorialCampaign.Required(data)) throw new InvalidOperationException("Training is not active.");
|
||||
if (_lesson == 1)
|
||||
{
|
||||
data.tutorialCheckpoint = _run.CaptureCheckpoint(_combat);
|
||||
data.tutorialLesson = 2;
|
||||
}
|
||||
else TutorialCampaign.Complete(data);
|
||||
_save.Save(data);
|
||||
_error = null;
|
||||
if (_lesson == 2) { _leaving = true; _returnToMenu(); return; }
|
||||
_lesson = 2; SetGuide(2);
|
||||
if (!_combat.ContinueTutorialWave()) throw new InvalidOperationException("Wave two could not start. Restart to resume the saved shop.");
|
||||
Redraw();
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is InvalidOperationException || ex is OverflowException)
|
||||
{ _error = ex.Message; _renderKey = null; Redraw(); }
|
||||
}
|
||||
|
||||
public void RestartLesson() { if (!_leaving) { _leaving = true; _returnToMenu(); } }
|
||||
public void Dispose()
|
||||
{
|
||||
_spotlight?.Dispose(); _spotlight = null;
|
||||
_combat.TutorialGuide = null; _combat.TutorialReading = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user