Home

A JavaScript game “BalloonPop”

I’ll provide you with a simple JavaScript game called “Balloon Pop”. In this game, the player clicks on balloons that appear on the screen, and each successful click will increment the score. The game will use the HTML Canvas API for the graphical rendering.

Here’s the code:

  1. Create an HTML file with the following content:
htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Balloon Pop</title>
  <style>
    canvas {
      display: block;
      margin: 0 auto;
      background-color: skyblue;
    }
  </style>
</head>
<body>
  <canvas id="gameCanvas" width="800" height="600"></canvas>
  <script src="balloonPop.js"></script>
</body>
</html>
  1. Create a JavaScript file named “balloonPop.js” and add the following code:
javascriptCopy codeconst canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");

let balloons = [];
let score = 0;

class Balloon {
  constructor() {
    this.x = Math.random() * canvas.width;
    this.y = canvas.height;
    this.speed = Math.random() * 3 + 1;
    this.radius = Math.random() * 20 + 10;
    this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
  }

  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.y -= this.speed;
  }
}

function addBalloon() {
  balloons.push(new Balloon());
  setTimeout(addBalloon, Math.random() * 2000);
}

function drawScore() {
  ctx.font = "24px Arial";
  ctx.fillStyle = "black";
  ctx.fillText(`Score: ${score}`, 10, 30);
}

function gameLoop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  for (const balloon of balloons) {
    balloon.update();
    balloon.draw();
  }

  drawScore();
  requestAnimationFrame(gameLoop);
}

canvas.addEventListener("click", (e) => {
  const mouseX = e.clientX - canvas.getBoundingClientRect().left;
  const mouseY = e.clientY - canvas.getBoundingClientRect().top;

  balloons = balloons.filter((balloon) => {
    const distance = Math.hypot(balloon.x - mouseX, balloon.y - mouseY);

    if (distance < balloon.radius) {
      score++;
      return false;
    }

    return true;
  });
});

addBalloon();
gameLoop();

To play the game:

  1. Save the HTML and JavaScript files in the same folder.
  2. Open the HTML file in a browser.
  3. Balloons will appear from the bottom of the screen and float upwards. Click on the balloons to pop them and increase your score. The game continues indefinitely.

The game uses the HTML Canvas API to draw balloons with random sizes, colors, and speeds. The score is displayed in the top-left corner of the screen. When a player clicks on a balloon, the score increases, and the balloon is removed from the screen.