xxxxxxxxxx
112
// A simple mouse-based bouncing ball game
// If you "mouse click" within ball, score goes up
// If you miss a "mouse click", score goes down
//
// Versions:
// - Version 1: https://editor.p5js.org/jonfroehlich/sketches/04sI6mCwQ
// - Version 2 (changes dir/speed after scoring): https://editor.p5js.org/jonfroehlich/sketches/TPN7xA0WD
// - Version 3 (has stages, gets faster): https://editor.p5js.org/jonfroehlich/sketches/Cs1lWc1-_
// - This version (has timing): https://editor.p5js.org/jonfroehlich/sketches/ZtbrCLdhw
//
// By Jon Froehlich
// https://makeabilitylab.cs.washington.edu/
//
let x;
let y;
let xSpeed;
let ySpeed;
let diameter = 40;
let score = 0;
let stage = 1;
let fastestTimeInMs = -1;
let currentHitTimeInMs = -1;
let lastHitTimestamp = -1;
function setup() {
createCanvas(400, 400);
x = width / 2;
y = height / 2;
xSpeed = random(1, 3); // random x speed
ySpeed = random(1, 2); // random y speed
lastHitTimestamp = millis()
}
function draw() {
background(220);
x += xSpeed;
y += ySpeed;
fill(200, 0, 0);
noStroke();
ellipse(x, y, diameter);
// check to make sure it doesn't go offscreen
let radius = diameter / 2;
if(x - radius < 0 || x + radius > width){
xSpeed = xSpeed * -1; // reverse x direction
}
if(y - radius < 0 || y + radius > height){
ySpeed = ySpeed * -1; // reverse y direction
}
textSize(16);
fill("black");
text("Score: " + score + " Stage: " + stage, 10, 25);
if(currentHitTimeInMs > 0){
currentHitTimeInSec = currentHitTimeInMs / 1000;
text("Current hit time: " + currentHitTimeInSec.toFixed(2) + " secs", 10, 45)
}
if(fastestTimeInMs > 0){
fastestTimeInSec = fastestTimeInMs / 1000;
text("Fastest hit time: " + fastestTimeInSec.toFixed(2) + " secs", 10, 65)
}
}
function mousePressed(event){
let distMouseAndCircleCenter = dist(mouseX, mouseY, x, y);
if(distMouseAndCircleCenter <= diameter / 2){
currentHitTimestamp = millis();
let timeBetweenHitsInMs = currentHitTimestamp - lastHitTimestamp;
if(fastestTimeInMs < 0 || timeBetweenHitsInMs < fastestTimeInMs){
fastestTimeInMs = timeBetweenHitsInMs;
}
currentHitTimeInMs = timeBetweenHitsInMs;
score++;
if(score > 0 && score % 5 == 0){ // if score is divisible by 5
stage++;
}
xSpeed = random(1, 2 * stage); // random x speed
ySpeed = random(1, 2 * stage); // random y speed
if(random() < 0.5){
xSpeed = xSpeed * -1;
}
if(random() < 0.5){
ySpeed = ySpeed * -1;
}
// Store the last hit
lastHitTimestamp = currentHitTimestamp;
}else{
score--;
if(score % 5 == 0 && stage > 1){ // if score is divisible by 5
stage--;
}
}
}
function keyPressed() {
if(key == ' '){
print("Reseting the game!")
score = 0;
stage = 0;
fastestTimeInMs = -1;
}
}