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

جواب «First Point» چالش 1 از جلسه‌ی 10

سؤال

قهرمان (hero) از x = 40 راه می‌افتد و سکه (coin) در x = 200 است.
- متغیر score را بیرون از حلقه با 0 بساز.
- وقتی قهرمان به سکه خورد، score یکی زیاد شود و سکه به coin.x = 20 برود (تا امتیاز فقط یک بار داده شود).
- امتیاز را با fillText بالای صحنه بنویس، مثلاً Score: 1.

راهنما

بالای برنامه let score = 0;. در حلقه: if (salam.hit(hero, coin)) { score = score + 1; coin.x = 20; }. آخر حلقه: ctx.fillStyle = "navy"; ctx.font = "24px sans-serif"; ctx.fillText("Score: " + score, 10, 30);

یک جواب درست

<script>
  const ctx = salam.canvas(360, 480);
  const hero = { x: 40, y: 380, w: 40, h: 40 };
  const coin = { x: 200, y: 390, w: 30, h: 30 };
  const heroPic = salam.image("hero");
  const coinPic = salam.image("coin");
  let score = 0;
  salam.touchKeys(["ArrowLeft", "ArrowRight"]);

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

    if (salam.hit(hero, coin)) {
      score = score + 1;
      coin.x = 20;
    }

    ctx.fillStyle = "skyblue";
    ctx.fillRect(0, 0, 360, 480);
    ctx.drawImage(coinPic, coin.x, coin.y, coin.w, coin.h);
    ctx.drawImage(heroPic, hero.x, hero.y, hero.w, hero.h);
    ctx.fillStyle = "navy";
    ctx.font = "24px sans-serif";
    ctx.fillText("Score: " + score, 10, 30);
  });
</script>

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