/** * Puts this actor into a grid. If there is another actor at the given location, it is removed. * <br> * Precondition: (1) This actor is not contained in a grid (2) <code>loc</code> is valid in <code> * gr</code> * * @param gr the grid into which this actor should be placed * @param loc the location into which the actor should be placed */ public void putSelfInGrid(Grid<Actor> gr, Location loc) { if (grid != null) throw new IllegalStateException("This actor is already contained in a grid."); Actor actor = gr.get(loc); if (actor != null) actor.removeSelfFromGrid(); gr.put(loc, this); grid = gr; location = loc; }
/** * Moves this actor to a new location. If there is another actor at the given location, it is * removed. <br> * Precondition: (1) This actor is contained in a grid (2) <code>newLocation</code> is valid in * the grid of this actor * * @param newLocation the new location */ public void moveTo(Location newLocation) { if (grid == null) throw new IllegalStateException("This actor is not in a grid."); if (grid.get(location) != this) throw new IllegalStateException( "The grid contains a different actor at location " + location + "."); if (!grid.isValid(newLocation)) throw new IllegalArgumentException("Location " + newLocation + " is not valid."); if (newLocation.equals(location)) return; grid.remove(location); Actor other = grid.get(newLocation); if (other != null) other.removeSelfFromGrid(); location = newLocation; grid.put(location, this); }