جواب «No More Lives» چالش 5 از جلسهی 10
سؤال
بازی شهاب با سه جان آماده است، ولی وقتی جانها تمام میشود بازی ادامه پیدا میکند و شهاب هنوز میافتد.
وقتی lives به 0 رسید، همه چیز بایستد: شهاب دیگر نیفتد، قهرمان راه نرود و lives منفی نشود. وسط صحنه هم Game Over بنویس.
راهنما
حرکت قهرمان و شهاب و برخورد را داخل if (lives > 0) { ... } بگذار. بعد از کشیدن صحنه: if (lives === 0) { ctx.fillText("Game Over", 80, 240); }
یک جواب درست
<script>
const ctx = salam.canvas(360, 480);
const hero = { x: 150, y: 420, w: 60, h: 40 };
const meteor = { x: 160, y: 0, w: 40, h: 40 };
const heroPic = salam.image("hero");
const meteorPic = salam.image("meteor");
const heart = salam.image("heart");
let lives = 3;
salam.touchKeys(["ArrowLeft", "ArrowRight"]);
salam.loop(function (dt) {
if (lives > 0) {
if (salam.keys.ArrowLeft) hero.x = hero.x - 300 * dt;
if (salam.keys.ArrowRight) hero.x = hero.x + 300 * dt;
hero.x = Math.max(0, Math.min(360 - hero.w, hero.x));
meteor.y = meteor.y + 240 * dt;
if (salam.hit(meteor, hero)) {
lives = lives - 1;
meteor.y = 0;
}
if (meteor.y > 480) meteor.y = 0;
}
ctx.fillStyle = "#1b1440";
ctx.fillRect(0, 0, 360, 480);
ctx.drawImage(meteorPic, meteor.x, meteor.y, meteor.w, meteor.h);
ctx.drawImage(heroPic, hero.x, hero.y, hero.w, hero.h);
for (let i = 0; i < lives; i++) {
ctx.drawImage(heart, 330 - i * 30, 10, 24, 24);
}
if (lives === 0) {
ctx.fillStyle = "white";
ctx.font = "40px sans-serif";
ctx.fillText("Game Over", 80, 240);
}
});
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن