Block breaker java game
Here is a simple implementation of a block breaker game in Java using Swing for the GUI and Java's built-in graphics capabilities for the game logic.
BlockBreakerGame.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
public class BlockBreakerGame extends JPanel {
private int paddleWidth = 100;
private int paddleHeight = 20;
private int paddleX = 0;
private int paddleY = 0;
private int ballDiameter = 20;
private int ballX = 0;
private int ballY = 0;
private int ballSpeedX = 5;
private int ballSpeedY = 5;
private List<Block> blocks = new ArrayList<>();
private int score = 0;
public BlockBreakerGame() {
setPreferredSize(new Dimension(400, 400));
setFocusable(true);
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT) {
paddleX -= 5;
} else if (keyCode == KeyEvent.VK_RIGHT) {
paddleX += 5;
}
}
});
initGame();
}
private void initGame() {
paddleX = (getWidth() - paddleWidth) / 2;
paddleY = getHeight() - paddleHeight;
ballX = getWidth() / 2;
ballY = getHeight() / 2;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
blocks.add(new Block(i * 80, j * 20));
}
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.WHITE);
g.fillRect(paddleX, paddleY, paddleWidth, paddleHeight);
g.fillOval(ballX, ballY, ballDiameter, ballDiameter);
for (Block block : blocks) {
g.fillRect(block.getX(), block.getY(), 80, 20);
}
g.drawString("Score: " + score, 10, 20);
}
@Override
public void update(Graphics g) {
paintComponent(g);
}
private class Block {
private int x;
private int y;
public Block(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Block Breaker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new BlockBreakerGame());
frame.pack();
frame.setVisible(true);
}
}
How to play:
- The game starts with a paddle at the bottom of the screen and a ball bouncing around.
- The player controls the paddle using the left and right arrow keys.
- The goal is to hit the blocks at the top of the screen with the ball.
- Each block hit increases the score.
- If the ball hits the bottom of the screen, the game is over.
Note: This is a very basic implementation and there are many ways to improve it (e.g., adding sound effects, smoother animations, more levels, etc.).