
In this article, we are going to build the simple Pong Game in Java. This is a two-player game in which players need to hit the ball with the paddle and if the ball fails to hit the paddle then the opponent wins.
Click here to play a pong game right now .
Project Overview: Pong Game in Java
Project Name: | Pong Game in Java |
Abstract: | It’s a GUI-based project used with the swing library to organize all the elements that work under the Pong Game. |
Language Used: | Java |
IDE: | VS Code |
Java version (Recommended): | Java SE 18.0. 2.1 |
Database: | None |
Type: | Desktop Application |
Recommended for: | Beginners of Java |
Time to build: | 1-2 hours |
What will you learn?
- Building the logic of the game with the help of simple loops and conditionals
- Utilizing the OOPs paradigm with the help of classes and objects
- Creating simple user-friendly graphics with the help of Java Swing
Features:
- Two players will be able to play
- Both the player will be able to move the paddle in the up-down direction
- The toughness of the level increases as one player wins
About Pong Game in Java
Let’s understand the requirements of the game first: Both paddle objects should only be able to move on the y-axis. The ball object should be able to move in a diagonal direction and this can be achieved if we move the ball in both the x and y direction simultaneously. And the ball object’s position and direction should be reset if it moves out of the screen on the x-axis. Both players should be able to control their paddle with their respective keys and this can be done by overriding the keyPressed method of the KeyAdapter interface and changing the coordinates of the paddle.
Complete Code for Pong Game in Java
Keep the file name as Pong.java. Now let’s look at the code below, comments are provided for explanation.
import javax.swing.*;import java.awt.*;import java.awt.event.*;// this class is used to implement all the logic for the gameclass Game extends JPanel implements ActionListener{boolean leftup; //used to check if the left paddle is moving upboolean leftdown; //used to check if the left paddle is moving downboolean rightup; //used to check if the right paddle is moving upboolean rightdown; //used to check if the right paddle is moving downint leftx,lefty,rightx,righty; // these variables are used to store the x and y coordinates of the paddlesTimer time; //used to create a timer objectint delay=100; //used to store the delay for the timerboolean inGame; //used to check if the game is in progressboolean ballleft; //used to check if the ball is moving leftboolean ballright; //used to check if the ball is moving rightboolean ballup; //used to check if the ball is moving upboolean balldown; //used to check if the ball is moving downint ballx,bally; //these variables are used to store the x and y coordinates of the ballint flag=0; //used to check if the ball has hit the paddleint win=0; //used to check if the game has been wonGame(int x,int y,int width,int height){setBorder(BorderFactory.createMatteBorder(2,2,2,2, Color.green));addKeyListener(new KeyMover());setBackground(Color.black); //sets the background color of the boardsetFocusable(true);setVisible(true);setBounds(x,y,width,height); //sets the bounds of the boardinitGame();}// this method is used to initialize the gamepublic void initGame(){leftdown=false;leftup=false;rightdown=false;rightup=false;leftx=20;lefty=300;rightx=1070;righty=300;inGame=true;delay=50;ballleft=false;ballright=true;ballup=true;balldown=false;win=0;ballx=50;bally=150;time=new Timer(delay, this);time.start();}// this method is used to paint the components on the board@Overridepublic void paintComponent(Graphics g){super.paintComponent(g);doPaint(g);}// this method is used to move the paddles and ballpublic void move(){if(leftup) //if the left paddle is moving up{if(lefty==0){lefty=0; //if the left paddle is at the top of the board, do not move it}else{lefty-=20; //move the left paddle up by 20 pixels}}if(leftdown) //if the left paddle is moving down{if(lefty==600){lefty=600; //if the left paddle is at the bottom of the board, do not move it}else{lefty+=20; //move the left paddle down by 20 pixels}}if(rightup) //if the right paddle is moving up{if(righty==0){righty=0; //if the right paddle is at the top of the board, do not move it}else{righty-=20; //move the right paddle up by 20 pixels}}if(rightdown) //if the right paddle is moving down{if(righty==600){righty=600; //if the right paddle is at the bottom of the board, do not move it}else{righty+=20; //move the right paddle down by 20 pixels}}if(ballright && ballup) // if the ball is moving right and up{if(bally==0){ //if the ball is at the top of the board, make it move downballup=false;balldown=true;ballx+=10;bally+=10;}else{ // if the ball is not at the border of the board, move it diagonallyballx+=10;bally-=10;}return;}if(ballright && balldown){ // if the ball is moving right and downif(bally==600){ //if the ball is at the bottom of the board, make it move upballup=true;balldown=false;ballx+=10;bally-=10;}else{ // if the ball is not at the border of the board, move it diagonallyballx+=10;bally+=10;}return;}if(ballleft && ballup){ // if the ball is moving left and upif(bally==0){ //if the ball is at the top of the board, make it move downballup=false;balldown=true;ballx-=10;bally+=10;}else{ // if the ball is not at the border of the board, move it diagonallyballx-=10;bally-=10;}return;}if(ballleft && balldown){if(bally==600){ //if the ball is at the bottom of the board, make it move upballup=true;balldown=false;ballx-=10;bally-=10;}else{ // if the ball is not at the border of the board, move it diagonallyballx-=10;bally+=10;}return;}}// this method is used to check the winnerpublic void checkWins(){if(ballx<=0){ //if the ball is at the left border of the board, the right player winsinGame=false;win=1;}if(ballx>=1100){ //if the ball is at the right border of the board, the left player winsinGame=false;win=0;}if(ballx==rightx){ //if the ball is at the right paddle, make it move leftif(bally>=righty && bally<=(righty+100)){ //if the ball is at the right paddle, make it move leftballright=false;ballleft=true;}}if(ballx==leftx){ //if the ball is at the left paddle, make it move rightif(bally>=lefty && bally<=(lefty+100)){ //if the ball is at the left paddle, make it move rightballright=true;ballleft=false;}}}// this method is used to paint the components on the boardpublic void doPaint(Graphics g){if(inGame){ //if the game is in progress, paint the boardg.setColor(Color.white);g.setFont(new Font("MV Boli", Font.BOLD, 30));g.drawString("Use P and L", 850,50);g.setColor(Color.white);g.setFont(new Font("MV Boli", Font.BOLD, 30));g.drawString("Use Q and A", 50,50);g.setColor(Color.DARK_GRAY);g.drawLine(550, 0, 550, 600);g.setColor(Color.red);g.fillOval(ballx, bally, 10, 10);g.setColor(Color.yellow);g.fillRect(leftx, lefty, 10, 100);g.setColor(Color.magenta);g.fillRect(rightx, righty, 10, 100);}else{ //if the game is not in progress, paint the winnergameOver(g);}Toolkit.getDefaultToolkit().sync();}public void gameOver(Graphics g){String msg = "Game Over";Font small = new Font("MV Boli", Font.BOLD, 35);FontMetrics metr = getFontMetrics(small);int width=this.getWidth();int height=this.getHeight();g.setColor(Color.white);g.setFont(small);g.drawString(msg, (width - metr.stringWidth(msg)) / 2, height/2 - 50);g.setColor(Color.ORANGE);if(win==0){g.drawString("Left Player Wins!", (width - metr.stringWidth(msg))/2 - 60, height/2 + 10);}else{g.drawString("Right Player Wins!", (width - metr.stringWidth(msg))/2 - 60, height/2 + 10);}g.setColor(Color.orange);g.setFont(new Font("MV Boli", Font.BOLD, 40));g.drawString("Press Enter to Restart", (width - metr.stringWidth(msg))/2 - 120, height/2 + 50);}@Overridepublic void actionPerformed(ActionEvent e){if (inGame){checkWins();move();}repaint();}// this method is used to move the paddlespublic class KeyMover extends KeyAdapter{@Overridepublic void keyPressed(KeyEvent e) {int key = e.getKeyCode(); // get the key pressedif ((key == KeyEvent.VK_Q) ) { // if the key pressed is Q, move the left paddle upleftup=true;leftdown=false;}if ((key == KeyEvent.VK_A) ) { // if the key pressed is A, move the left paddle downleftup=false;leftdown=true;}if ((key == KeyEvent.VK_P) ) { // if the key pressed is P, move the right paddle uprightup=true;rightdown=false;}if ((key == KeyEvent.VK_L)) { // if the key pressed is L, move the right paddle downrightup=false;rightdown=true;}if((key == KeyEvent.VK_ENTER)){ // if the key pressed is Enter, restart the gameif(!inGame){initGame();}}}@Overridepublic void keyReleased(KeyEvent e) {int key = e.getKeyCode();if ((key == KeyEvent.VK_Q) ) {leftup=false;}if ((key == KeyEvent.VK_A) ) {leftdown=false;}if ((key == KeyEvent.VK_P) ) {rightup=false;}if ((key == KeyEvent.VK_L)) {rightdown=false;}}}}// this class is used to create the frame of the gameclass Frame extends JFrame implements ActionListener,MouseListener{Container cont;int height,width,x,y;Game b1;String lab;Frame(int x,int y,int width,int height){cont = getContentPane();cont.setLayout(null);setLayout(null);this.height=height;this.width=width;this.x=x;this.y=y;setBounds(x,y,width,height);setVisible(true);setLayout(null);b1=new Game(0,0,width,height);cont.add(b1);setLocationRelativeTo(null);setResizable(false);pack();setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}public void actionPerformed(ActionEvent ae){lab=ae.getActionCommand();}// these methods are not used but required to implement MouseListenerpublic void mouseClicked(MouseEvent e) {}public void mouseEntered(MouseEvent e) {}public void mouseExited(MouseEvent e) {}public void mousePressed(MouseEvent e) {}public void mouseReleased(MouseEvent e) {}}class Pong {public static void main(String[] args) {EventQueue.invokeLater(new Runnable() {@Overridepublic void run() {Frame e1 = new Frame(0,0,1100,600);e1.setBounds(200,150,1100,638);e1.setVisible(true);}});}}
Output:
Image output:

Video Output:
Thank you for visiting our website.
Also Read:
- Dino Game in Java
- Java Games Code | Copy And Paste
- Supply Chain Management System in Java
- Survey Management System In Java
- Phone Book in Java
- Email Application in Java
- Inventory Management System Project in Java
- Blood Bank Management System Project in Java
- Electricity Bill Management System Project in Java
- CGPA Calculator App In Java
- Chat Application in Java
- 100+ Java Projects for Beginners 2023
- Airline Reservation System Project in Java
- Password and Notes Manager in Java
- GUI Number Guessing Game in Java
- How to create Notepad in Java?
- Memory Game in Java
- Simple Car Race Game in Java
- ATM program in Java
- Drawing Application In Java
- Tetris Game in Java
- Pong Game in Java
- Hospital Management System Project in Java
- Ludo Game in Java
- Restaurant Management System Project in Java
- Flappy Bird Game in Java
- ATM Simulator In Java
- Brick Breaker Game in Java
- Best Java Roadmap for Beginners 2023
- Snake Game in Java