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

جواب «Step 3: Crash and Score» چالش 3 از جلسه‌ی 16

سؤال

قدم ۳: قانون‌های بازی!
- let score = 0; و let state = "play";
- هر کاری در حلقه (حرکت موشک، شهاب تازه، افتادن) فقط وقتی انجام شود که state === "play" است.
- داخل for شهاب‌ها: اگر m.y > 480 شد، score یکی زیاد شود؛ اگر salam.hit(m, hero)، state = "over".
- score را روی صحنه بنویس و در حالت "over" متن Game Over را بکش.

راهنما

همه‌ی کارهای حرکت را داخل if (state === "play") { ... } بگذار. در for شهاب‌ها، بعد از m.y = ...: if (m.y > 480) score = score + 1; و if (salam.hit(m, hero)) state = "over";. کشیدن بیرون از آن if می‌ماند.

یک جواب درست

<script>
  const ctx = salam.canvas(360, 480);
  const hero = { x: 160, y: 420, w: 40, h: 40 };
  const heroImg = salam.image("rocket");
  const meteorImg = salam.image("meteor");
  let meteors = [];
  let timer = 0;
  let score = 0;
  let state = "play";
  salam.touchKeys(["ArrowLeft", "ArrowRight"]);

  salam.loop(function (dt) {
    if (state === "play") {
      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));

      timer = timer + dt;
      if (timer >= 1) {
        timer = 0;
        meteors.push({ x: salam.random(0, 330), y: -30, w: 30, h: 30 });
      }
      for (const m of meteors) {
        m.y = m.y + 200 * dt;
        if (m.y > 480) score = score + 1;
        if (salam.hit(m, hero)) state = "over";
      }
      meteors = meteors.filter(function (m) {
        return m.y <= 480;
      });
    }

    ctx.fillStyle = "#14123a";
    ctx.fillRect(0, 0, 360, 480);
    for (const m of meteors) {
      ctx.drawImage(meteorImg, m.x, m.y, m.w, m.h);
    }
    ctx.drawImage(heroImg, hero.x, hero.y, hero.w, hero.h);
    ctx.fillStyle = "white";
    ctx.font = "20px sans-serif";
    ctx.fillText("Score: " + score, 10, 30);
    if (state === "over") {
      ctx.font = "40px sans-serif";
      ctx.fillText("Game Over", 80, 240);
    }
  });
</script>

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