Advertisement
KevinNT03

Maze-Runner Karel

Jan 21st, 2020
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.17 KB | None | 0 0
  1. package Challenge2;
  2. import kareltherobot.*;
  3.  
  4. /**
  5.  * This program allows a robot to solve any maze
  6.  */
  7. public class Challenge2Main extends Robot{
  8.  
  9.     public Challenge2Main (int s, int a, Direction d, int b){ //constructor
  10.         super(s, a, d, b);
  11.     }
  12.  
  13.     public static void main(String[] args) {
  14.  
  15.         World.setVisible(); //reads and creates the world
  16.         World.setDelay(20);
  17.         World.readWorld("KarelChallenges2.kwld");
  18.  
  19.         Challenge2Main roach = new Challenge2Main(1,9, West,0);
  20.  
  21.         while(!roach.nextToABeeper()){ //the beeper indicates that the maze is solved
  22.  
  23.             if(roach.rightIsClear()){ //if the right is clear, turn right (right-hand method)
  24.                 roach.turnRight();
  25.                 roach.move();
  26.  
  27.             }else if(roach.frontIsClear()){ //if the front is clear, move forward
  28.                 roach.move();
  29.             }else{
  30.                 roach.turnLeft(); //if neither the front nor the right is clear, turn left
  31.             }
  32.         }
  33.  
  34.  
  35.     }
  36.  
  37.     /**
  38.      * This method allows the robot to instantly turn right
  39.      */
  40.     public void turnRight(){
  41.         int delay = World.delay();
  42.         World.setDelay(0);
  43.         turnLeft();
  44.         turnLeft();
  45.         World.setDelay(delay);
  46.         turnLeft();
  47.     }
  48.  
  49.     /**
  50.      * This method allows the robot to instantly check if there is a wall to the left
  51.      * @return if the left intersection is clear
  52.      */
  53.     public boolean leftIsClear(){
  54.         int delay = World.delay();
  55.         World.setDelay(0);
  56.         boolean z = false;
  57.         turnLeft();
  58.         if(frontIsClear()){
  59.             z = true;
  60.         }
  61.         World.setDelay(delay);
  62.         turnRight();
  63.         return z;
  64.     }
  65.  
  66.     /**
  67.      * This method allows the robot to instantly check if there is a wall to the right
  68.      * @return if the right intersection is clear
  69.      */
  70.     public boolean rightIsClear(){
  71.         int delay = World.delay();
  72.         World.setDelay(0);
  73.         boolean z = false;
  74.         turnRight();
  75.         if(frontIsClear()){
  76.             z = true;
  77.         }
  78.         World.setDelay(delay);
  79.         turnLeft();
  80.         return z;
  81.     }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement