Skip to content

Instantly share code, notes, and snippets.

@Codeplaza
Created January 7, 2014 07:53
Show Gist options
  • Save Codeplaza/8295977 to your computer and use it in GitHub Desktop.
Save Codeplaza/8295977 to your computer and use it in GitHub Desktop.
Pong Game in Java on Codeplaza
package pong;
import java.awt.geom.Rectangle2D;
/**
*
* @author Emil
*/
public class AIPaddle extends Rectangle2D.Double
{
private final int gameHeight, gameWidth;
private final double WIDTH = 10, HEIGHT = 60, SPEED;
public AIPaddle(int x, int y, double speed, int gameWidth, int gameHeight){
SPEED = speed;
this.x = x;
this.y = y;
this.height = HEIGHT;
this.width = WIDTH;
this.gameHeight = gameHeight;
this.gameWidth = gameWidth;
}
public void moveAi(double ballX, double ballY){
if(ballX >= gameWidth/2){
if(ballY < y && y>=2)
y-=SPEED;
if(ballY >y && y+height <=gameHeight+10)
y+=SPEED;
}
}
}
package pong;
import java.awt.geom.Ellipse2D;
/**
*
* @author daniele
*/
public class Ball extends Ellipse2D.Double {
private int speed;
public Ball(int x,int y,int width,int height)
{
this.x=x;
this.y=y;
this.width=width;
this.height=height;
}
boolean setSpeed(int speed)
{
if(speed<0||speed>10)
return false;
this.speed=speed;
return true;
}
void moveX(boolean right)
{
if(right)
x+=speed;
else x-=speed;
}
void moveY(boolean down)
{
if(down)
y+=speed;
else y-=speed;
}
boolean setX(int x)
{
if(x<width)
this.x=x;
return x<width;
}
boolean setY(int y)
{
if(y<height)
this.y=y;
return y<height;
}
}
package pong;
import java.awt.*;
import MGui.*;
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import javax.swing.Timer;
public class Game extends MFrame implements ActionListener {
private Timer timer,_timer;
private File sourceimage;
private Image immagineIc;
private int movement,points,_points,score,scorePX,scoreCX,scoreY;
private final int width,height;
private Ball ball;
private final Paddle player;
private final AIPaddle ai;
private boolean right,down,up,ballMovement;
private boolean[] keys;
private final URL url,_url;
private final AudioClip clipContact,clipScore;
private final KeyListener listener;
private final double SPEED_AI= 5.5;
public Game(int width, int height, String title) {
super(width, height);
super.setTitle(title);
super.setResizable(false);
super.setLocationRelativeTo(null);
super.setCanvasBackground(Color.BLACK);
try {
sourceimage=new java.io.File("src\\icon\\pong.gif");
Image image = ImageIO.read(sourceimage);
immagineIc=Toolkit.getDefaultToolkit().getImage(sourceimage.toString());
super.setIconImage(image);
} catch (IOException ex) {
Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
}
listener = new MyKeyListener();
keys=new boolean[256];
for(int i=0;i<keys.length;i++)
keys[i]=false;
addKeyListener(listener);
setFocusable(true);
score=0;
points=0;
_points=0;
movement=10;
scorePX=width/6;
scoreCX=430;
scoreY=30;
this.width=width;
this.height=height;
ball=new Ball(100,40,20,20);
ball.setSpeed(6);
player=new Paddle(0,0,10,60);
player.setSpeed(7);
ai=new AIPaddle(width,0,SPEED_AI,width,height);
url=Pong.class.getResource("pongLimit.wav");
_url=Pong.class.getResource("pongScore.wav");
clipContact=Applet.newAudioClip(url);
clipScore=Applet.newAudioClip(_url);
timer=new Timer(10,this);
timer.start();
ballMovement=true;
}
@Override
public void mpaint ( Graphics2D g2 ){
GraphSet.setColor(g2, 255, 255, 255);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
try
{
g2.draw(ball);
g2.fill(ball);
g2.draw(player);
g2.fill(player);
g2.draw(ai);
g2.fill(ai);
g2.setFont(new Font("8BIT WONDER", Font.BOLD, 20)); //OLD WILD 8 Bit FONT :D
setDimension(g2);
g2.drawString(""+_points,width/2+30,scoreY);
g2.drawString(""+points, width/2-45,scoreY);
for(int i=0;i<height+10;i+=10)
{
Rectangle2D.Double r=new Rectangle2D.Double(width/2,i,5,5);
g2.draw(r);
g2.fill(r);
}
}
catch(NullPointerException exc)
{
}
if(score!=0)
{
if(score==1)
g2.drawString("You score",scorePX,height/2);
else
g2.drawString("Computer score",scoreCX,height/2);
}
}
void moveBall()
{
if(points==10)
jackpot("Game Over\nWanna continue playing?","You win!");
else if(_points==10)
jackpot("Game Over\nWanna continue playing?","You lose!");
if(ball.getBounds().intersectsLine(new Line2D.Double(0,height,width,height)))
{
movement=0;
clipContact.play();
}
else if(ball.getBounds().intersectsLine(new Line2D.Double(0,0,width,0)))
{
movement=1;
clipContact.play();
}
else if(ball.getBounds().intersectsLine(new Line2D.Double(width+11,0,width+11,height))) //+11 offset
{
if(!ball.getBounds().intersects(ai))
{
score=1;
points++;
printScore();
new GameScore(clipScore).run(); //utilizzo oggetto esterno causa thread.
movement=2;
}
else
{
if(ball.getBounds().intersectsLine(ai.getX(),ai.getY(),ai.getX(),(ai.getY()+20)))
movement=4;
else if(ball.getBounds().intersectsLine(ai.getX(),ai.getY()+20,ai.getX(),(ai.getY()+40)))
movement=5;
else if(ball.getBounds().intersectsLine(ai.getX(),ai.getY()+40,ai.getX(),(ai.getY()+60)))
movement=6;
}
clipContact.play();
}
else if(ball.getBounds().intersectsLine(new Line2D.Double(-5,0,-5,height)))
{
if(!ball.getBounds().intersects(player))
{
score=2;
_points++;
printScore();
new GameScore(clipScore).run(); //utilizzo oggetto esterno causa thread.
movement=3;
}
else
{
if(ball.getBounds().intersectsLine(player.getX(),player.getY(),player.getX(),(player.getY()+20)))
movement=7;
else if(ball.getBounds().intersectsLine(player.getX(),player.getY()+20,player.getX(),(player.getY()+40)))
movement=8;
else if(ball.getBounds().intersectsLine(player.getX(),player.getY()+40,player.getX(),(player.getY()+60)))
movement=9;
}
clipContact.play();
}
switch(movement)
{
case 0: ball.moveY(false); ball.moveX(right); down=false; break;
case 1: ball.moveY(true); ball.moveX(right); down=true; break;
case 2: ball.moveX(false); ball.moveY(down); right=false; break;
case 3: ball.moveX(true); ball.moveY(down); right=true; break;
case 4: /*if(down&&!up)
{
down=false;
up=true;
}
else if(!down&&up)
{
down=true;
up=false;
}
else
{
down=false;
up=true;
}*/
right=false; if(ball.getX()>=ai.getX()) down=false; ball.moveY(down); ball.moveX(right); break;
case 5: right=false; ball.setSpeed(9); ball.moveX(right); ball.setSpeed(6); break;
case 6: right=false; if(ball.getX()>=ai.getX()) down=false; ball.moveY(down); ball.moveX(right); break;
case 7: right=true; if(ball.getX()<=player.getX()) down=true; ball.moveY(down); ball.moveX(right); break;
case 8: right=true; ball.setSpeed(9); ball.moveX(right); ball.setSpeed(6); break;
case 9: right=true; if(ball.getX()<=player.getX()) down=true; ball.moveY(down); ball.moveX(right); break;
default:ball.moveX(true);
ball.moveY(true);
down=true;
right=true;
break;
}
}
private void printScore()
{
timer.stop();
_timer=new Timer(1200,this);
_timer.start();
ballMovement=false;
}
private void reset()
{
ball=new Ball(350,80,20,20);
ball.setSpeed(6);
points=0;
_points=0;
player.setY(0);
mrepaint();
}
private void jackpot(String msg,String ttl)
{
if(JOptionPane.showConfirmDialog(this,msg,ttl,
JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)
reset();
else
{
dispose();
System.exit(0);
}
}
void setDimension(Graphics2D g2) //check the presence of a custom font
{
if(!g2.getFont().getName().equals("8BIT WONDER"))
{
g2.setFont(new Font("Serif", Font.BOLD, 50));
scoreY=40;
scorePX=width/5;
scoreCX=450;
}
}
private void updateStatus()
{
if(player.getY()>=2)
if(keys[KeyEvent.VK_UP])
{
player.move(false);
}
if(player.getY()<=(height-50))
if(keys[KeyEvent.VK_DOWN])
{
player.move(true);
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(timer)) {
if(ballMovement)
{
updateStatus();
ai.moveAi(ball.x,ball.y);
moveBall();
mrepaint();
}
}
else if(e.getSource().equals(_timer))
{
mrepaint();
score=0;
ballMovement=true;
_timer.stop();
timer.start();
}
}
private class MyKeyListener implements KeyListener {
@Override
public void keyTyped(KeyEvent e) {
keys[e.getKeyCode()]=true;
}
@Override
public void keyPressed(KeyEvent e) {
keys[e.getKeyCode()]=true;
}
@Override
public void keyReleased(KeyEvent e) {
keys[e.getKeyCode()]=false;
}
}
}
package pong;
import java.applet.AudioClip;
/**
*
* @author daniele
*/
public class GameScore implements Runnable {
AudioClip clip;
public GameScore(AudioClip clip)
{
this.clip=clip;
}
@Override
public void run() {
clip.play();
}
}
package pong;
import MGui.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.Random;
import javax.swing.*;
/**
*
* @author daniele&emil
*/
public final class MainMenu extends MFrame implements ActionListener{
private final int SCREEN_WIDTH = 800, SCREEN_HEIGHT = SCREEN_WIDTH/16*10;
private final int BTN_WIDTH = 100, BTN_HEIGHT = 40;
private int width, height,x,y;
private String title;
public MainMenu(int WIDTH, int HEIGHT, String TITLE){
//addButtons();
//addActions();
//getContentPane().setLayout(null);
//Play.setBounds((SCREEN_WIDTH-BTN_WIDTH)/2, 10, BTN_WIDTH, BTN_HEIGHT);
//Quit.setBounds((SCREEN_WIDTH-BTN_WIDTH)/2, 70, BTN_WIDTH, BTN_HEIGHT);
//getContentPane().add(Play);
//getContentPane().add(Quit);
//pack();
super.setCanvasBackground(Color.BLACK);
super.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
super.setVisible(true);
super.setTitle(TITLE);
super.setResizable(false);
super.setLocationRelativeTo(null);
super.setDefaultCloseOperation(MFrame.EXIT_ON_CLOSE);
this.width = WIDTH;
this.height = HEIGHT;
this.title = TITLE;
Timer timer=new Timer(250,this);
timer.start();
}
@Override
public void mpaint ( Graphics2D g2 ){
GraphSet.setColor(g2, 255, 255, 255);
Rectangle2D.Double r1=new Rectangle2D.Double(370,height/2,70,30),r2=new Rectangle2D.Double(370,r1.getY()+50,70,30);
g2.draw(r1);
g2.draw(r2);
g2.setFont(new Font("8BIT WONDER", Font.BOLD, 10));
g2.drawString("Play",380,height/2+20);
g2.drawString("Exit",380,(int)r2.getY()+20);
g2.setFont(new Font("8BIT WONDER", Font.BOLD, 40));
g2.drawString("Pong",320,40);
Rectangle2D.Double[] r=new Rectangle2D.Double[100];
for(int i=0;i<r.length;i++)
{
r[i]=new Rectangle2D.Double(new Random().nextInt(width),new Random().nextInt(height),5,5);
g2.draw(r[i]);
g2.fill(r[i]);
}
if(r1.contains(new Point2D.Double(x,y)))
start();
else if(r2.contains(new Point2D.Double(x,y)))
exit();
}
@Override
public void mouseClicked (MouseEvent e) {
x = e.getX();
y = e.getY();
mrepaint();
}
void start()
{
dispose();
new Game(width,height,title);
}
void exit()
{
dispose();
System.exit(0);
}
@Override
public void actionPerformed(ActionEvent e) {
mrepaint();
}
}
package pong;
import java.awt.geom.Rectangle2D;
/**
*
* @author daniele
*/
public class Paddle extends Rectangle2D.Double {
private int speed;
public Paddle(int x,int y,int width,int height)
{
this.x=x;
this.y=y;
this.width=width;
this.height=height;
}
boolean setSpeed(int speed)
{
if(speed<0||speed>16)
return false;
this.speed=speed;
return true;
}
boolean setY(int y)
{
if(y<height)
this.y=y;
return y<height;
}
void move(boolean dir)
{
if(dir)
y+=speed;
else
y-=speed;
}
}
package pong;
/**
*
* @author daniele&emil
*/
public class Pong {
public static void main(String[] args) {
final int WIDTH = 800;
final int HEIGHT = WIDTH / 16 * 9;
final String TITLE = "Pong Beta";
MainMenu a=new MainMenu(WIDTH, HEIGHT, TITLE);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment