Billiard

 

Now comes the real entry into the object-oriented programming. We play with balls or ball objects.

The class Ball is a circle that can move at a given speed in a given direction. This ball leaves inevitably the workspace. Of course we can create any number of ball objects and that can be moved by the applet window, but all eventually leave the window.

Now we create a class to a pool table that does nothing more than to draw a rectangle on the applet window and betray interested objects, how high and how wide is this rectangle.

In order to simulate the behavior of a billiard ball, a ball object must be able to retrieve the size of the table and bounce off the edges. Our simple ball can not. In the class Billiardball we must not  repeat everything we have already implemented in the Ball class. We define a billiard ball just as a subclass of the class Ball (ball is then upper class to Billiardball). Objects of the subclass have all the features and capabilities of the upper class and a few more. A billiard ball is so marked and moved like a ball, but learns know the size of the table and bounces off its edges.

 

 

Excerpts from the source code:

public class BilliardBall extends Ball{
    private Billiardtable knowsTable;
    
    public BilliardBall(int pX, int pY, int pR, int pDirection, Color pColor,
                       Billiardtable pTable){
        super(pX,pY,pR,pDirection,pColor);
        knowsTable=pTable;
    }
    
    
    
    
    @Override
    public void move(Graphics pG){
        if (!this.getVisible()){            
            if (upperEdge()||bottom())this.setDirection(360-this.getDirection());
            else if (leftEdge()||rightEdge())this.setDirection(180-this.getDirection());
            if (this.getDirection()<0)this.setDirection(this.getDirection()+360);
            super.move(pG);
        }
        else {   
            pause(10);
            clear(pG);
        }
    }
    
    public boolean upperEdge(){
        return this.getY()<=knowsTable.getY()+this.getRadius()+1;
    }
    public boolean bottom(){
        return this.getY()+this.getRadius()>=knowsTable.getY()+knowsTable.getHeight()+1;
    }
    
    public boolean rightEdge(){
        return this.getX()+this.getRadius()>=knowsTable.getY()+knowsTable.getWidth()+1;
    }
    
    public boolean leftEdge(){
        return this.getX()-this.getRadius()<=knowsTable.getX()+1;
    }
    
    
}