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

جواب «Catch or Miss» چالش 4 از جلسه‌ی 10

سؤال

ستاره (star) با سرعت ۲۴۰ پیکسل در ثانیه می‌افتد. score و lives ساخته شده‌اند و روی صحنه‌اند، ولی هیچ‌وقت عوض نمی‌شوند.
- اگر قهرمان (hero) ستاره را گرفت: score یکی زیاد شود و ستاره به بالا برگردد (star.y = 0).
- اگر ستاره از پایین بیرون رفت (star.y > 480): lives یکی کم شود و ستاره به بالا برگردد.

راهنما

دو if جدا: if (salam.hit(star, hero)) { score = score + 1; star.y = 0; } و if (star.y > 480) { lives = lives - 1; star.y = 0; }

یک جواب درست

<script>
  const ctx = salam.canvas(360, 480);
  const hero = { x: 140, y: 420, w: 70, h: 30 };
  const star = { x: 160, y: 0, w: 30, h: 30 };
  const heroPic = salam.image("hero");
  const starPic = salam.image("star");
  const heart = salam.image("heart");
  let score = 0;
  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));

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

    ctx.fillStyle = "#1b1440";
    ctx.fillRect(0, 0, 360, 480);
    ctx.drawImage(starPic, star.x, star.y, star.w, star.h);
    ctx.drawImage(heroPic, hero.x, hero.y, hero.w, hero.h);
    ctx.fillStyle = "white";
    ctx.font = "24px sans-serif";
    ctx.fillText("Score: " + score, 10, 30);
    for (let i = 0; i < lives; i++) {
      ctx.drawImage(heart, 330 - i * 30, 10, 24, 24);
    }
  });
</script>

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