← Nível 2 – Mago

Lição 6 de 8 ⏱ 40 minutos

Um quiz para os teus visitantes

Perguntas, respostas e contagem de pontos. Em miniatura, vais aprender a lógica por trás de cada jogo.

Como vai funcionar

Vais construir um quiz: uma pergunta, três escolhas, clica para responder e a pontuação aparece no fim. Os dados do quiz (perguntas e respostas) vão viver num array de objetos – parece complicado, mas vais ver que é só uma lista bem organizada.

Vou mostrar-te: os dados do quiz

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,
  },
];

Vou mostrar-te: o motor do quiz

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

Coisas novas:

Agora és tu 💪

Constrói um quiz com as tuas perguntas – pelo menos cinco. Ideias de projeto:

Basta trocar o conteúdo do array questions – o motor do quiz mantém-se igual. É exatamente por isso que dados e lógica ficam separados!

Bónus: feedback colorido para as respostas

Queres que a resposta correta pisque a verde? Ajusta answer para colorir os botões primeiro, depois mostra a próxima pergunta após um segundo:

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) significa «corre isto depois de 1000 milissegundos.» E style.backgroundColor muda o CSS diretamente a partir do JavaScript.

Verifica tu: O quiz faz perguntas uma a seguir à outra, conta pontos e mostra o resultado no fim. Acabaste de escrever a tua primeira aplicação a sério – tem dados, lógica e interface de utilizador.

O que ficas a saber desta lição