import becker.robots.*; import java.util.Random; /** A class of robot that can do a random walk. * * @author Duncan Buell * * **/ public class RandomWalker1 extends RobotSE { /** Construct a new RandomWalker robot. * @param aCity The city where the RandomWalker will be created. * @param aStreet The RandomWalker's initial street. * @param anAvenue The RandomWalker's initial avenue. * @param aDirection The RandomWalker's initial direction. * @param numThings the initial number of things in the backpack. **/ public RandomWalker1(City aCity,int aStreet,int anAvenue,Direction aDirection,int numThings) { super(aCity, aStreet, anAvenue, aDirection, numThings); } /* **************************************************************************** */ /** Do the random walk until you move "boundary" streets or avenues from (0,0). **/ public void doTheWalk(int boundary) { boolean atBoundary; int howManySteps,howManyTurns; Random theRandom = new Random(); atBoundary = false; while(false == atBoundary) { howManyTurns = getRandomNumber(theRandom,4); while(howManyTurns > 0) { this.turnRight(); howManyTurns = howManyTurns - 1; // we could write --howManyTurns; } howManySteps = getRandomNumber(theRandom,5); while(howManySteps > 0) { this.move(); // note that we read the following as "howManySteps <-- howManySteps - 1" // and not as a mathematical "equals" symbol howManySteps = howManySteps - 1; // we could write --howManySteps; } this.putThing(); if(this.getStreet() < -boundary) atBoundary = true; if(this.getStreet() > boundary) atBoundary = true; if(this.getAvenue() < -boundary) atBoundary = true; if(this.getAvenue() > boundary) atBoundary = true; } // while(false == atBoundary) } // public void doTheWalk(int boundary) /* **************************************************************************** */ /** get a random number * @param theRandom The random number class that has been invoked * @param upperBound The upper bound of the number to be returned * * This function returns a random integer number between 0 and upperBound-1 * inclusive. **/ private int getRandomNumber(Random theRandom, int upperBound) { return (int) (theRandom.nextFloat() * upperBound); } } // public class RandomWalker extends RobotSE