package RandomMoveInGrid; /** * Agent.java */ import java.util.Formatter; import java.awt.Point; import java.util.ArrayList; import uchicago.src.sim.util.*; import uchicago.src.sim.gui.*; import uchicago.src.sim.space.*; import uchicago.src.sim.gui.ColorMap; import java.awt.Color; public class Agent implements Drawable { // class variables public static int nextID = 0; // to give each an ID public static Object2DGrid world; // where the agents live public static Model model; // the model "in charge" // instance variables int ID; private int x, y; // the Agent constructor public Agent ( ) { ID = nextID++; x = 0; y = 0; } //////////////////////////////////////////////////////////////////////////// // step // Top level definition of what the agent can do each time its activiated. // Currenlty it does this: // - get random dx,dy values in -1,0,1 as possible move to make // - asks the world to move that way. // - if move, cache new x,y values in own instance variables public void step () { int moved = 0; // not moved this step if ( model.getRDebug() > 0 ) System.out.printf( " --Agent-step() for ID=%d at x,y=%d,%d.\n", ID, x, y ); int dx = Model.getUniformIntFromTo( -1, 1 ); // dx = { -1,0,1 } int dy = Model.getUniformIntFromTo( -1, 1 ); // dy = { -1,0,1 } if ( model.getRDebug() > 0 ) System.out.printf( " - try to move dx,dy = %d,%d\n", dx, dy ); // ask the world to move us: return of null means not allowed, // otherwise the Point object has the new x,y values. Point pt = model.moveObjectInWorld( this, dx, dy ); if ( pt == null ) { if ( model.getRDebug() > 0 ) System.out.printf( " - failed to move dx,dy = %d,%d.\n", dx, dy ); } else { // moved to location specified x = (int) pt.getX(); y = (int) pt.getY(); moved = 1; } if ( model.getRDebug() > 1 ) System.out.printf(" Agent.step() done. Agent moved = %d.\n", moved ); } //////////////////////////////////////////////////////////////////////////// // setters and getters public void setID(int i) { ID = i; } public int getID() { return ID; } // note these are class methods, to set class variables public static void setWorld( Object2DGrid w ) { world = w; } public static void setModel( Model m ) { model = m; } // instance variables to cache own x,y location public int getX() { return x; } public void setX( int i ) { x = i; } public int getY() { return y; } public void setY( int i ) { y = i; } // we implement Drawable interface, so we need this method // so that the agent can draw itself when requested // (by the GUI display). public void draw( SimGraphics g ) { g.drawFastRoundRect( Color.blue ); } }