html,
body {
  margin: 0;
  padding: 0;
}
canvas {
  display: block;
}
let balls = [];
let ballsTotal = 10;
let shouldWeReset = false;

function setup() {
  createCanvas(window.innerWidth, window.innerHeight);
  colorMode(HSB);
  textAlign(CENTER, CENTER);
  //while
  //creation
  while (balls.length < ballsTotal) {
    let MainBalls = new ball(
      random(100, 500),
      random(100, 500),
      random(2, 8),
      random(2, 8),
      random(20, 50),
      random(360)
    );
    balls.push(MainBalls);
  }
  setInterval(ScoreIncrease, 1000);
}

let score = 0;

function draw() {
  background("black");
  fill(0, 0, 100, 0.2);
  rect(45, 45, width - 90, height - 90);

  fill("white");
  textSize(20);
  text("Score: " + score, 50, 20);
  // Strive.drawTickAxes();

  //player
  if (mouseX > width - 50) {
    mouseX = width - 50;
  }
  if (mouseX < 50) {
    mouseX = 50;
  }

  if (mouseY > height - 50) {
    mouseY = height - 50;
  }
  if (mouseY < 50) {
    mouseY = 50;
  }
  fill("white");
  circle(mouseX, mouseY, 10);

  for (i = 0; i < balls.length; i++) {
    balls[i].display();
    balls[i].move();
    balls[i].collide();
  }
  if (shouldWeReset) {
    noLoop();
    background(0, 0, 0, 0.8);
    textSize(100);
    fill("red");
    text("GAME OVER", width / 2, height / 2);
    textSize(20);
    text("Score: " + score, width / 2, height / 2 + 60);
    fill("white");
    text("Press 'SPACE' to restart", width / 2, height / 2 + 100);
    timer = 0;
    score = 0;
  }
}

class ball {
  constructor(x, y, speedX, speedY, radius, hue) {
    this.x = x;
    this.y = y;
    this.speedX = speedX;
    this.speedY = speedY;
    this.radius = radius;
    this.hue = hue;
  }
  display() {
    fill(this.hue, 100, 100);
    noStroke();
    circle(this.x, this.y, 2 * this.radius);
  }
  move() {
    this.x = this.x + this.speedX;
    this.y = this.y + this.speedY;
    //left
    if (this.x <= this.radius) {
      this.speedX = -this.speedX;
    }
    //right
    if (this.x >= width - this.radius) {
      this.speedX = -this.speedX;
    }
    //top
    if (this.y <= this.radius) {
      this.speedY = -this.speedY;
    }
    //bottom
    if (this.y >= height - this.radius) {
      this.speedY = -this.speedY;
    }
  }

  collide() {
    if (dist(mouseX, mouseY, this.x, this.y) < this.radius + 5) {
      shouldWeReset = true;
    }
  }
}
function keyPressed() {
  if (keyCode == 32) {
    shouldWeReset = false;
    loop();
  }
}

function ScoreIncrease() {
  score++;
}
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js
  2. https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/addons/p5.sound.min.js
  3. https://cdn.jsdelivr.net/gh/StriveMath/p5-teach/dist/Strive.iife.js