xxxxxxxxxx
91
let player;
let circles = [];
let score = 0;
let timer = 99999;
function setup() {
createCanvas(400, 400);
player = new Player();
for (let i = 0; i < 10; i++) {
circles.push(new Circle());
}
textSize(20);
}
function draw() {
background(220);
player.show();
player.move();
for (let circle of circles) {
circle.show();
circle.move();
if (player.intersects(circle)) {
circle.reset();
score++;
}
}
fill(0);
text(`Score: ${score}`, 10, 30);
text(`Time left: ${timer}`, 10, 60);
if (timer == 0) {
noLoop();
alert(`Game over! Your score is ${score}.`);
}
timer--;
}
class Player {
constructor() {
this.x = width / 2;
this.y = height - 50;
this.size = 30;
}
show() {
fill(255, 0, 0);
rect(this.x, this.y, this.size, this.size);
}
move() {
if (keyIsDown(LEFT_ARROW) && this.x > 0) {
this.x -= 5;
}
if (keyIsDown(RIGHT_ARROW) && this.x < width - this.size) {
this.x += 5;
}
}
intersects(circle) {
let distance = dist(this.x + this.size / 2, this.y + this.size / 2, circle.x, circle.y);
if (distance < this.size / 2 + circle.size / 2) {
return true;
} else {
return false;
}
}
}
class Circle {
constructor() {
this.reset();
}
show() {
fill(0, 0, 255);
ellipse(this.x, this.y, this.size);
}
move() {
this.y += 2;
if (this.y > height) {
this.reset();
}
}
reset() {
this.x = random(width);
this.y = random(-200, -50);
this.size = random(20, 40);
}
}