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

90 lines
2.1 KiB
JavaScript

// circle_xy_list = [[circle_x, circle_y, clicked?], ......]
let circle_xy_list = [];
let total_circle = 0;
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
noFill();
// draw circle according to circle draw list
for (let i = 0; i < circle_xy_list.length; i++) {
[circle_x, circle_y] = circle_xy_list[i];
circle(circle_x, circle_y, 30);
}
// if more than 1 dots, a line formed
if (circle_xy_list.length > 1) {
line(
circle_xy_list[0][0],
circle_xy_list[0][1],
circle_xy_list[1][0],
circle_xy_list[1][1]
);
}
}
function mouseDragged() {
// console.log({ mouse_drag: [mouseX, mouseY] });
mouse_drag_end_xy = [mouseX, mouseY];
mouse_released = false;
for (let i = 0; i < circle_xy_list.length; i++) {
if (circle_xy_list[i][2] == true) {
circle_xy_list[i][0] = mouseX;
circle_xy_list[i][1] = mouseY;
}
}
// prevent default
return false;
}
function mouseReleased() {
// console.log({ mouse_release: [mouseX, mouseY] });
mouse_drag_end_xy = [mouseX, mouseY];
mouse_dragging = false;
mouse_released = true;
for (let i = 0; i < circle_xy_list.length; i++) {
circle_xy_list[i][2] = false;
}
}
function pythTheorem(a, b) {
return Math.pow(Math.pow(a, 2) + Math.pow(b, 2), 0.5);
}
function mousePressed() {
// console.log({ mouse_press: [mouseX, mouseY] });
mouse_drag_start_xy = [mouseX, mouseY];
mouse_dragging = true;
mouse_released = false;
if (circle_xy_list.length > 0) {
circle_found = false;
for (let i = 0; i < circle_xy_list.length; i++) {
[circle_x, circle_y] = circle_xy_list[i];
if (pythTheorem(circle_x - mouseX, circle_y - mouseY) < 30) {
circle_xy_list[i][2] = true;
circle_found = true;
break;
}
}
if (circle_found == false) {
if (total_circle < 2) {
circle_xy_list.push([mouseX, mouseY, false]);
total_circle = total_circle + 1;
}
}
} else {
if (total_circle < 2) {
circle_xy_list.push([mouseX, mouseY, false]);
total_circle = total_circle + 1;
}
}
}