// Fish Class
class Fish {
constructor(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
this.speed = Math.random() * 2 + 1;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, 10, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
update() {
const dx = Math.cos(this.angle) * this.speed;
const dy = Math.sin(this.angle) * this.speed;
this.x += dx;
this.y += dy;
if (this.x - 10 <= 0 || this.x + 10 >= width) {
this.x -= dx;
}
if (this.y - 10 <= 0 || this.y + 10 >= height) {
this.y -= dy;
}
}
}
// Player Class
class Player {
constructor(x, y) {
this.x = x;
this.y = y;
this.angle = 0;
}
update() {
this.x += Math.cos(this.angle) * speed;
this.y += Math.sin(this.angle) * speed;
if (this.x < 0) this.x = width;
if (this.x > width) this.x = 0;
if (this.y < 0) this.y = height;
if (this.y > height) this.y = 0;
}
chase(event) {
const dx = event.clientX - this.x;
const dy = event.clientY - this.y;
const angle = Math.atan2(dy, dx) + Math.PI / 2;
this.angle = angle;
}
}
// Initialize all objects
const player = new Player(width / 2, height / 2);
const redFish = [];
for (let i = 0; i < 20; i++) {
redFish.push(new Fish(Math.random() * width, Math.random() * height, "red"));
}
// Main game loop
function gameLoop() {
ctx.clearRect(0, 0, width, height);
redFish.forEach(fish => {
fish.draw();
fish.update();
if (collision(player, fish)) {
score++;
redFish.push(new Fish(Math.random() * width, Math.random() * height, "red"));
}
});
player.update();
if (score % 5 === 0 && score !== 0) {
speed++;
}
requestAnimationFrame(gameLoop);
}
gameLoop();
// Event listeners
canvas.addEventListener("mousemove", (event) => {
player.chase(event);
});
canvas.addEventListener("click", (event) => {
redFish.forEach(fish => {
if (fish.color === "red") {
redFish.push(new Fish(Math.random() * width, Math.random() * height, "red"));
}
});
});
// Collision function
function collision(a, b) {
const dx = Math.abs(a.x - b.x);
const dy = Math.abs(a.y - b.y);
if (dx <= 20 && dy <= 20) {
return true;
} else {
return false;
}
}
</script>