جواب «Grab the Apple» چالش 2 از جلسهی 9
سؤال
قهرمان (hero) از x = 40 راه میافتد و سیب (apple) در x = 200 است.
وقتی قهرمان به سیب خورد، سیب را به گوشهی بالا-چپ ببر: apple.x = 20 و apple.y = 20.
راهنما
بعد از حرکت قهرمان یک if بنویس: if (salam.hit(hero, apple)) { apple.x = 20; apple.y = 20; }
یک جواب درست
<script>
const ctx = salam.canvas(360, 480);
const hero = { x: 40, y: 380, w: 40, h: 40 };
const apple = { x: 200, y: 380, w: 40, h: 40 };
const heroPic = salam.image("hero");
const applePic = salam.image("apple");
salam.touchKeys(["ArrowLeft", "ArrowRight"]);
salam.loop(function (dt) {
if (salam.keys.ArrowLeft) hero.x = hero.x - 200 * dt;
if (salam.keys.ArrowRight) hero.x = hero.x + 200 * dt;
hero.x = Math.max(0, Math.min(360 - hero.w, hero.x));
if (salam.hit(hero, apple)) {
apple.x = 20;
apple.y = 20;
}
ctx.fillStyle = "skyblue";
ctx.fillRect(0, 0, 360, 480);
ctx.drawImage(applePic, apple.x, apple.y, apple.w, apple.h);
ctx.drawImage(heroPic, hero.x, hero.y, hero.w, hero.h);
});
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن