Monday, July 8, 2013

Ball and Paddle

package com.spconger.BreakoutPaddle;
import acm.graphics.*;
import acm.program.*;
import acm.util.*;

import java.awt.Color;
import java.awt.event.*;
import java.awt.color.*;

public class Program extends GraphicsProgram {
 /**
  * This class is a test for Breakout
  * it sets up the ball and the paddle and
  * gets the ball to interact with the paddle
  * in class 2013-7-8
  */
 
 //these are our constants
 private final int BALLDIAMETER = 20;
 private final int FORMWIDTH=400;
 private final int FORMHEIGHT=600;
 private final int PADDLEWIDTH=60;
 private final int PADDLEHEIGHT=10;
 private final int PADDLEOFFSET=FORMHEIGHT -30;
 private final int BALLSTARTX=FORMWIDTH/2-BALLDIAMETER/2;
 private final int BALLSTARTY=FORMHEIGHT/2-BALLDIAMETER/2;
 
 //class level variables
 private GOval ball;
 private GRect paddle;
 private double ballVX=3;
 private double ballVY;

 public void run(){
  setSize(FORMWIDTH, FORMHEIGHT);
  //call all the methods
  createPaddle();
  addKeyListeners();
  createBall();
  waitForClick();
  moveBall();
 }
 
 //create the paddle
 private void createPaddle(){
  paddle=new GRect(FORMWIDTH/2-PADDLEWIDTH/2, 
    PADDLEOFFSET, PADDLEWIDTH, PADDLEHEIGHT);
  paddle.setFillColor(Color.DARK_GRAY);
  paddle.setFilled(true);
  add(paddle);
  
 }
 public void keyPressed(KeyEvent e){
  //this method moves the paddle
  //and keeping it in form bounds
  double x=paddle.getX();
  double y=paddle.getY();
  
  switch (e.getKeyCode()){
  case KeyEvent.VK_RIGHT:
   if(x <(FORMWIDTH-PADDLEWIDTH)){
    paddle.move(PADDLEWIDTH, 0);
   }
   
   break;
  case KeyEvent.VK_LEFT:
   if (x > 0){
   paddle.move(-PADDLEWIDTH, 0);
   }
   break;
  default:
   break;
  }
 }
 
 private void createBall(){
  //create the ball and give it an initial
  //random y velocity
  RandomGenerator rand = new RandomGenerator();
  ballVY=rand.nextDouble(1.0,3.0);
  ball = new GOval(BALLSTARTX, BALLSTARTY, 
    BALLDIAMETER, BALLDIAMETER);
  ball.setFillColor(Color.BLUE);
  ball.setFilled(true);
  add(ball);
 }
 
 private void moveBall(){
  //this moves the ball and keeps it in bounds
  boolean play=true;
  
  while(play){
   if (ball.getX()>FORMWIDTH-BALLDIAMETER 
     || ball.getX()<=0){
    ballVX=-ballVX;
   }
   if(ball.getY()>=FORMHEIGHT-BALLDIAMETER 
     || ball.getY()<=0){
    ballVY=-ballVY;
   }
   
   //this makes it interact with the paddle,
   //though you should check for all for corners
   if(getElementAt(ball.getX()+ BALLDIAMETER, 
     ball.getY()+BALLDIAMETER)==paddle){
    ballVY=-ballVY;
   }
   
   //if the ball hits the bottom turn over
   if(ball.getY() >= FORMHEIGHT-BALLDIAMETER) {
    play=false;
   }
   ball.move(ballVX, ballVY);
   pause(30);
  }
 }
 
}






No comments:

Post a Comment