package class5_1_DuckFactories_v7.swimBehaviors; import class5_1_DuckFactories_v7.Duck; import class5_1_DuckFactories_v7.DuckPond; import java.awt.*; public class StandardSwimming implements SwimBehavior { /** * The duck that uses this behavior */ private final Duck parent; private Point currentPos = new Point(); // the duck's current position private Point increment = new Point(); // the duck's incremental movement public StandardSwimming(Duck parent) { this.parent = parent; } /** * Standard bounce-off-the-walls swimming */ @Override public void swim() { if( (currentPos.x > (DuckPond.PONDSIZE-parent.image.getWidth(null))) // leaving the window's right edge || (currentPos.x < 0) ) { // ...or left edge increment.x = -increment.x; // reverse direction parent.quack(); // quack each time we reverse direction } if( (currentPos.y > (DuckPond.PONDSIZE-parent.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; parent.setLocation(currentPos); // ...and update its location in the container } }