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) نباید صفر شود.
<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 state = "play";
salam.touchKeys(["ArrowLeft", "ArrowRight"]);
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;
});
}
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, 10, 30);
if (state === "over") {
ctx.font = "40px sans-serif";
ctx.fillText("Game Over", 80, 240);
}
});
</script>
راهنما و جواب این چالش · برگشت به درس جلسهی 16: پروژه: جاخالی
بیشتر بخوان: دیکشنری در پایتون: آموزش کامل کلید و مقدار با مثال