package ballwar.model.paint; import ballwar.model.*; import java.awt.*; import java.awt.geom.*; /** * Paint strategy that paints a filled square with the Ball's radius. * This functionality is duplicated by the RectanglePaintStrategy. * The class demonstrates a direct implementation of IPaintStrategy. */ public class SquarePaintStrategy implements IPaintStrategy { /** * The AffineTransformed used for internal calculations. */ private AffineTransform at = new AffineTransform(); /** * Unit sized rectangle used as a prototype */ private Rectangle rect; /** * No parameter constructor that creates a square with sides of * 2 pixels (1 pixel radius) located at the origin. * Instantiates a new AffineTransform for internal * use. */ public SquarePaintStrategy() { this(new AffineTransform(), 1, new Point(0,0)); } /** * Constructor that allows one to create the prototype square * of arbitrary side and location. The AffineTransform * is externally supplied. * @param at The AffineTransform to use for internal calculations * @param side The half-width (x-radius) of the square * @param loc The location of the center of the square. */ public SquarePaintStrategy(AffineTransform at, int side, Point loc) { this.at = at; rect = new Rectangle(loc.x-side,loc.y-side,2*side,2*side); } /** * Paints on the given graphics context using the color, scale and * direction provided by the host. This is done by setting up the * AffineTransform to scale then translate. * Calls paintXfrm to actually perform the painting, using the set up transform. * Calls paintCfg just before calling paintXfrm * param g The Graphics context that will be paint on * param host The host Ball that the required information will be pulled from. */ public void paint(Graphics g, Ball host) { double scale = host.getRadius(); at.setToTranslation(host.getLocation().x, host.getLocation().y); at.scale(scale, scale); g.setColor(host.getColor()); paintXfrm(g, host, at); } /** * Paints a transformed square, as per the given AffineTransform * Uses color already set in Graphics context * @param g The Graphics context to paint on * @param host The Ball host * @param at the AffineTransform to use */ public void paintXfrm(Graphics g, Ball host, AffineTransform at) { Shape s = at.createTransformedShape(rect); ((Graphics2D) g).fill(s); } /** * By default, do nothing for initialization. */ public void init(Ball context){ }; }