import uwcse.graphics.*; import java.awt.Point; import java.util.*; import java.awt.Color; /** * representation and display of a caterpillar */ public class Caterpillar implements CaterpillarConstants { // The body of a caterpillar is made of Points stored // in an ArrayList private ArrayList body = new ArrayList(); // Store the graphical elements of the caterpillar body // Useful to erase the body of the caterpillar on the screen private ArrayList bodyUnits = new ArrayList(); // The window the caterpillar belongs to private GWindow window; // Direction of motion of the caterpillar (NORTH initially) private int dir = NORTH; // Length of a unit of the body of the caterpillar // MUST be equal to the distance covered by the caterpillar // at every step of the animation. private final int bodyUnitLength=STEP; // Width of a unit of the body of the caterpillar private final int bodyUnitWidth=CATERPILLAR_WIDTH; /** * Construct a caterpillar */ public Caterpillar(GWindow window) { // Initialize the graphics window for this Caterpillar this.window = window; // Create the caterpillar (10 points) // First point // Other points // Show the caterpillar draw(); } /** * Draw the caterpillar in the graphics window */ private void draw() { // Connect the points of the body in the graphics window // (use lines, or rectangles...) } /** * Move the caterpillar in the current direction */ public void move() { move(dir); } /** * Move the caterpillar in the direction newDir.
* If the new direction is illegal, select a * legal direction of motion and move in that direction.
*/ public void move(int newDir) { // Is the move illegal? boolean isMoveNotOK; // newDir might not be legal // Before trying a random direction, try first // the current direction of motion (if not newDir) boolean isFirstTry = true; // move the caterpillar in direction newDir do{ // new position of the head Point head; // Is the new position in the window? if (isPointInTheWindow(head)) { // update the position of the caterpillar } else { // Select another direction } }while(isMoveNotOK); // Update the current direction of motion dir = newDir; // Show the new location of the caterpillar moveCaterpillarOnScreen(); } /** * Move the caterpillar on the screen */ private void moveCaterpillarOnScreen() { // Erase the body unit at the tail // Add a new body unit at the head // show it window.doRepaint(); } /** * Add a body unit to the caterpillar. The body unit * connects Point p and Point q.
* Insert this body unit at position index in bodyUnits.
* e.g. 0 to insert at the tail and bodyUnits.size() to insert * at the head. */ private void addBodyUnit(Point p, Point q, int index) { // Connect p and q with your preferred graphics element } /** * Is Point p in the window? */ private boolean isPointInTheWindow(Point p) { } }