xxxxxxxxxx
112
let shapes = [];
function setup() {
createCanvas(600, 400);
noStroke();
}
function draw() {
background(220);
// Create and display random shapes
for (let i = 0; i < shapes.length; i++) {
shapes[i].display();
shapes[i].move();
}
// Add a new shape to the array randomly
if (random(1) < 0.08) {
let x = random(width);
let y = random(height);
let choice = floor(random(3)); // Randomly choose a shape: 0, 1, or 2
let shape;
if (choice === 0) {
shape = new Circle(x, y);
} else if (choice === 1) {
shape = new Rectangle(x, y);
} else {
shape = new Triangle(x, y);
}
shapes.push(shape);
}
}
class Circle {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = random(90, 10);
this.color = color(random(255), random(255), random(255));
}
display() {
fill(this.color);
ellipse(this.x, this.y, this.size);
}
move() {
this.x += random(1, -1);
this.y += random(-1, 1);
}
}
class Rectangle {
constructor(x, y) {
this.x = x;
this.y = y;
this.width = random(80, 20);
this.height = random(80, 20);
this.color = color(random(255), random(255), random(255));
}
display() {
fill(this.color);
rect(this.x, this.y, this.width, this.height);
}
move() {
this.x += random(1, -1);
this.y += random(-1, 1);
}
}
class Triangle {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = random(90, 10);
this.color = color(random(255), random(255), random(255));
}
display() {
fill(this.color);
triangle(this.x, this.y - this.size / 2, this.x - this.size / 2, this.y + this.size / 2, this.x + this.size / 2, this.y + this.size / 2);
}
move() {
this.x += random(-1, 1);
this.y += random(-0, -1);
}
}
function mousePressed() {
// Remove a shap==e if clicked
for (let i = shapes.length - 1; i >= 0; i--) {
let d = dist(mouseX, mouseY, shapes[i].x, shapes[i].y);
if (d < shapes[i].size / 2 || d < shapes[i].width / 2) {
shapes.splice(i, 1);
}
}
}
function keyPressed() {
// Clear all shapes if 'C' key is pressed
if (key === 'c' || key === 'C') {
shapes = [];
}
}