Java Code
/* Breakout - Part 2
* Get the ball moving and knocking out blocks
* has flicker, ball update problems
*/
import java.awt.*;
import javax.swing.*;
import java.util.*;
import java.awt.event.*;
public class BreakoutPart2 extends JApplet implements Runnable
{
ArrayList blocks;
int width, height; // dimensions of applet
int numBlocks; // number of blocks horizontally
int numRows; // number of rows - 1 least difficult, 5 more difficult
// Part II
Thread thread;
Ball ball;
public void init( )
{
resize(600, 400 );
numBlocks = 10;
numRows = 3;
blocks = new ArrayList( );
width = getWidth( );
height = getHeight( );
buildBlocks( );
// PART II
ball = new Ball( 50, 120, 15, 5, width, height );
thread = new Thread(this);
thread.start( );
}
public void buildBlocks( )
{
int sizeOfBlock = width / numBlocks;
int heightOfBlock = 15;
for( int rows=0; rows<width; rows += sizeOfBlock )
for( int cols=0; cols<numRows*heightOfBlock; cols += heightOfBlock )
{
Rectangle r = new Rectangle( rows,80+cols, sizeOfBlock-2, heightOfBlock-2 );
blocks.add(r);
}
}
public void update( Graphics g )
{
paint(g);
}
public void paint( Graphics g )
{
g.clearRect(0,0,width,height); // clear screen
ball.paint( getGraphics( ) ); // paint ball
g.setColor( Color.RED );
for (int i=0; i<blocks.size( ); i++ ) // color remaining blocks
{
Rectangle r = (Rectangle )blocks.get(i);
g.fillRect( r.x, r.y, r.width, r.height );
}
g.setColor( Color.BLACK );
}
public void run( )
{
while( true )
{
ball.move( );
checkForCollision( );
repaint( );
try {
Thread.sleep(15);
}catch( Exception ex ) { }
}
}
public void checkForCollision( )
{
Rectangle ballR = new Rectangle( ball.x, ball.y, ball.size, ball.size);
for( int i=0; i<blocks.size( ); i++ )
{
Rectangle r = (Rectangle )blocks.get(i);
if ( r.intersects( ballR ) )
{
blocks.remove(r);
getGraphics( ).clearRect(r.x, r.y, r.width, r.height);
ball.dirX = -1 * ball.dirX;
ball.dirY = -1 * ball.dirY;
return;
}
}
}
}