import java.awt.Color; public class RandomWalker extends MobileSimObject { // OVERVIEW: A RandomWalker is a drunk simulator object that performace a random walk, // moving one square in a random direction each step. private boolean inTurn; // Currently in the middle of a turn (used for coloring) public RandomWalker() { inTurn = false; } public void executeTurn() throws RuntimeException // Note: requires isInitialized is inherited from SimObject // EFFECTS: Picks a random direction and tries to move that way. // If the move is successful, return true. If the move fails // because the spot being attempted to move into is already // occupied then return false. { inTurn = true; Direction dir = Direction.randomDirection(); int newy = getY() + dir.northerlyDirection(); int newx = getX() + dir.easterlyDirection(); if (getGrid().validLocation(newx, newy)) { if (getGrid().isSquareEmpty(newx, newy)) { //@nowarn Pre // Here, we pretend there is a lot of compution to do by sleeping, // to make race conditions more likely. //delay(500); setLocation(newx, newy); } } inTurn = false; } public Color getColor() { if (inTurn) { return Color.white; } else { return Color.cyan; } } //@nowarn Post // ESC/Java doesn't know Color constants are not null }