مثال دیکشنری در پایتون: const hero = { x: 140, y: 420, w: 70, h: 30…
مثال 6 از درس جلسهی 11 آموزش بازیسازی با HTML و JavaScript برای نوجوانان: شروع، بازی، پایان
همه با هم: یک بازی کامل گرفتن ستاره با سه حالت، امتیاز، جان و restart(). بازی کن، ببازی، و دوباره شروع کن. اشتباه رایج: یادت برود در restart() چیزی را صفر کنی؛ مثلاً اگر lives را سه نکنی، بازی بلافاصله دوباره «Game Over» میشود.
<script>
const ctx = salam.canvas(360, 480);
const hero = { x: 140, y: 420, w: 70, h: 30 };
const star = { x: 160, y: 0, w: 30, h: 30 };
const heroPic = salam.image("hero");
const starPic = salam.image("star");
let state = "start";
let score = 0;
let lives = 3;
salam.touchKeys(["ArrowLeft", "ArrowRight"]);
function restart() {
score = 0;
lives = 3;
hero.x = 140;
star.y = 0;
state = "play";
}
salam.tap(function (x, y) {
if (state === "start") {
state = "play";
} else if (state === "over") {
restart();
}
});
salam.loop(function (dt) {
if (state === "play") {
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));
star.y = star.y + 240 * dt;
if (salam.hit(star, hero)) {
score = score + 1;
star.y = 0;
}
if (star.y > 480) {
lives = lives - 1;
star.y = 0;
if (lives === 0) state = "over";
}
}
ctx.fillStyle = "#1b1440";
ctx.fillRect(0, 0, 360, 480);
ctx.fillStyle = "white";
ctx.font = "28px sans-serif";
if (state === "start") {
ctx.fillText("Catch the stars!", 70, 220);
ctx.fillText("Tap to start", 100, 270);
}
if (state === "play") {
ctx.drawImage(starPic, star.x, star.y, star.w, star.h);
ctx.drawImage(heroPic, hero.x, hero.y, hero.w, hero.h);
ctx.fillText("Score: " + score + " Lives: " + lives, 10, 34);
}
if (state === "over") {
ctx.fillText("Game Over", 100, 200);
ctx.fillText("Score: " + score, 120, 250);
ctx.fillText("Tap to play again", 70, 300);
}
});
</script>
این کد را همینجا در ویرایشگر پایتون اجرا کن، عددها و متنهایش را عوض کن و دوباره اجرا کن تا ببینی چه تغییری میکند.
بیشتر بخوان: دیکشنری در پایتون: آموزش کامل کلید و مقدار با مثال
← مثال قبلی · برگشت به درس جلسهی 11: شروع، بازی، پایان · مثال بعدی → · چالشهای این جلسه