🎮ArcadeLab

Target Game

by SonicBear35
113 lines1.9 KB
▶ Play
<!DOCTYPE html>
<html>
<head>
<title>Target Game</title>
<style>
  body {
    margin: 0;
    background: #222;
    overflow: hidden;
    font-family: Arial;
  }

  canvas {
    display: block;
    margin: auto;
    background: #111;
    cursor: crosshair;
  }

  #score {
    position: fixed;
    top: 10px;
    left: 10px;
    color: white;
    font-size: 20px;
  }
</style>
</head>
<body>

<div id="score">Score: 0</div>
<canvas id="game"></canvas>

<script>
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

let score = 0;

let targets = [];

function createTarget() {
  return {
    x: Math.random() * canvas.width,
    y: Math.random() * canvas.height,
    r: 25 + Math.random() * 20,
    dx: (Math.random() - 0.5) * 4,
    dy: (Math.random() - 0.5) * 4
  };
}

// create targets
for (let i = 0; i < 8; i++) {
  targets.push(createTarget());
}

function drawTargets() {
  for (let t of targets) {
    ctx.beginPath();
    ctx.fillStyle = "red";
    ctx.arc(t.x, t.y, t.r, 0, Math.PI * 2);
    ctx.fill();

    ctx.beginPath();
    ctx.fillStyle = "white";
    ctx.arc(t.x, t.y, t.r / 2, 0, Math.PI * 2);
    ctx.fill();
  }
}

function updateTargets() {
  for (let t of targets) {
    t.x += t.dx;
    t.y += t.dy;

    if (t.x < 0 || t.x > canvas.width) t.dx *= -1;
    if (t.y < 0 || t.y > canvas.height) t.dy *= -1;
  }
}

canvas.addEventListener("click", (e) => {
  let mx = e.clientX;
  let my = e.clientY;

  for (let i = 0; i < targets.length; i++) {
    let t = targets[i];
    let dist = Math.sqrt((mx - t.x) ** 2 + (my - t.y) ** 2);

    if (dist < t.r) {
      score++;
      document.getElementById("score").innerText = "Score: " + score;
      targets[i] = createTarget();
    }
  }
});

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

  updateTargets();
  drawTargets();

  requestAnimationFrame(loop);
}

loop();
</script>

</body>
</html>

Game Source: Target Game

Creator: SonicBear35

Libraries: none

Complexity: moderate (113 lines, 1.9 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: target-game-sonicbear35" to link back to the original. Then publish at arcadelab.ai/publish.