Message System

Post those lines of code you feel like sharing or find what you require for your project here; or simply use them as tutorials.
Post Reply
sudi
Posts: 1686
Joined: Fri Aug 26, 2005 8:38 pm

Message System

Post by sudi »

I guess u all already had problems when it came to distributing messages to different Entities in your. one way is just adding the receive method to the base class and then implementing it down the way. actually this approach is pretty much the same just templated which gives you full control.

MessageDispatcher.h
lets say you have an Entity base class that all your entities enherit from.

Code: Select all

class Entitiy
{
public:
        virtual ~Entity(void){}
};
class Player : public Entity
{
public:
protected:
    int Health;
};
No imagine you are a player and shooting in the game. one of your bullets now collides with an entity and it should be able to react to it no matter what kind of entity it is. so like:

Code: Select all

...
Entity* entity = getCollisionEntity();
DamageMessage damage;
damage.Damage = 20;
damage.Type = 1;
entity->send(&damage);
...
wouldn't that be cool? and u can send any type of message and the entity only reacts if it wants to.
ok here is how this can work:

Code: Select all

#include "MessageDispatcher.h"

class Entity : public MessageDispatcher
{
public:
    virtual ~Entity(void){}
};
struct DamageMessage : Message
{
    int Damage;
    int Type;
};
struct HealMessage : Message
{
    int Heal;
};
class Player : public Entity, public Subscriber_2<DamageMessage, HealMessage>
{
public:
    Player(void)
    {
        this->Bind(this);
    }
    void receiveMessage(DamageMessage* message)
    {
        printf("Received %i damage of Type %i\n", message->Damage, message->Type);
       Health -= message->Damage;
    }
    void receiveMessage(HealMessage* message)
    {
        printf("Received %i health\n", message->Heal, message->Type);
       Health += message->Heal;
    }
protected:
    int Health;
};
int main(void)
{
    Entity* p = new Player();
    DamageMessage damage;
    damage.Damage = 20;
    damage.Type = 1;
    p->send(&damage);

    HealMessage heal;
    heal.Heal = 10;
    p->send(&heal);

    delete p;
}
We're programmers. Programmers are, in their hearts, architects, and the first thing they want to do when they get to a site is to bulldoze the place flat and build something grand. We're not excited by renovation:tinkering,improving,planting flower beds.
Murloc992
Posts: 272
Joined: Mon Apr 13, 2009 2:45 pm
Location: Utena,Lithuania

Post by Murloc992 »

Sudi, I love your demos and tuts! :) Give us more! 8)
zet.dp.ua
Posts: 66
Joined: Sat Jul 07, 2007 8:10 am

Post by zet.dp.ua »

Very nice message system implementation, thank you!
What do you think about using map search (by message identifier) instead of dynamic_cast while redirecting to the specific receiveMessage method?
Post Reply