Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading