// Robot uses the built-in Color class in java.awt.Color. (see Java API) import java.awt.Color; /** BouncingRobot is a Robot which bounces when it hits a wall. * i.e., if it can't step in a certain direction, it changes direction */ public class BouncingRobot extends Robot { // fields // new state protected boolean movingForward = true; // true if moving Forward, // false if moving Backward // constructor public BouncingRobot( Stepper s, Color c ) { // call the superclass's constructor super( s, c ); } /** BouncingRobot overrides the act() method. * Instead of moving forward all the time, the robot moves * forward until it hits a wall and cannot step. Then, * it starts moving backward until it hits the wall, then * it starts moving forward again, ... ad nauseam. */ public void act() { if (movingForward) { try { // try to step forward myStepper.stepForward(); } catch (CannotStepException e) { // if it's not possible, then next time try moving backward movingForward = false; } } else { try { // try to step backward myStepper.stepBackward(); } catch (CannotStepException e) { // if it's not possible, then next time try moving forward movingForward = true; } } } }