import objectdraw.*;
import java.awt.*;

public class MovingBall extends ActiveObject {
    private static final int BALL_SIZE = 30;      
    
    // Constants to determine ball speeds
    private static final int MIN_SPEED = 2;
    private static final int MAX_SPEED = 10;
    private static final int PAUSE_TIME = 40;
    
    // the ball
    private FilledOval ball;                
    
    // components of speed vector
    private double xSpeed, ySpeed, initYspeed;
    
    // boundaries of playing area
    private double bLeft, bRight, bTop, bBottom;
    
    // the paddle
    private FilledRect paddle;
    
    public MovingBall(DrawingCanvas canvas, FilledRect aPaddle, 
                      FramedRect boundary) {
        paddle = aPaddle;
        
        ball = new FilledOval(boundary.getX() + 1,
                              boundary.getY() + 1,  
                              BALL_SIZE, BALL_SIZE, canvas);
        
        // pick random pixel speeds
        RandomIntGenerator speedGen = new RandomIntGenerator(MIN_SPEED, MAX_SPEED);
        
        xSpeed = speedGen.nextValue();
        ySpeed = speedGen.nextValue();
        initYspeed = ySpeed;
        
        // give names to boundary values
        bLeft = boundary.getX();
        bTop = boundary.getY();
        bRight = bLeft + boundary.getWidth() - BALL_SIZE;
        bBottom = canvas.getHeight();
        
        this.start();
    }
    
    public void run() {
        
        // run until we go off the bottom of the screen
        while (ball.getY() < bBottom) {
            
            ball.move(xSpeed, ySpeed);
            
            // bounce off vertial walls
            if (ball.getX() < bLeft  || ball.getX() > bRight) {
                xSpeed = -xSpeed;
            }
            
            // bounce off top or paddle
            if (ball.getY() < bTop) {
                ySpeed = initYspeed;
            } else if (ball.overlaps(paddle)) {
                ySpeed = -initYspeed;
            }
            
            pause(PAUSE_TIME);
        }
        
        ball.removeFromCanvas();
    }
}
