How would you program that [Global Effect] of card game?

Hi.
For example, at Magic the gathering card game, there are artifact and enchantment. It is sort of Global effect skills. And if some conditions are met, their effect being executed.

How program this?

Using event keyword and publisher & subscriber pattern?

I would have a singleton manager that has a dictionary of Trigger events (each event passes in the gameobject that triggered the event and return void) and an extra event that all cards and players subscribe to, the dictionary will store all the trigger types that could trigger a global ability(for example “OnCardCast” and “OnPlayerTurn”) . trigger events are specifically about the when, not the how.

CardAbilities (such as an enchament that “heals all players when any card is cast”, or an artifact that, “at the beginning of any turns, deal damage to all players and monsters, then heal the owner by 1 for each killed this way”) will listen to the relevent trigger events in the dictionary so they know when to activate their global effect. when a card with a CardAbilities is played (or if it can be triggered in hand) it will subscribe itself to the trigger dictionary and run its internal TriggerHandler script (like WhenSpellIsCast() and WhenOpponentsTurnBegins()) will when the trigger is called.

The second standalone event will pass in both an EffectCallback ( which is defined on the card with the cardTrigger ) and a “out EventStateObject” that all the listening cards in can populate and share with so that enchantment card can get return data all allocated in an singe object (since you can’t really use return on an event handler too effectively) the EffectCallback also expects a gameObject parameter. So each card will invoke the EffectCallback passing their gameObject and the EventStateObject as parameters. The EffectCallback will validate if the global effect applies to the gameObject, (like if gameObject.getComponent() != null) and if so applies the effect on them (player.Life++;) otherwise its returns and does nothing. The EffectCallback works on the Who and the how, but by keeping it all in the card’s class

the EventStateObject is just a simple empty class, but an artifact card can define a nested, class that inherits from EventStateObject like:

public class FeedOnTheWeak : EventStateObject
{
   public int monsterskilled;
}

and using polymorphism it still adheres to the global even definition set forth.
then the initial handler that was listening to the trigger dictionary can use that Feed on the Weak effect to then heal the player equal to the number of monsters that died.

this setup is mostly decoupled, every card must know about the Event manager, and CardTrigger Cards must know other component types (like Player, Card, Goblin, Red, Monster, etc…) thats relevent to their effects. However the setup is kept mostly abstract so that its easy to introduce new types of cards.

Most of the time such a complex system is not needed. But if this is a type of card that will commonly get new cards, than its important that you use decoupled systems to maintain developmental agility.

1 Like

@anon_90371718
Thanks for answer, its very good and promising, I want to implement, but a bit hard. And can’t understand 100% until I see the real code. Can you share the core mechanical code?
What the code of [Trigger events (each event passes in the gameobject that triggered the event and return void)] should be?

I can’t understand your second part, ‘Second Standalone event’ ? How implement?

and I don’t know well how use dictionary like your said.

So I wrote like this,

using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

[System.Serializable]
public abstract class Card
{
    public string name;
}

[System.Serializable]
public class Player
{
    public string name;
    public int hp;
}

public interface ITrigger
{
    bool ConditionMet();
}

public class OnCardCast : ITrigger
{
    public event EventHandler<CardEventArgs> onCard;

    public void OnCast(CardEventArgs e)
    {
        EventHandler< CardEventArgs> handler = onCard;
        if (handler != null && ConditionMet())
            handler(this, e);
    }

    public bool ConditionMet()
    {
        if (true) // if Card Casted,
        {
            Debug.Log("Card casted and condition are met!");
            return true;
        }
    }
   
}
public class OnPlayerTurn : ITrigger
{
    public bool ConditionMet ()
    {
        if (true) // if player turn,
        {
            Debug.Log("Player turn and condition are met!");
            return true;
        }
    }
}

public class GlobalCard : Card
{
    public GlobalCard(OnCardCast occ)
    {
        occ.onCard += Execute;
    }
    void Execute(object sender, CardEventArgs e)
    {
        Debug.Log(e.val+"This is global effect");
    }
}
public class GlobalEffectTest : MonoBehaviour
{
    public static GlobalEffectTest Instance;
    public Dictionary<ITrigger, string> TriggerDictionary = new Dictionary<ITrigger, string>();

    void Awake()
    {
        Instance = this;
    }
    void Start () {
        OnCardCast occ = new OnCardCast();
        GlobalCard gc = new GlobalCard(occ);
        CardEventArgs cardEvent = new CardEventArgs(3);
        occ.OnCast(cardEvent);
    }
  
    void Update () {
  
    }
}

public class CardEventArgs : EventArgs
{
    public int val;
    public CardEventArgs(int num)
    {
        val = num;
    }
}

Sorry for the delay. I’ve been too busy to give a proper answer to properly clarify.

I would first recommend watching the event messaging system live traning video. a large portion of my code is almost i direct copy. I like it since its easy to add new events in the future without even having to touch the event manager. also it can give you a better understanding of the dictionary.

below if just a rough draft of the event system I’m talking about. I actually spent more time trying to think of better names than job, task and action than I did typing it out.

using UnityEngine;
using UnityEngine.Events;
using System.Collections;
using System.Collections.Generic;

public abstract class EventStateData{}
public delegate void Job<GameObject, EventStateData>(GameObject go,out EventStateData eventstateData);

public delegate void GlobalEffect<EventStateData, GlobalEffectCallback>(out EventStateData eventstateData,Job<GameObject, EventStateData> job);
public class EventManager : MonoBehaviour
{
    public class GlobalEffect: UnityEvent<EventStateData,Job<GameObject, EventStateData>>{}
    public class Trigger: UnityEvent<GameObject>{}


    private Dictionary <string, Trigger> triggers;
    private GlobalEffect globalEffect;

    private static EventManager eventManager;

    public static EventManager instance
    {
        get
        {
            if (!eventManager)
            {
                eventManager = FindObjectOfType (typeof (EventManager)) as EventManager;

                if (!eventManager)
                {
                    Debug.LogError ("There needs to be one active EventManger script on a GameObject in your scene.");
                }
                else
                {
                    eventManager.Init ();
                }
            }

            return eventManager;
        }
    }

    void Init ()
    {
        if (triggers == null)
        {
            triggers = new Dictionary<string, UnityEvent>();
        }
    }

    void OnDestroy()
    {
        for (int i = triggers.Count - 1; i >= 0; i--)
        {
            triggers [i].RemoveAllListeners ();
        }
        triggers.Clear ();

        globalEffect = null;

    }

    public static void AddToEffects(GlobalEffect<EventStateData, Job<GameObject, EventStateData>> action)
    {
        instance.globalEffect += action;
    }

    public static void RemoveFromEffects(GlobalEffect<EventStateData, Job<GameObject, EventStateData>> action)
    {
        instance.globalEffect -= action;
    }

    public static void InvokeGlobalEffect(out EventStateData stateData, Job<GameObject, EventStateData> job)
    {
        if (instance.globalEffect != null)
        {
            instance.globalEffect(out stateData, callback);  
        }
    }


    public static void StartListening (string eventName, UnityAction listener)
    {
        Trigger thisEvent = null;
        if (instance.triggers.TryGetValue (eventName, out thisEvent))
        {
            thisEvent.AddListener (listener);
        }
        else
        {
            thisEvent = new UnityEvent ();
            thisEvent.AddListener (listener);
            instance.triggers.Add (eventName, thisEvent);
        }
    }

    public static void StopListening (string eventName, UnityAction listener)
    {
        if (eventManager == null) return;
        Trigger thisEvent = null;
        if (instance.triggers.TryGetValue (eventName, out thisEvent))
        {
            thisEvent.RemoveListener (listener);
        }
    }

    public static void Trigger (string eventName,GameObject source)
    {
        Trigger thisEvent = null;
        if (instance.triggers.TryGetValue (eventName, out thisEvent))
        {
            thisEvent.Invoke (source);
        }
    }
}

public sealed class Card: MonoBehaviour
{
    public CardProperties properties { get; set; }

    void OnEnable()
    {
        properties = GetComponent<CardProperties>();
        EventManager.AddToEffects (Participate);

        EventManager.Trigger ("OnCardEnabled");
    }
    void OnDisable()
    {
        EventManager.RemoveFromEffects (Participate);
    }

    public void Cast()
    {
            //validate that you can cast card, ten cast it

            EventManager.Trigger ("OnCardCast", gameObject);
    }

    void Participate(out EventStateData eventstateData,GlobalEffectCallback<GameObject, EventStateData> job)
    {
        job(gameObject,out eventstateData);
    }
}

// when a black card is cast, Card Owner gains life equal to black cards in play
public sealed class BlackChaliceEnchanment:MonoBehaviour
{
    public CardProperties properties { get; set; }
    public class EnchantmentData:EventStateData
    {
        public int BlackCardsInPlay;
    }

    void OnEnable()
    {
        properties = GetComponent<CardProperties>();
        EventManager.StartListening ("OnCardCast", WhenACardIsCast);
    }

    void OnDisable()
    {
        EventManager.StopListening ("OnCardCast", WhenACardIsCast);
    }

    void WhenACardIsCast(GameObject source)
    {
        if (source.GetComponent<BlackCard> () == null)
        {
            return; //source is not a black card enchantment doesn't trigger
        }

        EnchantmentData data = new EnchantmentData ();
        data.BlackCardsInPlay = 0;

        EventManager.InvokeGlobalEffect(out data,GlobalEffect);
        properties.currentOwner.Life += data.BlackCardsInPlay;

    }

    void GlobalEffect(GameObject gameObject,out EventStateData eventstateData)
    {
        BlackCard blackCard = gameObject.GetComponent<BlackCard> ();

        if (blackCard == null)
            return;

        if (blackCard.properties.IsInPlay)
        {
            EnchantmentData data = eventstateData as EnchantmentData;
            data.BlackCardsInPlay++;
        }
    }
}

Similar to my code, and since I know how Trading cards can get… I would try to make your classes SUPER modular so if a card is a black card, then the game object should have a BlackCard component script and a Card component script. the Enchantment card in my example would have a Card Component, a BlackChaliceEnchantment Component, a Enchantment Component, and maybe a BlackCard Component as well . Looking for a card that is either Red or Black? well you may invent a card that is both Red and Black (the card will have both components) and so it should pop up for the current set of cards, last season’s cards, and possibly any future cards.

These classes may also benefit by not holding any state (immutible), or as best as possible, and instead reference a single script that will store the state (CardProperties) which all the components can share with which will also reduce inconsistent data (bug example: one component may say the card is tapped, another says its not). it also abstracts the data from the components which will make adding a feature or fixing a bug only require you to change 1-2 files instead of 10-20, even 100-200 depending on how many card types you can think up.

@anon_90371718
Very thanks for answer, I just saw and copied above script to newly made unity empty project, made script name as ‘EventManager’ and copied your first part script, but occurs many errors. Anyway I would look into more.

So I revised error part and made it worked.
Though I dont know well why it needed to use out keyword and eventstatedata, and job syntax. Just I want to understand thoroughly.

Since you’re raising an event you can’t simply use a return to get data from every object that participated. event handlers typically return void. if it didn’t you would get bum rushed by possibly hundreds of different objects each trying to force their results down your throat and into a single value. So instead you craft a Memento object (from the memento design pattern) and give that to all the listeners. the memento is a single object which all the listeners will share and accumulate their data into. and when the event is done you’ll already have a reference to that same memento instance that you gave to everyone.

Think of it like a donation basket at mass. You hand it off and let it get passed around and when its done you get all the stuff you want consolidated into a single container. The beauty of the memento pattern is how you’re able to iterate over cards that have no idea how the enchantment works. from their point of view they just run a function inserting themselves into the handler function and let the handler worry about what it needs.

This decouples your cards form other cards. So if you make new cards, cardA only worries about its own special rules and uses Participate () so that cardB can enact its own rules on the cardA without cardA needing to know or even care what those new rules are. This makes adding new rules pretty easy as now you don’t need to touch the code in the Card class which might break another enchantment (which brings up the importance that you start up unit testing early so that a broken card doesn’t sneak into the build without your notice)

The job syntax is just defining a special type of function reference, a datatype. At the top I claim that there is a delegate, which I call “Job” and any function that the Job delegate will point to must have these parameters X (the GameObject and the EventStateData) and must return this type Y (void). so you can describe an abstract function to call which you can swap out concrete functions in real-time in one turn you may have an artifact that wants everyone to run it’s global effect, and in another turn an enchanment card wants to apply its effect. if you look at the Black Chalice example i’m bascially saying that if an “OnCardCast” event triggers and the source is a black card. than I give the eventManager my GlobalEffect function (notice that it has the same parameters and return type as the Job delegate) and I tell the EventManager to command everyone listening to participate in running the passed function.

Edit: I realized I answered why I used the “out” word, not what it is. Normally a function only passes data back through a return. however sometimes that is not enough. Physics.RayCast is a good example of this. it returns a true/false determining wheter it hit anything or not, but the raycast also needs to somehow pass the RayCastHit info back to the caller so that they know what to do with it. the out keyword means that I’m giving the function a reference to an object that I want them to affect, and when the function is done that object will have its data worked on and in the variable the I passed into the out parameter.

there is another reserved that’s very similar to the “out” word,“ref”. the only difference between out and ref is that the out version must be instantiated before its call, while ref must not.