Rebalance most languages and revamp main game loop

This commit is contained in:
2026-10-25 23:50:04 +01:00
parent 53f831d91e
commit a4109f5be0
76 changed files with 4198 additions and 573 deletions
+34 -22
View File
@@ -16,7 +16,7 @@ namespace KernelPanic.Combat
Cleanse, ShuffleToken, UpgradeHandCards, GenerateCard, NoOp, UpdateManager,
ShieldRepeatDamage, Timeshift, DnfAutoremove, FirstToPackage, Rawhide,
IncomingAttackHalve, ConsultWiki, RandomCommonLanguageCard, MinimalInstall, SizeofDamage,
RepairCorruptedCards, AskUbuntu
RepairCorruptedCards, AskUbuntu, FixedDraw, Python
}
/// <summary>
@@ -58,6 +58,8 @@ namespace KernelPanic.Combat
CardEffectKind.Damage => new DealDamageEffect(Amount, MaxAmount, Language, TrueDamage, CanCrit, AllEnemies),
CardEffectKind.Shield => new ShieldEffect(Amount),
CardEffectKind.Draw => new DrawEffect(Amount),
CardEffectKind.FixedDraw => new FixedDrawEffect(Amount),
CardEffectKind.Python => new PythonEffect((PythonOperation)SecondaryAmount, Amount),
CardEffectKind.AskUbuntu => new AskUbuntuEffect(),
CardEffectKind.ChanceDamage => new ChanceDamageEffect(Amount, SecondaryAmount, Language),
CardEffectKind.PreviousLanguageDamage => new PreviousLanguageDamageEffect(Amount, SecondaryAmount, Language),
@@ -126,6 +128,9 @@ namespace KernelPanic.Combat
/// Queue growth is resolved from the card without changing any combat state.
/// </summary>
public string GetRulesText(CardInstance card)
=> GetRulesText(card, null, 1);
public string GetRulesText(CardInstance card, string distroId, int distroVersion)
{
if (_rules == null)
{
@@ -133,7 +138,10 @@ namespace KernelPanic.Combat
? "effect not authored."
: card.Definition.Description + (card.UpgradeLevel > 0 ? " [upgraded]" : string.Empty);
}
string text = _rules;
int inspectCount = PythonPipeline.InspectCount(distroId, distroVersion);
int btwMultiplier = string.Equals(distroId, "arch", StringComparison.OrdinalIgnoreCase) && distroVersion >= 3 ? 4 : 3;
string text = _rules.Replace("{inspectCount}", inspectCount.ToString(CultureInfo.InvariantCulture))
.Replace("{btwMultiplier}", btwMultiplier.ToString(CultureInfo.InvariantCulture));
for (int i = 0; i < Effects.Count; i++)
{
CardEffectSpec effect = Effects[i];
@@ -148,6 +156,9 @@ namespace KernelPanic.Combat
text = Replace(text, "rawSecondary", i, effect.SecondaryAmount);
text = Replace(text, "failure", i, 100 - effect.SecondaryAmount);
text = Replace(text, "growth", i, UpgradeMath.ScaleAmount(effect.Amount + UnityEngine.Mathf.Max(0, (card?.QueuePlayCount ?? 0) - 1), card));
text = Replace(text, "listGrowth", i, CardScaling.Add(UpgradeMath.ScaleAmount(effect.Amount, card),
(int)Math.Min(int.MaxValue, 2L * Math.Max(0, (card?.QueuePlayCount ?? 0) - 1))));
text = Replace(text, "pythonBonus", i, UpgradeMath.ScaleAmount(5, card));
}
return text + (card?.UpgradeLevel > 0 ? " [upgraded]" : string.Empty);
}
@@ -168,7 +179,7 @@ namespace KernelPanic.Combat
private const CardTargeting Single = CardTargeting.SingleEnemy;
private const CardTargeting All = CardTargeting.AllEnemies;
private const string CRecoil = " 50% of overkill spills per jump (rounded down). 25%: segfault, uptime -3 and corrupt a hand card.";
private const string Jit = " overkill spills. JIT applies; discount decays by 1 after each wave.";
private const string Jit = " overkill spills. JIT: -1 Cycle per 2 Java plays, capped at -3; discount cools by 1 after each wave.";
private static readonly IReadOnlyDictionary<string, CardCatalogEntry> ById;
public static IReadOnlyList<CardCatalogEntry> Entries { get; }
@@ -200,30 +211,29 @@ namespace KernelPanic.Combat
Add("shop_hs_foldmap", All, false, "stack: deal {amount:0} to all living enemies.", Damage(4, Language.Haskell, all: true));
Add("shop_hs_deepseq", Single, false, "stack: deal {amount:0}.", Damage(9, Language.Haskell));
Add("shop_hs_dollar_bang", Single, false, "stack: deal {amount:0}. gain {shield:1} Shield.", Damage(5, Language.Haskell), Shield(2));
Add("lang_py_print", None, false, "queue: deal {amount:0}.", Damage(3, Language.Python));
Add("lang_py_import_antigravity", None, false, "queue: draw {amount:0}.", Draw(2));
Add("lang_py_for_loop", All, false, "queue: deal {amount:0} to all enemies.", Damage(2, Language.Python, all: true));
Add("lang_py_print", Single, false, "payload: deal {amount:0} to a chosen enemy.", Py(PythonOperation.Print, 4));
Add("lang_py_import_antigravity", None, false, "preparation: immediately draw 2 (fixed).", Py(PythonOperation.Draw, 2));
Add("lang_py_for_loop", None, false, "modifier: gain {shield:0} Shield. repeat the next payload once. unused repeat expires after next round.", Py(PythonOperation.Loop, 2));
Add("lang_js_console_log", Single, true, "deal {amount:0}-{max:0}.", Damage(3, Language.JavaScript, 9));
Add("lang_js_fetch", Single, true, "deal {amount:0}-{max:0}.", Damage(5, Language.JavaScript, 13));
Add("lang_rs_fn_main", Single, true, "deal {amount:0}. overkill becomes shield.", Damage(6, Language.Rust));
Add("lang_rs_unwrap", Single, true, "deal {amount:0}. overkill becomes shield. draw {amount:1}.", Damage(9, Language.Rust), Draw(1));
Add("lang_rs_unwrap", Single, true, "deal {amount:0}. overkill becomes shield. draw {raw:1} (fixed).", Damage(5, Language.Rust), Fx(CardEffectKind.FixedDraw, 1));
Add("lang_rs_borrow", None, false, "gain {shield:0} shield.", Shield(5));
Add("lang_c_malloc", Single, true, "deal {amount:0}." + CRecoil, Damage(12, Language.C));
Add("lang_c_printf", Single, true, "deal {amount:0}." + CRecoil + " then repair up to {amount:1} corrupted card{plural:1} in your active deck.",
Damage(7, Language.C), Fx(CardEffectKind.RepairCorruptedCards, 1));
Damage(4, Language.C), Fx(CardEffectKind.RepairCorruptedCards, 1));
Add("lang_c_pointer", Single, true, "deal {amount:0}; {secondary:0} if the previous card was C." + CRecoil,
Fx(CardEffectKind.PreviousLanguageDamage, 9, secondary: 15, language: Language.C));
Add("lang_java_public_static_main", Single, true, "uses 2 RAM. deal {amount:0}. overkill spills. JIT: Java cards cost 1 less this combat each time you play a Java card; discount decays by 1 after each wave.", Damage(7, Language.Java));
Add("lang_java_public_static_main", Single, true, "uses 2 RAM. deal {amount:0}." + Jit, Damage(7, Language.Java));
Add("lang_java_system_out_println", Single, true, "uses 2 RAM. deal {amount:0}." + Jit, Damage(5, Language.Java));
Add("lang_java_new_object", Single, true, "uses 2 RAM. deal {amount:0}." + Jit, Damage(3, Language.Java));
Add("ubuntu_ask_ubuntu", None, false, "queue: draw {amount:0}.", Fx(CardEffectKind.AskUbuntu, AskUbuntuEffect.BaseDrawCount));
Add("ubuntu_unattended_upgrades", None, false, "queue: gain {shield:0} shield now and next {rawSecondary:1} turns.",
Shield(4), Fx(CardEffectKind.UnattendedUpgrades, 4, secondary: 2));
Add("ubuntu_ask_ubuntu", None, false, "preparation: inspect the top {inspectCount} cards. take one; others keep their order.", Py(PythonOperation.Inspect));
Add("ubuntu_unattended_upgrades", None, false, "automation: gain {shield:0} Shield now and before the queue on each of the next 2 rounds. uses 1 of 2 script slots.", Py(PythonOperation.Unattended, 3));
Add("mint_fix_broken", Single, true, "deal {amount:0}. cleanse harmful statuses.", Damage(8, Language.JavaScript), Fx(CardEffectKind.Cleanse));
Add("lang_js_typeof", Single, true, "{rawSecondary:0}%: deal {amount:0}. {failure:0}%: deal 0.", Fx(CardEffectKind.ChanceDamage, 8, secondary: 75, language: Language.JavaScript));
Add("shop_py_list_append", Single, false, "queue: deal {growth:0}; +1 each time re-queued.", Fx(CardEffectKind.QueuedGrowthDamage, 4, language: Language.Python));
Add("shop_py_async_def", None, false, "queue: draw {amount:0}. gain {amount:1} cycle next turn.", Draw(2), Fx(CardEffectKind.NextTurnCycle, 1));
Add("shop_py_zip", None, false, "next {amount:0} queued cards resolve twice.", Fx(CardEffectKind.QueueRepeat, 2));
Add("lang_js_typeof", Single, true, "{rawSecondary:0}%: deal {amount:0}. {failure:0}%: deal 0.", Fx(CardEffectKind.ChanceDamage, 14, secondary: 75, language: Language.JavaScript));
Add("shop_py_list_append", Single, false, "payload: deal {listGrowth:0}. +2 per subsequent hand play this wave; replays do not grow it.", Py(PythonOperation.List, 6));
Add("shop_py_async_def", None, false, "automation: draw 1 immediately on play (fixed). capture the next payload without modifiers; replay it before the queue on each of the next 2 rounds. uses 1 of 2 script slots.", Py(PythonOperation.Async));
Add("shop_py_zip", Single, false, "modifier: deal {amount:0}. the next single-target damage payload hits all enemies. unused conversion expires after next round.", Py(PythonOperation.Zip, 2));
Add("shop_js_math_random", Single, true, "deal {amount:0}-{max:0}.", Damage(2, Language.JavaScript, 20));
CardEffectSpec promiseHit = Damage(4, Language.JavaScript, 10);
Add("shop_js_promise_all", Single, true, "deal {amount:0}-{max:0} three times.", promiseHit, promiseHit, promiseHit);
@@ -231,22 +241,22 @@ namespace KernelPanic.Combat
Add("ubuntu_snap_install", Single, true, "deal {amount:0}-{max:0}. shuffle an ubuntu pro trial into your draw pile.", Damage(6, Language.JavaScript, 14),
new CardEffectSpec(CardEffectKind.ShuffleToken, referenceId: "ubuntu_pro_trial"));
Add("ubuntu_do_release_upgrade", None, false, "upgrade {amount:0}-{max:0} random hand cards.", Fx(CardEffectKind.UpgradeHandCards, 1, 3));
Add("ubuntu_apt_install", None, false, "queue: generate a random common Python card at 0c.", Fx(CardEffectKind.GenerateCard, language: Language.Python));
Add("ubuntu_apt_install", None, false, "preparation: choose one of 3 Python cards. temporary copy costs 0 this turn and exhausts after play.", Py(PythonOperation.Install));
Add("ubuntu_pro_trial", None, false, null, new CardEffectSpec(CardEffectKind.NoOp, referenceId: "ubuntu pro trial is unplayable"));
// UpdateManager expands its own targets at execution, and historically asks for no target.
Add("mint_update_manager", None, false, "queue: deal {amount:0} to all enemies. repeats at the end of your next turn.", Fx(CardEffectKind.UpdateManager, 5, language: Language.Python, all: true));
Add("mint_cinnamon", None, false, "queue: gain {shield:0} shield. draw {amount:1}.", Shield(3), Draw(1));
Add("mint_update_manager", All, false, "payload: deal {amount:0} to all enemies; {pythonBonus:0} if an automation ran earlier this phase.", Py(PythonOperation.Update, 3, true));
Add("mint_cinnamon", None, false, "payload: gain {shield:0} Shield; {pythonBonus:0} if an earlier Python payload dealt damage this phase.", Py(PythonOperation.Cinnamon, 3));
Add("mint_nemo", Single, true, "deal {amount:0}. if you have shield, deal it again.", Fx(CardEffectKind.ShieldRepeatDamage, 6, language: Language.JavaScript));
Add("mint_timeshift", None, false, "queue: record uptime now. at end of your next turn, restore to it if lower.", Fx(CardEffectKind.Timeshift));
Add("mint_timeshift", None, false, "automation: save your Uptime when this resolves. after enemies act in each of the next 2 rounds, heal up to 6 Uptime, without exceeding the saved value. no healing this round or if defeated. healing does not scale with upgrades. uses 1 of 2 script slots until both rounds finish; ends when the wave ends.", Py(PythonOperation.Timeshift));
Add("fedora_dnf_autoremove", Single, true, "deal {amount:0}. exhaust a junk/NOP/broken card from hand; if you do, gain {secondary:0} cycle. if not, do nothing.", Fx(CardEffectKind.DnfAutoremove, 7, secondary: 1, language: Language.Rust));
Add("fedora_first_to_package", Single, true, "deal {amount:0}. Java cards cost 1 less this turn.", Fx(CardEffectKind.FirstToPackage, 7, language: Language.Java));
Add("fedora_dnf_update", Single, true, "deal {amount:0}. overkill spills. costs 1 less per Java card played this combat.", Damage(9, Language.Java));
Add("fedora_dnf_update", Single, true, "deal {amount:0}." + Jit, Damage(9, Language.Java));
Add("fedora_rawhide", None, false, "draw {amount:0}. next card this turn gains bleeding edge.", Fx(CardEffectKind.Rawhide, RawhideEffect.DrawCount));
Add("fedora_selinux", None, false, "next {amount:0} enemy attacks deal half damage.", Fx(CardEffectKind.IncomingAttackHalve, 2));
Add("arch_pacman_syu", Single, true, "deal {amount:0}." + CRecoil, Damage(14, Language.C));
Add("arch_consult_wiki", Single, true, "fix a broken card and draw {secondary:0}; if none, deal {amount:0}.",
Fx(CardEffectKind.ConsultWiki, ConsultWikiEffect.FallbackDamage, secondary: ConsultWikiEffect.DrawCount, language: Language.Rust));
Add("arch_makepkg", Single, true, "deal {amount:0} + btw x{rawSecondary:0}; x4 at Arch v3+." + CRecoil, Fx(CardEffectKind.BtwScaledDamage, 7, secondary: 3, language: Language.C));
Add("arch_makepkg", Single, true, "deal {amount:0} + btw x{btwMultiplier}." + CRecoil, Fx(CardEffectKind.BtwScaledDamage, 7, secondary: 3, language: Language.C));
Add("arch_aur_helper", None, false, "add a random C/Rust common card to hand; it costs 0 this turn.", Fx(CardEffectKind.RandomCommonLanguageCard));
Add("arch_minimal_install", None, false, "exhaust up to {raw:0} hand cards. per card: gain {rawSecondary:0} Shield and {rawMax:0} Cycle.",
Fx(CardEffectKind.MinimalInstall, MinimalInstallEffect.MaxExhaust, MinimalInstallEffect.CyclesPerCard, MinimalInstallEffect.ShieldPerCard));
@@ -275,6 +285,8 @@ namespace KernelPanic.Combat
=> new(CardEffectKind.Damage, amount, max, language: language, allEnemies: all, trueDamage: trueDamage);
private static CardEffectSpec Shield(int amount) => new(CardEffectKind.Shield, amount);
private static CardEffectSpec Draw(int amount) => new(CardEffectKind.Draw, amount);
private static CardEffectSpec Py(PythonOperation operation, int amount = 0, bool all = false) =>
new(CardEffectKind.Python, amount, secondaryAmount: (int)operation, language: Language.Python, allEnemies: all);
private static CardEffectSpec Fx(CardEffectKind kind, int amount = 0, int max = -1, int secondary = 0, Language language = default, bool all = false)
=> new(kind, amount, max, secondary, language, all);
}
+30 -1
View File
@@ -375,6 +375,28 @@ namespace KernelPanic.Combat
}
}
/// <summary>A fixed replacement draw; magnitude and source effect bonuses do not increase it.</summary>
public sealed class FixedDrawEffect : ICardEffect
{
private readonly int _count;
public FixedDrawEffect(int count)
{
_count = count;
}
public void Execute(CombatContext context)
{
int added = 0;
// Use the same ordered, RAM-aware draw operation as ordinary draw effects.
while (added < _count && context.DeckController.TryDrawToHand(context.HandController, out _))
added++;
string capped = added < _count && context.DeckController.AvailableToDrawCount > 0
? " (not enough RAM)" : string.Empty;
context.CombatManager.ReportEffectResult($"drew {added}{capped}");
}
}
public sealed class AskUbuntuEffect : ICardEffect
{
internal const int BaseDrawCount = 2;
@@ -892,6 +914,12 @@ namespace KernelPanic.Combat
}
public static string GetRulesText(CardInstance card)
=> GetRulesText(card, null, 1);
public static string GetRulesText(CardInstance card, KernelPanic.Run.RunConfig config)
=> GetRulesText(card, config?.Distro?.Id, config?.DistroVersion ?? 1);
public static string GetRulesText(CardInstance card, string distroId, int distroVersion)
{
if (card?.Definition == null)
{
@@ -910,7 +938,8 @@ namespace KernelPanic.Combat
if (CardCatalog.TryGet(card.Definition.Id, out CardCatalogEntry entry))
{
return entry.GetRulesText(card);
return entry.GetRulesText(card, distroId, distroVersion)
+ (card.ExhaustOnPlay ? " Temporary copy: exhaust after play." : string.Empty);
}
return string.IsNullOrWhiteSpace(card.Definition.Description)
+2
View File
@@ -25,6 +25,7 @@ namespace KernelPanic.Combat
public int PermanentCostDelta { get; private set; }
public int MagnitudeBonus { get; private set; }
public int DrawRider { get; private set; }
public bool ExhaustOnPlay { get; set; }
public int UpgradeLevel { get; private set; }
public int QueuePlayCount { get; private set; }
public bool WasFirstCardThisTurn { get; private set; }
@@ -157,6 +158,7 @@ namespace KernelPanic.Combat
IsBroken = IsBroken,
IsLocked = IsLocked
};
copy.ExhaustOnPlay = ExhaustOnPlay;
copy.PermanentCostDelta = PermanentCostDelta;
copy.MagnitudeBonus = MagnitudeBonus;
+30 -2
View File
@@ -68,6 +68,8 @@ namespace KernelPanic.Combat
int cardDamageFlat = CardScaling.Add(source.FlatCardDamageBonus,
prospective && deferred ? combat.PreviewNextDnfDamageStack() : 0);
bool allEnemies = entry.TargetsAllEnemies || entry.Effects.Any(effect => effect.AllEnemies);
var python = combat.Python.PreviewState(card);
if (PythonPipeline.IsPayload(card.Definition) && python.area) allEnemies = true;
var targets = PreviewTargets(combat, card, target, queued, allEnemies);
bool hasSelectedTarget = target != null || queued && card.TargetSnapshot.Any(t => t != null && !t.IsDefeated)
|| combat.SelectedEnemyIndex >= 0 && combat.SelectedEnemyIndex < combat.Enemies.Count;
@@ -79,7 +81,7 @@ namespace KernelPanic.Combat
result.IsConditional = true;
}
if (lazy != 100 || card.Definition.Language == Language.Haskell)
notes.Add($"Haskell {(lazyEntry == null ? "next stack" : "captured")}: x{lazy / 100m:0.0} damage and explicit Shield.");
notes.Add($"Haskell {(lazyEntry == null ? "next stack" : "captured")}: x{(lazy / 100m).ToString("0.0#", System.Globalization.CultureInfo.InvariantCulture)} damage and explicit Shield.");
if (combat.Compilation.Active)
notes.Add($"Compilation {combat.Compilation.Level}/{combat.Compilation.Maximum}: {combat.Compilation.DamagePercent}% damage, {combat.Compilation.ShieldPercent}% explicit Shield.");
if (magnitude > 0) notes.Add($"Card magnitude: +{magnitude}" + (growth > 0 ? $" (includes +{growth} non-crash growth)" : string.Empty) + ".");
@@ -116,6 +118,29 @@ namespace KernelPanic.Combat
int repeats = 1;
switch (effect.Kind)
{
case CardEffectKind.Python:
var operation = (PythonOperation)effect.SecondaryAmount;
AddNote(notes, CardEffectFactory.GetRulesText(card, combat.RunConfig));
if (operation is PythonOperation.Print or PythonOperation.List or PythonOperation.Update or PythonOperation.Zip)
{
damage = true;
low = high = effect.Amount;
if (operation == PythonOperation.List)
low = high = CardScaling.Add(effect.Amount, (int)Math.Min(int.MaxValue, 2L * Math.Max(0, card.QueuePlayCount + (prospective ? 1 : 0) - 1)));
if (operation == PythonOperation.Update && python.automation) low = high = 5;
if (operation != PythonOperation.Zip) repeats = python.repeats;
}
if (operation is PythonOperation.Loop or PythonOperation.Cinnamon or PythonOperation.Unattended)
{
int shieldBase = operation == PythonOperation.Cinnamon && python.damageBefore ? 5 : effect.Amount;
int shieldRepeats = operation == PythonOperation.Cinnamon ? python.repeats : 1;
hasShield = true;
int shieldValue = ScaledShield(shieldBase, sourceFlat, magnitude, lazy, combat);
for (int i = 0; i < shieldRepeats; i++) targetShield = CardScaling.Add(targetShield, shieldValue);
}
if (PythonPipeline.IsPayload(card.Definition))
AddNote(notes, $"Pipeline: {python.repeats} execution(s){(python.area ? ", all enemies" : "")}. Earlier payloads may change conditions; replays never repeat draw or installation.");
break;
case CardEffectKind.Damage:
damage = true;
break;
@@ -185,6 +210,9 @@ namespace KernelPanic.Combat
hasShield = true;
targetShield = CardScaling.Add(targetShield, ScaledShield(effect.Amount, sourceFlat, magnitude, lazy, combat));
break;
case CardEffectKind.FixedDraw:
AddNote(notes, $"Draw {effect.Amount} (fixed): magnitude and effect bonuses do not increase this draw; available RAM still limits it.");
break;
case CardEffectKind.HaskellMaybe:
if (source.CurrentUptime >= source.MaxUptime)
{
@@ -324,7 +352,7 @@ namespace KernelPanic.Combat
if (captured != null) return captured.MultiplierPercent;
if (card.Definition.ResolutionTrack != ResolutionTrack.LazyStack || card.Definition.Language != Language.Haskell) return 100;
int haskell = combat.LazyStack?.Entries.Count(item => item.Card.Definition?.Language == Language.Haskell) ?? 0;
return 100 + 50 * Math.Min(3, haskell);
return CombatTuning.HaskellStackMultiplierPercent(haskell);
}
private static IReadOnlyList<CombatantState> PreviewTargets(CombatManager combat, CardInstance card,
+42 -16
View File
@@ -87,6 +87,9 @@ namespace KernelPanic.Combat
private bool _evaluatingLazyStack;
private LazyStackEntry _activeLazyEntry;
public CompilationState Compilation { get; } = new();
public PythonPipeline Python { get; } = new();
public IReadOnlyList<CardDefinition> GeneratedCardPool => _generatedCardPool.AsReadOnly();
public void NotifyPythonChanged() => StateChanged?.Invoke();
public TurnPhase CurrentPhase => currentPhase;
public RunConfig RunConfig => _runConfig;
@@ -118,8 +121,10 @@ namespace KernelPanic.Combat
_selectedEnemyIndex = -1; _pendingTargetCard = null;
}
public int CurrentWaveNumber => _runManager == null ? 1 : _runManager.CurrentWaveNumber;
public int RoundNumber => _turnNumberThisWave;
public int ActiveKernelRamPenalty => _activeKernelRamPenalty;
public bool CanSurrenderRun => currentPhase == TurnPhase.Execute
&& !Python.HasChoice
&& !TutorialReading
&& !_waveTransitionActive
&& !_awaitingWaveContinue
@@ -135,6 +140,7 @@ namespace KernelPanic.Combat
private void Awake()
{
Python.Bind(this);
_runManager = GetComponent<RunManager>();
_damagePipeline.ResistanceResolver = ResolveDamageResistance;
_damagePipeline.PreviewResistanceResolver = ResolveDamageResistance;
@@ -208,6 +214,7 @@ namespace KernelPanic.Combat
public void RestoreBoundaryState(RunConfig config, CheckpointCombat snapshot)
{
Python.Clear();
RunCompleted = false;
_waveTransitionActive = false;
RunEndedBySurrender = false;
@@ -230,7 +237,7 @@ namespace KernelPanic.Combat
_fedoraCrashChance = snapshot.fedoraCrashChance;
_packageInterpreterQueueShieldTriggeredThisWave = snapshot.interpreterShieldUsed;
_packageNativeDamageTriggeredThisWave = snapshot.nativeDamageUsed;
_javaCardsPlayedThisCombat = snapshot.javaCardsPlayed;
_javaCardsPlayedThisCombat = Mathf.Clamp(snapshot.javaCardsPlayed, 0, CombatTuning.JavaMaximumWarmup);
_rawhideBonusCharges = snapshot.rawhideCharges;
_queuedRepeatCharges = snapshot.repeatCharges;
_nextTurnCycleBonus = snapshot.nextTurnCycles;
@@ -297,13 +304,15 @@ namespace KernelPanic.Combat
{
if (_runConfig?.IsTutorial == true) return;
if (!_awaitingWaveContinue || RunFinished || _waveTransitionActive
|| _runManager?.IsSuspended == true || _runManager?.CampaignChoicePending == true || _runManager?.BuildRewardPending == true)
|| _runManager?.IsSuspended == true || _runManager?.CampaignChoicePending == true || _runManager?.BuildRewardPending == true
|| _runManager?.RouteEventPending == true)
{
return;
}
_waveTransitionActive = true;
_runManager?.PrepareNextEncounter(_playerState);
if (_runManager?.RepositoryVisitActive == true) { _waveTransitionActive = false; return; }
_awaitingWaveContinue = false;
DecayJavaWarmupForNextWave();
StartCoroutine(ContinueToNextWaveSequenced());
@@ -452,7 +461,7 @@ namespace KernelPanic.Combat
_playerState.HasLastPlayedCardLanguage = true;
if (card.Definition.Language == Language.Java)
{
_javaCardsPlayedThisCombat++;
_javaCardsPlayedThisCombat = Mathf.Min(CombatTuning.JavaMaximumWarmup, _javaCardsPlayedThisCombat + 1);
}
GameEvents.RaiseCardPlayed(new CardPlayedEvent(card, track));
@@ -507,6 +516,7 @@ namespace KernelPanic.Combat
case ResolutionTrack.InterpreterQueue:
card.MarkQueued();
_interpreterQueue.Enqueue(card);
if (PythonPipeline.IsAsync(card.Definition)) new FixedDrawEffect(1).Execute(BuildContext(card, Array.Empty<CombatantState>()));
break;
case ResolutionTrack.LazyStack:
_lazyStack.Enqueue(card);
@@ -514,9 +524,12 @@ namespace KernelPanic.Combat
default:
GameEvents.RaiseCardResolving(new CardResolvedEvent(card, ResolutionTrack.Native));
ExecuteCardEffects(card, ResolveTargets(card));
ResolveCardRiders(card);
_deckController.Discard(card);
GameEvents.RaiseCardResolved(new CardResolvedEvent(card, ResolutionTrack.Native));
Python.AfterChoice(() =>
{
ResolveCardRiders(card);
_deckController.Discard(card);
GameEvents.RaiseCardResolved(new CardResolvedEvent(card, ResolutionTrack.Native));
});
_selectedEnemyIndex = -1;
break;
}
@@ -528,10 +541,12 @@ namespace KernelPanic.Combat
_cCardsPlayedThisTurn++;
}
ApplyPackageCardPlayedEffects(card);
_pendingTargetCard = null;
TryApplyUbuntuEmptyHandRefill();
Python.AfterChoice(() =>
{
ApplyPackageCardPlayedEffects(card);
TryApplyUbuntuEmptyHandRefill();
});
StateChanged?.Invoke();
return true;
}
@@ -551,7 +566,7 @@ namespace KernelPanic.Combat
int cost = GetCardCost(card);
if (card?.Definition != null && card.Definition.Language == Language.Java)
{
cost -= _javaCardsPlayedThisCombat + _javaCardsDiscountThisTurn;
cost -= CombatTuning.JavaWarmupDiscount(_javaCardsPlayedThisCombat) + _javaCardsDiscountThisTurn;
}
cost = ApplyPackageCostRules(card, cost);
@@ -604,7 +619,7 @@ namespace KernelPanic.Combat
int cost = GetCardCost(card);
if (card.Definition.Language == Language.Java)
{
int reduction = _javaCardsPlayedThisCombat + _javaCardsDiscountThisTurn;
int reduction = CombatTuning.JavaWarmupDiscount(_javaCardsPlayedThisCombat) + _javaCardsDiscountThisTurn;
if (reduction > 0) lines.Add($"Java warmup: -{reduction}");
cost -= reduction;
}
@@ -1290,13 +1305,18 @@ namespace KernelPanic.Combat
private IEnumerator InterpretQueueSequenced()
{
Python.BeginPhase(_turnNumberThisWave);
while (VisualResolutionPending && !_runLost && !_awaitingWaveContinue) yield return null;
if (CheckWinOrLoss()) yield break;
while (_interpreterQueue.TryDequeue(out CardInstance card))
{
LogPlayIntent(card);
int resolutionCount = ConsumeQueuedResolutionCount(card);
// Legacy repeat charges must never duplicate Python installation/preparation effects.
int resolutionCount = PythonPipeline.IsPythonCard(card.Definition) ? 1 : ConsumeQueuedResolutionCount(card);
for (int repeatIndex = 0; repeatIndex < resolutionCount; repeatIndex++)
{
ExecuteCardEffects(card, ResolveQueuedTargets(card));
while (Python.HasChoice && !_runLost && !_awaitingWaveContinue) yield return null;
if (CheckWinOrLoss())
{
yield break;
@@ -1373,6 +1393,7 @@ namespace KernelPanic.Combat
private void ClearDeferredCards()
{
Python.Clear();
foreach (var card in _lazyStack.Cards.Concat(_interpreterQueue.Cards).Distinct())
{
card.ClearTargetSnapshot();
@@ -1444,6 +1465,7 @@ namespace KernelPanic.Combat
return;
}
Python.EndRound();
ResolveDelayedEndOfTurnEffects();
if (CheckWinOrLoss())
{
@@ -1487,6 +1509,7 @@ namespace KernelPanic.Combat
private IEnumerator DrawCardsToHandSequenced(int requestedCount, string label)
{
while (Python.HasChoice) yield return null;
if (_handController == null || _playerState == null || requestedCount <= 0)
{
yield break;
@@ -1506,6 +1529,7 @@ namespace KernelPanic.Combat
int added = 0;
for (int i = 0; i < drawn.Count; i++)
{
while (Python.HasChoice) yield return null;
if (!_handController.Add(drawn[i]))
{
blockedByRam = true;
@@ -1632,8 +1656,9 @@ namespace KernelPanic.Combat
return;
}
_javaCardsPlayedThisCombat = Mathf.Max(0, _javaCardsPlayedThisCombat - 1);
Log($"Java JIT cooled: discount now -{_javaCardsPlayedThisCombat}");
_javaCardsPlayedThisCombat = Mathf.Max(0,
Mathf.Min(CombatTuning.JavaMaximumWarmup, _javaCardsPlayedThisCombat) - CombatTuning.JavaPlaysPerDiscount);
Log($"Java JIT cooled: discount now -{CombatTuning.JavaWarmupDiscount(_javaCardsPlayedThisCombat)}");
}
private bool CanApplyFedoraPassiveBonus()
@@ -2848,7 +2873,8 @@ namespace KernelPanic.Combat
{
EnemyArchetypeDescriptor archetype = EnemyArchetypeCatalog.Get(archetypeId);
int baseUptime = RandomRoll.RollRange(archetype.BaseUptimeMin, archetype.BaseUptimeMax, RollContext.None);
if (_runConfig?.IsTutorial == true && CurrentWaveNumber == 1 && archetypeId == "zombie_process") baseUptime = 6;
// The guided first hit must kill even when the starter unwrap() does not crit.
if (_runConfig?.IsTutorial == true && CurrentWaveNumber == 1 && archetypeId == "zombie_process") baseUptime = 5;
EnemyInstance enemy = new(archetype, baseUptime + Mathf.Max(0, uptimeBonus));
_enemies.Add(enemy);
return enemy;
@@ -3286,7 +3312,7 @@ namespace KernelPanic.Combat
|| _enemyExitAwaitingVisual != null
|| _deathSpawnSequencesActive > 0;
private bool IsCombatPaused => _awaitingWaveContinue || _waveTransitionActive || RunFinished || VisualResolutionPending;
private bool IsCombatPaused => Python.HasChoice || _awaitingWaveContinue || _waveTransitionActive || RunFinished || VisualResolutionPending;
private enum DelayedCombatEffectKind
{
+9
View File
@@ -13,6 +13,15 @@ namespace KernelPanic.Combat
public const int CCriticalChancePercent = 35;
public const int COverkillSpillPercent = 50;
public const int OrphanSpawnChancePercent = 25;
public const int JavaPlaysPerDiscount = 2;
public const int JavaMaximumWarmup = 6;
public static int JavaWarmupDiscount(int plays) =>
System.Math.Clamp(plays, 0, JavaMaximumWarmup) / JavaPlaysPerDiscount;
// Lift small stacks while preserving the third position and the x2.5 ceiling.
public static int HaskellStackMultiplierPercent(int pendingHaskellCards) =>
pendingHaskellCards <= 0 ? 150 : pendingHaskellCards == 1 ? 175 : pendingHaskellCards == 2 ? 200 : 250;
public const int BaseEnemyUptimeMin = 5;
public const int BaseEnemyUptimeMax = 10;
+14
View File
@@ -186,10 +186,24 @@ namespace KernelPanic.Combat
{
if (card != null)
{
if (card.ExhaustOnPlay) { Exhaust(card); return; }
_discardPile.Add(card);
}
}
public IReadOnlyList<CardInstance> PeekTop(int count)
{
if (_drawPile.Count == 0) ReshuffleDiscardIntoDraw();
return _drawPile.AsEnumerable().Reverse().Take(System.Math.Max(0, count)).ToArray();
}
public bool TakeToHand(CardInstance card, HandController hand)
{
if (!_drawPile.Contains(card) || hand == null || !hand.Add(card)) return false;
_drawPile.Remove(card);
return true;
}
public void AddToDrawPile(CardInstance card, bool shuffle)
{
if (card == null)
+46 -2
View File
@@ -22,6 +22,7 @@ namespace KernelPanic.Combat
// A stable integer mixer, independent of both gameplay random streams and runtime hash codes.
public static EncounterPlan Plan(int wave, WaveRoute route, int seed, int revision)
{
if (revision >= 2) return CampaignPlan(wave, route, seed);
if (revision == 0) return Plan(wave, route);
uint hash = unchecked((uint)seed ^ ((uint)wave * 0x9E3779B9u));
hash ^= hash >> 16; hash = unchecked(hash * 0x7FEB352Du); hash ^= hash >> 15;
@@ -56,7 +57,7 @@ namespace KernelPanic.Combat
enemies = new[] { "race_condition", "race_condition", variant == 1 ? "firewalld" : "memory_leak" };
advice = "Race partners act in uncertain order; defeating one enrages the survivor. Choose between support and paired threats.";
break;
case RunJourney.BossWave:
case RunJourney.LegacyBossWave:
title = variant == 1 ? "Kernel Overseer / scheduled interrupt" : "Kernel Overseer / memory pressure";
enemies = new[] { "kernel_overseer", variant == 1 ? "cron_job" : "memory_leak" };
advice = baseline.Advice;
@@ -99,7 +100,7 @@ namespace KernelPanic.Combat
title = "Concurrency fault";
advice = "Race partners attack in uncertain order; killing one enrages the survivor. Segfault has a death payload.";
enemies = new[] { "race_condition", "race_condition", "segfault" }; break;
case RunJourney.BossWave:
case RunJourney.LegacyBossWave:
title = "Kernel Overseer";
advice = "Boss cycle: shield, probe, heavy interrupt. At half uptime its NEXT announced attacks become stronger.";
enemies = new[] { "kernel_overseer", "firewalld" }; break;
@@ -123,5 +124,48 @@ namespace KernelPanic.Combat
}
return new EncounterPlan(title, advice, Math.Max(0, wave - 1) * CombatTuning.EnemyUptimeGrowthPerWave, enemies);
}
private static EncounterPlan CampaignPlan(int wave, WaveRoute route, int seed)
{
// Keep introductory encounters familiar; introduce the heavier systems before the final boss.
int legacyStage = wave <= 4 ? wave : wave == RunJourney.BossWave ? RunJourney.LegacyBossWave
: wave > RunJourney.BossWave ? wave - 5 : 3;
var baseline = Plan(legacyStage, route, seed, 1);
string title = baseline.Title, advice = baseline.Advice;
var enemies = new List<string>(baseline.Enemies);
string support = unchecked((uint)seed + (uint)wave) % 2 == 0 ? "firewalld" : "cron_job";
switch (wave)
{
case 5:
title = "Privilege escalation";
advice = "Rootkit resists damage while allies remain. Remove its support first.";
enemies = new() { "rootkit", "zombie_process", support }; break;
case 6:
title = "Telemetry breach";
advice = "Telemetry Collector interferes with your resources. Contain the growing Memory Leak.";
enemies = new() { "telemetry_collector", "memory_leak", support }; break;
case 7:
title = "Protected subsystem";
advice = "DRM Guardian protects the subsystem. Plan your damage around its defenses.";
enemies = new() { "drm_guardian", "segfault", support }; break;
case 8:
title = "Critical concurrency";
advice = "Race partners act in uncertain order; defeating one enrages the survivor. Remove their support deliberately.";
enemies = new() { "race_condition", "race_condition", support }; break;
case 9:
title = "Kernel perimeter";
advice = "Kernel Panic pressures your RAM. Clear this last perimeter before the Overseer.";
enemies = new() { "kernel_panic", "daemon", support }; break;
}
if (wave >= 5 && wave < RunJourney.BossWave && route == WaveRoute.Challenge)
{
enemies.Add("daemon"); title += " / challenge";
advice += baseline.EscortShield > 0 ? " Extra Daemon: 6 starting Shield, hidden intent."
: baseline.EscortUptime > 0 ? " Extra Daemon: +4 Uptime, hidden intent." : " Extra Daemon: hidden intent.";
}
if (wave > RunJourney.BossWave) title = "Survival / " + wave;
return new EncounterPlan(title, advice, Math.Max(0, wave - 1) * CombatTuning.EnemyUptimeGrowthPerWave, enemies.ToArray())
{ EscortShield = baseline.EscortShield, EscortUptime = baseline.EscortUptime };
}
}
}
+4 -2
View File
@@ -10,13 +10,15 @@ namespace KernelPanic.Combat
{
var lines = new List<string>();
if (combat?.PlayerState == null) return lines;
lines.Add("Native cards already executed. End turn resolves Python FIFO, then Haskell LIFO, then surviving enemies, then cleanup.");
lines.Add("Native cards and Python preparation already executed. End turn runs ready Python automation, then Python FIFO, Haskell LIFO, surviving enemies, and cleanup.");
if (combat.Python.AutomationCount > 0 || combat.Python.RepeatCount > 0 || combat.Python.AreaCount > 0)
foreach (string script in combat.Python.Readout) lines.Add(script);
int order = 0;
foreach (var card in combat.InterpreterQueue.Cards)
lines.Add(CardLine(combat, card, ++order, "FIFO", card.TargetSnapshot));
foreach (var entry in combat.LazyStack.Entries)
lines.Add(CardLine(combat, entry.Card, ++order, "LIFO " + entry.MultiplierLabel, entry.Targets));
if (order == 0) lines.Add("No deferred cards: surviving enemies act next.");
if (order == 0) lines.Add("No deferred cards: ready automation runs before surviving enemies act.");
lines.Add("ENEMIES / current announced intents (after deferred cards; each enemy's start-of-turn status ticks before its action)");
foreach (var enemy in combat.Enemies)
{
+2 -2
View File
@@ -11,7 +11,7 @@ namespace KernelPanic.Combat
public CardInstance Card { get; }
public int MultiplierPercent { get; }
public IReadOnlyList<CombatantState> Targets { get; }
public string MultiplierLabel => $"x{MultiplierPercent / 100}.{MultiplierPercent % 100 / 10}";
public string MultiplierLabel => "x" + (MultiplierPercent / 100m).ToString("0.0#", System.Globalization.CultureInfo.InvariantCulture);
internal LazyStackEntry(CardInstance card, int multiplierPercent)
{
Card = card;
@@ -34,7 +34,7 @@ namespace KernelPanic.Combat
if (card == null || _cards.Contains(card)) return;
int multiplier = 100;
if (card.Definition != null && card.Definition.Language == Language.Haskell)
multiplier = 100 + 50 * Math.Min(3, _entries.Count(e => e.Card.Definition != null && e.Card.Definition.Language == Language.Haskell));
multiplier = CombatTuning.HaskellStackMultiplierPercent(_entries.Count(e => e.Card.Definition != null && e.Card.Definition.Language == Language.Haskell));
_entries.Insert(0, new LazyStackEntry(card, multiplier));
_cards.Insert(0, card);
}
+275
View File
@@ -0,0 +1,275 @@
using System;
using System.Collections.Generic;
using System.Linq;
using KernelPanic.Core;
using KernelPanic.Data;
namespace KernelPanic.Combat
{
public enum PythonOperation { Print, Loop, Draw, List, Zip, Async, Inspect, Install, Unattended, Cinnamon, Update, Timeshift }
public sealed class PythonEffect : ICardEffect
{
private readonly PythonOperation _operation;
private readonly int _amount;
public PythonEffect(PythonOperation operation, int amount) { _operation = operation; _amount = amount; }
public void Execute(CombatContext context) => context.CombatManager.Python.Execute(context, _operation, _amount);
}
public sealed class PythonChoiceOption
{
public string Label { get; }
public bool Enabled { get; }
public PythonChoiceOption(string label, bool enabled = true) { Label = label; Enabled = enabled; }
public CardInstance Card { get; }
public int Cost { get; }
public string ActionLabel { get; }
public PythonChoiceOption(CardInstance card, int cost, string actionLabel, bool enabled = true)
{
Card = card; Cost = cost; ActionLabel = actionLabel;
Label = card.Definition.DisplayName; Enabled = enabled;
}
}
/// <summary>Wave-local FIFO transformations, immutable payload snapshots and bounded background tasks.</summary>
public sealed class PythonPipeline
{
private sealed class Payload
{
public CardInstance Card;
public int Damage, Shield;
public bool All;
public CombatantState Target;
}
private sealed class Script
{
public string Name;
public CardInstance Owner;
public Payload Payload;
public bool Waiting, Restore;
public int FirstRound, Remaining = 2, Uptime, LastRunRound = -1;
}
private readonly List<int> _loops = new(), _areas = new();
private readonly List<Script> _scripts = new();
private readonly Dictionary<CardInstance, int> _temporaryDiscounts = new();
private Action<int> _choose;
private Action _afterChoice;
private CombatManager _combat;
private int _round;
public bool DamageThisPhase { get; private set; }
public bool AutomationRan { get; private set; }
public string ChoiceTitle { get; private set; }
public IReadOnlyList<PythonChoiceOption> Choices { get; private set; } = Array.Empty<PythonChoiceOption>();
public bool HasChoice => _choose != null;
public int AutomationCount => _scripts.Count;
public int RepeatCount => _loops.Count;
public int AreaCount => _areas.Count;
public (int repeats, bool area, bool damageBefore, bool automation) PreviewState(CardInstance card)
{
int round = _combat.RoundNumber;
int loops = _loops.Count(r => round <= r + 1), areas = _areas.Count(r => round <= r + 1);
var ready = _scripts.Where(s => !s.Waiting && !s.Restore && round >= s.FirstRound && round > s.LastRunRound).ToArray();
bool damage = (_round == round && DamageThisPhase) || ready.Any(s => s.Payload.Damage > 0);
bool automated = (_round == round && AutomationRan) || ready.Length > 0;
foreach (var previous in _combat.InterpreterQueue.Cards)
{
if (previous == card) break;
if (!IsPythonCard(previous.Definition)) continue;
string id = previous.Definition.Id;
if (id == "lang_py_for_loop") loops++;
else if (id == "shop_py_zip") areas++;
else if (IsPayload(previous.Definition))
{
if (loops > 0) loops--;
if (id is "lang_py_print" or "shop_py_list_append") { if (areas > 0) areas--; }
if (id != "mint_cinnamon") damage = true;
}
}
return (loops > 0 ? 2 : 1, areas > 0 && card.Definition.Id is "lang_py_print" or "shop_py_list_append", damage, automated);
}
public IEnumerable<string> Readout => new[] { $"Python: repeat {_loops.Count} | area {_areas.Count} | scripts {_scripts.Count}/2" }
.Concat(_scripts.Select(s => s.Waiting ? $"{s.Name}: waiting for payload"
: $"{s.Name}{(s.Name == "async def" ? " / " + s.Payload.Card.Definition.DisplayName : "")}: {s.Remaining} runs remaining"));
public void Bind(CombatManager combat) => _combat = combat;
public void Clear()
{
ExpireDiscounts();
_loops.Clear(); _areas.Clear(); _scripts.Clear(); _choose = null; _afterChoice = null;
Choices = Array.Empty<PythonChoiceOption>(); ChoiceTitle = null;
DamageThisPhase = AutomationRan = false; _round = 0;
}
private void ExpireDiscounts()
{
foreach (var entry in _temporaryDiscounts) entry.Key.TemporaryCostDelta = entry.Value;
_temporaryDiscounts.Clear();
}
public bool Choose(int index)
{
if (!HasChoice || index < 0 || index >= Choices.Count || !Choices[index].Enabled) return false;
var action = _choose;
var afterChoice = _afterChoice;
_afterChoice = null;
_choose = null; Choices = Array.Empty<PythonChoiceOption>(); ChoiceTitle = null;
action(index);
afterChoice?.Invoke();
_combat.NotifyPythonChanged();
return true;
}
public void AfterChoice(Action action)
{
if (HasChoice) _afterChoice += action;
else action();
}
private void Offer(string title, IEnumerable<PythonChoiceOption> options, Action<int> choose)
{
if (HasChoice) throw new InvalidOperationException("Resolve the current Python choice first.");
ChoiceTitle = title; Choices = Array.AsReadOnly(options.ToArray()); _choose = choose;
_combat.NotifyPythonChanged();
}
public static bool IsPythonCard(CardDefinition card) => card != null && card.Language == Language.Python
&& !card.Effects.Any(e => e != null) && CardCatalog.TryGet(card.Id, out var entry)
&& entry.Effects.Any(e => e.Kind == CardEffectKind.Python);
public static bool IsPayload(CardDefinition card) => IsPythonCard(card)
&& card.Id is "lang_py_print" or "shop_py_list_append" or "mint_cinnamon" or "mint_update_manager";
public static bool IsAsync(CardDefinition card) => IsPythonCard(card) && card.Id == "shop_py_async_def";
public static int InspectCount(string distroId, int version) =>
string.Equals(distroId, "ubuntu", StringComparison.OrdinalIgnoreCase) && version >= 3 ? 5 : 3;
public void BeginPhase(int round)
{
_round = round;
ExpireDiscounts();
_loops.RemoveAll(r => round > r + 1); _areas.RemoveAll(r => round > r + 1);
DamageThisPhase = AutomationRan = false;
foreach (var script in _scripts.ToArray())
{
if (script.Waiting || script.Restore || round < script.FirstRound || round <= script.LastRunRound) continue;
script.LastRunRound = round;
AutomationRan = true;
Run(script.Payload, script.Payload.All);
if (--script.Remaining == 0) _scripts.Remove(script);
if (_combat.RunFinished || _combat.AwaitingWaveContinue || _combat.PlayerState.IsDefeated) break;
}
}
public void EndRound()
{
if (_combat.PlayerState.IsDefeated || _combat.RunFinished || _combat.AwaitingWaveContinue) return;
foreach (var script in _scripts.ToArray())
{
if (!script.Restore || _round < script.FirstRound || _round <= script.LastRunRound) continue;
script.LastRunRound = _round;
if (_combat.CanPlayerReceiveCardHeal(script.Owner))
{
int heal = Math.Min(6, Math.Max(0, Math.Min(script.Uptime, _combat.PlayerState.MaxUptime) - _combat.PlayerState.CurrentUptime));
_combat.PlayerState.CurrentUptime += heal;
_combat.ReportEffectResult($"timeshift restored {heal} Uptime");
}
if (--script.Remaining == 0) _scripts.Remove(script);
}
}
private CombatContext Context(CardInstance card, CombatantState target = null) => new(card, _combat.PlayerState,
target == null ? Array.Empty<CombatantState>() : new[] { target }, _combat, _combat.DamagePipeline,
new StatusEffectController(), _combat.DeckController, _combat.HandController, _combat.Enemies);
public void Execute(CombatContext context, PythonOperation operation, int amount)
{
Bind(context.CombatManager);
if (operation is PythonOperation.Print or PythonOperation.List or PythonOperation.Cinnamon or PythonOperation.Update)
{
int value = amount;
if (operation == PythonOperation.List) value = CardScaling.Add(value, (int)Math.Min(int.MaxValue, 2L * Math.Max(0, context.Card.QueuePlayCount - 1)));
if (operation == PythonOperation.Cinnamon && DamageThisPhase) value = 5;
if (operation == PythonOperation.Update && AutomationRan) value = 5;
var payload = new Payload { Card = context.Card.CopyForCombat(), Target = context.Targets.FirstOrDefault(), All = operation == PythonOperation.Update };
if (operation == PythonOperation.Cinnamon) payload.Shield = CardShieldExecutor.ScaleAmount(value, context);
else payload.Damage = CardDamageExecutor.ScaleAmount(value, context);
// Capture the operation once, before applying any temporary repeat/area transformations.
foreach (var script in _scripts.Where(s => s.Waiting))
{ script.Payload = payload; script.Waiting = false; script.FirstRound = _round + 1; }
bool all = payload.All;
if (!all && payload.Damage > 0 && _areas.Count > 0) { all = true; _areas.RemoveAt(0); }
int repeats = 1;
if (_loops.Count > 0) { repeats = 2; _loops.RemoveAt(0); }
for (int i = 0; i < repeats; i++)
{
Run(payload, all);
if (_combat.RunFinished || _combat.AwaitingWaveContinue || context.Source.IsDefeated) break;
}
return;
}
switch (operation)
{
case PythonOperation.Loop:
CardShieldExecutor.Execute(context, CardShieldExecutor.ScaleAmount(amount, context), "for loop");
_loops.Add(_round); break;
case PythonOperation.Zip:
CardDamageExecutor.Execute(context, () => CardDamageExecutor.ScaleAmount(amount, context), Language.Python);
_areas.Add(_round); break;
case PythonOperation.Draw: new FixedDrawEffect(amount).Execute(context); break;
case PythonOperation.Inspect: Inspect(context); break;
case PythonOperation.Install: Install(context); break;
case PythonOperation.Async:
AddScript(new Script { Name = "async def", Owner = context.Card.CopyForCombat(), Waiting = true }); break;
case PythonOperation.Unattended:
int shield = CardShieldExecutor.ScaleAmount(amount, context);
CardShieldExecutor.Execute(context, shield, "unattended-upgrades");
AddScript(new Script { Name = "unattended-upgrades", Owner = context.Card.CopyForCombat(), FirstRound = _round + 1,
Payload = new Payload { Card = context.Card.CopyForCombat(), Shield = shield } }); break;
case PythonOperation.Timeshift:
AddScript(new Script { Name = "timeshift snapshot", Owner = context.Card.CopyForCombat(), Restore = true,
Uptime = context.Source.CurrentUptime, FirstRound = _round + 1 }); break;
}
}
private void Run(Payload payload, bool all)
{
var target = payload.Target;
if (target == null || target.IsDefeated)
target = _combat.Enemies.Where(e => !e.State.IsDefeated).OrderBy(e => e.State.CurrentUptime).Select(e => e.State).FirstOrDefault();
var context = Context(payload.Card, target);
var before = _combat.Enemies.Select(e => (state: e.State, health: (long)e.State.CurrentUptime + e.State.Shield)).ToArray();
if (payload.Damage > 0) CardDamageExecutor.Execute(context, () => payload.Damage, Language.Python, allEnemies: all);
if (before.Any(e => (long)e.state.CurrentUptime + e.state.Shield < e.health)) DamageThisPhase = true;
if (payload.Shield > 0 && !_combat.PlayerState.IsDefeated) CardShieldExecutor.Execute(context, payload.Shield, "Python payload");
}
private void AddScript(Script script)
{
if (_scripts.Count < 2) { _scripts.Add(script); return; }
var existing = _scripts.ToArray();
Offer($"Install {script.Name}: replace a script (2/2 slots)", existing.Select((s, slot) => new PythonChoiceOption($"Slot {slot + 1}: {s.Name}"
+ (s.Name == "async def" && !s.Waiting ? " / " + s.Payload.Card.Definition.DisplayName : "")
+ (s.Waiting ? " — waiting for payload" : $" — {s.Remaining} runs left"))), index =>
{ _scripts.Remove(existing[index]); _scripts.Add(script); });
}
private void Inspect(CombatContext context)
{
var cards = context.DeckController.PeekTop(InspectCount(_combat.RunConfig?.Distro?.Id, _combat.RunConfig?.DistroVersion ?? 1)).ToArray();
if (cards.Length == 0) { _combat.ReportEffectResult("ask ubuntu: draw pile empty"); return; }
if (!cards.Any(context.HandController.CanAdd)) { _combat.ReportEffectResult("ask ubuntu: not enough RAM"); return; }
Offer("ask ubuntu: choose one card; the others keep their order", cards.Select(c =>
new PythonChoiceOption(c, _combat.GetDisplayedPlayCost(c),
context.HandController.CanAdd(c) ? $"> take card / {HandController.GetRamCost(c)} RAM" : $"needs {HandController.GetRamCost(c)} free RAM",
context.HandController.CanAdd(c))),
index => context.DeckController.TakeToHand(cards[index], context.HandController));
}
private void Install(CombatContext context)
{
if (context.HandController.RemainingRam < 1) { _combat.ReportEffectResult("apt install: not enough RAM"); return; }
var pool = _combat.GeneratedCardPool.Where(c => IsPythonCard(c) && !c.DistroExclusive && !c.IsToken && !c.IsJunk)
.GroupBy(c => c.Id).Select(g => g.First()).OrderBy(c => c.Id, StringComparer.Ordinal).ToList();
var offers = new List<CardDefinition>();
while (offers.Count < 3 && pool.Count > 0)
{ int index = RandomRoll.RollRange(0, pool.Count - 1, RollContext.None); offers.Add(pool[index]); pool.RemoveAt(index); }
if (offers.Count == 0) { _combat.ReportEffectResult("apt install: no Python packages available"); return; }
Offer("apt install: choose a temporary card (0 Cycles this turn; exhausts after play)", offers.Select(c =>
new PythonChoiceOption(new CardInstance(c) { ExhaustOnPlay = true }, 0, "> install / 1 RAM")), index =>
{
var card = new CardInstance(offers[index]) { ExhaustOnPlay = true };
if (!context.HandController.Add(card)) return;
_temporaryDiscounts[card] = card.TemporaryCostDelta;
card.TemporaryCostDelta = -card.Definition.CycleCost;
});
}
}
}