← 레벨 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>

자바스크립트:

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`따라서 먼저 버튼의 색상을 지정하고 잠시 후에 다음 질문을 표시해.
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.backgroundColorCSS를 JavaScript에서 직접 변경해.

**직접 확인해 보세요:** 퀴즈는 차례로 질문하고 점수를 기록하며 마지막에 결과를 보여줍니다. 방금 첫 번째 실제 애플리케이션을 작성했어. 여기에는 데이터, 로직 및 사용자 인터페이스가 포함되어 있어.

이번 수업에서 배울 점