// file: GMovingSquare.java // date: 3/23/2014 // authors: Andrew Mertz and Nancy Van Cleave // // This class represents a square graphical object that can animate itself, // bouncing in the window that contains it when it is told to move. // // The parent class is GSmartSquare, which knows where it is relative to its // window's boundaries. // This class adds storage for the direction and speed of an object's movement // (GPoint displacement), and thus adds inspector and mutator for this new // data member. package graphics; import acm.graphics.*; import java.awt.*; public class GMovingSquare extends GSmartSquare { // DATA MEMBER // The velocity of the GMovingSquare. private GPoint displacement; // CONSTRUCTORS -- construct the inner GSmartSquare and initialize // data member displacement // // Constructs a new GMovingSquare with the specified width and height, // positioned at (x,y), colored the given color (note that the square is // filled), and with the velocity (deltax, deltay). // Since the parent class is GSmartSquare, a constructor for that class is // invoked with super() and the data member displacement is initialized. public GMovingSquare(double x, double y, double size, Color color, double deltax, double deltay, GCanvas screen) { super(x, y, size, color, screen); displacement = new GPoint(deltax, deltay); } // Constructs a new GMovingSquare with the specified width and height, // positioned at the origin, colored the given color (note that the square is // filled), and with the velocity (deltax, deltay). Makes use of the full // constructor above, sending in the origin as the position. public GMovingSquare(double size, Color color, double deltax, double deltay, GCanvas screen) { this(0.0, 0.0, size, color, deltax, deltay, screen); } // INSPECTOR for displacement // Returns a copy of the current displacement (velocity) of the GMovingSquare. public GPoint getDisplacement() { return new GPoint(displacement); } // MUTATORS for displacement // Sets the displacement (velocity) of the GMovingSquare to be a copy of the // given GPoint. public void setDisplacement(GPoint displacement) { this.displacement.setLocation(displacement); } // Sets the displacement (velocity) of the GMovingSquare to be (x,y). public void setDisplacement(double x, double y) { displacement.setLocation(x, y); } // FACILITATOR METHOD /** * Moves the GMovingSquare according to the current displacement. */ public void move() { /************************************************************************* * add code here to modify displacement when necessary to "bounce" *************************************************************************/ // move as usual -- since this invocation uses two double parameter, it will // match the move in one of the parent classes above this one move(displacement.getX(), displacement.getY()); } }