Files
sunny9898/task4/Q3c/index.js
louiscklaw 5637fbf94f update,
2025-02-01 02:07:58 +08:00

87 lines
2.0 KiB
JavaScript

function setup() {
createCanvas(400, 400);
background(220);
let balls = []; // 20 objects
for (let i = 0; i < 20; i++) {
// with random position and size (from 10-50)
// [Your Code Here]
random_size = random(10, 50);
balls.push([
random(0 + random_size / 2, 400 - random_size / 2),
random(0 + random_size / 2, 400 - random_size / 2),
random_size,
]);
}
drawBalls(balls);
drawBoundingBox(balls);
}
function drawBalls(balls) {
// [Your Code Here]
let fill_what = [];
let num_balls = balls.length;
for (let i = 0; i < num_balls; i++) {
fill_what.push("white");
}
for (let i = 0; i < num_balls; i++) {
for (let j = 0; j < num_balls; j++) {
if (i == j) {
} else {
start_x = balls[i][0];
start_y = balls[i][1];
end_x = balls[j][0];
end_y = balls[j][1];
d_x = end_x - start_x;
d_y = end_y - start_y;
distance = (d_x ** 2 + d_y ** 2) ** 0.5;
temp = balls[i][2] / 2 + balls[j][2] / 2;
console.log({ i, d_y, distance, temp });
if (distance < temp) {
fill_what[i] = "gray";
fill_what[j] = "gray";
}
}
}
}
console.log(fill_what);
for (let i = 0; i < num_balls; i++) {
fill(fill_what[i]);
circle(balls[i][0], balls[i][1], balls[i][2]);
}
}
// draws smallest rect fitting all balls
function drawBoundingBox(balls) {
// [Your Code Here]
box_top = 99999;
box_left = 9999999;
box_bottom = -1;
box_right = -1;
num_balls = balls.length;
for (let i = 0; i < num_balls; i++) {
circle_left = balls[i][0] - balls[i][2] / 2;
circle_right = balls[i][0] + balls[i][2] / 2;
circle_top = balls[i][1] - balls[i][2] / 2;
circle_bottom = balls[i][1] + balls[i][2] / 2;
box_top = min(box_top, circle_top);
box_left = min(box_left, circle_left);
box_bottom = max(box_bottom, circle_bottom);
box_right = max(box_right, circle_right);
}
stroke("red");
noFill();
rect(box_left, box_top, box_right - box_left, box_bottom - box_top);
}