xxxxxxxxxx
73
// Base class
class Shape {
constructor(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
}
// Common method for all shapes
display() {
fill(this.color);
noStroke();
}
move() {
this.x += random(-2, 2);
this.y += random(-2, 2);
}
}
// Child class: Circle
class Circle extends Shape {
constructor(x, y, color, radius) {
super(x, y, color); // Call the parent constructor
this.radius = radius;
}
// Override the display method
display() {
super.display(); // Call the parent display method
ellipse(this.x, this.y, this.radius * 2);
}
}
// Child class: Square
class Square extends Shape {
constructor(x, y, color, size) {
super(x, y, color); // Call the parent constructor
this.size = size;
}
// Override the display method
display() {
super.display(); // Call the parent display method
rect(this.x - this.size / 2, this.y - this.size / 2, this.size, this.size);
}
}
let shapes = [];
function setup() {
createCanvas(600, 400);
// Create some shapes
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
shapes.push(new Circle(random(width), random(height), color(random(255), random(255), random(255)), random(20, 50)));
} else {
shapes.push(new Square(random(width), random(height), color(random(255), random(255), random(255)), random(20, 50)));
}
}
}
function draw() {
background(220);
// Display and move each shape
for (let shape of shapes) {
shape.move();
shape.display();
}
}