/* * Created on Oct 12, 2003 * */ package kareltherobot; import java.awt.Color; /** A robot that can use a Compute Strategy to compute the function y=2x; * @author jbergin * */ public class TwoXRobot extends UrRobot { /** These robots always start at the origin so there is no need for * the parameters * @param badge the color badge that the robot wears */ public TwoXRobot( Color badge) { super(1, 1, East, 0, badge); } public TwoXRobot() { super(1, 1, East, 0); } /** Do an ordinary move, by also remember the new y * coordinate. * */ public void moveAndLearn() { move(); computeStrategy = new TwoX(computeStrategy); } /** The robot world's origin is (1,1) not (0,0) so we adjust * at the end of a computation. */ private void adjust() { turnLeft(); move(); turnLeft(); move(); } /** After executing moveAndLearn zero or more times execute this once * to compute the y coordinate by moving there. * * PostCondition: The robot has turned off. */ public void compute() { turnLeft(); computeStrategy.compute(this); adjust(); turnOff(); } /** This class is used to decorate a strategy by adding * two moves to whatever else is known to do. * @author jbergin * */ private class TwoX implements ComputeStrategy { public TwoX(ComputeStrategy decorated) { this.decorated = decorated; } public void compute(UrRobot who) { who.move(); who.move(); decorated.compute(who); } ComputeStrategy decorated = null; } private ComputeStrategy computeStrategy = ComputeStrategy.NULL; }