xxxxxxxxxx
// Removing Objects from Arrays
// Code! Programming with p5.js
// The Coding Train / Daniel Shiffman
// https://thecodingtrain.com/beginners/p5js/7.5-removing-objects-from-array.html
// https://youtu.be/tA_ZgruFF9k
// Main Sketch: https://editor.p5js.org/codingtrain/sketches/smC4Jedi
// Trail Sketch: https://editor.p5js.org/codingtrain/sketches/9Ve9S6Mx
let bricks = [];
var ball;
var counter =0;
let timer = 20;
function setup() {
createCanvas(windowWidth, windowHeight);
for (let i = 0; i < 30; i++) {
let x = random(width);
let y = random(height);
let r = random(20, 60);
let b = new Brick(x, y, r);
bricks.push(b);
textSize(60);
}
}
function mousePressed() {
for (let i = bricks.length - 1; i >= 0; i--) {
if (bricks[i].contains(mouseX, mouseY)) {
bricks.splice(i, 1);
}
}
}
function draw() {
background(0);
textAlign(CENTER, CENTER);
textSize(100);
text(timer, width/2, height/3);
if (frameCount % 60 == 0 && timer > 0) { // if the frameCount is divisible by 60, then a second has passed. it will stop at 0
timer --;
}
fill(255);
textAlign(CENTER);
if(frameCount%60>30) text('POINTS:', width/2, height/2); text(counter, width/2, height/1.5);
if (timer == 0) {
background(0);
text("GAME OVER. SCORE: ", width/2, height*0.7);
text(counter, width/2, height*0.8);
}
for (let i = 0; i < bricks.length; i++) {
if (bricks[i].contains(mouseX, mouseY)) {
bricks[i].changeColor(255);
if(mouseIsPressed){
counter++;
}
} else {
bricks[i].changeColor(0);
}
bricks[i].move();
bricks[i].show();
}
}
class Brick {
constructor(x, y, r) {
this.x = x;
this.y = y;
this.r = r;
this.rr = random(128,255);
this.g = random(128,255);
this.b = random(128,255);
this.brightness = 0;
}
changeColor(bright) {
this.brightness = bright;
}
contains(px, py) {
let d = dist(px, py, this.x, this.y);
if (d < this.r) {
return true;
} else {
return false;
}
}
move() {
this.x = this.x + random(-30, 30);
this.y = this.y + random(-30, 30);
}
show() {
stroke(255);
strokeWeight(4);
fill(this.rr,this.g,this.b);
ellipse(this.x, this.y, this.r * 2);
}
}