Harvest Around Square 4 Robots with Threads
Code
package HarvestAroundSquare4Threads;
import cs1Lib.karel.*;
/** Use four robots to harvest beepers that are positioned
around a square. Each robot is running in its own thread
and, once started, is independent of the others.
@author Byron Weber Becker
@version 1.0 */
public class HarvestAroundSquare4T extends KarelApplet
{
public void run()
{ // Read the specification of the world from a URL. Then add the
// world to the applet.
World world = new World(this.getDocumentBase(), "HarvestAroundSquare.txt");
this.add(world);
// Construct four robots and position them in the world.
Harvester karel = new Harvester();
Harvester mary = new Harvester();
Harvester john = new Harvester();
Harvester suelynn = new Harvester();
world.addRobot(karel, 2, 3, World.EAST);
world.addRobot(mary, 6, 2, World.NORTH);
world.addRobot(john, 7, 6, World.WEST);
world.addRobot(suelynn, 3, 7, World.SOUTH);
// Start each robot.
new Thread(karel).start();
new Thread(mary).start();
new Thread(john).start();
new Thread(suelynn).start();
}
}
package HarvestAroundSquare4Threads;
import cs1Lib.karel.*;
/** A robot to pick up a line of beepers, ending in
a wall. Checks to see if the beeper is actually
present before attempting to pick it up.
@author Byron Weber Becker
@version 1.0 */
public class Harvester extends Robot implements Runnable
{
public void run()
{
while (this.frontIsClear())
{ this.move();
if (this.nextToABeeper())
this.pickBeeper();
}
this.turnOff();
}
}