xxxxxxxxxx
125
// Slighly modified from an original implementation by Grace Wang
let backgroundColor = 240;
let gravity = 0.3;
let ball = { x: 0, y: 0, dy: 0, falling: false };
let hole;
let launchPointY, hardLevelY, mediumLevelY, easyLevelY;
let [xTextOffset, yTextOffset] = [15, 10];
let score = 0;
function setup() {
// Initialize everything that requires the canvas to be created first
createCanvas(windowWidth, windowHeight);
hole = {
x: width / 2,
y: 0.75 * height,
width: 100,
dx: 1
};
hardLevelY = height / 6;
mediumLevelY = 2 * hardLevelY;
easyLevelY = 3 * hardLevelY;
cursor('grab');
}
function draw() {
background(backgroundColor);
drawLevels();
drawText();
drawHole();
drawBall();
updateBall();
}
function mousePressed() {
if (!ball.falling) {
// Only launch ball if it is not already falling
launchBall();
}
}
function drawBall() {
stroke(0);
fill("#C720BF");
if (ball.falling) {
circle(ball.x, ball.y, 30);
} else {
circle(mouseX, mouseY, 30);
}
}
function updateBall() {
if (ball.falling) {
ball.y += ball.dy;
ball.dy += gravity;
if (ballInHole() || ball.y > height) {
ball.falling = false;
updateScore();
}
}
}
function launchBall() {
// Remember where it was launched from, then initalize for falling
launchPointY = mouseY;
[ball.x, ball.y, ball.dy, ball.falling] = [mouseX, mouseY, 0, true];
}
function ballInHole() {
return abs(ball.y - hole.y) < 10 && abs(ball.x - hole.x) <= hole.width / 2;
}
function drawHole() {
fill(0);
ellipseMode(CENTER);
ellipse(hole.x, hole.y, hole.width, 50);
hole.x += hole.dx;
if (hole.x >= width - hole.width / 2 || hole.x <= hole.width / 2) {
hole.dx *= -1;
}
}
function updateScore() {
if (ballInHole()) {
if (launchPointY < hardLevelY) {
score += 3;
} else if (launchPointY < mediumLevelY) {
score += 2;
} else if (launchPointY < easyLevelY) {
score += 1;
}
}
}
function drawLevels() {
drawLevel(0, hardLevelY, "#F6A193", "red");
drawLevel(hardLevelY, mediumLevelY, "#F6D793", "orange");
drawLevel(mediumLevelY, easyLevelY, "#94E6AB", "green");
}
function drawLevel(top, bottom, fillColor, lineColor) {
noStroke();
fill(fillColor);
rect(0, top, width, bottom - top);
stroke(lineColor);
strokeWeight(2);
line(0, bottom, width, bottom);
}
function drawText() {
noStroke();
fill(0);
text("SCORE: " + score, width - 90, 50);
text("Hard (+3)", xTextOffset, hardLevelY - yTextOffset);
text("Medium (+2)", xTextOffset, mediumLevelY - yTextOffset);
text("Easy (+1)", xTextOffset, easyLevelY - yTextOffset);
text(
"Click to drop a ball. Earn points by dropping a ball into the hole.",
xTextOffset,
height - yTextOffset - 30
);
}