Files
linuxdistro-roguelite/Assets/Scripts/Combat/GoroutineScheduler.cs
T

70 lines
3.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using KernelPanic.Core;
namespace KernelPanic.Combat
{
public sealed class Goroutine
{
public long Id { get; internal set; }
public CardInstance SourceCard { get; internal set; }
public string SourceInstanceId => SourceCard.InstanceId;
public int BaseDamage { get; internal set; }
public CombatantState Target { get; internal set; }
public int RemainingTicks { get; internal set; }
public int DeploymentRound { get; internal set; }
public int LastTickRound { get; internal set; }
public bool Active { get; internal set; }
public bool Resolving { get; internal set; }
}
/// <summary>Bounded persistent work, advanced only by the authoritative Interpret phase.</summary>
public sealed class GoroutineScheduler
{
public const int Capacity = 3, MaximumTicks = 5;
private readonly List<Goroutine> _active = new();
private long _nextId;
public IReadOnlyList<Goroutine> Active => _active.AsReadOnly();
public int Count => _active.Count;
public bool HasCapacity => Count < Capacity;
public event Action<Goroutine> Terminated;
public Goroutine Deploy(CardInstance card, int damage, int ticks, int round, CombatantState target)
{
if (card == null || !HasCapacity || ticks <= 0 || _active.Any(g => g.SourceCard == card)) return null;
var work = new Goroutine { Id = checked(++_nextId), SourceCard = card,
BaseDamage = CardScaling.Add(Math.Max(0, damage), card.MagnitudeBonus),
Target = target, RemainingTicks = Math.Min(MaximumTicks, ticks), DeploymentRound = round,
LastTickRound = round, Active = true };
_active.Add(work);
return work;
}
public bool CanExtend(Goroutine work) => work != null && _active.Contains(work) && work.RemainingTicks < MaximumTicks;
public bool Extend(Goroutine work, int ticks)
{
if (!CanExtend(work) || ticks <= 0) return false;
work.RemainingTicks = (int)Math.Min(MaximumTicks, (long)work.RemainingTicks + ticks);
return true;
}
public bool Terminate(Goroutine work)
{
if (work == null || !_active.Remove(work)) return false;
work.Active = false; work.Resolving = false; work.Target = null;
Terminated?.Invoke(work); return true;
}
public bool Tick(Goroutine work, int round, Action<Goroutine> resolve)
{
if (work == null || !_active.Contains(work) || work.DeploymentRound >= round || work.LastTickRound >= round) return false;
work.LastTickRound = round; work.Resolving = true;
try { resolve(work); }
finally
{
work.Resolving = false;
if (work.Active && --work.RemainingTicks <= 0) Terminate(work);
}
return true;
}
public void Clear() { foreach (var work in _active.ToArray()) Terminate(work); }
}
}