جواب «Step 4: Start and Game Over» چالش 4 از جلسهی 12
سؤال
آخرین قدم: حالتها.
- let state = "start"; در صفحهی شروع PONG و Tap to start نوشته شود و هیچ چیز حرکت نکند. یک لمس بازی را "play" کند.
- همهی حرکتها و برخوردها فقط در حالت "play".
- وقتی lives صفر شد: state = "over"، و Game Over با امتیاز نوشته شود.
- در حالت "over" یک لمس، تابع restart() را صدا بزند: score = 0، lives = 3، serve() و state = "play".
راهنما
کل کار حلقه را داخل if (state === "play") { ... } بگذار. بعد از serve() در افتادن توپ: if (lives === 0) state = "over";. در salam.tap: if (state === "start") { state = "play"; } else if (state === "over") { restart(); }
یک جواب درست
<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;
let state = "start";
salam.touchKeys(["ArrowLeft", "ArrowRight"]);
function serve() {
ball.x = 170;
ball.y = 100;
ball.vx = 120;
ball.vy = -180;
}
function restart() {
score = 0;
lives = 3;
serve();
state = "play";
}
salam.tap(function (x, y) {
if (state === "start") {
state = "play";
} else if (state === "over") {
restart();
}
});
salam.loop(function (dt) {
if (state === "play") {
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();
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("PONG", 140, 200);
ctx.fillText("Tap to start", 100, 260);
}
if (state === "play") {
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);
}
if (state === "over") {
ctx.fillText("Game Over", 100, 200);
ctx.fillText("Score: " + score, 120, 250);
ctx.fillText("Tap to play again", 70, 300);
}
});
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن