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

جواب «Step 2: Bounce and Score» چالش 2 از جلسه‌ی 12

سؤال

حالا توپ از وسط راکت رد می‌شود. درستش کن و امتیاز اضافه کن:
- let score = 0;
- وقتی توپ به راکت خورد و پایین می‌آمد (ball.vy > 0)، برگردد بالا و score یکی زیاد شود.
- امتیاز را بالای صحنه بنویس: Score: 1.

راهنما

if (salam.hit(ball, paddle) && ball.vy > 0) { ball.vy = -ball.vy; score = score + 1; } و در کشیدن: ctx.fillText("Score: " + score, 10, 30);

یک جواب درست

<script>
  const ctx = salam.canvas(360, 480);
  const ball = { x: 170, y: 100, w: 16, h: 16, vx: 120, vy: -180 };
  const paddle = { x: 130, y: 440, w: 100, h: 14 };
  let score = 0;
  salam.touchKeys(["ArrowLeft", "ArrowRight"]);

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

    ball.x = ball.x + ball.vx * dt;
    ball.y = ball.y + ball.vy * dt;
    if (ball.x < 0 || ball.x + ball.w > 360) ball.vx = -ball.vx;
    if (ball.y < 0) ball.vy = -ball.vy;
    if (salam.hit(ball, paddle) && ball.vy > 0) {
      ball.vy = -ball.vy;
      score = score + 1;
    }

    ctx.fillStyle = "#1b1440";
    ctx.fillRect(0, 0, 360, 480);
    ctx.fillStyle = "white";
    ctx.fillRect(ball.x, ball.y, ball.w, ball.h);
    ctx.font = "24px sans-serif";
    ctx.fillText("Score: " + score, 10, 30);
    ctx.fillStyle = "gold";
    ctx.fillRect(paddle.x, paddle.y, paddle.w, paddle.h);
  });
</script>

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