بتل کد Battle Codeدارد باز می‌شود…

جواب «Three Hearts» چالش 3 از جلسه‌ی 10

سؤال

شهاب (meteor) با سرعت ۲۴۰ پیکسل در ثانیه می‌افتد. اگر به قهرمان بخورد، به بالا برمی‌گردد.
- متغیر lives را با 3 بساز.
- هر بار که شهاب به قهرمان خورد، lives یکی کم شود.
- بالای صحنه به تعداد lives قلب بکش، با salam.image("heart") و یک for.

راهنما

بیرون از حلقه: const heart = salam.image("heart"); و let lives = 3;. در if برخورد: lives = lives - 1;. آخر حلقه: for (let i = 0; i < lives; i++) { ctx.drawImage(heart, 330 - i * 30, 10, 24, 24); }

یک جواب درست

<script>
  const ctx = salam.canvas(360, 480);
  const hero = { x: 150, y: 420, w: 60, h: 40 };
  const meteor = { x: 160, y: 0, w: 40, h: 40 };
  const heroPic = salam.image("hero");
  const meteorPic = salam.image("meteor");
  const heart = salam.image("heart");
  let lives = 3;
  salam.touchKeys(["ArrowLeft", "ArrowRight"]);

  salam.loop(function (dt) {
    if (salam.keys.ArrowLeft) hero.x = hero.x - 300 * dt;
    if (salam.keys.ArrowRight) hero.x = hero.x + 300 * dt;
    hero.x = Math.max(0, Math.min(360 - hero.w, hero.x));

    meteor.y = meteor.y + 240 * dt;
    if (salam.hit(meteor, hero)) {
      lives = lives - 1;
      meteor.y = 0;
    }
    if (meteor.y > 480) meteor.y = 0;

    ctx.fillStyle = "#1b1440";
    ctx.fillRect(0, 0, 360, 480);
    ctx.drawImage(meteorPic, meteor.x, meteor.y, meteor.w, meteor.h);
    ctx.drawImage(heroPic, hero.x, hero.y, hero.w, hero.h);
    for (let i = 0; i < lives; i++) {
      ctx.drawImage(heart, 330 - i * 30, 10, 24, 24);
    }
  });
</script>

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن