Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Challenge3;
- import kareltherobot.*;
- /**
- * This program makes a robot collect piles of beepers
- */
- public class Challenge3Main extends Robot{
- public Challenge3Main(int s, int a, Direction d, int b){ //constructor
- super(s, a, d, b);
- }
- public static void main(String[] args) {
- World.setVisible(); //reads and creates the world
- World.setDelay(25);
- World.readWorld("KarelChallenges3.kwld");
- Challenge3Main paul = new Challenge3Main(1,1, North, 0);
- while(!paul.nextToABeeper()){ //runs until it finds the pile with two beepers
- if(paul.checkBeeperFront()){ //if there's a beeper in front, pick it
- paul.move();
- paul.pickBeeper();
- }else if(paul.checkBeeperLeft()){ //if there's a beeper to the left, pick it
- paul.turnLeft();
- paul.move();
- paul.pickBeeper();
- }else{ //if it is not in front or to the left, it should be to the right
- paul.turnRight();
- paul.move();
- paul.pickBeeper();
- }
- }
- }
- /**
- * This method allows the robot to instantly turn right
- */
- public void turnRight(){
- int delay = World.delay();
- World.setDelay(0);
- turnLeft();
- turnLeft();
- World.setDelay(delay);
- turnLeft();
- }
- /**
- * allows the robot to instantly turn around
- */
- public void turnAround(){
- int delay = World.delay();
- World.setDelay(0); //by changing the delay, the robot turns left instantaneously
- turnLeft();
- World.setDelay(delay);
- turnLeft();
- }
- /**
- * Immediately checks if there is a beeper in front of the robot
- * @return temp
- */
- public boolean checkBeeperFront(){
- int delay = World.delay();
- World.setDelay(0);
- boolean temp = false;
- if(frontIsClear()) { //checks if the front is clear to avoid errors
- move();
- if (nextToABeeper()) { //if there's a beeper there, return true
- temp = true;
- }
- turnAround(); //move back
- move();
- turnAround();
- }
- World.setDelay(delay);
- return temp;
- }
- /**
- * Immediately checks if there is a beeper to the left of the robot
- * @return temp
- */
- public boolean checkBeeperLeft(){
- int delay = World.delay();
- World.setDelay(0);
- boolean temp = false;
- turnLeft(); //Because we're checking the left
- if(frontIsClear()) { //checks if the front is clear to avoid errors
- move();
- if (nextToABeeper()) { //if there is a beeper there, return true
- temp = true;
- }
- turnAround(); //move back
- move();
- turnAround();
- }
- turnRight();
- World.setDelay(delay);
- return temp;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment