جواب «Three Tries» چالش 6 از جلسهی 11
سؤال
بازی با اولین افتادن توپ تمام میشود. سه فرصت بده:
- let lives = 3;
- وقتی توپ از پایین رد شد: lives یکی کم شود و توپ به ball.y = 100 برگردد. اگر lives صفر شد، state = "over".
- وقتی بازی دوباره شروع میشود، lives دوباره 3 شود.
راهنما
به جای if (ball.y > 480) state = "over"; بنویس: if (ball.y > 480) { lives = lives - 1; ball.y = 100; if (lives === 0) state = "over"; }. در salam.tap هم lives = 3; را اضافه کن.
یک جواب درست
<script>
const ctx = salam.canvas(360, 480);
const ball = { x: 170, y: 100, w: 20, h: 20 };
let state = "start";
let lives = 3;
salam.tap(function (x, y) {
if (state === "start") {
state = "play";
} else if (state === "over") {
ball.y = 100;
lives = 3;
state = "play";
}
});
salam.loop(function (dt) {
if (state === "play") {
ball.y = ball.y + 240 * dt;
if (ball.y > 480) {
lives = lives - 1;
ball.y = 100;
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("Tap to start", 100, 240);
}
if (state === "play") {
ctx.fillRect(ball.x, ball.y, ball.w, ball.h);
}
if (state === "over") {
ctx.fillText("Game Over", 100, 220);
ctx.fillText("Tap to play again", 70, 270);
}
});
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن