import java.awt.*; import java.util.*; /** * This class represents a hungry fish that eats * other fish * */ public class HungryFish extends Fish { ////////// fields ///////////////////////////// /** how hungry this fish is */ private int hunger = 0; // start off not hungry private static final int NEED_TO_EAT = 5; // how hungry /////////////// Constructors ////////////////// /** * Constructor that takes an environment and a location * @param env the environment that this fish is in * @param loc the location (row,col) that this fish is in */ public HungryFish(Environment env, Location loc) { // Construct and initialize the attributes inherited from Fish. super(env, loc, env.randomDirection(), Color.black); } /** * Constructor that takes the environment, location, and direction * @param env the environment that this fish is in * @param loc the location (row,col) that this fish is in * @param dir the direction the fish is facing */ public HungryFish(Environment env, Location loc, Direction dir) { super(env,loc,dir, Color.black); } public HungryFish(Environment env, Location loc, Direction dir, Color col) { // Construct and initialize the attributes inherited from Fish. super(env, loc, dir, col); } /** Creates a new hungry fish. * @param loc location of the new fish **/ protected void generateChild(Location loc) { // Create new fish, which adds itself to the environment. HungryFish child = new HungryFish(environment(), loc, environment().randomDirection(), color()); Debug.println(" New HungryFish created: " + child.toString()); } /** * Method to do the action during a timestep */ public void act() { // only act if still in the environment if (isInEnv()) { // increment the hunger hunger = hunger + 1; // get a list of locations with neighboring fish java.util.List neighbors = fullFishNeighbors(); // first see if hungry and have neighbors if (hunger >= NEED_TO_EAT && neighbors.size() > 0) { // eat a random neighbor Random randNumGen = RandNumGenerator.getInstance(); Location loc = (Location) neighbors.get(randNumGen.nextInt(neighbors.size())); Fish neighbor = (Fish) environment().objectAt(loc); neighbor.die(); hunger = 0; // reset hunger Debug.println("Fish " + this + " eating fish at " + loc); // Move to eaten fish location. Location oldLoc = location(); changeLocation(loc); // Update direction in case fish had to turn to move. Direction newDir = environment().getDirection(oldLoc, loc); changeDirection(newDir); } // else move like a normal fish else { Debug.println("Fish " + this + "is not hungry or doesn't have any neighboring fish to eat"); move(); } } } }