> show canvas only <


/* built with Studio Sketchpad: 
 *   https://sketchpad.cc
 * 
 * observe the evolution of this sketch: 
 *   https://p5js.sketchpad.cc/sp/pad/view/ro.IK-4Sq4sciK/rev.3
 * 
 * authors: 
 *   GoToLoop

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



/**
 * Clickable Balls (v1.0)
 * Jcov (2017-May-21)
 * Mod GoToLoop
 *
 * forum.Processing.org/two/discussion/22678/
 * problem-regarding-arraylist#Item_10
 *
 * p5js.SketchPad.cc/sp/pad/view/ro.CaQVvhrEKxAeXd/latest
 */

"use strict";

const BALLS = 10, balls = [];
let bg;

function setup() {
  createCanvas(500, 500);
  noLoop();

  ellipseMode(CENTER).colorMode(RGB);
  fill('blue').stroke('cyan').strokeWeight(1.5);

  bg = color('#F0A');
}

function draw() {
  background(bg);
  balls.length || makeBalls();
  for (const b of balls)  b.display();
}

function mousePressed() {
  for (let i = balls.length; i--; )
    if (balls[i].isMouseWithinCircle()) {
      const tail = balls.pop();
      if (i !== balls.length)  balls[i] = tail;
      redraw();
      break;
    }
  return false;
}

function makeBalls() {
  balls.length = 0;
  for (let i = 0; i++ < BALLS; balls.push(new Ball));
}

class Ball {
  constructor() {
    this.x = round(random(Ball.RAD, width  - Ball.RAD));
    this.y = round(random(Ball.RAD, height - Ball.RAD));
  }

  display() {
    ellipse(this.x, this.y, Ball.DIAM);
  }

  isMouseWithinCircle() {
    return sq(mouseX - this.x) + sq(mouseY - this.y) < Ball.RAD_SQ;
  }
}

Ball.DIAM = 20;
Ball.RAD = Ball.DIAM >> 1;
Ball.RAD_SQ = Ball.RAD * Ball.RAD;