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".
<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>
راهنما و جواب این چالش · برگشت به درس جلسهی 12: پروژه: توپ و راکت
بیشتر بخوان: دیکشنری در پایتون: آموزش کامل کلید و مقدار با مثال