Difference between revisions of "Simple Game of Pong"

From dftwiki3
Jump to: navigation, search
(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...")
 
Line 5: Line 5:
  
 
<source lang="java">
 
<source lang="java">
 +
// pong.pde
 +
// D. Thiebaut
 +
// Processing
 +
// Defines a ball and a paddle.  The ball moves on the screen with directions dirX and dirY
 +
// and bounces off the walls and off the paddle, if it hits it.
 +
// The paddle moves only in a fixed vertical axis and its position is controlled by the mouse.
 +
//
  
 
int width = 600;
 
int width = 600;

Revision as of 22:15, 21 November 2011

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


  • This is a quick game of pong written in Processing.
// pong.pde
// D. Thiebaut
// Processing
// Defines a ball and a paddle.  The ball moves on the screen with directions dirX and dirY
// and bounces off the walls and off the paddle, if it hits it.
// The paddle moves only in a fixed vertical axis and its position is controlled by the mouse.
//

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 );
}