Tuesday, January 9, 2018

architecture - Game Messaging System Design


I'm making a simple game, and have decided to try to implement a messaging system.


The system basically looks like this:


Entity generates message -> message is posted to global message queue -> messageManager notifies every object of the new message through onMessageReceived(Message msg) -> if object wants, it acts on the message.


The way I'm making message objects is like this:


//base message class, never actually instantiated
abstract class Message{
Entity sender;
}


PlayerDiedMessage extends Message{
int livesLeft;
}

Now my SoundManagerEntity can do something like this in its onMessageReceived() method


public void messageReceived(Message msg){
if(msg instanceof PlayerDiedMessage){
PlayerDiedMessage diedMessage = (PlayerDiedMessage) msg;
if(diedMessage.livesLeft == 0)

playSound(SOUND_DEATH);
}
}

The pros to this approach:



  1. Very simple and easy to implement

  2. The message can contain as much as information as you want, because you can just create a new Message subclass that has whatever info necessary.


The cons:




  1. I can't figure out how I can recycle Message objects to a object pool, unless I have a different pool for each subclass of Message. So I have lots and lots of object creation/memory allocation over time.

  2. Can't send a message to a specific recipient, but I haven't needed that yet in my game so I don't mind it too much.


What am I missing here? There must be a better implementation or some idea that I'm missing.




No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...