Java Project – Pong Game
FREE Online Courses: Transform Your Career – Enroll for Free!
Welcome to the digital reincarnation of a classical pong game from the 1970s with the elegance and simplicity of Java, where the Swing library comes in handy for building this game. Let’s dive into it.
About Java Pong Game Project
The Pong game is a two-player game where the left player will control the left paddle with the keys W and S, along with the right player controlling the right paddle with UP and DOWN arrow keys.
Prerequisites For Java Pong Game Project:
- Java Development Kit: Latest JDK, like JDK 8 or 11.
- IntelliJ IDEA
Download Java Pong Game Project Code:
Please download the source code of Java Pong Game Project Code: Java Pong Game Project Code
RULES for Java Pong Game
- The pong game is a classic two player game where each player controls their own paddles, moving them up and down vertically.
- Each player has to bounce the ball back to the opponent by making their paddles come in contact with the ball.
- A player gains a point when the opponent player fails to bounce the ball back with their own paddle.
Steps to Create a Pong Game in Java
These are the steps we will follow to build Pong Game in Java:
1. Creating a welcome page
2. Creating the game
- Creating GameFrame
- Creating GamePanel
- Creating Paddles
- Creating Ball
- Creating Scoreboard
1. Creating A welcome page
In this step, we basically create a welcome page which will be the opening page for all our users, and here they can set the level of difficulty and can also view how to play the game.
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; //This is the first opening page of the game where you can view the instructions and set up the level of the game public class WelcomePage extends JFrame { private JTextField levelField; // To accept level input from user which will increase the speed of the ball public WelcomePage() { // Set up the JFrame details setTitle("Pong Game Welcome Page"); setSize(500, 250); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); // This will center the JFrame on the screen // Create a JPanel to place components on JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); // Add welcome message JLabel welcomeMessage = new JLabel("Welcome to Pong Game by TechVidvan", SwingConstants.CENTER); welcomeMessage.setFont(new Font("Serif", Font.BOLD, 16)); panel.add(welcomeMessage, BorderLayout.NORTH); // Create a central panel for input and buttons GridLayout gd=new GridLayout(2,2); JPanel centerPanel = new JPanel(gd); // Add label and field for level input JLabel levelLabel = new JLabel("Enter Level:"); centerPanel.add(levelLabel); levelField = new JTextField(); centerPanel.add(levelField); // Adding a play now button to the welcome page JButton playNowButton = new JButton("Play Now"); playNowButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Action to perform when Play Now is clicked startGame(); } }); centerPanel.add(playNowButton); // Adding a How To Play button JButton howToPlayButton = new JButton("How To Play"); howToPlayButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Show instructions for the game showInstructions(); } }); centerPanel.add(howToPlayButton); panel.add(centerPanel, BorderLayout.CENTER); // Adding the created panel to the Jframe created in welcome page add(panel); // Make the JFrame visible setVisible(true); } private void startGame() { String level = levelField.getText(); /*After taking the level input,we are going to send this as a parameter to the GameFrame constructor * */ new GameFrame(Integer.parseInt(level)); // Close the welcome page dispose(); } private void showInstructions() { // Displaying Instructions to play JOptionPane.showMessageDialog(this, "Pong Game Instructions:\n" + "1. Use the Pg up and Pg down keys to move the paddle for the player-right.\n" + "2. Use the W and S keys to control the paddle for the player-left."+ "3. Prevent the ball from touching the ground.\n" + "4. The player gains a point when the opponent fails to bounce ball back with the paddle.", "How To Play", JOptionPane.INFORMATION_MESSAGE); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new WelcomePage(); } }); } }
2. Creating the game
For creating our actual game, we are dividing each working of the game and the build of the game into different components such that we are going to create GameFrame, GamePanel, Ball, Paddle, and Score class.
a. Creating GameFrame
The GameFrame class is responsible for creating and managing the main window or frame of the Pong game. Upon its instantiation, it expects an integer value for the game’s speed.
import java.awt.*; import javax.swing.*; public class GameFrame extends JFrame{ GamePanel panel; GameFrame(int speed){ panel = new GamePanel(speed); this.add(panel); this.setTitle("Pong Game"); this.setResizable(false); this.setBackground(Color.white); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.pack(); this.setVisible(true); this.setLocationRelativeTo(null); } }
b. Creating GamePanel
This class will be applying the paddles of the game and the ball of the game, moreover, this class will have the run() function, which will start the game loop and will move the ball, check the collisions of the ball, and this class will be implementing runnable interface so that everything shall run simultaneously on Threads.
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; public class GamePanel extends JPanel implements Runnable{ static final int WIDTH = 1000; static final int height = 555; static final Dimension dimen = new Dimension(WIDTH,height); static final int BALL_DIAMETER = 20; //Setting Paddle width and height static final int P_WIDTH = 25; static final int P_HEIGHT = 100; Thread gameThread; Image image; Graphics graphics; Random random; Paddle p1; Paddle p2; Ball ball; Score score; int speed; GamePanel(int speed){ this.speed=speed; newPaddles(); newBall(speed); score = new Score(WIDTH,height); this.setFocusable(true); this.addKeyListener(new AL()); this.setPreferredSize(dimen); gameThread = new Thread(this); gameThread.start(); } public void newBall(int speed) { //Random object to generate a random integer for the coordinates of the ball placement random = new Random(); ball = new Ball((WIDTH/2)-(BALL_DIAMETER/2),random.nextInt(height-BALL_DIAMETER),BALL_DIAMETER,BALL_DIAMETER,speed); } public void newPaddles() { //Creating the paddles for the users to control the ball with p1 = new Paddle(0,(height/2)-(P_HEIGHT/2),P_WIDTH,P_HEIGHT,1); p2 = new Paddle(WIDTH-P_WIDTH,(height/2)-(P_HEIGHT/2),P_WIDTH,P_HEIGHT,2); } public void paint(Graphics g) { image = createImage(getWidth(),getHeight()); graphics = image.getGraphics(); draw(graphics); g.drawImage(image,0,0,this); } public void draw(Graphics g) { p1.draw(g); p2.draw(g); ball.draw(g); score.draw(g); //For smooth animation Toolkit.getDefaultToolkit().sync(); } public void move() { p1.move(); p2.move(); ball.move(); } public void checkCollision() { //bouncing the ball away from the top and bottom edges of the screen if(ball.y <=0) { ball.setYDirection(-ball.vel_y); } if(ball.y >= height-BALL_DIAMETER) { ball.setYDirection(-ball.vel_y); } //bounce ball off paddles if(ball.intersects(p1)) { ball.vel_x = Math.abs(ball.vel_x); ball.setXDirection(ball.vel_x); ball.setYDirection(ball.vel_y); } if(ball.intersects(p2)) { ball.vel_x = Math.abs(ball.vel_x); ball.setXDirection(-ball.vel_x); ball.setYDirection(ball.vel_y); } //stops paddles at window edges if(p1.y<=0) p1.y=0; if(p1.y >= (height-P_HEIGHT)) p1.y = height-P_HEIGHT; if(p2.y<=0) p2.y=0; if(p2.y >= (height-P_HEIGHT)) p2.y = height-P_HEIGHT; //give a player 1 point and creates new paddles & ball if(ball.x <=0) { score.player2++; newPaddles(); newBall(speed); } if(ball.x >= WIDTH-BALL_DIAMETER) { score.player1++; newPaddles(); newBall(speed); } } public void run() { //game loop to run the game long lastTime = System.nanoTime(); double amountOfTicks =60.0; double ns = 1000000000 / amountOfTicks; double delta = 0; while(true) { long now = System.nanoTime(); delta += (now -lastTime)/ns; lastTime = now; if(delta >=1) { move(); checkCollision(); repaint(); delta--; } } } /*Nested class for the keyAdapter to perform the particular functionality when a key is pressed * */ public class AL extends KeyAdapter { public void keyPressed(KeyEvent e) { p1.keyPressed(e); p2.keyPressed(e); } public void keyReleased(KeyEvent e) { p1.keyReleased(e); p2.keyReleased(e); } } }
c. Creating paddles
This class will create the paddles, which will be controlled by the users to play the game which are going to be implemented in the GamePanel.
import java.awt.*; import java.awt.event.*; public class Paddle extends Rectangle{ int id; int yVelocity; int speed = 10; //speed to move the pedals Paddle(int x, int y, int P_Width, int P_Height, int id){ super(x,y,P_Width,P_Height); this.id=id; } public void keyPressed(KeyEvent e) { switch(id) { case 1: if(e.getKeyCode()==KeyEvent.VK_W) { setYDirection(-speed); } if(e.getKeyCode()==KeyEvent.VK_S) { setYDirection(speed); } break; case 2: if(e.getKeyCode()==KeyEvent.VK_UP) { setYDirection(-speed); } if(e.getKeyCode()==KeyEvent.VK_DOWN) { setYDirection(speed); } break; } } public void keyReleased(KeyEvent e) { switch(id) { case 1: if(e.getKeyCode()==KeyEvent.VK_W) { setYDirection(0); } if(e.getKeyCode()==KeyEvent.VK_S) { setYDirection(0); } break; case 2: if(e.getKeyCode()==KeyEvent.VK_UP) { setYDirection(0); } if(e.getKeyCode()==KeyEvent.VK_DOWN) { setYDirection(0); } break; } } public void setYDirection(int yDirection) { yVelocity = yDirection; } public void move() { y= y + yVelocity; } public void draw(Graphics g) { if(id==1) g.setColor(Color.blue); else g.setColor(Color.red); g.fillRect(x, y, width, height); } }
d. Creating Ball
This class will be creating a ball for the game by inheriting the rectangle class and setting up its width and height and will initialize its speed in the game, which we took input by the user on the welcome page.
import java.awt.*; import java.util.*; public class Ball extends Rectangle{ Random random; int vel_x; //velocity with which ball will move horizontally int vel_y; //velocity with which ball will move vertically int initialSpeed; //speed of the ball in the game which we will take the input Ball(int x, int y, int width, int height,int speed){ super(x,y,width,height); //Initialising the speed of the ball with the level of the game given input by the user initialSpeed=speed; random = new Random(); int randomXDirection = random.nextInt(2); if(randomXDirection == 0) randomXDirection--; setXDirection(randomXDirection*initialSpeed); int randomYDirection = random.nextInt(2); if(randomYDirection == 0) randomYDirection--; setYDirection(randomYDirection*initialSpeed); } public void setXDirection(int randomX) { vel_x = randomX; } public void setYDirection(int randomY) { vel_y = randomY; } public void move() { x += vel_x; y += vel_y; } public void draw(Graphics g) { g.setColor(Color.black); g.fillOval(x, y, height, width); } }
e. Creating Scoreboard
This class will inherit the rectangle class and set up the scoreboard for the score of the two players.
import java.awt.*; //This class will be used to display the score of each player public class Score extends Rectangle{ static int GAME_WIDTH; static int GAME_HEIGHT; int player1; int player2; Score(int GAME_WIDTH, int GAME_HEIGHT){ Score.GAME_WIDTH = GAME_WIDTH; Score.GAME_HEIGHT = GAME_HEIGHT; } public void draw(Graphics g) { g.setColor(Color.black); g.setFont(new Font("Consolas",Font.ROMAN_BASELINE,60)); g.drawLine(GAME_WIDTH/2, 0, GAME_WIDTH/2, GAME_HEIGHT); g.drawString(String.valueOf(player1/10)+String.valueOf(player1%10), (GAME_WIDTH/2)-85, 50); g.drawString(String.valueOf(player2/10)+String.valueOf(player2%10), (GAME_WIDTH/2)+20, 50); } }
Java Pong Game Output
1. Welcome page
2. Instructions
3. Game Playing
Summary
Using Java’s Swing and AWT frameworks, we’ve re-made the iconic Pong game for analyzing Java implementation in various applications. These toolkits, often utilized for business applications, demonstrate surprising flexibility when applied to interactive entertainment. The combination of Swing’s sophisticated components with AWT’s foundational graphics has allowed us to remake this 1970’s classic.