Part (a)
// returns the forward diagonal cell to the left or right of this fish
// (depending on willZigRight) if that cell is empty;
// otherwise, returns this fish's current location
// postcondition: the state of this ZigZagFish is unchanged
protected Location nextLocation()
{
Environment env = environment();
Location nextLoc = env.getNeighbor(location(), direction()); 1
if (willZigRight)
nextLoc = env.getNeighbor(nextLoc, direction().toRight());
else
nextLoc = env.getNeighbor(nextLoc, direction().toLeft());
if (env.isEmpty(nextLoc))
return nextLoc;
return location();
}
Notes:
- You need to first make one step forward, then one step
to the left or to the right.
env.getNeighbor(location(), direction().toRight(45)) and
env.getNeighbor(location(), direction().toLeft(45))
won't work, because, even though you get the right direction,
diagonally adjacent cells are not considered neighbors.
Part (b)
// moves this ZigZagFish diagonally (as specified in nextLocation) if
// possible; otherwise, reverses direction without moving;
// after a diagonal move, willZigRight is updated
protected void move()1
{
Location nextLoc = nextLocation();
if (!nextLoc.equals(location()))
{
changeLocation(nextLoc);
willZigRight = !willZigRight;
}
else
changeDirection(direction().reverse());
}
Notes:
- This method is very similar to the
move method in DarterFish .
|