Wanderer: random numbers
Let’s make the robot wander randomly around the maze. The sequence of steps to do this is:
- Pick a random direction.
- Set the velocity to make the robot drive in that direction.
- Tell the maze to animate for one turn.
- Repeat.
A sequence of steps to solve a problem is called an algorithm, and an algorithm can be described in any language you like, including English. We want to implement this algorithm in Java, by writing code.
Random numbers
The first step is to pick a random direction. Java can pick random integers, like this:
import java.util.Random;class RandomDemo {public static void main(String[] args) {Random randomGenerator = new Random();int number;// pick a number from 0 to 9:number = randomGenerator.nextInt(10);System.out.println("I'm thinking of the number " + number);}}
First, we create an object called a “Random Number Generator”, with the new Random()
command, and save a reference to that object in randomGenerator. Now we can use randomGenerator.nextInt(upperBound)
to generate a random number between 0 and (upperBound - 1).
We can store the random integer in a variable. Each variable stores a particular type of data; an int
variable stores an integer.
Run the code and see how it works. In this code, we’ve also created an integer variable number
to temporarily store the random integer that was created.
Exercise: moving in a random direction
We want the robot to move randomly in one of four directions: North, East, South, or West. Let’s use the method setDirection
, which can take one parameter that is an integer value between 0 and 3, and sets the velocity to cause the robot to drive in one of the four cardinal directions.
Write code below to make the robot drive in random directions for five turns.
import com.educative.robot.*;import java.util.Random;class Wanderer {public static void main(String[] args) {// set up variables to store the robot and the mazeRobot robbie;Maze maze;Random randomGenerator = new Random();int dir;// create the robot and maze, and add// the robot to the mazerobbie = new Robot(3.0, 3.0, "red");maze = new Maze(8, 8, 50);maze.add(robbie);// choose the first random direction:dir = randomGenerator.nextInt(4);// your code here:}}