Wanderer: random numbers
We'll cover the following...
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:
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.