import objectdraw.*; import java.awt.Color; import java.util.Random; /** * A class that draws a flower in the window and that can grow * and change its color. */ public class Flower { // Dimensions of the parts of the flower private static final int PETAL_SIZE = 80; private static final int STEM_WIDTH = 4; private static final int BUD_WIDTH = 25; // The amount the flower's size should increase // when grow is invoked private static final int GROWTH_RATE = 2; // Used to pick colors for the flower's petals private static final int MAX_COLOR_LEVEL = 256; private Random rand = new Random(); // The ovals that make up the four petals private FilledOval petal1, petal2; // The flower's stem private FilledRect stem; // The bud/center of the flower private FilledOval center; // The controller's canvas private DrawingCanvas canvas; // Limit on the flower's growth private double maxHeight; // create the flower as just a stem with a a certain // width and no height and a "bud" on top of the stem public Flower(Location point, double heightLimit, DrawingCanvas inCanvas) { maxHeight = heightLimit; canvas = inCanvas; // stem starts out with zero height stem = new FilledRect(point.getX() - STEM_WIDTH / 2, point.getY(), STEM_WIDTH, 0, canvas ); center = new FilledOval(point.getX() - BUD_WIDTH / 2, point.getY() - BUD_WIDTH / 2, BUD_WIDTH, BUD_WIDTH, canvas ); stem.setColor(Color.GREEN); center.setColor(Color.RED); } // if there is a flower, check to see if the petals or // flower center contain the point sent in public boolean flowerContains(Location point) { return petal1 != null && (center.contains(point) || petal1.contains(point) || petal2.contains(point)); } // if the flower has not grown to maximum height grow it // a little more by increasing the height of the stem // rectangle and moving that rectangle up by the same // as the growth amount. if the flower has reached // maximum height, draw the petals with a random color // and bring the center forward so it's not hidden by // the petals public void grow() { if (stem.getHeight() < maxHeight ) { center.move(0, -GROWTH_RATE ); stem.move(0, -GROWTH_RATE ); stem.setHeight(stem.getHeight() + GROWTH_RATE ); } else { if (petal1 == null) { petal1 = new FilledOval(center.getX() + BUD_WIDTH/2 - PETAL_SIZE / 2, center.getY() + BUD_WIDTH/2 - PETAL_SIZE / 4, PETAL_SIZE, PETAL_SIZE / 2, canvas ); petal2 = new FilledOval(center.getX() + BUD_WIDTH/2 - PETAL_SIZE / 4, center.getY() + BUD_WIDTH/2 - PETAL_SIZE / 2, PETAL_SIZE / 2, PETAL_SIZE, canvas); changeColor(); center.sendToFront(); } } } // generate a random color and set the color of the // petals to that color public void changeColor() { Color petalColor = new Color(rand.nextInt(MAX_COLOR_LEVEL), rand.nextInt(MAX_COLOR_LEVEL), rand.nextInt(MAX_COLOR_LEVEL)); petal1.setColor(petalColor); petal2.setColor(petalColor); } }