بتل کد Battle Codeدارد باز می‌شود…

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.

<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);

// 4. coins, next, the function buy and the function press
</script>

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 15: پروژه: فروشگاه بازی

بیشتر بخوان: جاوااسکریپت چیست؟ از دکمه‌ی وب تا Node.js