import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.Random; public class Pong { private static final int X_SIZE = 600, Y_SIZE = 600; public static void main(String[ ] args) { JFrame frame = new JFrame("Graphics Skeleton"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(X_SIZE, Y_SIZE); PongPanel panel = new PongPanel( ); panel.setFocusable(true); frame.add(panel); frame.setVisible(true); } private static class PongPanel extends JPanel implements KeyListener, ActionListener { private int p1y,p2y,p1d,p2d,bx,by,bdx,bdy, score1, score2, winner; private Timer t; private Random gen; public PongPanel() { gen=new Random(); launch(); // launches the ball score1=0; winner=0; score2=0; p1y=280; // start each paddle around the middle p2y=280; p1d=0; // each paddle is stopped p2d=0; addKeyListener(this); t=new Timer(10, this); t.start(); } public void launch() { bx=247; // starting point for the ball in the x direction by=gen.nextInt(400)+100; // randomly generate starting point for ball in y direction do{ bdx=gen.nextInt(5)-2; }while(bdx==0); bdy=gen.nextInt(5)-2; } public void bounce() { bdx*=-1; bdy=gen.nextInt(5)-2; } public boolean collide(int p, int bx, int by, int px, int py) { if(p==1&&(bx==px+1||bx==px+2||bx==px+3||bx==px+4)&&by-5>=py&&by+5<=py+30) return true; if(p==2&&(bx==px-9||bx==px-8||bx==px-7||bx==px-6)&&by-5>=py&&by+5<=py+30) return true; return false; } public void actionPerformed(ActionEvent e) { p1y+=p1d; p2y+=p2d; if(p1y<20||p1y>480) p1d=0; if(p2y<20||p2y>480) p2d=0; bx+=bdx; by+=bdy; if(by<20) { bdy*=-1; by=22; } if(by>480) { bdy*=-1; by=478; } if(collide(1,bx,by,20,p1y)) bounce(); if(collide(2,bx,by,480,p2y)) bounce(); if(bx<20) { score2++; if(score2==10) { winner=2; t.stop(); } else launch(); } if(bx>480) { score1++; if(score1==10) { winner=1; t.stop(); } else launch(); } repaint(); } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.black); g.fillRect(0,0,X_SIZE,Y_SIZE); g.setColor(Color.white); g.fillOval(bx,by,10,10); g.fillRect(20,p1y,5,30); g.fillRect(480,p2y,5,30); g.drawString("Player 1: " +score1+" Player2: "+score2,200, 510); if(winner==1) g.drawString("Player 1 wins!", 250,380); else if(winner==2) g.drawString("Player 2 wins!", 250,380); } public void pause(Boolean b) { if(b) t.stop(); else if(!b) t.start(); } public void keyPressed(KeyEvent e) { char c=e.getKeyChar(); if(c=='a') { p1d--; if(p1d<-3) p1d=-3; } if(c=='z') { p1d++; if(p1d>3) p1d=3; } if(c=='k') { p2d--; if(p2d<-3) p2d=-3; } if(c=='m') { p2d++; if(p2d>3) p2d=3; } if(c=='p') pause(true); if(c=='r') pause(false); } public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} } }