import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class ball here. * * @author (your name) * @version (a version number or a date) */ public class Ball extends Actor { private int vSpeed=5; private int hSpeed=5; private Score1 score1; private Score2 score2; public Paddle paddle1; public Paddle2 paddle2; /** * Set speed of the ball. */ public Ball(Score1 pointScore1, Score2 pointScore2, Paddle paddle1, Paddle2 paddle2) { score1 = pointScore1; score2 = pointScore2; paddle1 = paddle1; paddle2 = paddle2; } /** * Do whatever a ball does. */ public void act() { move(); if (checkLeft() == true) { score1.add(1); setLocation(getWorld().getWidth()/2, Greenfoot.getRandomNumber(getWorld().getHeight())); resetPaddle(); Greenfoot.delay(25); } if (checkRight() == true) { score2.add(1); setLocation(getWorld().getWidth()/2, Greenfoot.getRandomNumber(getWorld().getHeight())); resetPaddle(); Greenfoot.delay(25); } } /** * Make the ball move. */ public void move() { setLocation( getX() + hSpeed, getY() + vSpeed ); if (checkTop() == true) { vSpeed = vSpeed * -1; } if (checkBottom() == true) { vSpeed = vSpeed * -1; } if (checkPaddle() == true) { hSpeed = hSpeed * -1; } if (checkPaddle2() == true) { hSpeed = hSpeed * -1; } } public void resetPaddle() { paddle1.setLocation(575, 200); paddle2.setLocation(575, 200); } /** * Check to see if the ball has reached the left side. */ public boolean checkLeft() { int margin = getImage().getWidth()/2; if (getX()-margin < 0){ return true; } return false; } /** * Check to see if the ball has reached the right side. */ public boolean checkRight() { int margin = getImage().getWidth()/2; if (getX()+margin > getWorld().getWidth()){ return true; } return false; } /** * Check to see if the ball has reached the top. */ public boolean checkTop() { int margin = getImage().getWidth()/2; if (getY()-margin < 0){ return true; } return false; } /** * Check to see if the ball has reached the bottom. */ public boolean checkBottom() { int margin = getImage().getWidth()/2; if (getY()+margin > getWorld().getHeight()){ return true; } return false; } /** * Check to see if the the ball has hit a paddle. * If true, bounce off the paddle. */ public boolean checkPaddle() { int margin = getImage().getWidth()/2; if ( getOneObjectAtOffset(0,0,Paddle.class ) !=null) { return true; } return false; } /** * Check to see if the the ball has hit a paddle. * If true, bounce off the paddle. */ public boolean checkPaddle2() { if ( getOneObjectAtOffset(0,0,Paddle2.class ) !=null) { return true; } return false; } }

