import java.awt.*; // use graphics // This Sprite is a Buggle that moves along the x-axis and turns around when reaching sides of frame. public class RightLeftBuggle extends Sprite { // Instance variables // variables to keep track of initial state of Buggle // make protected to allow extended classes to have access protected Color c; // color of Buggle protected int size; // size of Buggle protected int startX; // initial x-coordinate of Buggle protected int y; // y-coordinate of Buggle (never changes) protected int dx; // distance Buggle moves in each frame protected boolean startRight; // direction Buggle initially facing // variables to keep track of current state of Buggles protected int currentX; // current x-coordinate of Buggle protected boolean headedRight; // current direction Buggle is facing // Constructors public RightLeftBuggle () { this.c = Color.red; this.size = 40; this.startX = 0; this.y = 0; this.dx = 5; this.startRight = true; this.resetState(); } public RightLeftBuggle (Color c, int size, int startX, int y, int dx) { this.c = c; this.size = size; this.startX = startX; this.y = y; if (dx>0) { // facing right startRight=true; } else { startRight=false; } this.dx = Math.abs(dx); this.resetState(); } // Required Sprite methods protected void drawState (Graphics g) { Polygon p = new Polygon(); p.addPoint(currentX, y); if (headedRight) { p.addPoint(currentX+size, y+size/2); } else { p.addPoint(currentX-size, y+size/2); } p.addPoint(currentX, y+size); p.addPoint(currentX, y); g.setColor(c); g.fillPolygon(p); g.setColor(Color.black); g.drawPolygon(p); } protected void updateState () { if (headedRight) { currentX = currentX + dx; if ((currentX+size)>this.width) { // turn LEFT headedRight = false; } } else { // must be headed left currentX = currentX - dx; if ((currentX-size)<0) { // turn RIGHT headedRight = true; } } } protected void resetState () { currentX = startX; headedRight = startRight; } // For Debugging public String className () { return "RightLeftBuggle"; } public String toString () { return className() + ":" + getName() + "[bounds=("+this.width+","+this.height+")" + "[color="+c + "; size="+size + "; startX="+startX + "; startY="+y + "; dx="+dx + "; startRight="+startRight + "]"; } public String getState () { return className() + ":" + getName() + "[bounds=("+this.width+","+this.height+")" + "[currentX="+currentX + "; headedRight="+headedRight + "]"; } }