279 lines
16 KiB
C#
279 lines
16 KiB
C#
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, Shield }
|
|
|
|
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;
|
|
if (HasOperation(previous.Definition, PythonOperation.Loop)) loops++;
|
|
else if (HasOperation(previous.Definition, PythonOperation.Zip)) areas++;
|
|
else if (IsPayload(previous.Definition))
|
|
{
|
|
if (loops > 0) loops--;
|
|
if (HasOperation(previous.Definition, PythonOperation.Print, PythonOperation.List) && areas > 0) areas--;
|
|
if (HasOperation(previous.Definition, PythonOperation.Print, PythonOperation.List, PythonOperation.Update)) damage = true;
|
|
}
|
|
}
|
|
return (loops > 0 ? 2 : 1, areas > 0 && HasOperation(card.Definition, PythonOperation.Print, PythonOperation.List), 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);
|
|
private static bool HasOperation(CardDefinition card, params PythonOperation[] operations) => IsPythonCard(card)
|
|
&& CardCatalog.TryGet(card.Id, out var entry)
|
|
&& entry.Effects.Any(effect => effect.Kind == CardEffectKind.Python && operations.Contains((PythonOperation)effect.SecondaryAmount));
|
|
public static bool IsPayload(CardDefinition card) => HasOperation(card,
|
|
PythonOperation.Print, PythonOperation.List, PythonOperation.Cinnamon, PythonOperation.Update, PythonOperation.Shield);
|
|
public static bool IsAsync(CardDefinition card) => HasOperation(card, PythonOperation.Async);
|
|
|
|
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 or PythonOperation.Shield)
|
|
{
|
|
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 is PythonOperation.Cinnamon or PythonOperation.Shield) 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)
|
|
{
|
|
string source = context.Card.Definition.DisplayName;
|
|
var cards = context.DeckController.PeekTop(InspectCount(_combat.RunConfig?.Distro?.Id, _combat.RunConfig?.DistroVersion ?? 1)).ToArray();
|
|
if (cards.Length == 0) { _combat.ReportEffectResult(source + ": draw pile empty"); return; }
|
|
if (!cards.Any(context.HandController.CanAdd)) { _combat.ReportEffectResult(source + ": not enough RAM"); return; }
|
|
Offer(source + ": 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;
|
|
});
|
|
}
|
|
}
|
|
}
|