import objectdraw.*; import java.awt.*; /** * This program creates a garden of up to 10 flowers, creating a * flower each time the user presses the mouse button. Any * existing flowers grow when the user drags the mouse. The flowers * grow to a specified maximum height (which is a parameter sent to * the Flower construct) and then "bloom." Clicking on a flower's * petals changes their color randomly. If the mouse leaves the * window and then re-enters, the canvas is cleared. */ public class Garden extends FrameWindowController { private static final int WINDOW_SIZE = 600; private static final int MAX_FLOWER_HEIGHT = 200; private static final int MAX_NUM_FLOWERS = 10; // create array of Flowers and keep track of how many there are private Flower[] garden; private int currentNumFlowers; public void begin() { resize(WINDOW_SIZE, WINDOW_SIZE); garden = new Flower[MAX_NUM_FLOWERS]; currentNumFlowers = 0; } // Create a new flower if the maximum number of // flowers has not been reached or change the color of // the flower clicked on. NOTE: if the user clicks // on a flower when the maximum number of flowers // has not been reached,. the clicked-on flower will // change colors and a new flower will NOT be created public void onMousePress(Location point) { // change color of flower if one was clicked on; // keep track of whether a flower was clicked on boolean clickedInFlower = false; for (int i = 0; i < currentNumFlowers; i++) { if (garden[i].flowerContains(point)) { garden[i].changeColor(); clickedInFlower = true; } } // create a new flower only if there is room for more // flowers and if the user did not click on a flower // (we don't want one flower growing out of the petals // of another flower) if (!clickedInFlower && currentNumFlowers < garden.length) { garden[currentNumFlowers] = new Flower(point, MAX_FLOWER_HEIGHT, canvas); currentNumFlowers++; } } // make all the existing flowers grow public void onMouseDrag(Location point) { for (int i = 0; i < currentNumFlowers; i++) { garden[i].grow(); } } // clear the canvas to start again when mouse enters // into window public void onMouseEnter(Location point) { canvas.clear(); currentNumFlowers = 0; } }