🎮ArcadeLab

Castle Defense Demo

by WildOwl82
87 lines1.7 KB
▶ Play
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Castle Defense Demo</title>
<style>
  body { background:#111; color:white; margin:0; overflow:hidden; }
  canvas { background:#222; display:block; margin:0 auto; }
</style>
</head>
<body>
<canvas id="game" width="420" height="300"></canvas>

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

// Player
let player = { x:40, y:150, w:30, h:30, hp:5 };

// Enemy
let enemies = [];
function spawnEnemy(){
  enemies.push({ x:380, y:Math.random()*260+20, w:25, h:25, hp:1 });
}
setInterval(spawnEnemy, 1200);

// Movement
let touchY = player.y;
canvas.addEventListener("touchmove", e=>{
  let t = e.touches[0];
  touchY = t.clientY - 40;
});

// Game loop
function loop(){
  ctx.clearRect(0,0,420,300);

  // Draw castle wall
  ctx.fillStyle="#444";
  ctx.fillRect(0,0,60,300);

  // Draw player
  player.y += (touchY - player.y)*0.1;
  ctx.fillStyle="cyan";
  ctx.fillRect(player.x, player.y, player.w, player.h);

  // Draw enemies
  ctx.fillStyle="red";
  enemies.forEach(e=>{
    e.x -= 1.5;
    ctx.fillRect(e.x,e.y,e.w,e.h);

    // If enemy hits wall
    if(e.x < 60){
      player.hp--;
      e.x = 9999;  
    }

    // Sword hitbox
    if(e.x < player.x+player.w+20 && e.y > player.y-20 && e.y < player.y+50){
      e.hp = 0;
    }
  });

  // Remove dead enemies
  enemies = enemies.filter(e=>e.hp>0 && e.x>0);

  // Draw HP
  ctx.fillStyle="white";
  ctx.fillText("HP: "+player.hp,10,20);

  if(player.hp <= 0){
    ctx.fillStyle="yellow";
    ctx.font="30px Arial";
    ctx.fillText("GAME OVER", 130,150);
    return;
  }

  requestAnimationFrame(loop);
}

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

Game Source: Castle Defense Demo

Creator: WildOwl82

Libraries: none

Complexity: moderate (87 lines, 1.7 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: castle-defense-demo-wildowl82" to link back to the original. Then publish at arcadelab.ai/publish.