Untitled

Anonymous
plain_text
02/14/2026 6:14 PM
2.3 KB
11
Indexable
<!DOCTYPE html>
<html>
<head>
<title>Mini Battle Game</title>
<style>
body { margin: 0; overflow: hidden; background: #222; }
#player {
  width: 40px;
  height: 40px;
  background: lime;
  position: absolute;
  bottom: 20px;
  left: 50%;
}
.enemy {
  width: 40px;
  height: 40px;
  background: red;
  position: absolute;
  top: 0;
}
.bullet {
  width: 5px;
  height: 15px;
  background: yellow;
  position: absolute;
}
</style>
</head>
<body>

<div id="player"></div>

<script>
let player = document.getElementById("player");
let bullets = [];
let enemies = [];

document.addEventListener("keydown", function(e) {
  if (e.key === "ArrowLeft") {
    player.style.left = player.offsetLeft - 20 + "px";
  }
  if (e.key === "ArrowRight") {
    player.style.left = player.offsetLeft + 20 + "px";
  }
  if (e.key === " ") {
    shoot();
  }
});

function shoot() {
  let bullet = document.createElement("div");
  bullet.classList.add("bullet");
  bullet.style.left = player.offsetLeft + 18 + "px";
  bullet.style.bottom = "60px";
  document.body.appendChild(bullet);
  bullets.push(bullet);
}

function spawnEnemy() {
  let enemy = document.createElement("div");
  enemy.classList.add("enemy");
  enemy.style.left = Math.random() * window.innerWidth + "px";
  document.body.appendChild(enemy);
  enemies.push(enemy);
}

setInterval(spawnEnemy, 1500);

function gameLoop() {
  bullets.forEach((bullet, bIndex) => {
    bullet.style.bottom = bullet.offsetTop - 10 + "px";
  });

  enemies.forEach((enemy, eIndex) => {
    enemy.style.top = enemy.offsetTop + 2 + "px";
  });

  requestAnimationFrame(gameLoop);
}

gameLoop();
</script>

</body>
</html>

Editor is loading...
Leave a Comment