← 第 2 关 – 魔法师

第 6/8 课 ⏱ 40 分钟

给访客的测验

问题、答案和记分。你会学到每个游戏背后的逻辑。

它会怎么工作

你要做一个测验:一个问题、三个选项、点击作答、最后显示分数。测验数据(问题和答案)存在 对象数组 里——听起来高级,其实就是整齐排列的列表。

跟我看:测验数据

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

新东西:

轮到你了 💪

你自己的 问题做测验——至少五题。项目想法:

只换 questions 数组的内容——测验引擎不变。这就是数据和逻辑分开的原因!

额外:答案彩色反馈

想让正确答案闪绿?调整 answer,先给按钮上色,一秒后再显示下一题:

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。

检查一下: 测验一题接一题,记分,最后显示结果。你刚刚写了第一个真正的应用——有数据、逻辑和用户界面。

这堂课你要记住