// Stuart Reges // 1/26/00 // // Class CritterModel keeps track of the state of the critter simulation. import java.util.*; import java.awt.*; public class CritterModel { public CritterModel(int width, int height) { myWidth = width; myHeight = height; myGrid = new Critter[width][height]; myList = new Hashtable(); } public void add(int number, Class critter) { if (myList.size() + number > myWidth * myHeight) throw new RuntimeException("adding too many critters"); for (int i = 0; i < number; i++) { Critter next; try { next = (Critter)critter.newInstance(); } catch (Exception e) { throw new RuntimeException("" + e); } int x, y; do { x = randomInt(0, myWidth - 1); y = randomInt(0, myHeight - 1); } while (myGrid[x][y] != null); myGrid[x][y] = next; myList.put(next, new Point(x, y)); } } private static int randomInt(int low, int high) { return low + (int)(Math.random() * (high - low + 1)); } public int getWidth() { return myWidth; } public int getHeight() { return myHeight; } public char getChar(int x, int y) { if (myGrid[x][y] == null) return '.'; else return myGrid[x][y].getChar(); } public void update() { Critter[][] newGrid = new Critter[myWidth][myHeight]; Object[] list = myList.keySet().toArray(); shuffle(list); for (int i = 0; i < list.length; i++) { Critter next = (Critter)list[i]; Point p = (Point)myList.get(next); int move = next.getMove(p.x, p.y); if (move == Critter.NORTH) p.y = (p.y + myHeight - 1) % myHeight; else if (move == Critter.SOUTH) p.y = (p.y + 1) % myHeight; else if (move == Critter.EAST) p.x = (p.x + 1) % myWidth; else if (move == Critter.WEST) p.x = (p.x + myWidth - 1) % myWidth; else throw new RuntimeException("Illegal move from " + list[i]); if (newGrid[p.x][p.y] != null) myList.remove(newGrid[p.x][p.y]); newGrid[p.x][p.y] = next; } myGrid = newGrid; } private Class oneNeighbor(int x, int y, int xInc, int yInc) { x = (x + xInc + myWidth) % myWidth; y = (y + yInc + myHeight) % myHeight; if (myGrid[x][y] == null) return null; else return myGrid[x][y].getClass(); } private static void shuffle(Object[] list) { for (int i = 0; i < list.length; i++) { int j = randomInt(0, list.length - 1); Object temp = list[i]; list[i] = list[j]; list[j] = temp; } } private int myHeight; private int myWidth; private Critter[][] myGrid; private Hashtable myList; }