Code

float px;
float py;
float vx;
float vy;
float mx0;
float mx1;
float my0;
float my1;
int nLives;

void setup(){
  size(300,300);
  nLives = 5;
  reset();
}

void draw(){
  if (nLives > 0){
    background(0,0,48);
    updatePuckMovement();
    drawLives();
    drawPuck();
  } else {
    background(255,0,0);
  }
  updatePaddle();
}

void updatePaddle(){
  mx0 = 10;
  mx1 = 20;
  float my = max(25, min(height-25, mouseY));
  my0 = my - 25;
  my1 = my + 25;
  fill(255,255,255, 127);
  rect(mx0,my0, mx1-mx0,my1-my0); 
}

void drawPuck(){
  fill(255);
  stroke(255);
  ellipse (px,py,10,10);
}

void drawLives(){
  fill(255,255,255,64);
  stroke(255,255,255,64);
  for (int i=0; i<nLives; i++){ 
    ellipse (10 + i*10,10,7,7);
  }
}

void updatePuckMovement(){
  px += vx;
  py += vy;
  if (px >= width){
    vx = -vx;
  }
  if ((py >= height) || (py <= 0)){
    vy = -vy;
  }

  // reflect if puck hits paddle
  if ((px >= mx0) && (px <= mx1) && 
    (py >= my0) && (py <= my1)){
    vx = -vx;
  }
  // update life count
  if (px < 0){
    nLives--;
    reset();
  }
}


void mousePressed(){
  reset();
}

void reset(){
  px = width/2;
  py = height/2;

  /* 
   // a simple way to generate a random velocity is as follows:
   vx = random(-4,4);
   vy = random(-4,4);
   */

  // This way of generating a random velocity is more sophisticated. 
  // It guarantees a known speed, while choosing a random orientation.
  float angle = random(0, TWO_PI);
  float speed = 4.0;
  vx = speed * cos(angle);
  vy = speed * sin(angle); 
}

0405 - Pong IV: Towards a simple game

Statement:

  • Add a "life counter" to your applet. Initialize this counter at the start of the program so that the player starts out with 5 lives.
  • Indicate the player's current number of lives with a small display in the upper corner. Your indicator could be built either with a series of small pips, or with rendered text. (I haven't demonstrated how to render text in class yet, but there are plenty of good examples.)
  • Each time the puck leaves the left edge of the screen, diminish the user's life count by 1.
  • If the life-count hits zero, turn the screen red and disable further play.

    hide statement