import java.util.*; public class SMBE extends SquareEnvironment { private LinkedList[] steveirwin; private int numcols; public SMBE(int r, int c) { super(); numcols = c; steveirwin = new LinkedList[r]; int i; for(i = 0; i < r; i++) steveirwin[i] = new LinkedList(); } public int numRows() { return steveirwin.length; } public int numCols() { return numcols; } public boolean isValid(Location loc) { if(loc == null) return false; return (0 <= loc.row() && loc.row() < numRows()) && (0 <= loc.col() && loc.col() < numCols()); } public int numObjects() { return objectCount; } public Locatable[] allObjects() { Locatable[] theObjects = new Locatable[numObjects()]; int tempObjectCount = 0; for(int r = 0; r < numRows(); r++) { for ( int c = 0; c < numCols(); c++ ) { Locatable obj = theGrid[r][c]; if(obj != null) { theObjects[tempObjectCount] = obj; tempObjectCount++; } } } return theObjects; } public boolean isEmpty(Location loc) { return isValid(loc) && objectAt(loc) == null; } public Locatable objectAt(Location loc) { if(!isValid(loc)) return null; return theGrid[loc.row()][loc.col()]; } public String toString() { Locatable[] theObjects = allObjects(); String s = "Environment contains " + numObjects() + " objects: "; for(int index = 0; index < theObjects.length; index++) s += theObjects[index].toString() + " "; return s; } public void add(Locatable obj) { Location loc = obj.location(); if(!isEmpty(loc)) throw new IllegalArgumentException("Location " + loc + " is not a valid empty location"); theGrid[loc.row()][loc.col()] = obj; objectCount++; } public void remove(Locatable obj) { Location loc = obj.location(); if(objectAt(loc) != obj) throw new IllegalArgumentException("Cannot remove " + obj + "; not there"); theGrid[loc.row()][loc.col()] = null; objectCount--; } public void recordMove(Locatable obj, Location oldLoc) { Location newLoc = obj.location(); if(newLoc.equals(oldLoc)) return; Locatable foundObject = objectAt(oldLoc); if(!(foundObject == obj && isEmpty(newLoc))) throw new IllegalArgumentException("Precondition violation moving " + obj + " from " + oldLoc); theGrid[newLoc.row()][newLoc.col()] = obj; theGrid[oldLoc.row()][oldLoc.col()] = null; } }