/**
* @author Amanda Gorski
* @date July 7, 2002
*
* Requires Bouncer.java, run it there
*/
import java.awt.*;
import javax.swing.*;
import java.text.*;

public class Ball extends JComponent implements Runnable
{
    private volatile int x; //present co-ordinate
    private volatile int y; //present co-ordinate
    private volatile boolean dir_x; //true equals right
    private volatile boolean dir_y; //true equals up
    private volatile boolean stopped; //true if the ball isn't bouncing
    private int bound_x; //how big the screen is in the x direction
    private int bound_y; //how big the screen is in the y direction
    private int speed; //how fast the ball is moving

    public Ball (int xx, int yy)
    { //Pre: xx is how big the screen is in the x direction, yy for the y direction
	//Post: a new ball is constructed and initialized
	x = 150;
	y = 82;
	dir_x = true;
	dir_y = true;
	bound_x = xx;
	speed = 7;
	bound_y = (yy);
	setBackground (Color.white);
    }
 

    public void run ()
    { //run method, starts when "Bounce" button is pressed
	moveBall ();
    }


    public void stopBall ()
    { //to pause the thread in the moveball method, stopped must be true
	//this stops the loop in moveball
	stopped = true;
    }


    public void moveBall ()
    { //calculates the new position of the ball and moves it
	//repeats until the user clicks the stop button.
	stopped = false;

	while (!stopped)
	{

	    drawBall ();

	    //choose new position
	    if (dir_x) //moving right
	    {
		if (x < (bound_x - 12))
		    x += speed + 2;
		else
		{
		    dir_x = false;
		    x += 4;
		}
	    }
	    else //moving left
	    {
		if (x > 5)
		    x -= speed;
		else
		{
		    dir_x = true;
		    x += speed;
		}
	    }

	    if (dir_y) //moving up
	    {
		if (y < (bound_y - 12))
		    y += speed;
		else
		    dir_y = false;
	    }
	    else //moving down
	    {
		if (y > 5)
		    y -= speed;
		else
		{
		    dir_y = true;
		    y += 2;
		}
	    }


	    //sleep for a bit after choosing new position
	    try
	    {
		Thread.sleep (50);
	    }
	    catch (InterruptedException x)
	    {
		;
	    }

	}
    }


    public void drawBall ()
    {
	repaint ();
    }


    /** draw the ball on the screen
    */
    public void paint (Graphics g)
    {
	//Draw a white square on screen to erase old ball
	g.setColor (Color.white);
	g.fillRect (x - 2 * speed, y - 2 * speed, 4 * speed, 4 * speed);
	//Choose a colour based on position
	int b = (int) x / 2;
	int gr = (int) y / 3;
	g.setColor (new Color (0, b, gr));
	//Draw the new ball
	g.fillOval (x - 5, y - 5, 12, 12);
    }



}

