Storing methods in a list

I am creating a card game similar to Magic: the Gathering where there is a stack system for effects to resolve. E.g. I cast draw a card and my opponent can respond with his own draw effect. Then the last effect that entered the stack will trigger and so on until all effects in the stack resolve. I thought the best way to handle this would to have a list store effects as methods and then have a new method resolve and remove them from last to first. Is this possible or am I going about this the wrong way?

>Solution :

I would not store the actual methods but rather objects.

For instance you could make an interface IAction with the function Run.

Then create a class for each action implementing IAction.

Then where you maintain the MTG equivalent of the ‘stack’ you have an IEnumerable<IAction> to which you add the instances.

Does this make sense?

EDIT: I wrote a bit of code to illustrate the idea

interface IEffect
{
    void Resolve();
}

class SomeEffect : IEffect
{
    public void Resolve()
    {
        // do something
    }
}

class EffectStack
{
    private LinkedList<IEffect> _effectStack = new LinkedList<IEffect>();

    public void AddToStack(IEffect effect)
    {
        _effectStack.AddLast(effect);
    }

    public bool IsEmpty()
    {
        return !_effectStack.Any();
    }

    public void ResolveLast()
    {
        _effectStack.Last.Resolve();
        _effectStack.RemoveLast();
    }
}

class Client
{
    private EffectStack _effectStack = new();
    
    public void Run()
    {
        while (!_effectStack.IsEmpty())
        {
            _effectStack.ResolveLast();
        }
    }
}

Leave a Reply