COME 2 CODE
Learn by Yourself

Bouncing Ball Game using JAVA

Hello friends, we are going to make a ball game which bounce back whenever touches up, right and left of the window but not at the bottom. At bottom, there will be a paddle which can be moved with left and right arrow key. If the ball does not touch the paddle, it will fall below the screen and the game will be over. After that, we will move the paddle automatically by adding a little more code. After adding this code, the ball will always fall on the paddle.Now, Open your IntelliJ or any other IDE and create a new Project. Now, name this project whatever you likes and go to Main.java file.

Now, write the following code in Main.java file.

Main.java :

import javax.swing.*;


public class Main {
  public static int height = 600;
  public static int width = 600;

  public static void main(String[] args) {
    JFrame obj = new JFrame();
    Ball ball = new Ball();

    obj.setBounds(100,100,width,height);
    obj.setTitle("Bouncing Ball Game");
    obj.setResizable(false);
    obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    obj.add(ball);
    obj.setVisible(true);
  }
}

Now, go to Projects tab.
Right Click on src folder, go to New and Click on JAVA Class.
Name the new JAVA Class as Ball.java
Write the following code in Ball.java.

Ball.java :

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import static java.awt.Font.BOLD;


public class Ball extends JPanel implements KeyListener{
  private boolean play = true;
  final static int diameter = 50;
  private int x = 250;
  private int y = 250;
  private int velocityX = 10;
  private int velocityY = 5;
  private int interval = 20;
  private Timer timer;

  private int playerX = 250;
  private int score = 0;

  public Ball() {
    timer = new Timer(interval, new TimerAction());
    timer.start();
    this.addKeyListener(this);
    this.setFocusable(true);
  }

  class TimerAction implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      if (play) {
        move();
        updateScore();
        repaint();
      }
    }
  }


  public void move() {
    x += velocityX;
    y += velocityY;

    if (x < 0) {
      x = 0;
      velocityX = -velocityX;
    } else if (x > getWidth() - diameter) {
      velocityX = -velocityX;
    }
    if ( y < 0) {
      y = 0;
      velocityY = -velocityY;
    } else if (y + diameter == 550 && x < (playerX + 100) && x > playerX) {
      velocityY = -velocityY;
    }
  }

  public void updateScore() {
    if (y + diameter == 550) {
      score = score + 1;
    }
    else if (y + diameter > 610){
      score = score;
      play = false;
    }
  }
  public void autoplay() {
    playerX = x - 25;
  }


  public void paintComponent(Graphics g) {
    super.paintComponent(g);

    g.setColor(Color.RED);
    g.fillOval(x,y,diameter,diameter);
    setVisible(true);

    g.setColor(Color.GREEN);
    g.fillRect(playerX,550, 100, 10);
    setVisible(true);

    g.setColor(Color.BLACK);
    g.setFont(new Font("serif", Font.BOLD, 15));
    g.drawString(" SCORE : " + score, 500, 50);

    if (y + diameter > 610) {
      g.setColor(Color.BLACK);
      g.setFont(new Font("serif", BOLD, 20));
      g.drawString("GAME OVER !", 200, 250);
      g.drawString("Your Score is " + score, 200, 300);
    }
  }

  public void keyTyped(KeyEvent kevt) {}

  public void keyPressed(KeyEvent e) {
    switch (e.getKeyCode()) {
      case KeyEvent.VK_LEFT -> leftPressed();
      case KeyEvent.VK_RIGHT -> rightPressed();
    }

    this.repaint();
  }

  public void keyReleased(KeyEvent ke) { }

  public void leftPressed() {
    if (playerX > 0) {
      playerX -= 20;
    } else {
      playerX = playerX;
    }
  }

  public void rightPressed() {
    if (playerX < 480) {
      playerX += 20;
    } else {
      playerX = playerX;
    }
  }
}

Now, you can play the game. If you want autoplay, we have to run the autoplay function everytime the timer ticks. So, replace the actionListener function code with the following code.

Ball.java :

  class TimerAction implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      if (play) {
        move();
        updateScore();
        autoplay();
        repaint();
      }
    }
  }
QUICK LINKS :