Agent Communication

For some AI implementations communications is crucial. To this end, starting from Framework version 43, agents can communicate directly. The Circle agent can send messages directly to the Rectangle and vice versa. Notice that these messages are only delivered if both agents are still playing the game at the same time.

The purpose of this article is to introduce how to use this capability. As a starting point for this code example we use the Example: The Random Circle Agent. We then describe the modifications needed to demonstrate the newly introduced capability in the circle agent. Don’t forget that for you to see this properly working you need to implement this mechanism (or another similar to it) in both agents.

A working example of this functionality can be found here.

WARNING: the overriden methods to get the messages from the agents and to process the messages from the agents should not perform computationally intensive operations which might block the agents’ manager in the framework. If you intent to do heavy processing based on the messages just save the messages when you receive them from the agents manager and perform these operations in the agent’s thread.

Additional Variables Declared

private List<AgentMessage> messages;

Additional Constructor Initializations

//messages exchange
messages = new List<AgentMessage>();

Additional Setup Processing

//send a message to the rectangle informing that the circle setup is complete and show how to pass an attachment: a pen object
messages.Add(new AgentMessage("Setup complete, testing to send an object as an attachment.", new Pen(Color.AliceBlue)));

 

Additional Action Selection logic (under the RandomAction method)

//send a message to the rectangle agent telling what action it chose
messages.Add(new AgentMessage("Going to :" + currentAction));

Overriding GetAgentMessages

//implememts abstract agent interface: send messages to the rectangle agent
public override List<GeometryFriends.AI.Communication.AgentMessage> GetAgentMessages()
{
    List<AgentMessage> toSent = new List<AgentMessage>(messages);
    messages.Clear();
    return toSent;
}

Overriding HandleAgentMessages

//implememts abstract agent interface: receives messages from the rectangle agent
public override void HandleAgentMessages(List<GeometryFriends.AI.Communication.AgentMessage> newMessages)
{
    foreach (AgentMessage item in newMessages)
    {
        Log.LogInformation("Circle: received message from rectangle: " + item.Message);
        if (item.Attachment != null)
        {
            Log.LogInformation("Received message has attachment: " + item.Attachment.ToString());
            if (item.Attachment.GetType() == typeof(Pen))
            {
                Log.LogInformation("The attachment is a pen, let's see its color: " + ((Pen)item.Attachment).Color.ToString());
            }
        }
    }
}