> show canvas only <


/* built with Studio Sketchpad: 
 *   https://sketchpad.cc
 * 
 * observe the evolution of this sketch: 
 *   https://bard117s14.sketchpad.cc/sp/pad/view/ro.hCJHmMcxrs0/rev.30
 * 
 * authors: 
 *   Keith O'Hara

 * license (unless otherwise specified): 
 *   creative commons attribution-share alike 3.0 license.
 *   https://creativecommons.org/licenses/by-sa/3.0/ 
 */ 



/*
 * Skeleton of a ball bouncing /game/.
 *
 * Keith O'Hara <[email protected]>
 * March 2014
 *
 */

Ball b; 

float paddle_x;
float paddle_step;
float paddle_size = 15;

void setup() {
  size(500, 200);
  smooth();

  paddle_x = width/2;
  paddle_step = 0;
  b = new Ball();
  b.r = 10;
}

void draw() {
  background(196);

  // move paddle
  paddle_x = paddle_x + paddle_step;

  // draw paddle
  stroke(24);
  fill(64);
  rect(paddle_x, height-paddle_size, paddle_size*3, paddle_size);

  b.move();
  b.show();
}

void keyPressed() {
  if (keyCode == LEFT) {
    paddle_step = -3;
  }
  else if (keyCode == RIGHT) {
    paddle_step = 3;
  }
  else {
    b.reset();
  }
}

void keyReleased() {
  paddle_step = 0;
}

class Ball {

  float x, y;
  float x_step, y_step;
  float r = 5;
  color col;

  Ball() {
    reset();
  }

  void reset() {
    col = color(random(255), random(255), random(255));
    x = random(r, width - r);
    y = random(r, height/2);
    x_step = random(-3, 3);
    y_step = random(1, 3);
  }

  void move() {
    // is the ball hitting the right or left wall?
    if (x - r < 0 || x + r > width) {
      x_step = -x_step;
    } 

    // is the ball hitting the top or bottom wall?
    if (y - r < 0) {
      y_step = -y_step;
    } 

    if (y + r > height - paddle_size) {
      if ( x - r > paddle_x && 
        x + r < paddle_x + paddle_size*3) {
        y_step = -y_step;
        y = height - paddle_size - r;
      } 
    }

    // move ball by ball_x_step and ball_y_step
    x = x + x_step;
    y = y + y_step;
  }

  void show() {
    //draw ball
    noStroke();
    fill(col);
    ellipse(x, y, r*2, r*2);
  }
}