Fruits and Vegetables Trivia Game
#game { max-width: 600px; margin: 0 auto; text-align: center;}#question { font-size: 24px; margin-top: 20px;}#choices { margin-top: 20px;}#choices button { font-size: 16px; padding: 10px 20px; margin: 10px;}#result { margin-top: 20px;}#next { font-size: 18px; padding: 10px 20px; margin-top: 20px;}
$(document).ready(function() { // Define the trivia questions var questions = [ { question: "Which fruit is known as the 'king of fruits' in Southeast Asia?", choices: ["Apple", "Mango", "Banana", "Watermelon"], correctAnswer: 1 }, { question: "Which vegetable is a member of the nightshade family?", choices: ["Carrot", "Cucumber", "Tomato", "Pepper"], correctAnswer: 2 }, { question: "Which fruit is the only one with seeds on the outside?", choices: ["Strawberry", "Raspberry", "Blueberry", "Blackberry"], correctAnswer: 0 }, { question: "Which vegetable is a rich source of vitamin C?", choices: ["Broccoli", "Asparagus", "Lettuce", "Cabbage"], correctAnswer: 0 } ]; var currentQuestion = 0; var score = 0; // Display the current question and choices function displayQuestion() { var question = questions[currentQuestion]; $("#question").text(question.question); $("#choices").empty(); for (var i = 0; i < question.choices.length; i++) { var choice = question.choices[i]; var button = $("").text(choice); button.attr("data-index", i); button.click(function() { var index = $(this).attr("data-index"); checkAnswer(index); }); $("#choices").append(button); } } // Check the selected answer and update the score function checkAnswer(index) { var question = questions[currentQuestion]; if (index == question.correctAnswer) { score++; $("#result").text("Correct!"); } else { $("#result").text("Incorrect. The correct answer is " + question.choices[question.correctAnswer] + "."); } $("#choices button").attr("disabled", true); $("#next").show(); } // Go to the next question
