0% found this document useful (0 votes)
31 views18 pages

None

This document contains code for a Pong game written in Java. It includes classes for the main game (PongGame), the ball (Ball), and paddles (Paddle). PongGame extends JPanel and implements MouseMotionListener to track mouse movement. It contains the game logic and draws the graphics. Ball tracks its position and movement, bouncing off paddles and edges. Paddle represents player and computer-controlled paddles that can move and check for ball collisions. The main method sets up the frame and game components to launch the Pong game.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views18 pages

None

This document contains code for a Pong game written in Java. It includes classes for the main game (PongGame), the ball (Ball), and paddles (Paddle). PongGame extends JPanel and implements MouseMotionListener to track mouse movement. It contains the game logic and draws the graphics. Ball tracks its position and movement, bouncing off paddles and edges. Paddle represents player and computer-controlled paddles that can move and check for ball collisions. The main method sets up the frame and game components to launch the Pong game.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

MAIN:

package com.mycompany.pingpong;
import javax.swing.*;
import java.awt.event.ActionEvent;

public class Main {

//declare and initialize the frame


static JFrame f = new JFrame("Pong");

public static void main(String[] args) {

//make it so program exits on close button click


f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

//the size of the game will be 640x480, the size of the JFrame needs to be slightly larger
f.setSize(900,500);

//create a new PongGame and add it to the JFrame


PongGame game = new PongGame();
f.add(game);

//show the frame/program window


f.setVisible(true);
//make a new swing Timer
Timer timer = new Timer(10, (ActionEvent e) -> {
//game logic
game.gameLogic();

//repaint the screen


game.repaint();
});

//start the timer after it's been created


timer.start();

}
}

PADDLE:
package com.mycompany.pingpong;

import java.awt.*; //needed for Color

public class Paddle {

//declare instance variables


private final int height;
private final int x;
private int y;
private final int speed;
private final Color color;
//Width of paddle will always be 15 for this app, you may change if you want
static final int PADDLE_WIDTH = 15;

/**
* A paddle is a rectangle/block that can move up and down
* @param x the x position to start drawing the paddle
* @param y the y position to start drawing the paddle
* @param height the paddle height
* @param speed the amount the paddle may move per frame
* @param color the paddle color
*/
public Paddle(int x, int y, int height, int speed, Color color) {
this.x = x;
this.y = y;
this.height = height;
this.speed = speed;
this.color = color;
}

/**
* Paints a rectangle on the screen
* @param g graphics object passed from calling method
*/
public void paint(Graphics g){

//set brush color to whatever this paddle's color is


g.setColor(color);
//paint the rectangle, starting in the upper left corner at x, y
g.fillRect(x, y, PADDLE_WIDTH, height);

/**
* Move the paddle towards this y position until it's centered on it
* @param moveToY - position the paddle is centered on
*/
public void moveTowards(int moveToY) {

//find the location of the center of the paddle


int centerY = y + height / 2;

//make sure the paddle is far enough away from the target moveToY position. If it's closer
than the speed to where it should be, don't bother moving the paddle.
if(Math.abs(centerY - moveToY) > speed){
//if the center of the paddle is too far down
if(centerY > moveToY){
//move the paddle up by the speed
y -= speed;
}
//if the center of the paddle is too far up
if(centerY < moveToY){
//move the paddle down by speed
y += speed;
}
}
}

/**
* Checks if this paddle is colliding with a ball
* @param b the ball we're checking for a collision with
* @return true if collision is detected
*/
public boolean checkCollision(Ball b){

int rightX = x + PADDLE_WIDTH;


int bottomY = y + height;

//check if the Ball is between the x values starting from one ball width to the left of the
paddle to the right side of the paddle
if(b.getX() > (x - b.getSize()) && b.getX() < rightX){

//check if Ball is between the top and bottom y values of the paddle
if(b.getY() > y && b.getY() < bottomY){
//if we get here, we know the ball and the paddle have collided
return true;
}
}

//if we get here, one of the checks failed, and the ball has not collided
return false;

}
}

BALL:
package com.mycompany.pingpong;

import java.awt.*;
import static java.awt.Color.black;

public class Ball {

static final int MAX_SPEED = 7;


//declare instance variables
private int x;
private int y;
private int cx;
private int cy;
private int speed;
private final int size;
private final Color color;

//ball constructor assigns values to instance variables


public Ball(int x, int y, int cx, int cy, int speed, Color color, int size) {
this.x = x;
this.y = y;
this.cx = cx;
this.cy = cy;
this.speed = speed;
this.color = color;
this.size = size;
}

public void paint(Graphics g){

//set the brush color to the ball color


g.setColor(black);

//paint the ball at x, y with a width and height of the ball size
g.fillOval(x, y, size, size);

public void moveBall(){


x += cx;
y += cy;
}

/**
* Detect collision with screen borders and reverse direction
* @param top - the y value of the top of the screen
* @param bottom - the y value of the bottom of the screen
*/
public void bounceOffEdges(int top, int bottom){

//if the y value is at the bottom of the screen


if (y > bottom - size){
reverseY();
}
//if y value is at top of screen
else if(y < top){
reverseY();
}

/**
* Reverse's the ball's change in x value
*/
public void reverseX(){
cx *= -1;
}

/**
* Reverse's the ball's change in y value
*/
public void reverseY(){
cy *= -1;
}

/**
* Increases the speed of the ball (and cy/cx) by 1 up to the possible MAX_SPEED constant
*/
public void increaseSpeed(){
//make sure current speed is less than max speed before incrementing
if(speed < MAX_SPEED){
//increase the speed by one
speed ++;

//figure out if cx or cy is positive or negative (+1 or -1) and multiply this by the speed, for
the new speed
//e.g. -3 becomes -4, 3 becomes 4, and so on.
cx = (cx / Math.abs(cx)*speed);
cy = (cy / Math.abs(cy)*speed);

}
}

public int getY(){


return y;
}

public void setY(int y){


this.y = y;
}

public int getX(){


return x;
}

public void setX(int x){


this.x = x;
}

public void setSpeed(int speed){


this.speed = speed;
}

public void setCy(int cy){


this.cy = cy;
}

public void setCx(int cx){


this.cx = cx;
}

public int getSize(){


return size;
}

PONGGAME:
package com.mycompany.pingpong;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
//This class must extend JPanel so we can use paintComponent and implement
MouseMotionListener to track mouse
public class PongGame extends JPanel implements MouseMotionListener {

//Constants for window width and height, in case we want to change the width/height later
static final int WINDOW_WIDTH = 900, WINDOW_HEIGHT = 480;
private final Ball gameBall;
private final Paddle userPaddle;
private final Paddle pcPaddle;
private int userScore, pcScore;

private int userMouseY; //to track the user's mouse position


private int bounceCount; //to count number of ball bounces between paddles

/**
* Standard constructor for a PongGame
*/
public PongGame() {

//Make the ball and paddles


gameBall = new Ball(300, 200, 3, 3, 10, Color.green, 18);
userPaddle = new Paddle(10, 190, 95, 40, Color.BLUE);
pcPaddle = new Paddle(855, 190, 95, 3, Color.RED);

//Set instance variables to zero to start


userMouseY = 0;
userScore = 0; pcScore = 0;
bounceCount = 0;
//listen for motion events on this object
addMouseMotionListener(this);

}
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);
int win = 1;
if(win==0)
{
g.drawString("PLAYER1 WINS", (width - metr.stringWidth(msg))/2 - 60, height/2 + 0);
}
else
{
g.drawString("COMPUTER WINS", (width - metr.stringWidth(msg))/2 - 60, height/2 +
0);
}
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);
}

public void actionPerformed(ActionEvent e)


{
boolean inGame = true;

if (inGame)
{
int checkWins = 1;
move();
}

repaint();

/**
* resets the game to start a new round
*/
public void reset(){

//pause for a second


try{
Thread.sleep(1000);
}
catch(InterruptedException e){
}

gameBall.setX(300);
gameBall.setY(200);
gameBall.setCx(3);
gameBall.setCy(3);
gameBall.setSpeed(7);
bounceCount = 0;

/**
* Updates and draws all the graphics on the screen
*/
@Override
public void paintComponent(Graphics g) {

//draw the background


g.setColor(Color.lightGray);
g.fillRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
g.setColor(Color.BLACK);
g.setFont(new Font("Times New Roman", Font.BOLD, 12));
g.drawString("MODIFIED BY: NEIL ALEXIS GABRIEL", 50,460);

g.setColor(Color.BLACK);
g.drawLine(857, 20, 20, 20);
g.drawLine(857, 450, 857, 21);
g.drawLine(857, 450, 20, 450);
g.drawLine(20, 450, 20, 21);
g.drawLine(857, 245, 20, 245);
g.drawRect(425, 450, 50, 10);
g.drawRect(425, 20, 50, 10);
g.setColor(Color.white);
g.drawLine(450, 21, 450, 580);
g.drawLine(448, 21, 448, 580);
g.drawLine(446, 21, 446, 580);
g.drawLine(452, 21, 452, 580);
g.drawLine(444, 21, 444, 580);
g.drawLine(454, 21, 454, 580);
g.drawLine(456, 21, 456, 580);
g.drawLine(442, 21, 442, 580);
g.drawLine(458, 21, 458, 580);

//draw the ball


gameBall.paint(g);

//draw the paddles


userPaddle.paint(g);
pcPaddle.paint(g);

//update score
g.setColor(Color.black);
g.setFont(new Font("Times New Roman", Font.BOLD, 15));
//the drawString method needs a String to print, and a location to print it at.
g.drawString("Player " + userScore + " Computer " + pcScore + " ", 180, 16 );
}

/**
* Called once each frame to handle essential game operations
*/
public void gameLogic() {

//move the ball one frame


gameBall.moveBall();

//edge check/bounce
gameBall.bounceOffEdges(0, WINDOW_HEIGHT);

//move the paddle towards where the mouse is


userPaddle.moveTowards(userMouseY);

//move the PC paddle towards the ball y position


pcPaddle.moveTowards(gameBall.getY());

//check if ball collides with either paddle


if(pcPaddle.checkCollision(gameBall) || userPaddle.checkCollision(gameBall)){
//reverse ball if they collide
gameBall.reverseX();
//increase the bounce count
bounceCount++;
}
//after 5 bounces
if (bounceCount == 5){
//reset counter
bounceCount = 0;
//increase ball speed
gameBall.increaseSpeed();
}

//check if someone lost


if(gameBall.getX() < 0){
//player has lost
pcScore++;
reset();
}
else if(gameBall.getX() > WINDOW_WIDTH){
//pc has lost
userScore++;
reset();
}

@Override
public void mouseDragged(MouseEvent e) {

}
@Override
public void mouseMoved(MouseEvent e) {
//Update saved mouse position on mouse move
userMouseY = e.getY();

private void move() {


throw new UnsupportedOperationException("Not supported yet."); // Generated from
nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}

private void checkWins() {

}
}
OUTPUT:

You might also like