جواب «Step 4: Buy with Coins» چالش 4 از جلسهی 15
سؤال
قدم آخر: خرید با دکمهی Buy. زیر کد قبلی بنویس:
- دو جعبهی number: coins با مقدار 50 (سکههای بازیکن) و next با مقدار 0 (نوبت کدام کالاست).
- تابع buy یک Item میگیرد و یک string برمیگرداند. اگر coins از قیمت کمتر است، چیزی نمیخرد و برمیگرداند Not enough coins for Shield (با اسم همان کالا). وگرنه قیمت را از coins کم میکند و برمیگرداند Bought Sword, 20 coins left.
- تابع press (دکمه آن را صدا میزند): buy(items[next]) را نشان میدهد و next را یکی زیاد میکند. اگر next به items.length رسید، دوباره 0 شود.
با چهار بار زدن دکمه باید این خطها اضافه شوند: Bought Sword, 20 coins left، Not enough coins for Shield، Bought Potion, 10 coins left، Not enough coins for Sword.
راهنما
در buy: if (coins < item.price) { return "Not enough coins for " + item.name; } بعد coins = coins - item.price; و return "Bought " + item.name + ", " + coins + " coins left";. تابع دکمه: function press(): void { ... }
یک جواب درست
<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>
<button id="buy" onclick="press()">Buy</button>
<pre id="out"></pre>
<script type="text/typescript">
interface Item {
name: string;
price: number;
}
function label(item: Item): string {
return item.name + ": " + item.price + " coins";
}
const items: Item[] = [
{ name: "Sword", price: 30 },
{ name: "Shield", price: 45 },
{ name: "Potion", price: 10 },
];
for (const item of items) {
show(label(item));
}
function total(list: Item[]): number {
let sum: number = 0;
for (const item of list) {
sum = sum + item.price;
}
return sum;
}
function cheapest(list: Item[]): Item {
let best: Item = list[0];
for (const item of list) {
if (item.price < best.price) {
best = item;
}
}
return best;
}
show("Total: " + total(items));
show("Cheapest: " + cheapest(items).name);
let coins: number = 50;
let next: number = 0;
function buy(item: Item): string {
if (coins < item.price) {
return "Not enough coins for " + item.name;
}
coins = coins - item.price;
return "Bought " + item.name + ", " + coins + " coins left";
}
function press(): void {
show(buy(items[next]));
next = next + 1;
if (next === items.length) {
next = 0;
}
}
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن