🎮ArcadeLab

Catch the Falling Objects

by SilverFalcon87
106 lines2.3 KB
▶ Play
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Catch the Falling Objects</title>
<style>
  body { margin: 0; background: #222; }
  canvas { display: block; margin: auto; background: #333; }
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="600"></canvas>
<script>
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");

let player = { x: 180, y: 550, width: 40, height: 20, speed: 5 };
let objects = [];
let score = 0;
let gameOver = false;

// Spawn falling objects
function spawnObject() {
  objects.push({
    x: Math.random() * (canvas.width - 20),
    y: -20,
    width: 20,
    height: 20,
    speed: 2 + Math.random() * 3
  });
}

// Handle player movement
document.addEventListener("keydown", e => {
  if (e.key === "ArrowLeft") player.x -= player.speed;
  if (e.key === "ArrowRight") player.x += player.speed;
});

// Game loop
function update() {
  if (gameOver) return;

  // Move objects
  for (let obj of objects) {
    obj.y += obj.speed;
    // Collision check
    if (
      obj.y + obj.height >= player.y &&
      obj.x < player.x + player.width &&
      obj.x + obj.width > player.x
    ) {
      score++;
      obj.y = canvas.height + 1; // remove
    }
    // Missed object
    if (obj.y > canvas.height) {
      gameOver = true;
    }
  }
  objects = objects.filter(o => o.y <= canvas.height);

  // Keep player inside canvas
  player.x = Math.max(0, Math.min(canvas.width - player.width, player.x));
}

// Draw everything
function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Player
  ctx.fillStyle = "lime";
  ctx.fillRect(player.x, player.y, player.width, player.height);

  // Objects
  ctx.fillStyle = "red";
  for (let obj of objects) {
    ctx.fillRect(obj.x, obj.y, obj.width, obj.height);
  }

  // Score
  ctx.fillStyle = "white";
  ctx.font = "20px Arial";
  ctx.fillText("Score: " + score, 10, 30);

  if (gameOver) {
    ctx.fillStyle = "yellow";
    ctx.font = "30px Arial";
    ctx.fillText("Game Over!", 120, 300);
  }
}

// Main loop
function loop() {
  update();
  draw();
  requestAnimationFrame(loop);
}

// Spawn objects every second
setInterval(spawnObject, 1000);

loop();
</script>
</body>
</html>

Game Source: Catch the Falling Objects

Creator: SilverFalcon87

Libraries: none

Complexity: moderate (106 lines, 2.3 KB)

The full source code is displayed above on this page.

Remix Instructions

To remix this game, copy the source code above and modify it. Add a ARCADELAB header at the top with "remix_of: catch-the-falling-objects-silverfalcon87" to link back to the original. Then publish at arcadelab.ai/publish.