using System; using System.Collections.Generic; using System.Linq; using KernelPanic.Core; namespace KernelPanic.Combat { /// Potential incoming damage and explicit Shield, never a prediction of RNG or kills. 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; } } /// /// 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. /// 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(); 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(); 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 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 HandAfterPlay(CombatManager combat, CardInstance card) => combat.HandController == null ? Enumerable.Empty() : 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 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; } } }