جواب «Step 3: Lives and Serve» چالش 3 از جلسهی 12
سؤال
حالا توپ که بیفتد، برای همیشه رفته. سه جان بده:
- let lives = 3; و قلبها را بالای صحنه بکش (salam.image("heart")).
- یک تابع serve() بنویس که توپ را به x = 170، y = 100 با vx = 120 و vy = -180 برگرداند.
- وقتی توپ از پایین رد شد (ball.y > 480): lives یکی کم شود و serve() صدا زده شود.
(فعلاً بعد از تمام شدن جانها بازی ادامه دارد؛ قدم بعد درستش میکنیم.)
راهنما
if (ball.y > 480) { lives = lives - 1; serve(); }. قلبها: for (let i = 0; i < lives; i++) { ctx.drawImage(heart, 330 - i * 30, 10, 24, 24); }
یک جواب درست
<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 };
const heart = salam.image("heart");
let score = 0;
let lives = 3;
salam.touchKeys(["ArrowLeft", "ArrowRight"]);
function serve() {
ball.x = 170;
ball.y = 100;
ball.vx = 120;
ball.vy = -180;
}
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;
}
if (ball.y > 480) {
lives = lives - 1;
serve();
}
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);
for (let i = 0; i < lives; i++) {
ctx.drawImage(heart, 330 - i * 30, 10, 24, 24);
}
ctx.fillStyle = "gold";
ctx.fillRect(paddle.x, paddle.y, paddle.w, paddle.h);
});
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن