xxxxxxxxxx
78
var screen = 0;
var y = -20;
var x = 200;
var speed = 2;
var score = 0;
function setup() {
createCanvas(600, 400);
}
function draw() {
if (screen == 0) {
startScreen();
} else if (screen == 1) {
gameOn();
} else if (screen == 2) {
endScreen();
}
}
function startScreen() {
background(96, 157, 255);
fill(255);
textAlign(CENTER);
text('WELCOME TO AVOID THE BALL GAME', width / 2, height / 2);
text('click to start', width / 2, height / 2 + 20);
reset();
}
function gameOn() {
background(0);
text("score = " + score, 30, 20);
ellipse(x, y, 20, 20); // The ball
rectMode(CENTER);
rect(mouseX, height - 10, 50, 30); // The player platform
y += speed;
// Check for collision with the platform
if (y > height - 25 && x > mouseX - 25 && x < mouseX + 25) {
screen = 2; // End the game when the ball touches the platform
}
// If the ball goes off the screen without touching, reset its position and increase score and speed
if (y > height) {
y = -20;
speed += 0.5;
score += 1;
pickRandom();
}
}
function pickRandom() {
x = random(20, width - 20); // Pick a random x position for the ball
}
function endScreen() {
background(150);
textAlign(CENTER);
text('GAME OVER', width / 2, height / 2);
text("SCORE = " + score, width / 2, height / 2 + 20);
text('click to play again', width / 2, height / 2 + 40);
}
function mousePressed() {
if (screen == 0) {
screen = 1;
} else if (screen == 2) {
screen = 0;
}
}
function reset() {
score = 0;
speed = 2;
y = -20;
}