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

جواب «Catch the Star» چالش 6 از جلسه‌ی 9

سؤال

ستاره (star) با سرعت ۱۵۰ پیکسل در ثانیه می‌افتد و قهرمان (hero) پایین صحنه است.
هر بار که قهرمان ستاره را گرفت یا ستاره از پایین صحنه بیرون رفت (star.y > 480)، ستاره را دوباره بالا ببر: star.y = 0، با یک x تصادفی: star.x = salam.random(0, 330).

راهنما

دو حالت در یک if، با || (یا): if (salam.hit(star, hero) || star.y > 480) { star.y = 0; star.x = salam.random(0, 330); }

یک جواب درست

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

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

    star.y = star.y + 150 * dt;

    if (salam.hit(star, hero) || star.y > 480) {
      star.y = 0;
      star.x = salam.random(0, 330);
    }

    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);
  });
</script>

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