본문 바로가기

개발/javascript

[JS]퀴즈앱 (quiz app)만들기

이번에 만들어 볼 앱은 퀴즈앱이다

여기서 만드는 퀴즈는 주관식은 아니고 객관식에 해당하는 퀴즈를 만든다. 

 

해당 문제에서 퀴즈를 맞추면 문항이 초록색으로 표시되어 다음문제로 넘어가고 

퀴즈를 틀리면 선택한 문항은 빨간색으로 표시되면 동시에 정답인 문항은 초록색으로 표시된다. 

그리고 마지막으로 문제들 중에서 몇 개를 맞추었는지도 나타나게 되는 아주아주 간단하고 쉬운 앱이다.

 

1. 문제 형태

 

2. 정답에 틀렸을 때
3. 정답을 맞췄을 때
4. 최종 점수!


1. 문제 생성 

먼저 어떤 질문들이 들어 가야 할지에 대한 내용을 생성해야한다. 

question이라는 변수를 만들어서 이안에 배열 형태로 질문과 정답을 만든다. 그리고 정답 부분에는 text와 correct로 나누어 해당 질문에 대한 정답인지 아닌지를 판단하게 한다. 

const questions = [
  {
    question: "한입 베어 문 사과는?",
    answers: [
      { text: "사과", correct: false },
      { text: "파인애플", correct: true },
      { text: "오렌지", correct: false },
      { text: "복숭아", correct: false },
    ],
  },
  {
    question: "프론트엔드에서 가장 점유율이 높은 라이브러리는? ",
    answers: [
      { text: "Vue.js", correct: false },
      { text: "Svelte", correct: false },
      { text: "typescript", correct: false },
      { text: "React.js", correct: true },
    ],
  },
  {
    question: "저녁 머 먹지?",
    answers: [
      { text: "김밥", correct: false },
      { text: "햄버거 ", correct: false },
      { text: "우동 ", correct: false },
      { text: "몰라", correct: true },
    ],
  },
];

 

2. DOM

그리고 ID값을 받아서 dom을 만든다.

const questionElement = document.getElementById("question");
const answerButtons = document.getElementById("answer-buttons");
const nextButton = document.getElementById("next-btn");

 

3. 변수 초기화 

currentQuestionIndex는 현재 표시되고 있는 질문의 인덱스를 생성하고 

score는 사용자의 점수를 저장한다. 

let currentQuestionIndex = 0;
let score = 0;

 

4. StartQuiz() 함수 

이 함수는 퀴즈가 시작할 때 호출된다. 

currentQuestionIndex와 Score를 초기화 하고, Next버튼의 텍스트를 Next로 설정한 후 showQuestion()함수를 통해 첫번째 질문을 화면에 표시한다. 

function startQuiz() {
  currentQuestionIndex = 0;
  score = 0;
  nextButton.innerHTML = "Next";
  showQuestion();
}

5. ShowQuestion()함수 

이 함수는 현재 질문과 선택지를 화면에 표시하는 역할을 한다. resetState()를 호출해서 이전 질문의 상태를 초기화하고 현재 질문과 선택지를 화면에 표시하고 각 선택지 버튼을 동적으로 생성하여 answerButtons요소에 추가한다. 

 

정답일 경우에는 button.dataset.correct 에 correct값을 설정한다. 

각 버튼에 selectAnswer함수가 클릭이벤트로 연결된다. 

function showQuestion() {
  resetState();
  let currentQuestion = questions[currentQuestionIndex];
  let questionNo = currentQuestionIndex + 1;
  questionElement.innerHTML = questionNo + ". " + currentQuestion.question;

  currentQuestion.answers.forEach((answer) => {
    const button = document.createElement("button");
    button.innerHTML = answer.text;
    button.classList.add("btn");
    answerButtons.appendChild(button);
    if (answer.correct) {
      button.dataset.correct = answer.correct;
    }
    button.addEventListener("click", selectAnswer);
  });
}

 

6. resetState함수 

이 함수는 새로운 질문을 표시하기 전에 이전 질문과 선택지 버튼들을 초기화한다 .

Nex버튼을 숨기고 answerButton요소에 있는 모든 버튼을 제거한다. 

function resetState() {
  nextButton.style.display = "none";
  while (answerButtons.firstChild) {
    answerButtons.removeChild(answerButtons.firstChild);
  }
}

 

7. selectAnswer함수 

사용자가 선택지를 클릭했을 때 호출되는 함수이다. 사용자가 선택한 답변이 정답인지 확인하고 정답일 경우 해당 버튼에 correct클래스를 추가하여 스타일을 변경하고 점수를 증가시킨다. 모든 버튼을 비활성화하고 정답버튼을 항상 correct클래스를 추가하여 표시한다. 

Next버튼을 다시표시한다. 

function selectAnswer(e) {
  const selectedBtn = e.target;
  const isCorrect = selectedBtn.dataset.correct === "true";
  if (isCorrect) {
    selectedBtn.classList.add("correct");
    score++;
  } else {
    selectedBtn.classList.add("incorrect");
  }
  Array.from(answerButtons.children).forEach((button) => {
    if (button.dataset.correct === "true") {
      button.classList.add("correct");
    }
    button.disabled = true;
  });
  nextButton.style.display = "block";
}

8. ShowScore() 함수 

퀴즈가 끝났을 때 사용자의 점수를 표시하는 함수이다. 이전 상태를 초기화한 후, 사용자가 획득한 점수를 화면에 표시한다. Next버튼의 텍스트를 play Again으로 변경하고 버튼을 다시 표시한다. 

function showScore() {
  resetState();
  questionElement.innerHTML = `You scored ${score} out of ${questions.length}!`;
  nextButton.innerHTML = "play Again";
  nextButton.style.display = "block";
}

9. HandleNextButton()함수 

next버튼을 클릭했을 때 호출되는 함수이다. currentQuestionIndex를 증가시키고, 남은 질문이 있다면 showQuestion()함수를 호출하여 다음 질문을 표시한다. 모든 질문이 끝났다면 showScore()함수를 호출하여 점수를 표시한다. 

function handleNextButton() {
  currentQuestionIndex++;
  if (currentQuestionIndex < questions.length) {
    showQuestion();
  } else {
    showScore();
  }
}

10. nextButton클릭 이벤트 리스너 

next버튼이 클릭되었을 때 호출되는 이벤트 리스너 이다. 현재 질문이 남아있다면 handleNextButton()을 호출하고 , 그렇지 않다면 퀴즈를 다시 시작하기 위해 startQuiz()함수를 호추한다. 

 

11. 그리고 마직막으로 startQuiz()호출해서 퀴즈가 처음 로드될때 바로 시작하도록 한다. !! 

 

'개발 > javascript' 카테고리의 다른 글

[JS] 노트 앱 만들기!  (0) 2024.09.09
[JS]랜덤 패스워드 생성기!!  (0) 2024.09.09
[JS] To do List 만들기 !  (0) 2024.09.05
[JS]날씨앱을 만들어 보자  (2) 2024.09.04
[JS]FAQ만들기  (0) 2024.06.24