Simple Game of Pong

From dftwiki3
Revision as of 23:13, 21 November 2011 by Thiebaut (talk | contribs) (Created page with "--~~~~ ---- * This is a quick game of pong written in [http://processing.org Processing]. <source lang="java"> int width = 600; int height = 400; int ballX = width/2; int ball...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

--D. Thiebaut 22:13, 21 November 2011 (EST)


  • This is a quick game of pong written in Processing.
int width = 600;
int height = 400;
int ballX = width/2;
int ballY = height/2;
int radius = 20;
int dirX = 5;
int dirY = 5;

int paddleW = 20;
int paddleH = 100;
int paddleX = width-30;
int paddleY = height/2;

void setup() {
   size( width, height );
   smooth(); 
}

boolean touchesHorzWall( int ballX, int ballY ) {
   return ( ballY - radius < 0 || ballY + radius > height );
}

boolean touchesVertWall( int ballX, int ballY ) {
   return ( ballX - radius < 0 || ballX + radius > width );  
}

boolean touchesPaddle( int ballX, int ballY ) {
  return ( (ballY > paddleY && ballY < paddleY+paddleH )
           && ( ballX+radius > paddleX ) );
}
void draw() {
  //--- erase backgound ---
  background( 0 );
  
  //--- draw ball ---
  ballX += dirX;
  ballY += dirY; 
  if ( touchesHorzWall( ballX, ballY ) ) dirY *= -1;
  if ( touchesVertWall( ballX, ballY ) ) dirX *= -1; 
  if ( touchesPaddle( ballX, ballY ) ) dirX = -abs( dirX );
  fill( 255 );
  stroke( 255 );
  ellipse( ballX, ballY, radius, radius );
  
  //--- draw paddle ---
  paddleY = mouseY - paddleH/2;
  fill( 128 );
  rect( paddleX, paddleY, paddleW, paddleH );
}