Cakey3101

Javascript Trivia Game

May 25th, 2025
322
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 7.14 KB | Source Code | 0 0
  1. const allQuestions = [
  2.     { question: "What is the capital of France?", options: ["Paris", "London", "Rome"], answer: "Paris", explanation: "Paris is the capital of France, known for its art, fashion, and culture." },
  3.     { question: "Who wrote 'Hamlet'?", options: ["Shakespeare", "Hemingway", "Poe"], answer: "Shakespeare", explanation: "'Hamlet' is one of Shakespeare's most famous plays, known for its themes of revenge and existential struggle." },
  4.     { question: "What is 5 + 3?", options: ["5", "8", "10"], answer: "8", explanation: "5 plus 3 equals 8. A simple math calculation using addition." },
  5.     { question: "Which planet is known as the Red Planet?", options: ["Earth", "Mars", "Jupiter"], answer: "Mars", explanation: "Mars is called the 'Red Planet' due to its iron oxide-rich surface." },
  6.     { question: "How many continents are there?", options: ["5", "6", "7"], answer: "7", explanation: "Earth has seven continents: Africa, Antarctica, Asia, Europe, North America, South America, and Australia." },
  7.     { question: "What is the largest ocean on Earth?", options: ["Atlantic", "Pacific", "Indian"], answer: "Pacific", explanation: "The Pacific Ocean is the largest and deepest ocean on Earth." },
  8.     { question: "Which gas do plants use for photosynthesis?", options: ["Oxygen", "Nitrogen", "Carbon Dioxide"], answer: "Carbon Dioxide", explanation: "Plants use carbon dioxide (CO₂) during photosynthesis to produce oxygen." },
  9.     { question: "Who discovered gravity?", options: ["Newton", "Einstein", "Galileo"], answer: "Newton", explanation: "Sir Isaac Newton formulated the theory of gravity when he observed an apple falling from a tree." },
  10.     { question: "What is the square root of 64?", options: ["6", "8", "10"], answer: "8", explanation: "The square root of 64 is 8, because 8 × 8 = 64." },
  11.     { question: "What is the chemical symbol for gold?", options: ["Ag", "Au", "Pb"], answer: "Au", explanation: "Gold's chemical symbol is 'Au', derived from the Latin word 'Aurum'." },
  12.     { question: "What is the fastest land animal?", options: ["Cheetah", "Horse", "Kangaroo"], answer: "Cheetah", explanation: "The cheetah is the fastest land animal, capable of speeds up to 75 mph." },
  13.     { question: "What is the freezing point of water in Celsius?", options: ["0", "32", "100"], answer: "0", explanation: "Water freezes at 0°C, which is equivalent to 32°F." },
  14.     { question: "How many bones are in the human body?", options: ["206", "150", "300"], answer: "206", explanation: "Adults have 206 bones, while babies are born with around 300, which fuse together over time." },
  15.     { question: "Who painted the Mona Lisa?", options: ["Van Gogh", "Da Vinci", "Picasso"], answer: "Da Vinci", explanation: "Leonardo da Vinci painted the Mona Lisa, one of the most famous artworks in history." },
  16.     { question: "What does DNA stand for?", options: ["Deoxyribonucleic Acid", "Dynamic Nucleotide Array", "Double Nuclear Atom"], answer: "Deoxyribonucleic Acid", explanation: "DNA stands for Deoxyribonucleic Acid and carries genetic information." },
  17. ];
  18.  
  19. // **Select 10 Random Questions**
  20. let questions = [];
  21. while (questions.length < 10) {
  22.     let randomIndex = Math.floor(Math.random() * allQuestions.length);
  23.     if (!questions.some(q => q.question === allQuestions[randomIndex].question)) {
  24.         questions.push(allQuestions[randomIndex]);
  25.     }
  26. }
  27.  
  28. const quizContainer = document.getElementById("quiz-container");
  29. const clickSound = new Audio("click.mp3");
  30.  
  31. questions.forEach((q, index) => {
  32.     let questionElement = document.createElement("div");
  33.     questionElement.innerHTML = `<p>${index + 1}. ${q.question}</p>`;
  34.    
  35.     q.options.forEach(option => {
  36.         let button = document.createElement("button");
  37.         button.className = "answer-button";
  38.         button.innerText = option;
  39.         button.onclick = () => {
  40.             clickSound.play();
  41.             document.querySelectorAll(`[data-question="${index}"]`).forEach(btn => btn.classList.remove("selected"));
  42.             button.classList.add("selected");
  43.         };
  44.         button.setAttribute("data-question", index);
  45.         questionElement.appendChild(button);
  46.     });
  47.  
  48.     quizContainer.appendChild(questionElement);
  49. });
  50.  
  51. function submitQuiz() {
  52.     let score = 0;
  53.     let feedbackContent = "";
  54.  
  55.     questions.forEach((q, index) => {
  56.         let selectedOption = document.querySelector(`.answer-button.selected[data-question="${index}"]`);
  57.         let resultText = selectedOption && selectedOption.innerText === q.answer ? "✅ Correct" : "❌ Incorrect";
  58.  
  59.         feedbackContent += `<p>${index + 1}. ${q.question} - <strong>${resultText}</strong></p>`;
  60.         feedbackContent += `<button onclick="showExplanation(${index})">Explain It to Me</button><br><br>`;
  61.  
  62.         if (selectedOption && selectedOption.innerText === q.answer) {
  63.             score++;
  64.         }
  65.     });
  66.  
  67.     document.getElementById("feedback-content").innerHTML = feedbackContent;
  68.     document.getElementById("feedback-frame").classList.add("show");
  69.     document.getElementById("feedback-frame").style.display = "block";
  70.  
  71.     // 🎉 Trigger Confetti if score is 10/10
  72.     if (score === 10) {
  73.         startConfetti();
  74.     }
  75. }
  76.  
  77. // 🎊 Confetti Effect
  78. function startConfetti() {
  79.     const canvas = document.createElement("canvas");
  80.     document.body.appendChild(canvas);
  81.     canvas.style.position = "fixed";
  82.     canvas.style.top = "0";
  83.     canvas.style.left = "0";
  84.     canvas.style.width = "100%";
  85.     canvas.style.height = "100%";
  86.     canvas.style.pointerEvents = "none";
  87.  
  88.     const ctx = canvas.getContext("2d");
  89.     const particles = [];
  90.  
  91.     for (let i = 0; i < 100; i++) {
  92.         particles.push({
  93.             x: Math.random() * window.innerWidth,
  94.             y: Math.random() * window.innerHeight,
  95.             r: Math.random() * 6 + 4,
  96.             color: `hsl(${Math.random() * 360}, 100%, 70%)`,
  97.             speed: Math.random() * 4 + 1
  98.         });
  99.     }
  100.  
  101.     function render() {
  102.         ctx.clearRect(0, 0, canvas.width, canvas.height);
  103.         particles.forEach(p => {
  104.             ctx.fillStyle = p.color;
  105.             ctx.beginPath();
  106.             ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
  107.             ctx.fill();
  108.             p.y += p.speed;
  109.         });
  110.         requestAnimationFrame(render);
  111.     }
  112.  
  113.     render();
  114.  
  115.     setTimeout(() => {
  116.         document.body.removeChild(canvas);
  117.     }, 3000); // Confetti lasts for 3 seconds
  118. }
  119.  
  120. function showExplanation(index) {
  121.     document.getElementById("explanation-text").innerText = questions[index].explanation;
  122.    
  123.     let popup = document.getElementById("explanation-popup");
  124.     popup.classList.add("show");
  125.     popup.style.display = "block";
  126.  
  127.     popup.querySelector(".popup-content").scrollTop = 0; /* Reset scroll position */
  128. }
  129.  
  130. function closeFeedback() {
  131.     document.getElementById("feedback-frame").classList.remove("show");
  132.     setTimeout(() => { document.getElementById("feedback-frame").style.display = "none"; }, 300);
  133. }
  134.  
  135. function closeExplanation() {
  136.     document.getElementById("explanation-popup").classList.remove("show");
  137.     setTimeout(() => { document.getElementById("explanation-popup").style.display = "none"; }, 300);
  138. }
  139.  
Advertisement
Add Comment
Please, Sign In to add comment