جواب «Step 4: Best Score» چالش 4 از جلسهی 16
سؤال
قدم ۴: رکورد و دوباره!
- let best = salam.load("best", 0);
- وقتی بازی تمام شد و score > best: best = score و salam.save("best", best).
- best را کنار امتیاز بنویس.
- لمس صحنه در حالت "over": meteors = []، timer = 0، score = 0، hero.x = 160 و state = "play". رکورد (best) نباید صفر شود.
راهنما
بعد از filter، هنوز داخل if (state === "play"): if (state === "over" && score > best) { best = score; salam.save("best", best); }. برای دوباره: salam.tap(function (x, y) { if (state === "over") { ... } });
یک جواب درست
<script>
const ctx = salam.canvas(360, 480);
const hero = { x: 160, y: 420, w: 40, h: 40 };
const heroImg = salam.image("rocket");
const meteorImg = salam.image("meteor");
let meteors = [];
let timer = 0;
let score = 0;
let best = salam.load("best", 0);
let state = "play";
salam.touchKeys(["ArrowLeft", "ArrowRight"]);
salam.tap(function (x, y) {
if (state === "over") {
meteors = [];
timer = 0;
score = 0;
hero.x = 160;
state = "play";
}
});
salam.loop(function (dt) {
if (state === "play") {
if (salam.keys.ArrowLeft) hero.x = hero.x - 250 * dt;
if (salam.keys.ArrowRight) hero.x = hero.x + 250 * dt;
hero.x = Math.max(0, Math.min(360 - hero.w, hero.x));
timer = timer + dt;
if (timer >= 1) {
timer = 0;
meteors.push({ x: salam.random(0, 330), y: -30, w: 30, h: 30 });
}
for (const m of meteors) {
m.y = m.y + 200 * dt;
if (m.y > 480) score = score + 1;
if (salam.hit(m, hero)) state = "over";
}
meteors = meteors.filter(function (m) {
return m.y <= 480;
});
if (state === "over" && score > best) {
best = score;
salam.save("best", best);
}
}
ctx.fillStyle = "#14123a";
ctx.fillRect(0, 0, 360, 480);
for (const m of meteors) {
ctx.drawImage(meteorImg, m.x, m.y, m.w, m.h);
}
ctx.drawImage(heroImg, hero.x, hero.y, hero.w, hero.h);
ctx.fillStyle = "white";
ctx.font = "20px sans-serif";
ctx.fillText("Score: " + score + " Best: " + best, 10, 30);
if (state === "over") {
ctx.font = "40px sans-serif";
ctx.fillText("Game Over", 80, 240);
ctx.font = "20px sans-serif";
ctx.fillText("Tap to play again", 100, 280);
}
});
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن