package class2_1_DuckStrategies_v6; import java.awt.Point; public class RandomSwimming implements SwimBehavior { private Duck parent; public RandomSwimming(Duck parent) { this.parent = parent; } @Override public void swim() { if( (parent.currentPos.x > (DuckPond.PONDSIZE-parent.image.getWidth(null))) // leaving the window's right edge || (parent.currentPos.x < 0) ) { // ...or left edge parent.increment.x = -parent.increment.x; // reverse direction } if( (parent.currentPos.y > (DuckPond.PONDSIZE-parent.image.getHeight(null))) // leaving the window's top edge || (parent.currentPos.y < 0) ) {//... or bottom edge parent.increment.y = -parent.increment.y; // reverse direction } parent.currentPos.x += parent.increment.x; // increment the position of the duck parent.currentPos.y += parent.increment.y; // Create a new random increment for the next movement (the next time this method is called) // Note: increments between -2 and +2 will be generated. parent.increment = new Point(parent.random.nextInt(5)-2, parent.random.nextInt(5)-2 ); parent.setLocation(parent.currentPos); // ...and update its location in the container } }