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

مثال JavaScript: <button id="a" onclick="answer(0)">A</butto…

مثال 1 از درس جلسه‌ی 40 آموزش تایپ‌اسکریپت (TypeScript) برای نوجوانان، با بررسی نوع در مرورگر: پروژه: کوییز روز، با تایپ‌اسکریپت

مینا پارسال با جاوااسکریپت یک «کوییز روز» ساخته است: سه سؤال، هر سؤال سه جواب، و یک امتیاز. اجرایش کن و بازی کن (جواب‌ها: 5، 5 و 9). یک چیز عجیب است: حتی اگر همه را درست بزنی، آخرش می‌نویسد Done! 2 of 3. سؤال سوم هیچ‌وقت درست حساب نمی‌شود! مینا هر چه کد را خوانده، دلیلش را پیدا نکرده است. در این پروژه برنامه را به تایپ‌اسکریپت می‌آوری، و خواهی دید نوع‌ها در چند ثانیه باگ را پیدا می‌کنند.

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
</style>

<p id="msg"></p>
<button id="a" onclick="answer(0)">A</button>
<button id="b" onclick="answer(1)">B</button>
<button id="c" onclick="answer(2)">C</button>
<p id="score">Score: 0</p>
<button id="again" onclick="restart()">Again</button>

<script type="text/typescript">
const questions = [
  { text: "2 + 3", choices: ["4", "5", "6"], answer: 1 },
  { text: "10 / 2", choices: ["5", "2", "20"], answer: 0 },
  { text: "3 * 3", choices: ["6", "33", "9"], answer: "2" },
];
let current = 0;
let score = 0;

function setText(id: string, text: string): void {
  const el = document.getElementById(id);
  if (el) {
    el.textContent = text;
  }
}

function draw(): void {
  setText("score", "Score: " + score);
  if (current >= questions.length) {
    setText("msg", "Done! " + score + " of " + questions.length);
    return;
  }
  const q = questions[current];
  setText("msg", q.text);
  setText("a", q.choices[0]);
  setText("b", q.choices[1]);
  setText("c", q.choices[2]);
}

function answer(choice: number): void {
  if (current >= questions.length) {
    return;
  }
  if (choice === questions[current].answer) {
    score = score + 1;
  }
  current = current + 1;
  draw();
}

function restart(): void {
  current = 0;
  score = 0;
  draw();
}

draw();
</script>

این کد را همین‌جا در ویرایشگر HTML اجرا کن، عددها و متن‌هایش را عوض کن و دوباره اجرا کن تا ببینی چه تغییری می‌کند.

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

برگشت به درس جلسه‌ی 40: پروژه: کوییز روز، با تایپ‌اسکریپت · چالش‌های این جلسه