Problem 1

Here is my solution to the very first problem of Assignment 1. This problem is fairly simple. Karel starts off in a house in the northwest corner of the room. He must go outside the house and pickup the paper and then return to the same spot.

/* * File: CollectNewspaperKarel.java * -------------------------------- * At present, the CollectNewspaperKarel subclass does nothing. * Your job in the assignment is to add the necessary code to * instruct Karel to walk to the door of its house, pick up the * newspaper (represented by a beeper, of course), and then return * to its initial position in the upper left corner of the house. */

import stanford.karel.*;

/* * Name: Ken Swain * Section Leader: */

public class CollectNewspaperKarel extends SuperKarel {

public void run() {
findPaper();
pickPaper();
returnHome();
}

// Go and find the paper. Could have included picking up the paper in this step
private void findPaper() {
    while (frontIsClear()) {
        move();
    } 
    turnRight();
    while (leftIsBlocked()) {
        move();
    }
}

// Pick up the beeper/paper
private void pickPaper() {
    turnLeft();
    while (noBeepersPresent()) {
        move();
    }
    pickBeeper();
}

// Return to starting point.
private void returnHome() {
    turnAround();
    while (frontIsClear()) {
        move();
    }
    turnRight();
    while (frontIsClear()) {
        move();
    }
    while (notFacingEast()) {
        turnRight();
    }
}

}

Share