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

Fresh Start چالش 7 از جلسه‌ی 11، سخت

یک بازی گرفتن ستاره با سه حالت، score و lives آماده است. ولی لمسِ صفحه‌ی پایان فقط state را "play" می‌کند، و چون lives هنوز صفر است، چیزی درست کار نمی‌کند!
یک تابع restart() بنویس که همه چیز را به اول برگرداند: score = 0، lives = 3، قهرمان به hero.x = 140، ستاره به star.y = 0 و state = "play". در صفحه‌ی پایان، لمس آن را صدا بزند.

<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");
  let state = "start";
  let score = 0;
  let lives = 3;
  salam.touchKeys(["ArrowLeft", "ArrowRight"]);

  salam.tap(function (x, y) {
    if (state === "start") {
      state = "play";
    } else if (state === "over") {
      state = "play";
    }
  });

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

    ctx.fillStyle = "#1b1440";
    ctx.fillRect(0, 0, 360, 480);
    ctx.fillStyle = "white";
    ctx.font = "28px sans-serif";
    if (state === "start") {
      ctx.fillText("Catch the stars!", 70, 220);
      ctx.fillText("Tap to start", 100, 270);
    }
    if (state === "play") {
      ctx.drawImage(starPic, star.x, star.y, star.w, star.h);
      ctx.drawImage(heroPic, hero.x, hero.y, hero.w, hero.h);
      ctx.fillText("Score: " + score + "   Lives: " + lives, 10, 34);
    }
    if (state === "over") {
      ctx.fillText("Game Over", 100, 200);
      ctx.fillText("Score: " + score, 120, 250);
      ctx.fillText("Tap to play again", 70, 300);
    }
  });
</script>

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 11: شروع، بازی، پایان · چالش بعدی: Pause

بیشتر بخوان: دیکشنری در پایتون: آموزش کامل کلید و مقدار با مثال