import sofia.micro.*;
import java.util.List;
import java.util.ArrayList;
//-------------------------------------------------------------------------
/**
* A shark that chases and eats sardines.
*
* @author Emily A
...
import sofia.micro.*;
import java.util.List;
import java.util.ArrayList;
//-------------------------------------------------------------------------
/**
* A shark that chases and eats sardines.
*
* @author Emily Ashburn (emily2000)
* @version (2019.03.26)
*/
public class Shark extends Actor
{
//~ Fields ................................................................
private List
stomach;
//~ Constructor ...........................................................
// ----------------------------------------------------------
/**
* Creates a new Shark object.
*/
public Shark()
{
super();
stomach = new ArrayList();
}
//~ Methods ...............................................................
// ----------------------------------------------------------
/**
* Calculate the distance to another actor.
*
* @param actor The other actor.
* @return The distance from this shark to the other actor.
*/
public double distanceTo(Actor actor)
{
int xDistance = actor.getGridX() - this.getGridX();
int yDistance = actor.getGridY() - this.getGridY();
return (Math.sqrt((xDistance * xDistance) + (yDistance * yDistance)));
}
// ----------------------------------------------------------
/**
* Find the sardine nearest to this shark.
*
* @return The sardine that is closest, if there is one, or
* null if there are no more sardines in the sea.
*/
public Sardine nearestSardine()
{
Sardine nearest = null;
double distance = 600;
for (Sardine sardine: this.getWorld().getObjects(Sardine.class))
{
if (this.distanceTo(sardine) < distance)
{
distance = this.distanceTo(sardine);
nearest = sardine;
}
}
return nearest;
}
https://www.coursehero.com/file/54213464/Sharkjava/
This study resource was
shared via CourseHero.com// ----------------------------------------------------------
/**
* Eat a sardine by removing it from the world and adding it
* to this shark's stomach contents.
*
* @param sardine The sardine to eat.
*/
public void eat(Sardine sardine)
{
sardine = this.getOneIntersectingObject(Sardine.class);
stomach.add(sardine);
sardine.remove();
}
// ----------------------------------------------------------
/**
* Sharks move towards the nearest sardine, eating it if they
* reach it.
*/
public void act()
{
if (this.nearestSardine() != null)
{
this.turnTowards(nearestSardine());
this.move(1);
}
if (this.getOneIntersectingObject(Sardine.class) != null)
{
this.eat(nearestSardine());
}
}
/**
* stomach contents
* @return List this is a getStomachContents()
*/
public List getStomachContents()
{
return (stomach);
[Show More]