// Setup canvas and game variables
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
canvas.width = 800;
canvas.height = 600;
// Bubble object
class Bubble {
constructor(x, y, color) {
this.x = x;
this.y = y;
this.radius = 20;
this.color = color;
this.dx = 0;
this.dy = 0;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
update() {
this.x += this.dx;
this.y += this.dy;
}
checkCollision(bubbles) {
for (let i = 0; i < bubbles.length; i++) {
const b = bubbles[i];
const distance = Math.sqrt((this.x - b.x) ** 2 + (this.y - b.y) ** 2);
if (distance < this.radius + b.radius) {
return b;
}
}
return null;
}
}
// Game variables
let shooterBubble = new Bubble(canvas.width / 2, canvas.height - 30, "red");
let bubbles = [];
let isShooting = false;
// Colors for the bubbles
const colors = ["red", "green", "blue", "yellow", "purple"];
// Event Listener for shooting
document.addEventListener("click", (event) => {
if (!isShooting) {
const angle = Math.atan2(event.clientY - shooterBubble.y, event.clientX -
shooterBubble.x);
shooterBubble.dx = Math.cos(angle) * 5;
shooterBubble.dy = Math.sin(angle) * 5;
isShooting = true;
}
});
// Function to generate random bubbles
function generateBubbles() {
for (let i = 0; i < 5; i++) {
const x = Math.random() * (canvas.width - 40) + 20;
const y = Math.random() * 200 + 20;
const color = colors[Math.floor(Math.random() * colors.length)];
bubbles.push(new Bubble(x, y, color));
}
}
// Game loop
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw shooter bubble
shooterBubble.draw();
// Update and draw all bubbles
for (let i = 0; i < bubbles.length; i++) {
const bubble = bubbles[i];
bubble.draw();
}
// Update shooting bubble position
if (isShooting) {
shooterBubble.update();
if (shooterBubble.y <= 0) {
isShooting = false;
shooterBubble = new Bubble(canvas.width / 2, canvas.height - 30, "red");
}
// Check for collision with other bubbles
const collidedBubble = shooterBubble.checkCollision(bubbles);
if (collidedBubble) {
shooterBubble.dy = 0;
shooterBubble.dx = 0;
isShooting = false;
shooterBubble = new Bubble(canvas.width / 2, canvas.height - 30, "red");
// Add the new bubble to the bubble array
bubbles.push(new Bubble(collidedBubble.x, collidedBubble.y,
shooterBubble.color));
}
}
requestAnimationFrame(gameLoop);
}
// Start the game
generateBubbles();
gameLoop();