// Bug.java // Written by THC for CS 5 Lab Assignment #2 Extra Credit. // Represents an individual Bug. import java.applet.Applet; import java.awt.*; public class Bug { private static Image[] bugImages; // array of references to the sequence of images for this Bug private static Applet theApplet; // the applet that will be displaying the image private static final int HEIGHT = 50, WIDTH = 33; // height and width of this Bug's image private Point upperLeft; // upper left corner of the current location of this Bug's image private int posture; // index into bugImages of this Bug's posture private int speed; // how many pixels this Bug moves each time // Static method to initialize the static variables bugImages and theApplet. public static void init(Image[] images, Applet applet) { bugImages = images; theApplet = applet; } // Constructor. Makes a new Bug at the given location and with a given speed. public Bug(Point where, int howFast) { upperLeft = where; posture = 0; speed = howFast; } // Draw this Bug. public void draw(Graphics page) { // Which image we use depends on this Bug's posture. page.drawImage(bugImages[posture], upperLeft.x, upperLeft.y, theApplet); } // Move this Bug toward the top of the applet window and update this Bug's // posture to the next image in the sequence of images. // Returns true if any part of this Bug is still in the window, // false if this Bug has moved fully off the top of the window. public boolean move() { upperLeft.y -= speed; posture = (posture + 1) % bugImages.length; return upperLeft.y + HEIGHT >= 0; } // Determines whether a Bug is hit by a Point. // Returns true if the Point is anywhere within this Bug's image. public boolean isHit(Point p) { return upperLeft.x <= p.x && p.x < upperLeft.x + WIDTH && upperLeft.y <= p.y && p.y < upperLeft.y + HEIGHT; } }