Bonus challenge: robot ecosystem
Put it all together to put several robots in the maze.
Now you know how to make a robot move around in the maze, and that’s the main goal of the hour of code.
If you still have time, here’s a grand final challenge to work through: creating an ecosystem of robots that live in a maze.
You have already seen that there are different types of objects: A Maze
object, for example, and Robot
and Wall
objects.
In more advanced Java programming, you will learn to create your own types of objects, with their own behavior. As a taste of how useful this can be, we’ve created a new object type, or class
called a Wanderer
. It’s just a robot that has a special instruction wander
that causes the robot to set its direction randomly.
Your final challenge is to add several wanderers to the maze and have them wander around. Don’t forget to create a new variable for each Wanderer, create new Wanderer objects with the new
command
You can then use a loop to make the wanderers wander; execute one maze turn each time through the loop.
We’ve also added a gold coin to the maze; a realy advanced challenge would be to have the robots look for the gold coin and see who could find it first; you could have a team of red robots, and a team of blue robots.
import com.educative.robot.*;import java.util.Random;class Wanderer extends Robot {static Random randomGenerator = new Random();public Wanderer(double x, double y, String color) {super(x, y, color);}public void wander() {int dir;dir = randomGenerator.nextInt(4);this.setDirection(dir);}}class Ecosystem {public static void main(String[] args) {// set up variables to store the robot and the mazeWanderer robbie;Maze maze;Thing gold;// create the robot and maze, and add// the robot to the mazerobbie = new Wanderer(0.0, 1.0, "red");gold = new Thing(7.0, 7.0);// add the robot and the gold, and some other robots// add some walls here:// For ten turns, have the robots wander around// the maze, by calling the wander method, or some// other method you devise.}}