Home > front end >  Storing methods in a list
Storing methods in a list

Time:08-26

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?

CodePudding user response:

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

EDIT2: Use Stack data structure instead of LinkedList

interface IEffect
{
    void Resolve();
}

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

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

    public void Add(IEffect effect)
    {
        _effectStack.Push(effect);
    }

    public void ResolveAll()
    {
        while (_effectStack.Count)
        {
            _effectStack.Pop().Resolve();
        }
    }
}

class Client
{
    private EffectStack _effectStack = new();
    
    public void Run()
    {
        _effectStack.Add(new SomeEffect());
        
        _effectStack.ResolveAll();
    }
}

CodePudding user response:

I guess you can do that more easily.

As long is you just want to store method references in a collection in memory, there is no problem to do it. You just have to define the signature you want for those methods, and define a delegate for that.

Also if you want a collection designed to retrieve the elements from last to first, that's exactly what Stack do (LIFO = Last In, First Out).

Here is a simple exemple:

public class Card
{
  //...
}

public delegate void Effect(Card card);
Stack<Effect> EffectsStack; 

CodePudding user response:

You might want to checkout delegates, often used in the generic form of Action with different number of generic parameters. These can be collected in a list and called one at a time. There is also Multi-delegates that essentially is a list of delegates, with some special syntax to call all of them at once.

  • Related