Hi everybody. I am new to this site and am sure you guys could help me. I am currently writing a pool game using eclipse and need to create an array of objects.I have two balls placed individually onto the screen but I'm not certain how to write an array of objects and place them on the screen in different positions and colours. I must then use the mouseEvent() method to strike the white ball. Here is the code I have written so far. Any help would be greatly appreciated as I have hit a rut. If there are any other suggestions as to fix the code I would gratefully welcome them too.

Thanks in advance.

import java.awt.*;

/**Ball class which contains the code for creating the balls and setting the
* boundaries of the screen.
* @author Steve
*
*/
public class Ball {

/**integer which declares the x and y starting positions of the cue ball
 * and the radius of both balls on the table.
 */
private int x = 200, y = 425, radius = 10; 

//double which is used for a change in the x value.
 private double deltaX = 125;

//double which is used for a change in the y value.
private double deltaY = 125;

/**double which declares the amount of energy lost when the ball makes
 * contact with the cushion.
 */
private double energyLoss = .65;

//
//private double deltaTime = .2;

/**double which declares the friction applied to the balls when traveling
 * along the table.
 */
private double friction = .9;

/**double which declares a minimum velocity below which the balls will
 * come to a stop.
 */
private double minVelocity = 0.01;

//boolean which sets the ball to stopped when the program begins.
private boolean stopped = false;

/**boolean which sets the ball to moving when the ball is traveling
 * around the table. Set to false when the program begins.
 */
private boolean moving = false;

//Ball constructor
public Ball() {

}

/**Ball constructor for the second ball which allows the ball to be positioned 
 * differently from the first ball.
 */
public Ball(int i, int j) {

    x = i;
    y = j;

}

//get constructor for radius variable.
public int getRadius(){

    return radius;

}

//set constructor for radius variable.
public void setRadius(int radius) {

    this.radius = radius;

}

//get constructor for x variable.
public int getX() {

    return x;

}

//set constructor for x variable.
public void setX(int x) {

    this.x = x;

}

//get constructor for y variable.
public int getY() {

    return y;

}

//set constructor for y variable.
public void setY(int y) {

    this.y = y;

}

//get constructor for deltaX variable.
public double getDeltaX() {

    return deltaX;

}

//set constructor for deltaX variable.
public void setDeltaX(double deltaX) {

    this.deltaX = deltaX;

}

//get constructor for deltaY variable.
public double getDeltaY() {

    return deltaY;

}

//set constructor for deltaY variable.
public void setDeltaY(double deltaY) {

    this.deltaY = deltaY;

}

//get constructor for energyLoss variable.
public double getEnergyLoss() {

    return energyLoss;

}

//set constructor for energyLoss variable.
public void setEnergyLoss(double energyLoss) {

    this.energyLoss = energyLoss;

}

/*// get constructor for deltaTime variable.
public double getDeltaTime() {

    return deltaTime;

}*/

/*//set constructor for deltaTime variable.
public void setDeltaTime(double deltaTime) {

    this.deltaTime = deltaTime;

}*/

//get constructor for friction variable.
public double getFriction() {

    return friction;

}

//set constructor for friction variable.
public void setFriction(double friction) {

    this.friction = friction;

}

//get constructor for minVelocity variable.
public double getMinVelocity() {

    return minVelocity;

}

//set constructor for minVelocity variable.
public void setMinVelocity(double minVelocity) {

    this.minVelocity = minVelocity;

}

//is constructor for stopped variable.
public boolean isStopped() {

    return stopped;

}

//set constructor for stopped variable.
public void setStopped(boolean stopped) {

    this.stopped = stopped;

}

//is constructor for moving variable.
public boolean isMoving() {

    return moving;

}

//set constructor for moving variable.
public void setMoving(boolean moving) {

    this.moving = moving;

}

/**update method which uses the PoolHustler class in its parameters and
 * contains the code for keeping the ball within the boundaries of the window
 * rebounding the ball each time it connects with a cushion.
 */
public void update(PoolHustler ph){

    //sets moving to true.
    moving = true;

    /**if statement which adds the x and deltaX values and checks to see whether the
     * total is greater than the width of the window minus the radius value - 1.
     * Stops the ball right at the border using minus radius minus 1
     */
    if(x + deltaX > ph.getWidth() - radius - 1){

        /**x is equal to the width of the applet minus radius minus 1. Minus 1 is used 
         * to ensure the pixel next to the wall still appears within the window.
         */
        x = ph.getWidth() - radius - 1;

        //when the ball hits the side walls it will lose the energy declared in energyLoss
        deltaX *= energyLoss;

        // makes the deltaX negative so that the ball bounces off the right wall.
        deltaX = - deltaX;

    }

    /**else if statement which checks to see whether x plus deltaX is less than
     * 0 plus the radius on the left side of the window. 
     */
    else if(x + deltaX < 0 + radius){

        /**if it is then x is equal to 0 plus the radius and will stop the ball at the
         * cushion
         */
        x = 0 + radius;

        //makes the deltaX negative so that the ball bounces off the left wall.
        deltaX = - deltaX;

    }

    //else statement which runs if neither the two previous if statements are true.
    else {

        /**if x plus deltaX is less than the width of the applet then the ball continues 
         * to move
         */
        x += deltaX;

        //multiplies the deltaX value by the friction value to bring balls to a halt.
        deltaX *= friction;

        /**if statement which uses the absolute value in the Math class to check that
         * the deltaX value is less than .8. 
         */
        if(Math.abs(deltaX) < .8){

            //if the statement is true then deltaX is set to 0.
            deltaX = 0;

        }

    }

    /**if statement which adds the y and deltaY values and checks to see whether the
     * total is greater than the height of the window minus the radius value - 1.
     * Stops the ball right at the border using minus radius minus 1
     */
    if(y > ph.getHeight() - radius - 1){

        /**y is equal to the height of the applet minus radius minus 1. Minus 1 is used 
         * to ensure the pixel next to the wall still appears within the window.
         */
        y = ph.getHeight() - radius - 1;

        //when the ball hits the top and bottom walls it will lose the energy declared in energyLoss
        deltaY *= energyLoss;

        // makes the deltaY negative so that the ball bounces off the bottom wall.
        deltaY = - deltaY;

    }

    /**else if statement which checks to see whether Y plus deltaY is less than
     * 0 plus the radius on the top side of the window. 
     */
    else if(y + deltaY < 0 + radius){

        /**if it is then y is equal to 0 plus the radius and will stop the ball at the
         * cushion
         */
        y = 0 + radius;

        // makes the deltaY negative so that the ball bounces off the bottom wall.
        deltaY = - deltaY;

    }

    //else statement which runs if neither the two previous if statements are true.
    else{

        /**if y plus deltaY is less than the width of the applet then the ball continues 
         * to move
         */
        y += deltaY;

        //multiplies the deltaX value by the friction value to bring balls to a halt.
        deltaY *= friction;

        /**if statement which uses the absolute value in the Math class to check that
         * the deltaY value is less than .8. 
         */
        if(Math.abs(deltaY) < .8){

            //if the statement is true then deltaY is set to 0.
            deltaY = 0;

        }

    }

    /**if statement which checks to see whether the deltaX value is greater than the negative minVelocity value,
     * less than minVelocity, deltaY greater than the negative minVelocity and less than the minVelocity value.
     */
    if((deltaX > - minVelocity) && (deltaX < minVelocity) && (deltaY > - minVelocity) && (deltaY < minVelocity)){

        //if the statement is true then stopped becomes true.
        stopped = true;

        //moving becomes false.
        moving = false;

        //deltaX changes to 0.
        deltaX = 0;

        //deltaY changes to 0
        deltaY = 0;

    }

}

/**paint method with object Graphics and names the variable g paints all
 * the graphics to the applet.
 */
public void paint(Graphics g){


    /*g.setColor(Color.WHITE);
    g.fillOval(x - radius, y - radius, radius * 2, radius * 2);*/

}

/**display method which uses the same parameter and variable as paint
 * plus the parameter Color with the variable colour. 
 */
public void display(Graphics g, Color colour){

    //setColor() method which sets the colour of the line to black
    g.setColor(Color.BLACK);

    /**drawLine() method which draws the line on the table using the
     * starting x and y coordinates and the ending x and y coordinates.
     */
    g.drawLine(0, 425, 400, 425);

    /**drawArc method which draws the arc on the table and positions it
     * appropriately on the line in the right position. It contains the
     * parameters of the starting x and y coordinates, the width and height
     * size and the starting angle and the arc angle.
     */
    g.drawArc(100, 335, 180, 180, 180, 180);

    /**setColor method which uses the parameter colour declared in the
     * display method parameter and used in the PoolHustler class. 
     */
    g.setColor(colour);

    /**fills a circle determining its position by using the declared x and y
     * coordinates and its size by using the radius for both width and height.
     * The x and y coordinates subtract the radius value and the width and height
     * values are multiplied by 2 so that the circle is painted from the centre
     * out thus giving the diameter which is double the radius. 
     */
    g.fillOval(x - radius, y - radius, radius * 2, radius * 2);

}

}

import java.applet.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;

/**class which extends applet therefore eliminating the need for a main method to run the program.
* also implements Runnable which adds the run method to the class.
* @author Steve
*
*/
public class PoolHustler extends Applet implements Runnable, MouseListener, MouseMotionListener{

// Image which passes in an image to be copied.
private Image i;

//Graphics which passes in graphics to be copied.
private Graphics doubleBuffer;

//creates two new instances of the ball class.
Ball b, b2;

//creates a new instance of the Vector2 class.
Vector2 collision;

int mouseDrag = 0;

//initialise method which is called the very first time the applet is called upon.
public void init(){

    //sets the size of the window giving it a width and height.
    setSize(400, 600);

    //sets the background colour of the window.
    setBackground(Color.GREEN);

    //adds the Mouse Listener to the window on running the program the very first time.
    addMouseListener(this);

    //adds the Mouse Motion listener to the window on running the program the very first time.
    addMouseMotionListener(this);

}

//start method is called every time the applet is started. 
public void start(){

    //initialises the first instance of the Ball class using the defined methods.
    b = new Ball();

    /**initialises the second instance of the Ball class using the defined methods
     * however changing the starting coordinates of the second ball.
     */
    b2 = new Ball(200, 100);

    //initialises an instance of the Vector2 class.
    collision = new Vector2();

    /**Threads allow multiple events to occur at the same time.
     * Thread declares a new thread which uses the parameter 'this' to use
     * the run method in the class. 
     */
    Thread thread = new Thread(this);

    //thread.start which begins the thread when the program starts.
    thread.start();

    /*//creates an instance of the Vector class with initial vector size of (2,2)
    Vector v = new Vector(2,2);

    //for loop for 20 entries.
    for(int i = 1; i <= 20; i++){

    //inserts an object using the addElement method.
    v.addElement(new Ball(+ i,i));

    }

    //prints out the element in the given number.
    System.out.println("Element: " + v.elementAt(0));*/

}

//run method which contains the code needed to run the applet.
public void run() {

    //infinite loop which will always be true and loops through and repaints the canvas 60 times a second.
    while(true){

        /**calls the update method in the Ball class which contains the code for moving
         * the ball and rebounding off the cushions.
         */
        b.update(this);
        b2.update(this);

        /**calls the update method in the Vector2 class which contains the code for collisions between
         * the balls.
         */
        collision.update(this, b, b2);

        /**called 60 times a second initially goes to the update method then clears the 
         * screen and calls the paint method. 
         */
        repaint();

        /**A try and catch statement which asks the thread to try and sleep. If it fails
         * to do so then an exception occurs and the catch statement implemented.
         */
        try{

            /**Thread.sleep() method which refers to the Thread class and
             * defines the frame rate of the game by dividing 1000 by 60.
             * The Thread.sleep() is used to allow the program to reset so
             * that the program doesn't crash. 
             */
            Thread.sleep(20);

        }

        //catches the exception if the program does not sleep for 20ms.
        catch(InterruptedException e){

            //If an error occurs the error is printed to the stack trace in the debugger.
            e.printStackTrace();

        }

    }



}

/**Update method which copies the image currently on the screen and replaces the clear 
 * screen with the copied image so when the paint method is called it paints on top of 
 * the copied image.  
 */
public void update(Graphics g) {

    /**an if statement which when a blank screen occurs replaces the blank screen with the
     * image on the screen originally.
     */
    if(i == null){

        //creates an image which sets the width and height the same as the applet.
        i = createImage(this.getSize().width, this.getSize().height);

        //sets the graphics to the image which has been created.
        doubleBuffer = i.getGraphics();

    }

    //sets colour to the current background colour.
    doubleBuffer.setColor(getBackground());

    /**fills the rectangle from the top left x and y coordinates and sets its
     * its width and height to that of the set size of the window.
     */
    doubleBuffer.fillRect(0, 0, this.getSize().width, this.getSize().height);

    //sets the colour to the foreground colour when used.
    doubleBuffer.setColor(getForeground());

    //calls the paint method and passes in the doubleBuffer image.
    paint(doubleBuffer);

    /**g refers to the Graphics parameter passed into the Update method draws
     * the i which was set up and places it at the starting point 0 for both
     * x and y coordinates. Image observer uses 'this'. 
     */
    g.drawImage(i, 0, 0, this);

}

/**paint method with object Graphics and names the variable g paints all
 * the graphics to the applet.
 */
public void paint(Graphics g) {

    //calls the display method in the Ball class and sets the colour of ball one to white.
    b.display(g, Color.WHITE);

    //calls the display method in the Ball class and sets the colour of ball two to Black.
    b2.display(g, Color.BLACK);

    //calls the paint method from the Vector2 class.
    collision.paint(g);

}

public void mouseDragged(MouseEvent e) {



}

public void mouseMoved(MouseEvent e) {


}

public void mouseClicked(MouseEvent e) {


}

public void mouseEntered(MouseEvent e) {


}

public void mouseExited(MouseEvent e) {


}

public void mousePressed(MouseEvent e) {

    mouseDrag = 1;

}

public void mouseReleased(MouseEvent e) {



}

}

import java.awt.*;

//Vector class which contains the code for performing the collisions between the balls
public class Vector2 {

/**paint method with object Graphics and names the variable g paints all
 * the graphics to the applet.
 */
public void paint(Graphics g) {


}

//Update method which passes in references for the two balls and the PoolHustler class.
public void update(PoolHustler ph, Ball b, Ball b2) {

    //calls the check collision method into the update method. Passes in ball details.
    checkForCollision(b, b2);
}

/**checkForCollision method which passes in references to the two ball objects and adds
 * which sets up integers for each ball
 */
private void checkForCollision(Ball b, Ball b2) {

    //integer which passes in the object b and returns the x value of b in the Ball class.
    int ballX = b.getX();

    //integer which passes in the object b and returns the y value of b in the Ball class.
    int ballY = b.getY();

    //integer which passes in the object b and returns the radius value of b in the Ball class.
    int radiusb = b.getRadius();

    //integer which passes in the object b2 and returns the x value of b2 in the Ball class.
    int ball2X = b2.getX();

    //integer which passes in the object b2 and returns the y value of b2 in the Ball class.
    int ball2Y = b2.getY();

    //integer which passes in the object b2 and returns the radius value of b2 in the Ball class.
    int radiusb2 = b2.getRadius();

    //integer called a which is equal to the x position of ball two minus the x position of ball one
    int a = ball2X - ballX;

    //integer called bb which is equal to the y position of ball two minus the y position of ball one
    int bb = ball2Y  - ballY;

    //integer collide which is equal to the radius of ball two plus the radius of ball 1.
    int collide = radiusb2 + radiusb;

    /*int a1 = ballX - ball2X;
    int bb1 = ballY = ball2Y;
    int collide1 = radiusb + radiusb2;*/

    //distance between object centres using the square root method from the Math class.
    double c = Math.sqrt((double) (a * a) + (double) (bb * bb));

    /**if statement which checks to see if the distance between the centres of the balls
     * is less than the sum of radiusb plus radiusb2.
     */
    if (c < collide){

        //performs the commands defined in the perfomAction method on both b and b2 objects.
        performAction(b, b2);

    }

}

    //performAction method which passes in the two objects from the Ball class and is called in the if statement.
    private void performAction(Ball b, Ball b2) {

        //sets the newDy of b which is the reverse of the current deltaY for b moving the ball in the opposite direction. 
        double newDY = b.getDeltaY() * - 1;

        //sets the current deltaY to the newDY of b object.
        b.setDeltaY(newDY);

        //sets the newDy2 of b2 which is the reverse of the current deltaY for b2 moving the ball in the opposite direction. 
        double newDY2 = b2.getDeltaY() * - 1;

        //sets the current deltaY to the newDY of b2 object.
        b2.setDeltaY(newDY2);

    }

}

Recommended Answers

All 2 Replies

Put the Ball objects into an arraylist and change the code that refers to the 2 individual Ball objects to use a loop to get the objects one at a time from the arraylist.

Thanks for the information. Got that working. Thank you very much.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.