Smooth Graphics Java

// Arrange Bricks in Game
//java brick breaker game code without flickering
// added game levels 1,2,3 in the game
//java paddle ball game code
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.TexturePaint;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;

public class BrickInteraction extends JPanel implements ActionListener,MouseMotionListener {

    private static final String[] LEVELS_ONE = new String[]
    {
        "     ",
        "WW   ",
        "     ",
        "W    " };
    private static final String[] LEVELS_TWO = new String[]
    {
        "     ",
        "W   W",
        "     ",
        "W    " };
    private static final String[] LEVELS_THREE = new String[]
            {
              "     ",
              "W    ",
              "     ",
              "W    " };
    private static String[] currentLevel;
    private int ballDimension = 10;
    private int moveX = 1;
    private int moveY = 1;
    static int gameSpeed = 15;
    private ArrayList<Rectangle> brickList = new ArrayList<Rectangle>();
    Rectangle ball = new Rectangle(0,0,ballDimension,ballDimension);
    Rectangle paddle = new Rectangle(290, 240, 40, 10);
    private Graphics2D graphics2D;
 
    TexturePaint texturePaint;
    BufferedImage bufferedImage;
    Rectangle shades;
    Timer timer;
    Container container;
    private String[][] levels = {LEVELS_ONE,LEVELS_TWO,LEVELS_THREE};
    BrickInteraction(Container container) {
        this.container= container;
        bufferedImage = new BufferedImage(5,5,BufferedImage.TYPE_INT_RGB);
        shades = new Rectangle(0, 0, 5, 5);
        texturePaint = new TexturePaint(bufferedImage, shades);
       // constructBricks();
        addMouseMotionListener(this);
      
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        final BrickInteraction game = new BrickInteraction(frame.getContentPane());
        frame.setSize(350, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
        frame.getContentPane().add(game);
     
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.LEADING));
        JButton button = new JButton("start");
     
        buttonPanel.add(button);
        JButton pauseButton = new JButton("pause");
        buttonPanel.add(pauseButton);
        frame.getContentPane().add(buttonPanel,BorderLayout.SOUTH);
     
     
        frame.setLocationRelativeTo(null);
     
        frame.setResizable(false);
        frame.setVisible(true);
        frame.getSize();
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                JButton button = (JButton)e.getSource();
                if(button.getText().equals("start")){
                    button.setText("restart");
                    game.restartGame();
                }
            }
        });
     
        pauseButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JButton button = (JButton)e.getSource();
                if(button.getText().equals("pause")){
                    button.setText("play");
                    game.pauseGame();
                }
                else if(button.getText().equals("play")){
                    button.setText("pause");
                    game.resumeGame();
                }
            }
        });
    }

    public void texture(){
        Graphics2D big = bufferedImage.createGraphics();
        big.setColor(Color.magenta);
        big.fillRect(0, 0, 5, 5);
        big.setColor(Color.lightGray);
        big.fillOval(0, 0, 5, 5);
    }
 
    public void paintBackGround(){
        graphics2D.setColor(Color.BLACK);
        graphics2D.fillRect(0, 0, 350, 400);
        texture();
        graphics2D.setPaint(texturePaint);
        graphics2D.fillRect(0, 251, 400, 200);
     
        graphics2D.setColor(Color.red);
        graphics2D.drawRect(0, 0, 343, 250);
     
    }
 
 
 
 
    public void paintBall(){     
        graphics2D.setColor(Color.BLUE);
        graphics2D.fillOval(ball.x, ball.y, ballDimension, ballDimension);
    }
 
    public void paintBricks(){
        for (Rectangle brick : brickList) {
            graphics2D.fill3DRect(brick.x, brick.y, brick.width, brick.height, true);
        }
    }
 
    public void paintPaddle(){
        graphics2D.setColor(Color.green);
        graphics2D.fill3DRect(paddle.x, paddle.y, paddle.width, paddle.height, true);
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        graphics2D = (Graphics2D) g;
        graphics2D.setRenderingHint(
                RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
     
        paintBackGround();
        paintBricks();
        paintBall();
        paintPaddle();
     
    }

    public void paintGameOver() {
        timer.stop();
        JOptionPane.showMessageDialog(container, "Game Over");
        currentLevel = LEVELS_TWO;
        restartGame();
    }
    public void constructBricks() {
        // starting position of the bricks
        int initialBrickXAxis = 85;
        int initialBrickYAxis = 50;
        // You can specify length and breadth of the bricks here
        int brickBreadth = 30;
        int brickHeight = 10;
        int variableXAxisPosition = initialBrickXAxis;
        int variableYAxisPosition = initialBrickYAxis;

        for (String colBricks : currentLevel) {
            char[] rowBrick = colBricks.toCharArray();
            for (char eachBrick : rowBrick) {
                if (eachBrick == 'W') {
                    brickList.add(new Rectangle(variableXAxisPosition, variableYAxisPosition, brickBreadth,
                            brickHeight));
                    variableXAxisPosition += (brickBreadth + 1);
                } else if (eachBrick == ' ') {
                    variableXAxisPosition += (brickBreadth + 1);
                }
            }
            variableYAxisPosition += (brickHeight + 2);
            variableXAxisPosition = initialBrickXAxis;
        }

    }
 
    public void moveBall(){
     
        ball.x = ball.x + moveX;
        ball.y = ball.y + moveY;
        if(ball.x > (343 - ballDimension) ){
            moveX = -1;
        }
        if(ball.y > (250 - ballDimension)){
            moveY = -1;
        }
     
        if(ball.y < 0){
            moveY = +1;
        }
        if(ball.x < 0 ){
            moveX = +1;
        }
    }
 
    public void whenHitBrick(){
        Iterator<Rectangle> iterator = brickList.iterator();
        int count = 0;
        while (iterator.hasNext()) {
            count++;
            Rectangle brick = (Rectangle) iterator.next();
            Line2D verticalSideRight = new Line2D.Double(ball.x+ballDimension, ball.y+2, ball.x+ballDimension, ball.y+ballDimension -2);
         
            Line2D verticalSideLeft = new Line2D.Double(ball.x, ball.y+2, ball.x, ball.y+ballDimension-2);
            Line2D horizonBottom = new Line2D.Double(ball.x+2, ball.y+ballDimension, ball.x+ballDimension-2, ball.y+ballDimension);
            Line2D horizonTop = new Line2D.Double(ball.x+2, ball.y, ball.x+ballDimension-2, ball.y);
            if(brick.intersectsLine(verticalSideRight)){
               //System.out.println("Rig"+count);
            moveX = -1;
            iterator.remove();
            }else if(brick.intersectsLine(verticalSideLeft)){
                //System.out.println("lef"+count);
            moveX = +1;
            iterator.remove();
            break;
            }
         
            if(brick.intersectsLine(horizonBottom)){
                //System.out.println("bot"+count);
                moveY = -1;
                iterator.remove();
            }else if(brick.intersectsLine(horizonTop)){
                //System.out.println("top"+count);
                moveY = +1;
                if(!brick.equals(null))
                iterator.remove();
            }
        }
        if(brickList.size() <= 0){
            paintGameOver();
        }
     
    }
   boolean gameOver = false;
    public void ballHitPaddle(){
        if(ball.intersects(paddle)){
            moveY = -1;
        }
    }
public void pauseGame(){
    timer.stop();
}
public void resumeGame(){
    timer.start();
}
    @Override
    public void actionPerformed(ActionEvent e) {
        moveBall();
        whenHitBrick();
        ballHitPaddle();
        repaint();
    }
    int levelCount = 0;
    public void restartGame(){
        ball.x = 0;
        ball.y = 0;
        if(levelCount < levels.length){
        currentLevel =    levels[levelCount];
        levelCount++;
        gameSpeed -= 3;
      
        constructBricks();
        timer = new Timer(gameSpeed, this);
        timer.start();
        }
      
      
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        mouseMoved(e);
     
    }

    @Override
    public void mouseMoved(MouseEvent e) {
        paddle.x = (int) e.getPoint().getX();
        repaint();
    }

}
View more...

Brick Breaker , Advanced Collision



//you can restart this game and pause the game. with collision detection.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.TexturePaint;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;

public class BrickInteraction extends JPanel implements ActionListener {

    private static final String[] LEVELS_ONE = new String[]
    { "WWWWW",
      "W   W",
      "W W W",
      "W   W",
      "W W W",
      "W   W",
      "WWWWW" };
    private static final String[] LEVELS_TWO = new String[]
    { "WWWWW",
      " W W ",
      "W W W",
      " W W ",
      "WWWWW" };
    private static final String[] LEVELS_Three = new String[]
            {
              "     ",
              "W    ",
              "     ",
              "WW   " };
    private int ballDimension = 10;
    private int moveX = 1;
    private int moveY = 1;
    static int gameSpeed = 5;
    private ArrayList<Rectangle> brickList = new ArrayList<Rectangle>();
    Rectangle ball = new Rectangle(0,0,ballDimension,ballDimension);
    private Graphics2D graphics2D;
   
    TexturePaint texturePaint;
    BufferedImage bufferedImage;
    Rectangle shades;
    Timer timer;
    Container container;
    BrickInteraction(Container container) {
        this.container= container;
        bufferedImage = new BufferedImage(5,5,BufferedImage.TYPE_INT_RGB);
        shades = new Rectangle(0, 0, 5, 5);
        texturePaint = new TexturePaint(bufferedImage, shades);
        constructBricks();
       
        timer = new Timer(gameSpeed, this);
        timer.start();
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        final BrickInteraction game = new BrickInteraction(frame.getContentPane());
        frame.setSize(350, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
        frame.getContentPane().add(game);
       
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.LEADING));
        JButton button = new JButton("restart");
       
        buttonPanel.add(button);
        JButton pauseButton = new JButton("pause");
        buttonPanel.add(pauseButton);
        frame.getContentPane().add(buttonPanel,BorderLayout.SOUTH);
       
       
        frame.setLocationRelativeTo(null);
       
        frame.setResizable(false);
        frame.setVisible(true);
        frame.getSize();
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                game.restartGame();
            }
        });
       
        pauseButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JButton button = (JButton)e.getSource();
                if(button.getText().equals("pause")){
                    button.setText("play");
                    game.pauseGame();
                }
                else if(button.getText().equals("play")){
                    button.setText("pause");
                    game.resumeGame();
                }
            }
        });
       

    }

    public void texture(){
        Graphics2D big = bufferedImage.createGraphics();
        big.setColor(Color.magenta);
        big.fillRect(0, 0, 5, 5);
        big.setColor(Color.lightGray);
        big.fillOval(0, 0, 5, 5);
    }
   
    public void paintBackGround(){
        graphics2D.setColor(Color.LIGHT_GRAY);
        graphics2D.fillRect(0, 0, 350, 400);
        texture();
        graphics2D.setPaint(texturePaint);
        graphics2D.fillRect(0, 251, 400, 200);
       
        graphics2D.setColor(Color.red);
        graphics2D.drawRect(0, 0, 343, 250);
       
       
    }
   
   
   
   
    public void paintBall(){       
        graphics2D.setColor(Color.BLUE);
        graphics2D.fillOval(ball.x, ball.y, ballDimension, ballDimension);
    }
   
    public void paintBricks(){
        for (Rectangle brick : brickList) {
            graphics2D.fill3DRect(brick.x, brick.y, brick.width, brick.height, true);
        }
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        graphics2D = (Graphics2D) g;
        graphics2D.setRenderingHint(
                RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
       
        paintBackGround();
        paintBricks();
        paintBall();
       
       
    }

    public void constructBricks() {
        // starting position of the bricks
        int initialBrickXAxis = 85;
        int initialBrickYAxis = 50;
        // You can specify length and breadth of the bricks here
        int brickBreadth = 30;
        int brickHeight = 10;
        int variableXAxisPosition = initialBrickXAxis;
        int variableYAxisPosition = initialBrickYAxis;

        for (String colBricks : LEVELS_ONE) {
            char[] rowBrick = colBricks.toCharArray();
            for (char eachBrick : rowBrick) {
                if (eachBrick == 'W') {
                    brickList.add(new Rectangle(variableXAxisPosition, variableYAxisPosition, brickBreadth,
                            brickHeight));
                    variableXAxisPosition += (brickBreadth + 1);
                } else if (eachBrick == ' ') {
                    variableXAxisPosition += (brickBreadth + 1);
                }
            }
            variableYAxisPosition += (brickHeight + 2);
            variableXAxisPosition = initialBrickXAxis;
        }

    }
   
    public void paintGameOver(){
        JOptionPane.showMessageDialog(container,
                "Game Over");
    }
   
   
   
    public void moveBall(){
       
        ball.x = ball.x + moveX;
        ball.y = ball.y + moveY;
        if(ball.x > (343 - ballDimension) ){
            moveX = -1;
        }
        if(ball.y > (250 - ballDimension)){
            moveY = -1;
        }
       
        if(ball.y < 0){
            moveY = +1;
        }
        if(ball.x < 0 ){
            moveX = +1;
        }
    }
   
    public void whenHitBrick(){
        for (Iterator<Rectangle> iterator = brickList.iterator(); iterator.hasNext();) {
            Rectangle brick = (Rectangle) iterator.next();
            Line2D verticalSideRight = new Line2D.Double(ball.x+ballDimension, ball.y+2, ball.x+ballDimension, ball.y+ballDimension -2);
           
            Line2D verticalSideLeft = new Line2D.Double(ball.x, ball.y+2, ball.x, ball.y+ballDimension-2);
            Line2D horizonBottom = new Line2D.Double(ball.x+2, ball.y+ballDimension, ball.x+ballDimension-2, ball.y+ballDimension);
            Line2D horizonTop = new Line2D.Double(ball.x+2, ball.y, ball.x+ballDimension-2, ball.y);
            if(brick.intersectsLine(verticalSideRight)){
               
            moveX = -1;
            iterator.remove();
            }else if(brick.intersectsLine(verticalSideLeft)){
            moveX = +1;
            iterator.remove();
            }
           
            if(brick.intersectsLine(horizonBottom)){
                moveY = -1;
                iterator.remove();
            }else if(brick.intersectsLine(horizonTop)){
                moveY = +1;
                iterator.remove();
            }
        }
        if(brickList.size() <= 0){
            paintGameOver();
            timer.stop();
        }
       
    }
public void pauseGame(){
    timer.stop();
}
public void resumeGame(){
    timer.start();
}
    @Override
    public void actionPerformed(ActionEvent e) {
        moveBall();
        whenHitBrick();
        repaint();
    }
   
    public void restartGame(){
        ball.x = 0;
        ball.y = 0;
        constructBricks();
        timer.start();
    }

}
View more...

Restart and pause in Brick Breaker game



import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.TexturePaint;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;

public class BrickInteraction extends JPanel implements ActionListener {

    private static final String[] LEVELS_ONE = new String[]
    { "WWWWW",
      "W   W",
      "W W W",
      "W   W",
      "WWWWW" };
    private static final String[] LEVELS_TWO = new String[]
    { "WWWWW",
      "     ",
      "W W W",
      "     ",
      "WWWWW" };
    private static final String[] LEVELS_Three = new String[]
            {
              "     ",
              "W    ",
              "     ",
              "WW   " };
    private int ballDimension = 10;
    private int moveX = 1;
    private int moveY = 1;
    static int gameSpeed = 5;
    private ArrayList<Rectangle> brickList = new ArrayList<Rectangle>();
    Rectangle ball = new Rectangle(0,0,ballDimension,ballDimension);
    private Graphics2D graphics2D;
   
    TexturePaint texturePaint;
    BufferedImage bufferedImage;
    Rectangle shades;
    Timer timer;
    Container container;
    BrickInteraction(Container container) {
        this.container= container;
        bufferedImage = new BufferedImage(5,5,BufferedImage.TYPE_INT_RGB);
        shades = new Rectangle(0, 0, 5, 5);
        texturePaint = new TexturePaint(bufferedImage, shades);
        constructBricks();
       
        timer = new Timer(gameSpeed, this);
        timer.start();
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        final BrickInteraction game = new BrickInteraction(frame.getContentPane());
        frame.setSize(350, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
        frame.getContentPane().add(game);
       
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.LEADING));
        JButton button = new JButton("restart");
       
        buttonPanel.add(button);
        JButton pauseButton = new JButton("pause");
        buttonPanel.add(pauseButton);
        frame.getContentPane().add(buttonPanel,BorderLayout.SOUTH);
       
       
        frame.setLocationRelativeTo(null);
       
        frame.setResizable(false);
        frame.setVisible(true);
        frame.getSize();
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                game.restartGame();
            }
        });
       
        pauseButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JButton button = (JButton)e.getSource();
                if(button.getText().equals("pause")){
                    button.setText("play");
                    game.pauseGame();
                }
                else if(button.getText().equals("play")){
                    button.setText("pause");
                    game.resumeGame();
                }
            }
        });
       

    }

    public void texture(){
        Graphics2D big = bufferedImage.createGraphics();
        big.setColor(Color.magenta);
        big.fillRect(0, 0, 5, 5);
        big.setColor(Color.lightGray);
        big.fillOval(0, 0, 5, 5);
    }
   
    public void paintBackGround(){
        graphics2D.setColor(Color.LIGHT_GRAY);
        graphics2D.fillRect(0, 0, 350, 400);
        texture();
        graphics2D.setPaint(texturePaint);
        graphics2D.fillRect(0, 251, 400, 200);
       
        graphics2D.setColor(Color.red);
        graphics2D.drawRect(0, 0, 343, 250);
       
       
    }
   
   
   
   
    public void paintBall(){       
        graphics2D.setColor(Color.BLUE);
        graphics2D.fillOval(ball.x, ball.y, ballDimension, ballDimension);
    }
   
    public void paintBricks(){
        for (Rectangle brick : brickList) {
            graphics2D.fill3DRect(brick.x, brick.y, brick.width, brick.height, true);
        }
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        graphics2D = (Graphics2D) g;
        graphics2D.setRenderingHint(
                RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
       
        paintBackGround();
        paintBricks();
        paintBall();
       
    }

    public void constructBricks() {
        // starting position of the bricks
        int initialBrickXAxis = 85;
        int initialBrickYAxis = 50;
        // You can specify length and breadth of the bricks here
        int brickBreadth = 30;
        int brickHeight = 10;
        int variableXAxisPosition = initialBrickXAxis;
        int variableYAxisPosition = initialBrickYAxis;

        for (String colBricks : LEVELS_ONE) {
            char[] rowBrick = colBricks.toCharArray();
            for (char eachBrick : rowBrick) {
                if (eachBrick == 'W') {
                    brickList.add(new Rectangle(variableXAxisPosition, variableYAxisPosition, brickBreadth,
                            brickHeight));
                    variableXAxisPosition += (brickBreadth + 1);
                } else if (eachBrick == ' ') {
                    variableXAxisPosition += (brickBreadth + 1);
                }
            }
            variableYAxisPosition += (brickHeight + 2);
            variableXAxisPosition = initialBrickXAxis;
        }

    }
   
    public void paintGameOver(){
        JOptionPane.showMessageDialog(container,
                "Game Over");
    }
   
   
   
    public void moveBall(){
       
        ball.x = ball.x + moveX;
        ball.y = ball.y + moveY;
        if(ball.x > (343 - ballDimension) ){
            moveX = -1;
        }
        if(ball.y > (250 - ballDimension)){
            moveY = -1;
        }
       
        if(ball.y < 0){
            moveY = +1;
        }
        if(ball.x < 0 ){
            moveX = +1;
        }
    }
   
    public void whenHitBrick(){
        for (Iterator<Rectangle> iterator = brickList.iterator(); iterator.hasNext();) {
            Rectangle brick = (Rectangle) iterator.next();
            if(brick.intersects(ball)){
                iterator.remove();
            }
        }
        if(brickList.size() <= 0){
           
            paintGameOver();
            timer.stop();
        }
        /*while (iterator.hasNext()) {
            Rectangle brick = (Rectangle) iterator.next();
            if(brick.intersects(ball)){
                iterator.remove();
            }
        }*/
       
    }
public void pauseGame(){
    timer.stop();
}
public void resumeGame(){
    timer.start();
}
    @Override
    public void actionPerformed(ActionEvent e) {
        moveBall();
        whenHitBrick();
        repaint();
    }
   
    public void restartGame(){
        ball.x = 0;
        ball.y = 0;
        constructBricks();
        //timer.setInitialDelay(500);
        timer.start();
    }

}


//Please feel free to comment
View more...

Breaking bricks when ball hits them.



                                      








import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class BrickInteraction extends JPanel implements ActionListener {

    private static final String[] LEVELS_ONE = new String[]
    { "WWWWW",
      "W   W",
      "W W W",
      "W   W",
      "WWWWW" };
    private static final String[] LEVELS_TWO = new String[]
    { "WWWWW",
      "     ",
      "W W W",
      "     ",
      "WWWWW" };
    private int ballDimension = 10;
    private int moveX = 1;
    private int moveY = 1;
    private ArrayList<Rectangle> brickList = new ArrayList<Rectangle>();
    BrickInteraction() {       
        constructBricks();
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        BrickInteraction game = new BrickInteraction();
        JButton restart = new JButton("start");
        frame.setSize(350, 450);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(game);
        frame.add(restart, BorderLayout.SOUTH);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setVisible(true);
        frame.getSize();
        Timer timer = new Timer(20, game);
        timer.setInitialDelay(500);
        timer.start();
       

    }

    public void paintBackGround(Graphics2D g){
        g.setColor(Color.LIGHT_GRAY);
        g.fillRect(0, 0, 350, 450);
        g.setColor(Color.GRAY);
        g.fillRect(0, 251, 450, 200);
        g.setColor(Color.red);
        g.drawRect(0, 0, 343, 250);
       
    }
   
   
    Rectangle ball = new Rectangle(0,0,ballDimension,ballDimension);
    public void paintBall(Graphics2D g){       
        g.setColor(Color.BLUE);
        g.fillOval(ball.x, ball.y, ballDimension, ballDimension);
    }
   
    public void paintBricks(Graphics2D g){
        for (Rectangle brick : brickList) {
            g.fill3DRect(brick.x, brick.y, brick.width, brick.height, true);
        }
    }
   

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(
                RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        paintBackGround(g2d);
        paintBricks(g2d);
        paintBall(g2d);
       
    }

    public void constructBricks() {
       
        // starting position of the bricks
        int initialBrickXAxis = 85;
        int initialBrickYAxis = 50;
        // You can specify length and breadth of the bricks here
        int brickBreadth = 30;
        int brickHeight = 10;
        int variableXAxisPosition = initialBrickXAxis;
        int variableYAxisPosition = initialBrickYAxis;

        for (String colBricks : LEVELS_TWO) {
            char[] rowBrick = colBricks.toCharArray();
            for (char eachBrick : rowBrick) {
                if (eachBrick == 'W') {
                    brickList.add(new Rectangle(variableXAxisPosition, variableYAxisPosition, brickBreadth,
                            brickHeight));
                    variableXAxisPosition += (brickBreadth + 1);
                } else if (eachBrick == ' ') {
                    variableXAxisPosition += (brickBreadth + 1);
                }
            }
            variableYAxisPosition += (brickHeight + 2);
            variableXAxisPosition = initialBrickXAxis;
        }

    }
   
    public void moveBall(){
       
        ball.x = ball.x + moveX;
        ball.y = ball.y + moveY;
        if(ball.x > (343 - ballDimension) ){           
            moveX = -1;
        }
        if(ball.y > (250 - ballDimension)){           
            moveY = -1;
        }
       
        if(ball.y < 0){
            moveY = +1;
        }
        if(ball.x < 0 ){           
            moveX = +1;
        }
    }
   
    public void whenHitBrick(){
        for (Iterator<Rectangle> iterator = brickList.iterator(); iterator.hasNext();) {
            Rectangle brick = (Rectangle) iterator.next();
            if(brick.intersects(ball)){
                iterator.remove();
            }
        }
       
        /*while (iterator.hasNext()) {
            Rectangle brick = (Rectangle) iterator.next();
            if(brick.intersects(ball)){
                iterator.remove();
            }
        }*/
       
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        moveBall();
        whenHitBrick();
        repaint();
    }

}
View more...

Working Bullet Shooting Java Game Source Code

Below is the working code for Bullet Shooting Game developed using Java.
This game project includes 5 java files:





  • Window.java
package balloone_Shooting;
import javax.swing.JFrame;
public class Window {
/**
 * @param args
 */
public static void main(String[] args) {
Combine c = new Combine();
JFrame f = new JFrame("Cloud Shooting");
f.add(c);
f.setResizable(false);
f.setSize(800,700);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
}
}


  • Paddle.java
package balloone_Shooting;
import java.awt.Image;
import javax.swing.ImageIcon;

public class Paddle {
private int x, y;
private boolean left = false, right = false;;

Image volcano;
ImageIcon big = new ImageIcon(this.getClass()
.getResource("volcano_big.png"));
ImageIcon small = new ImageIcon(this.getClass().getResource(
"volcano_small.png"));
public Paddle() {
x = 395;
y = 630;
volcano = small.getImage();
}
public void setLeft(boolean left) {
this.left = left;
}
public void setRight(boolean right) {
this.right = right;
}
public boolean getLeft() {
return left;
}
public boolean getRight() {
return right;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Image getImage() {
return volcano;
}
public void left() {
x -= 2;
if (x <= 0)
x = 0;
}
public void right() {
x += 2;
if (x >= 706)
x = 706;
}
public void volcano_Pressed() {
y = 630;
volcano = small.getImage();
}
public void volcano_Release() {
y = 620;
volcano = big.getImage();
}
}

  • FireBall.java
package balloone_Shooting;

import java.awt.Image;
import java.awt.Rectangle;
import javax.swing.ImageIcon;

public class FireBall {

private int x, y;
private Image image;
boolean visible;
private int width, height;
private int dy;

public FireBall(int x) {
dy = 20;
y = 605;
ImageIcon ii = new ImageIcon(this.getClass()
.getResource("fireball.png"));
image = ii.getImage();
visible = true;
width = image.getWidth(null);
height = image.getHeight(null);
this.x = x;
}

public Image getImage() {
return image;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Rectangle getBounds() {
return new Rectangle(x, y, width, height);
}
public void move() {
y = y - dy;
}
}

  • Cloudball.java
package balloone_Shooting;

import java.awt.Image;
import java.awt.Rectangle;
import javax.swing.ImageIcon;

public class Cloudball {
private int x, y, width, height;
private Image img;

public Cloudball(int x) {
ImageIcon ic = new ImageIcon(this.getClass().getResource(
"cloudball.png"));
img = ic.getImage();
this.x = x;
y = 0;
width = img.getWidth(null);
height = img.getHeight(null);
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void move() {
y++;
}
public Image getImage()
{
return img;
}
public Rectangle getBounds() {
return new Rectangle(x, y, width, height);
}
}



    • Combine.java
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Rectangle;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.util.Random;
    import javax.swing.*;

    public class Combine extends JPanel implements ActionListener {
    Image back_Ground;
    Timer timer;
    Paddle paddle;
    ArrayList<FireBall> fireballs_array;
    ArrayList<Cloudball> cloud_array;
    FireBall fireBall;
    private boolean fire;

    public boolean isFire() {
    return fire;
    }
    public void setFire(boolean fire) {
    this.fire = fire;
    }
    public Combine() {
    addKeyListener(new Action());
    ImageIcon ii = new ImageIcon(this.getClass().getResource(
    "skybackground.png"));
    fireballs_array = new ArrayList<FireBall>();
    cloud_array = new ArrayList<Cloudball>();

    paddle = new Paddle();
    setFocusable(true);
    back_Ground = ii.getImage();
    timer = new Timer(70, this);
    timer.start();
    Thread startCloud = new Thread(new Runnable() {
    public void run() {
    while (true)
    try {
    cloudBalls();
    Thread.sleep(1000 * 2);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    });
    startCloud.start();
    Thread startFire = new Thread(new Runnable() {
    public void run() {
    while (true)
    try {
    //System.out.println("fire " + fire);
    if (fire == true) {
    fire();
    }
    Thread.sleep(200);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    });
    startFire.start();
    Thread movePaddle = new Thread(new Runnable() {
    public void run() {
    while (true)
    try {
    if (paddle.getLeft() == true) {
    paddle.left();
    }
    if (paddle.getRight() == true) {
    paddle.right();
    }
    Thread.sleep(9);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    });
    movePaddle.start();
    }
    public void actionPerformed(ActionEvent arg0) {
    for (int k = 0; k < fireballs_array.size(); k++) {
    fireballs_array.get(k).move();
    if (fireballs_array.get(k).getY() < 1) {
    fireballs_array.remove(k);
    }
    }
    for (int i = 0; i < cloud_array.size(); i++) {
    cloud_array.get(i).move();
    if (cloud_array.get(i).getY() > 600) {
    cloud_array.remove(i);
    }
    }
    Thread collide = new Thread(new Runnable() {
    public void run() {
    collision();
    }
    });
    collide.start();
    repaint();
    }
    public void paintComponent(Graphics g) {
    g.drawImage(back_Ground, 0, 0, null);
    g.drawImage(paddle.getImage(), paddle.getX(), paddle.getY(), null);
    if (!cloud_array.isEmpty()) {
    for (int i = 0; i < cloud_array.size(); i++) {
    g.drawImage(cloud_array.get(i).getImage(), cloud_array.get(i)
    .getX(), cloud_array.get(i).getY(), null);
    }
    }
    if (!fireballs_array.isEmpty()) {
    for (int k = 0; k < fireballs_array.size(); k++) {
    g.drawImage(fireballs_array.get(k).getImage(), fireballs_array
    .get(k).getX(), fireballs_array.get(k).getY(), null);
    }
    }
    }
    public void cloudBalls() {
    Random rn = new Random();
    int ran = rn.nextInt(730);
    Cloudball ball = new Cloudball(ran);
    cloud_array.add(ball);
    }
    public void fire() {
    fireBall = new FireBall(paddle.getX() + 35);
    // fireBall.setY(20);
    fireballs_array.add(fireBall);
    }
    public void collision() {
    for (int k = 0; k < fireballs_array.size(); k++) {
    for (int j = 0; j < cloud_array.size(); j++) {
    Rectangle r1;
    if(!fireballs_array.isEmpty()){
     r1 = fireballs_array.get(k).getBounds();
    Rectangle r2 = cloud_array.get(j).getBounds();
    if (r1.intersects(r2)) {
    fireballs_array.remove(k);
    cloud_array.remove(j);
    }
    }
    }
    }
    }
    private class Action extends KeyAdapter {
    public void keyPressed(KeyEvent e) {
    paddle.volcano_Pressed();
    int keyCode = e.getKeyCode();
    if (keyCode == KeyEvent.VK_SPACE) {
    fire = true;
    }
    if (keyCode == KeyEvent.VK_LEFT) {
    paddle.setLeft(true);
    }
    if (keyCode == KeyEvent.VK_RIGHT) {
    paddle.setRight(true);
    }
    }
    public void keyReleased(KeyEvent e) {
    paddle.volcano_Release();
    if (e.getKeyCode() == KeyEvent.VK_SPACE) {
    fire = false;
    }
    if (e.getKeyCode() == KeyEvent.VK_LEFT) {
    paddle.setLeft(false);
    }
    if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
    paddle.setRight(false);
    }
    }
    }
    }

    Download source code HERE
    View more...

    KeyListener example in java

    KeyListener Example


    /*
    *its the first class
    *save is as Car.java
    /*
    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.event.KeyEvent;

    public class Car {

    static int CARWIDTH = 40;
    static int CARLENGTH = 70;
    int x = Game.WIDTH/2 - CARWIDTH/2;
    int y = Game.HEIGHT - 105;
    int dx = 0;
    int dy = 0;
    private Game game;

    public Car(Game game){
    this.game = game;
    }

    public void paint(Graphics2D g2d){
    g2d.setColor(Color.blue);
    g2d.fillRect(x, y, CARWIDTH, CARLENGTH);
    }

    public void move(){

    if(x+dx > 0 && x+dx < Game.WIDTH-56) x = x+dx;
    if(y+dy > 0 && y+dy < Game.HEIGHT-105) y = y+dy;

    }

    public void keyPressed(KeyEvent e){
    if(e.getKeyCode() == KeyEvent.VK_LEFT) dx = -1;
    if(e.getKeyCode() == KeyEvent.VK_RIGHT) dx = 1;
    if(e.getKeyCode() == KeyEvent.VK_UP) dy = -1;
    if(e.getKeyCode() == KeyEvent.VK_DOWN) dy = 1;
    }

    public void keyReleased(){
    dx = 0;
    dy = 0;
    }

    }
    //////////////EnD of First Class////////////////

    /*
    *its the SECOND class
    *save is as Game.java
    /*


    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;

    import javax.swing.JFrame;
    import javax.swing.JPanel;

    @SuppressWarnings("serial")
    public class Game extends JPanel{

    static int WIDTH = 500;
    static int HEIGHT = 700;
    Car car = new Car(this);


    public Game(){
    addKeyListener(new KeyListener() {

    @Override
    public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

    }

    @Override
    public void keyReleased(KeyEvent e) {
    car.keyReleased();

    }

    @Override
    public void keyPressed(KeyEvent e) {
    car.keyPressed(e);

    }
    });
    setFocusable(true);
    }

    private void move(){
    car.move();
    }

    public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D)g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
    car.paint(g2d);
    }



    public static void main(String args[]) throws InterruptedException{
    Game game = new Game();
    JFrame frame = new JFrame("Car Game");
    frame.add(game);
    frame.getContentPane().setBackground(Color.white);
    frame.setSize(WIDTH, HEIGHT);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    while(true){
    game.move();
    game.repaint();
    Thread.sleep(1);
    }
    }


    }
    ////////////////////EnD of Second Class////////////////////////////

    View more...