// Helene Martin, CSE 142 // Draws squares of random color and position on a DrawingPanel // until 20 red squares are drawn. import java.util.*; import java.awt.*; public class RandomRects { public static final int SIZE = 500; public static final int SIDE = 10; public static void main(String[] args) { Random r = new Random(); DrawingPanel p = new DrawingPanel(SIZE, SIZE); Graphics g = p.getGraphics(); Point center = new Point(SIZE / 2, SIZE / 2); int redCounter = 0; int rects = 0; while(redCounter < 20) { int col = randomRect(g, r, center); p.sleep(50); rects++; if(col == 0) { redCounter++; } } System.out.println("Got 20 red rectangles in " + rects + " tries"); } // draws a randomly colored rectangle at a random location // prints its location and distance from center public static int randomRect(Graphics g, Random r, Point center) { int x = r.nextInt(SIZE - SIDE + 1); int y = r.nextInt(SIZE - SIDE + 1); Point rect = new Point(x, y); int col = r.nextInt(3); if(col == 0) { g.setColor(Color.RED); } else if(col == 1) { g.setColor(Color.BLUE); } else { // 2 g.setColor(Color.GREEN); } g.fillRect(rect.x, rect.y, SIDE, SIDE); System.out.println("Drawing square at (" + rect.x + ", " + rect.y + ")"); System.out.println("\tdistance from center: " + rect.distance(center)); return col; } }