Using packages
[Agent practical 5 of 9]


We'll now build some communication into our model.

Each of our agents now has the ArrayList of all the other agents, so it can get and set information within them -- this is how we communicate between agents, by calling methods and passing in information. Note that when we do this, we'd usually filter out ourselves:

for (int j = 0; j < agents.size(); j++) {
   if (agents.get(j) != this) {
      agents.get(j).getX();
   }
}

Although we have all the agents, we don't have to communicate with all of them. We could limit outselves to dealing with the agents in our neighbourhood. This could, for example, be used to build models where the agents have imperfect information or distributed knowledge, rather than perfect knowledge of what's going on with all the agents (or the complete environment, if we also limit our interactions with that). Even though we know we have all the agents(/environment), we're not obliged to use all of them(/it).

While we could get our agents to register with the environment, and continually search for agents close to ourselves via the environment, it is much simpler to just keep a reference to all the agents and filter them by location if we can. Remember, the Agent's ArrayList is just a label attached to the Model.java ArrayList, it isn't a separate copy, so there's no extra memory needed to store it (well, very little -- just what the label uses).


So, here's what we're going to do to demonstrate some of these ideas. We're going to get our agents to check whether there's another agent near the area they're thinking of moving to before they move. If there's another agent that is near enough to potentially cope with the area, our agent will find another. To do this we'll need to ask each agent where it is, and identify those that fall into a neighbourhood around our potential location. While we won't then interact with the agents after that, you can see that this could provide the foundations for then interacting only with agents that fall within a neighbourhood.

First, let's start with identifying if another agent is in exactly the spot we're trying to move to. So far, our move() method in Nibbler looks like this:

private void move() {

   // Code to find a new x.
   // Code to find a new y.

}

At the end of this we know if an individual x is in the right range, and the same for an individual y. Let's now make a new method that checks whether the location fixed by these together is suitable, i.e. empty of other agents:

private void move() {

   do {

      // Code to find a new x.
      // Code to find a new y.

   } while (locationSuitable(x,y) == false);

}

Can you implement the locationSuitable method? It will need to take in the new x and y coordinates (not the agent's current x and y), returning the boolean value true when a location is not occupied by another agent, and false otherwise. Give it a go.


We'll now look at expanding this method to use a neighbourhood.