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

/*
 * 
 * A simple active object that controls a ball that falls down the
 * canvas and interacts with a pong paddle
 *
 * Jim Teresco, Siena College, CSIS 120, Fall 2011
 *
 * $Id: SimplePongBall.java 1549 2011-02-22 04:01:53Z terescoj $
 */

public class SimplePongBall extends ActiveObject {

    // size and speed of falling balls
    private static final int BALLSIZE = 30;
    private static final double Y_SPEED = 8;
    private static final int DELAY_TIME = 33;

    // the ball controlled by this instance
    private FilledOval ball;

    // the paddle with which we will interact
    private FilledRect paddle;

    // how far to fall before stopping and disappearing?
    private double yMax;
    // how far up to go before bouncing off the ceiling?
    private double yMin;

    // Draw a ball and start it falling.
    public SimplePongBall(Location start, FilledRect paddle, 
                          double courtTop, DrawingCanvas aCanvas) {

        // draw the ball at its initial position
        ball = new FilledOval(start.getX() - BALLSIZE/2,
            start.getY(),
            BALLSIZE, BALLSIZE, aCanvas);

        // ask the canvas how big it is so we know when to stop
        yMax = aCanvas.getHeight();

        // remember the top of the court as the minimum y
        yMin = courtTop;

        // remember the paddle
        this.paddle = paddle;

        // activate!
        start();
    }

    // move the ball repeatedly until it falls off screen, bouncing
    // off the paddle and the ceiling along the way
    public void run() {
        double ySpeed;
        
        // start by moving downward
        ySpeed = Y_SPEED;
        
        // keep moving as long as we haven't fallen off the bottom of
        // the screen
        while (ball.getY() <= yMax) {
            // if we are above the top line, start moving down
            if (ball.getY() < yMin) {
                ySpeed = Y_SPEED;
            }
            
            // if we are in contact with the paddle, start moving up
            if (ball.overlaps(paddle)) {
                ySpeed = -Y_SPEED;
            }
            
            // move a little in the appropriate direction
            ball.move(0, ySpeed);
            pause(DELAY_TIME);
        }
        ball.removeFromCanvas();
    }
}
