import java.awt.*; class MovingText extends Sprite { // This Sprite moves text by the specified dx/dy with each frame. // dx/dy are specified as pixels in the Java coordinate system. // positive dx moves the text to the right; negative dx moves the text to the left // positive dy moves the text to the bottom; negative dx moves the text to the top // When the starting position of the text moves out of bounds, // the Sprite starts at its initial position again. private String text; private int startX; private int startY; private int dx; private int dy; private Font font; private Color color; // state variables private int currentX; private int currentY; public String name () { return "MovingText"; } public String toString () { return name() + "[text="+this.text + "; start=("+startX+","+startY+")" + "; dx="+this.dx + "; dy="+this.dy + ";\n" + " font="+this.font + "; color="+this.color + "]"; } public String getState () { return name() + "[currentX="+currentX + "; currentY="+currentY + "; bounds=("+this.width+","+this.height+")" + "]"; } // constructors public MovingText (String t, int x, int y) { this.text = t; this.startX = x; this.startY = y; this.dx = 1; this.dy = 1; this.font = new Font("Helvetica", Font.BOLD, 16); this.color = Color.black; this.resetState(); } public MovingText (String t, int x, int y, int dx, int dy, Color c) { this(t,x,y); this.dx = dx; this.dy = dy; this.color = c; } public void setFont (Font f) { this.font = f; } // required Sprite methods protected void resetState () { this.currentX = this.startX; this.currentY = this.startY; } protected void drawState (Graphics g) { g.setColor(this.color); g.setFont(this.font); g.drawString(this.text, currentX, currentY); } protected void updateState () { this.currentX+=this.dx; this.currentY+=this.dy; // if words go off the screen, start at initial position again if ((currentX<0) || (currentY<0)) { resetState(); } else if ((currentY>this.height) || (currentX>this.width)) { resetState(); } } }