package OOPLS;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.Random;

public class DroppedBall {
    double centerx, centery; // Exact coordinates of center.
    double dx, dy;  // Exact speed in x and y directions, 
                    // respectively.  Units are pixels per 
                    // second.
    int ddy = 400;  // Gravitational acceleration in pixels 
                    // per second per second.
    int radius = 20;  // Radius of ball.
    double bouncePct = 0.95; // Bouncing damps vertical 
                             // speed using this fraction.
    double rollPct = 0.70;   // Rolling damps horizontal 
                             // speed using this fraction.
    double epsilon = 1.0E-2; // Ball is considered to be 
                             // touching bottom edge of win-
                             // dow if it is this close.
    Color ballColor;
    boolean bounced = false;
    Random rnd = new Random();
    Rectangle rectangle = new Rectangle();
    public final void randomizeLocationAndSpeed() {
        centerx = Math.abs(rnd.nextInt()) % 200 + 100;
        centery = Math.abs(rnd.nextInt()) % 100;
        dx = rnd.nextInt() % 100 + 100;
        dy = rnd.nextInt() % 50;
    }
    public DroppedBall() {
        randomizeLocationAndSpeed();
        float red = rnd.nextFloat(), 
              green = rnd.nextFloat(), 
              blue = rnd.nextFloat();
        ballColor = new Color(red, green, blue);
    }
    public void setRectangle(Rectangle rect) {
        rectangle = rect;
    }
    public void setColor(Color c) {
        ballColor = c;
    }
    public void cycle(int elapsedMillis) {
        centerx += dx * elapsedMillis/1000.0;
        centery += dy * elapsedMillis/1000.0;
        if (centerx - radius <= rectangle.x ||
            centerx + radius >= rectangle.x + rectangle.width) 
            dx = -dx;
        bounced = false;
        if (centery + radius >= rectangle.y + rectangle.height) {
            centery = rectangle.y + rectangle.height - radius;
            dy = -bouncePct * dy;
            if (Math.abs(dy) < 15) dy = 0; // 
            else bounced = true;
        }
        dy += ddy * elapsedMillis/1000.0;
        if (Math.abs(centery+radius - rectangle.height) < epsilon 
            && dy >= 0) 
            dx *= rollPct;
    }
    public void draw(Graphics g) {
        g.setColor(ballColor);
        int leftx = (int)(centerx-radius),
            topy = (int)(centery-radius);
        g.fillOval(leftx, topy, 2*radius, 2*radius);
        g.setColor(Color.BLACK);
        g.drawOval(leftx, topy, 2*radius, 2*radius);
    }
    public Point getCenter() { 
        return new Point((int)centerx, (int)centery);
    } 
}
