Arbitrator.java
package prey; import lejos.nxt.LCD; /** * @author HS * */ public class Arbitrator extends Thread { private Behavior[] behaviors; // The list of all active behaviors. private Behavior maxBehavior; // The behavior with the maximum motivation. private Behavior lastBehavior; // The behavior from the previous run. private int lastMotivation; // The maximum motivation from the previous run. private boolean running = true; // Setting running to false stops the arbitrator. public Arbitrator(Behavior[] behaviors) { this.behaviors = behaviors; this.setDaemon(true); } public void run() { int maxMotivation = 0; // Keeps track of the highest motivation for each run. int motivation; // The motivation for the current behavior when running through behaviors. while (running) { for (Behavior currentBehavior : behaviors) { // Print the behavior along with the priority and motivation to the LCD. LCD.drawString(currentBehavior.getBehaviorPriority() + ", " + currentBehavior.getMotivation() + ", " + currentBehavior.getName() + " ", 0, currentBehavior.getBehaviorPriority()); // Reset the maxMotivation. maxMotivation = (maxBehavior != null ? maxBehavior.getMotivation() : 0); motivation = currentBehavior.getMotivation(); /* * If no previous maxBehavior exist or the new behavior has * higher motivation or if to behaviors are tied for motivation * and the new has higher priority. */ if (maxBehavior == null || motivation > maxMotivation || (motivation == maxMotivation && maxBehavior.getBehaviorPriority() > currentBehavior.getBehaviorPriority()) && motivation > 0) { // A new behavior has taken the lead. maxBehavior = currentBehavior; } } // Stop lastBehavior and starts new one, if the two aren't the same if (lastBehavior == null || !maxBehavior.getName().equals(lastBehavior.getName())) { // lastBehavior could be null. If it is not it should be stopped. if (lastBehavior != null) { lastBehavior.stopAction(); } // Run the highest motivated behavior and print the name of the // behavior on the first line of the LCD. maxBehavior.startAction(); LCD.drawString("Running " + maxBehavior.getName() + " ", 0, 0); // Prepare for the next run. lastBehavior = maxBehavior; lastMotivation = maxMotivation; // Lets a behavior interrupt itself if it is selfInterruptible // and has higher or equal motivation } else if (maxBehavior.getName().equals(lastBehavior.getName()) && maxBehavior.isSelfInterruptible() && maxMotivation >= lastMotivation) { // Interrupt itself maxBehavior.stopAction(); maxBehavior.startAction(); // Prepare for the next run. lastMotivation = maxMotivation; } // Every 10 ms the entire loop is repeated and all motivations are checked. try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * Stops the arbitrator and thereby causing the behaviors to stop running. */ public void stopRunning() { maxBehavior.stopAction(); running = false; } }