Home | Tools and articles | Donate
Israeli Space Force | Santa Presents Delivery
 

Ping Pong with GameApplet / Alex Zak


This is the final version of the ping-pong java game, as described here





And here is the code:

package pingpong2;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.geom.*;
import java.math.*;
public class PingPong extends Game {
public static final int BATWIDTH=60;
public static final int BATHEIGHT=20;
private int batX=150, batY=400;
private int ballX=150, ballY=50;
private int ballSpeedX=0; //the ball speed on the X axis
private int ballSpeedY=9; //the ball speed on the Y axis
private static final int BALLRADIUS=10;
public void init(){
resize(600,600);
setSleepTime(50);

}
public Color getBackgroundColor(){
return Color.black;
}

public void paint(Graphics g) {
ballX=ballX+ballSpeedX;
ballY=ballY+ballSpeedY;
checkCollisions();
g.setColor(Color.red); //To make the bat red
Point mp=gp.getMousePosition(); //point mp will hold the coordinates of the mouse
if(mp!=null)
{
//Then, if the mouse is in the game window, it's coordinates are copied to
//batX and batY. If the mouse is out of the game window, batX and batY will not change.
batX=mp.x;
batY=mp.y;
}
//finaly, to draw the bat, I call the Garphics method fillRect, that draws and fills
//a rectangle.
g.fillRect(batX-BATWIDTH/2,batY-BATHEIGHT/2,BATWIDTH,BATHEIGHT);
g.setColor(Color.green);
g.fillOval(ballX-BALLRADIUS,ballY-BALLRADIUS,BALLRADIUS*2,BALLRADIUS*2);
}
public void checkCollisions(){
if(ballX-BALLRADIUS<0){
ballSpeedX=-ballSpeedX;
}
if(ballY-BALLRADIUS<0){
ballSpeedY=-ballSpeedY;
}
if(ballX+BALLRADIUS>600){
ballSpeedX=-ballSpeedX;
}
if(ballY+BALLRADIUS>600){
ballX=150;
ballY=50;
ballSpeedX=0;
ballSpeedY=9;
}
Ellipse2D.Double ball=new Ellipse2D.Double(ballX-BALLRADIUS,ballY-BALLRADIUS,BALLRADIUS*2,BALLRADIUS*2);
if(ball.intersects(batX-BATWIDTH/2,batY-BATHEIGHT/2,BATWIDTH,BATHEIGHT)){
ballSpeedX=(ballX-batX)/5;
ballSpeedY=-(int)Math.sqrt(81-ballSpeedX^2);
}

}
}


Questions, complaints and requests? Send them to admin@mysuperiorgames.com