Code

float vx=0;
float vy=0;
float px=0;
float py=0;
float lifeCount = 5;

void setup (){
  size (300,300);
  stroke (255);
  fill (255);
  smooth ();
  reset ();
}

void draw (){
  background (0,0,50);
  for (int i=1; i<=lifeCount; i++){
    ellipse (200+i*12,10, 10,10);
  }
  if (lifeCount == -1) {
    background (255,0,0);
    px = width/2;
    py = height/2;
  }
  int puck=16;
  int onCanvas = max (0, min(mouseY-25,height-50));
  rect (20,onCanvas, 5,50);
  px = px +vx;
  py = py + vy;
  boolean bLoseLife = (px<0);
  boolean bOutsideWidth = (px+puck/2>width);
  boolean bOutsideHeight = ((py+puck/2>height) || (py-puck/2<0));
  boolean bPuckHitsPaddle = ((px-puck/2<25) && (px+puck/2>20) && (py-puck/2<(mouseY+25)) && (py+puck/2>(mouseY-25)));
  if (bOutsideWidth) {
    vx = vx*-1;
  }
  if (bOutsideHeight) {
    vy = vy*-1;
  }
  if (bPuckHitsPaddle) {
    vx = vx*-1;
  }
  if (bLoseLife) {
    vx = -1;
    vy = -1;
  }
  ellipse (px,py, puck,puck);
}

void mousePressed () {
  reset ();
  lifeCount = lifeCount-1;
}

void reset (){
  vx = random (-4,4);
  vy = random (-4,4);
  px = width/2;
  py = height/2;
}

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