package class1_3_DuckStrategies_v2; import java.awt.Point; /** * This class represents a specialized type of Duck * @author hornick */ public class Mallard extends Duck { /** * Mallard-specific constructor */ public Mallard(String name) { super(name, "mallard.jpg"); // this value defines how far a Mallard moves each update period - s random value between 3 and 8. increment = new Point(random.nextInt(3)+5, random.nextInt(3)+5 ); //Note that the duck's image and incremental movements could potentially be parameterized // as constructor call arguments, but this would increase the coupling between this class and the // class invoking the constructor, since the invoking class would then have to know more about // the inherent behavior of each type of duck created. } /** * This method implements a duck's default quacking behavior */ @Override public void quack() { System.out.println(name + ": quack!"); quacker.play(); } /** * This method implements a duck's default swimming behavior. * Every time this method is called, the duck's position on the screen moves * a little bit according to the algorithm we implement here. */ @Override public void swim() { if( (currentPos.x > (DuckPond.PONDSIZE-image.getWidth(null))) // leaving the window's right edge || (currentPos.x < 0) ) { // ...or left edge increment.x = -increment.x; // reverse direction quack(); // quack each time we reverse direction } if( (currentPos.y > (DuckPond.PONDSIZE-image.getHeight(null))) // leaving the window's top edge || (currentPos.y < 0) ) {//... or bottom edge increment.y = -increment.y; // reverse direction } currentPos.x += increment.x; // increment the position of the duck currentPos.y += increment.y; setLocation(currentPos); // ...and update its location in the container } }