1   import interfaces.Controller;
2   import interfaces.AbstractRobot;
3   
4   import java.lang.*;
5   
6   /**
7   * A simple obstacle avoiding controller which uses touch sensors.
8   * Try it it MazeWorld!
9   *
10  * @author Graham Ritchie
11  */
12  public class ObstacleAvoider extends Controller
13  {
14      private AbstractRobot robot;
15      private boolean running;
16  
17      private int[] sensors={Controller.SENSOR_TYPE_TOUCH,Controller.SENSOR_TYPE_TOUCH,Controller.SENSOR_TYPE_TOUCH};
18      
19      public void initController(AbstractRobot r)
20      {
21          robot=r;
22      }
23      
24      public AbstractRobot getRobot()
25      {
26          return robot;
27      }
28      
29      public int[] getSensors()
30      {
31          return sensors;
32      }
33      
34      public void run()
35      {
36          running=true;
37          go();
38      }
39      
40      public void halt()
41      {
42          // stops the robot
43          running=false;
44          
45          robot.stopMoving();
46      }
47      
48      /**
49      * Main control loop, continuously checks the touch sensors and 
50      * backs the robot up if necessary.
51      */
52      public void go()
53      {
54          // keep looping while running
55          while (running)
56          {
57              // if the touch sensor hits anything, back off and turn round a bit
58              
59              if (robot.getSensor1()==1)
60              {
61                  robot.backward(500);
62                  robot.right(1000);
63              }
64              if (robot.getSensor2()==1)
65              {
66                  robot.backward(500);
67                  robot.right(1000);
68              }
69              if (robot.getSensor3()==1)
70              {
71                  robot.backward(500);
72                  robot.left(1000);
73              }
74              robot.forward();
75              
76              try{Thread.sleep(50);}catch(Exception e){}
77          }
78      }
79  }   
80