Showing posts with label Brick Game. Show all posts
Showing posts with label Brick Game. Show all posts

27 May 2016

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();
    }

}

13 July 2014

How to paddle in brick breaker

Simple Paddle in Brick Breaker




Code for simple paddle in java brick breaker game

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

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

import test1.BallBreaker;



public class Bat extends JPanel{


private int x = 140;

private int y = 240;

int width = 30;

int height = 10;
public Bat(){
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent evt) {
moveIt(evt);
}
});
setFocusable(true);
}

public void paint(Graphics g)
{
/*
*
* As we are extending JPanel,
* we need to paint background with some color first
* Note: if we extend Canvas class than we need not
* paint back ground. we can directly draw peddle
*/
g.setColor(Color.LIGHT_GRAY);//paint background with light gray
g.fillRect(0, 0, 350, 450);//screen dimensions
g.setColor(Color.blue);//change color value from gray to blue
g.drawRect(x, y, width, height);
g.fillRect(x, y, width, height);//fill blue color to paddle

/*
* you can uncomment below two lines to see styles of peddle
*/
// g.fill3DRect(x, y+40, width, height, false);

// g.fill3DRect(x, y+80, width, height, true);
}
protected void moveIt(KeyEvent evt) {////finds which key is pressed eighter left of right
if (x < 3) {
x = 3;
} else if (x > 290) {
x = 290;
}

switch (evt.getKeyCode()) {
case KeyEvent.VK_LEFT:
x -= 5;
break;
case KeyEvent.VK_RIGHT:
x += 5;
break;
}

repaint();
}

//public int getX() {
// return x;
//}
//
//public void setX(int x) {
// this.x = x;
//}
//
//public int getY() {
// return y;
//}
//
//public void setY(int y) {
// this.y = y;
//}

public static void main(String[] args) {
Bat bat = new Bat();
JFrame jf = new JFrame("game");
jf.add(bat);
jf.setSize(350,450);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


}


}

06 December 2012

Brick Breaker java game source code


Brickbreaker-game


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

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

public class BrickBreaker extends JPanel implements KeyListener, ActionListener, Runnable {
private static final long serialVersionUID = 1L;
// movement keys..
private static boolean right = false;
private static boolean left = false;

private static final int brickBreadth = 30;
private static final int brickHeight = 20;
// variables declaration for brick...............................
// ===============================================================
// declaring ball, paddle,bricks
private Rectangle Ball;//
private Rectangle Bat;//
private Rectangle[] Brick;
private Rectangle background = new Rectangle(0, 0, 350, 450);

//reverses......==>
private int movex = -1;
private int movey = -1;
private boolean ballFallDown = false;
private boolean bricksOver = false;
private int count = 0;
private String status;
private JButton button;

private static enum STATUS {
START, PAUSE, RESUME, STOP
}

private static boolean PAUSE = false;
private static boolean RUNNING = false;

BrickBreaker() {
initializeVariables();
JFrame frame = new JFrame();
button = new JButton(STATUS.START.name());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// using this as parent layout exists (JFrame)
this.setPreferredSize(new Dimension(background.width, background.height));
frame.getContentPane().add(this);
frame.pack();

frame.add(button, BorderLayout.SOUTH);
// frame.setLocationRelativeTo(null);
// frame.setResizable(false);
frame.setVisible(true);

button.addActionListener(this);

this.addKeyListener(this);
this.setFocusable(true);
}

public static void main(String[] args) {
new BrickBreaker();

}

// declaring ball, paddle,bricks

public void paint(Graphics g) {
g.setColor(Color.LIGHT_GRAY);
g.fillRect(background.x, background.y, background.width, background.height);
g.setColor(Color.blue);
g.fillOval(Ball.x, Ball.y, Ball.width, Ball.height);
g.setColor(Color.green);
g.fill3DRect(Bat.x, Bat.y, Bat.width, Bat.height, true);

// this will paint below the peddle
g.setColor(Color.GRAY);
g.fillRect(0, 251, background.width, 200);

// this will draw border line
g.setColor(Color.RED);
g.drawRect(0, 0, background.width - 1, 250);
for (int i = 0; i < Brick.length; i++) {
if (Brick[i] != null) {
g.fill3DRect(Brick[i].x, Brick[i].y, Brick[i].width, Brick[i].height, true);
}
}

if (ballFallDown == true || bricksOver == true) {
Font f = new Font("Arial", Font.BOLD, 20);
g.setFont(f);
g.drawString(status, 70, 120);
ballFallDown = false;
bricksOver = false;
}

}

// /...Game Loop

public void run() {

// == ball reverses when touches the brick=======
//ballFallDown == false && bricksOver == false
while (RUNNING) {
if (PAUSE) {
sleep();
continue;
}

//   if(gameOver == true){return;}
for (int i = 0; i < Brick.length; i++) {
if (Brick[i] != null) {
if (Brick[i].intersects(Ball)) {
Brick[i] = null;
// movex = -movex;
movey = -movey;
count++;
} // end of 2nd if..
} // end of 1st if..
} // end of for loop..

// /////////// =================================

if (count == Brick.length) {// check if ball hits all bricks
bricksOver = true;
status = "YOU WON THE GAME";
repaint();
}
// /////////// =================================
repaint();
Ball.x += movex;
Ball.y += movey;

if (left == true) {

Bat.x -= 3;
right = false;
}
if (right == true) {
Bat.x += 3;
left = false;
}
if (Bat.x <= 4) {
Bat.x = 4;
} else if (Bat.x >= 298) {
Bat.x = 298;
}
// /===== Ball reverses when strikes the bat
if (Ball.intersects(Bat)) {
movey = -movey;
// if(Ball.y + Ball.width >=Bat.y)
}
// //=====================================
// ....ball reverses when touches left and right boundary
if (Ball.x <= 0 || background.width - Ball.width <= Ball.x) {
movex = -movex;
} // if ends here
if (Ball.y <= 0) {// ////////////////|| bally + Ball.height >= 250
movey = -movey;
} // if ends here.....
if (Ball.y >= 250) {// when ball falls below bat game is over...
ballFallDown = true;
status = "YOU LOST THE GAME";
repaint();
button.setText(STATUS.START.toString());
break;
}

sleep();
} // while loop ends here

}
private void sleep() {
try {
Thread.sleep(10);
} catch (Exception ex) {
} // try catch ends here
}

// loop ends here

// ///////..... HANDLING KEY EVENTS................//
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT) {
left = true;
// System.out.print("left");
}

if (keyCode == KeyEvent.VK_RIGHT) {
right = true;
// System.out.print("right");
}
}

@Override
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT) {
left = false;
}

if (keyCode == KeyEvent.VK_RIGHT) {
right = false;
}
}

@Override
public void keyTyped(KeyEvent arg0) {

}

@Override
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();
if (str.equals(STATUS.START.toString())) {
button.setText(STATUS.PAUSE.toString());
this.startGame();
}
if (str.equals(STATUS.PAUSE.toString())) {
PAUSE = true;
button.setText(STATUS.RESUME.toString());
}
if (str.equals(STATUS.RESUME.toString())) {
PAUSE = false;
button.setText(STATUS.PAUSE.toString());
}

// if (str.equals(STATUS.STOP.toString())) {
// RUNNING = false;
// button.setText(STATUS.START.toString());
// }

}

public void startGame() {
requestFocus(true);
initializeVariables();
Thread t = new Thread(this);
t.start();
}

public void initializeVariables() {
// default size of a brick...............................
int brickx = 70;
int bricky = 50;
RUNNING = true;
// x = 160, y = 218, width = 5, height = 5
Ball = new Rectangle(160, 218, 5, 5);
// x = 160, y = 245, width = 40, height = 5

Bat = new Rectangle(160, 245, 40, 5);

Brick = new Rectangle[12];
// //////////// =====Creating bricks for the game===>.....
createBricks(brickx, bricky);
// ===========BRICKS created for the game new ready to use===
movex = -1;
movey = -1;
ballFallDown = false;
bricksOver = false;
count = 0;
status = null;

}

public void createBricks(int brickx, int bricky) {
// //////////// =====Creating bricks for the game===>.....
/*
* creating bricks again because this for loop is out of while loop in run
* method
*/
for (int i = 0; i < Brick.length; i++) {
Brick[i] = new Rectangle(brickx, bricky, brickBreadth, brickHeight);
if (i == 5) {
brickx = 70;
bricky = (bricky + brickHeight + 2);

}
if (i == 9) {
brickx = 100;
bricky = (bricky + brickHeight + 2);

}
brickx += (brickBreadth + 1);
}
}

}

Help improve my way to approach you by commenting. PLZ do comment.
Thank you.

 How To Arrainge Bricks In Game

GitHub Link

Contact Form

Name

Email *

Message *

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 ga...