xxxxxxxxxx
88
/*
*** CATCH THE SHEEP GAME ***
Help capturing the flock of sheep that escaped to get back to the corral. Catch them and move them back by clicking and dragging with your mouse, but be careful, if you handle without care, they will escape from you (moving your mouse too fast while dragging them will cause them to fall).
Mouse Interaction with The Coding Train ˜ https://thecodingtrain.com/
Sketch made by Leonardo M. Louzas ( https://github.com/leonardomlouzas ) | 23/aug/24
*/
let sheepAmount = 25;
let sheepsFree = [];
let sheepsCaught = [];
let corral;
function setup() {
createCanvas(windowWidth, windowHeight);
let x;
let y;
corral = new Corral(width / 2, height / 2, (width + height) / 9);
// Create all the sheep making sure they aren't placed inside the corral
for (i = 0; i < sheepAmount; i++) {
sheepsFree.push(new Sheep(0, 0));
do {
x = random(width);
y = random(height);
} while (corral.isInside(x, y));
sheepsFree[i].x = x;
sheepsFree[i].y = y;
}
}
function draw() {
background(100, 205, 100);
frameRate(60);
// Show the text
textAlign(CENTER);
textSize(25);
if (sheepsFree.length) {
text("Caught the sheep and put them back in the corral!", width / 2, 50);
} else {
text("You win!", width / 2, 50);
}
// Show the corral and flock
corral.show();
sheepsFree.forEach((sheep) => sheep.show());
sheepsCaught.forEach((sheep) => sheep.show());
// Move the flock every half second
sheepsFree.forEach((sheep) => {
if (sheep.free && frameCount % 30 == 0) {
do {
pos = sheep.move(width, height);
} while (corral.isInside(pos[0], pos[1]));
}
});
sheepsCaught.forEach((sheep) => {
if (frameCount % 30 == 0) {
do {
pos = sheep.move(width, height);
} while (!corral.isInside(pos[0], pos[1]));
}
});
}
function mouseDragged() {
// Grab the sheep and move them
sheepsFree.forEach((sheep) => {
if (sheep.grabbed(mouseX, mouseY)) {
sheep.free = false;
}
});
}
function mouseReleased() {
// Check if the sheep is dropped inside the corral and "ungrab" them
sheepsFree.forEach((sheep, index) => {
if (corral.isInside(sheep.x, sheep.y)) {
sheepCaught = sheepsFree.splice(index, 1);
sheepCaught[0].maxDistance = 20;
sheepCaught[0].smile = true;
sheepsCaught.push(sheepCaught[0]);
}
sheep.free = true;
});
}