← レベル2 – ウィザード

レッスン 6/8 ⏱ 40 分

訪問者向けクイズ

問題、選択肢、得点管理。ミニチュアで、すべてのゲームのロジックを学ぶ。

どう動くか

クイズを作る:問題、3つの選択肢、クリックで回答、最後に得点表示。クイズデータ(問題と答え)は オブジェクトの配列 に入る——難しそうだけど、きれいに整理されたリストに過ぎない。

見てみよう:クイズデータ

const questions = [
  {
    text: "How many legs does a spider have?",
    choices: ["6", "8", "10"],
    correct: 1,
  },
  {
    text: "Which animal is the fastest?",
    choices: ["cheetah", "falcon", "hare"],
    correct: 1,
  },
  {
    text: "What's the name of our website?",
    choices: ["Code with Martin", "Code with Charlie", "Web with Wendy"],
    correct: 0,
  },
];

見てみよう:クイズエンジン

HTML:

<div class="card">
  <h2 id="quiz-question"></h2>
  <div id="quiz-choices"></div>
  <p id="quiz-status"></p>
</div>

JavaScript:

const questionEl = document.getElementById("quiz-question");
const choicesEl = document.getElementById("quiz-choices");
const statusEl = document.getElementById("quiz-status");

let questionNumber = 0;
let points = 0;

function showQuestion() {
  const question = questions[questionNumber];
  questionEl.textContent = question.text;
  choicesEl.innerHTML = "";   // clear the old buttons

  question.choices.forEach((choice, index) => {
    const button = document.createElement("button");
    button.textContent = choice;
    button.addEventListener("click", () => answer(index));
    choicesEl.appendChild(button);
  });

  statusEl.textContent = "Question " + (questionNumber + 1) + " of " + questions.length;
}

function answer(index) {
  if (index === questions[questionNumber].correct) {
    points++;
  }

  questionNumber++;

  if (questionNumber < questions.length) {
    showQuestion();
  } else {
    questionEl.textContent = "Done! 🎉";
    choicesEl.innerHTML = "";
    statusEl.textContent = "You scored " + points + " out of " + questions.length + " points.";
  }
}

showQuestion();

新しいもの:

やってみよう 💪

自分の 問題でクイズを作ろう——少なくとも5問。プロジェクトのアイデア:

questions 配列の中身を入れ替えるだけ——クイズエンジンは同じ。だからデータとロジックは分ける!

ボーナス:答えの色付きフィードバック

正解を緑に光らせたい? answer を調整して、まずボタンに色を付け、1秒後に次の問題:

function answer(index) {
  const buttons = choicesEl.querySelectorAll("button");
  const correct = questions[questionNumber].correct;

  buttons[correct].style.backgroundColor = "#16a34a";
  if (index !== correct) {
    buttons[index].style.backgroundColor = "#dc2626";
  } else {
    points++;
  }

  setTimeout(() => {
    questionNumber++;
    if (questionNumber < questions.length) {
      showQuestion();
    } else {
      questionEl.textContent = "Done! 🎉";
      choicesEl.innerHTML = "";
      statusEl.textContent = "You scored " + points + " out of " + questions.length + " points.";
    }
  }, 1000);
}

setTimeout(() => {...}, 1000) = 「1000ミリ秒後にこれを実行。」style.backgroundColor で JavaScript から直接 CSS を変更。

確認: クイズが問題を順に出し、得点を記録し、最後に結果を表示。初めての本物のアプリ——データ、ロジック、UI がある。

このレッスンのまとめ