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

73 lines
1.3 KiB
JavaScript

let xpos, ypos, size, numParts;
function setup() {
createCanvas(400, 400);
restartRight();
}
function draw() {
background(220);
caterpillar(xpos, ypos, size, numParts);
xpos -= 2;
if (xpos < 0) {
restartRight();
}
}
// x, y: center point of head
// diam: size of the head
// num: number of body parts
function caterpillar(x, y, diam, num) {
// [Your Code Here]
body(x + diam * 0.8, y, diam * 0.8, num);
head(x, y, diam);
}
function restartRight() {
// [Your Code Here]
xpos = 400;
ypos = Math.floor(random(20, 200 - 20));
size = Math.floor(random(20, 50));
numParts = Math.floor(random(5, 10));
}
function body(x, y, diam, repeat) {
invert = 0;
for (i = 0; i < repeat; i++) {
if (invert == 0) {
fill("rgb(0,200,0)");
invert = 1;
} else {
fill("rgb(0,255,0)");
invert = 0;
}
circle(x + i * diam * 0.8, y, diam);
}
}
// x, y: the center of the head
// diam: the diameter of the head
function head(x, y, diam) {
// [Your Code Here]
fill("rgb(0,255,0)");
circle(x, y, diam);
// eyes
x_factor = diam * 0.15;
y_factor = diam * 0.1;
fill("rgb(0,0,0)");
circle(x - x_factor, y - y_factor, x_factor);
fill("rgb(0,0,0)");
circle(x + x_factor, y - y_factor, x_factor);
noFill();
arc(x, y + y_factor, x_factor * 2, x_factor * 2, 0, PI);
}