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

جواب «Never Leaves» چالش 4 از جلسه‌ی 7

سؤال

دیوار چپ آماده است. دیوار راست را هم با Math.min بساز. قهرمان ۴۰ پهنا دارد، پس hero.x نباید از 360 - hero.w (یعنی ۳۲۰) بیشتر شود.

راهنما

یک خط دیگر: hero.x = Math.min(360 - hero.w, hero.x);. یا هر دو را با هم: hero.x = Math.max(0, Math.min(360 - hero.w, hero.x));

یک جواب درست

<script>
  const ctx = salam.canvas(360, 480);
  const hero = { x: 160, y: 420, w: 40, h: 40 };

  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));

    ctx.fillStyle = "skyblue";
    ctx.fillRect(0, 0, 360, 480);
    ctx.fillStyle = "tomato";
    ctx.fillRect(hero.x, hero.y, hero.w, hero.h);
  });
</script>

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