25 agosto 2017

A simple example using 2 agents one of them with a Java class

This examples shows 2 Jason agents interacting by internal messages and one of them has a Java class where an interface is shown. The user can interact with the agents by a button.

This project can run in Eclipse using JasonIDE plugin of by JEdit.

Project code (project.mas2j file):
MAS jasonEmbedded {
infrastructure: Centralised
agents:
a1;
a2 agentArchClass agent2;
aslSourcePath:
"src/asl";
}

Agent1 code (a1.asl file):
!start.

+!start : true 
<- .print("Hello, I am here!").

+!goalPerformed[source(X)] : true

<- .send(X, achieve, beReady).

Agent2 code (a2.asl file):
!start.

+!start : true 
<- .print("Hello, I am here!").

@doSomething
+!doSomething : true   // this goal is created by the GUI of the agent 
<- .print("Agent 2 is performing something.");
.send(a1, achieve, goalPerformed).
    
@beReady
+!beReady : true
<- .print("I am ready for the next task!").

Agen2 java class (agent2.java file):
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import jason.architecture.*;
import jason.asSyntax.ASSyntax;
import jason.asSyntax.Literal;
import javax.swing.*;

/** example of agent architecture's functions overriding */
public class agent2 extends AgArch {

  JTextArea jt;
  JFrame f;
  JButton button;

  public agent2() {
    jt = new JTextArea(10, 30);
    button = new JButton("Perform goal 1");
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        Literal goal = ASSyntax.createLiteral("doSomething");
jt.append("\n\rPerforming goal 1...");
getTS().getC().addAchvGoal(goal, null);
      }
    });
    f = new JFrame("Agent2");
    f.getContentPane().setLayout(new BorderLayout());
    f.getContentPane().add(BorderLayout.CENTER, new JScrollPane(jt));
    f.getContentPane().add(BorderLayout.SOUTH, button);
    f.pack();
    f.setVisible(true);
  }

  @Override
  public void stop() {
    f.dispose();
    super.stop();
  }
}