Building a Quiz Game in JavaScript
Question: Imagine you are tasked with building a quiz game in JavaScript. The game should display questions, allow the user to choose answers, calculate the score, and provide feedback. Here’s what you need to accomplish:
- Create an array of question objects, each containing a question, answer options, and the correct answer.
- Display each question to the user and prompt them to choose an answer using the
prompt()function. - Validate the user’s input and compare it to the correct answer. Keep track of the user’s score.
- Display the current score after each question.
- After all questions have been answered, provide feedback to the user about their performance.
- Utilize functions, loops, conditionals, and scope effectively.
Quiz Game: Test Your Knowledge! – SAMPLE SOLUTION
//script. -- make this a script opening tag
// Array of question objects
var questions = [
{
question: "What is the capital of France?",
options: ["Paris", "London", "Madrid"],
correctAnswer: "Paris"
},
{
question: "Which planet is known as the Red Planet?",
options: ["Earth", "Mars", "Jupiter"],
correctAnswer: "Mars"
},
{
question: "What programming language is used for web development?",
options: ["Python", "JavaScript", "Java"],
correctAnswer: "JavaScript"
}
];
// Initialize score
var score = 0;
// Iterate through each question
for (var i = 0; i < questions.length; i++) {
var userAnswer = prompt(questions[i].question + "nOptions: " + questions[i].options.join(", "));
// Validate user input
if (questions[i].options.includes(userAnswer)) {
if (userAnswer === questions[i].correctAnswer) {
score++;
alert("Correct! Your current score is: " + score);
} else {
alert("Incorrect. The correct answer is: " + questions[i].correctAnswer);
}
} else {
alert("Invalid input. Please choose a valid option.");
}
}
// Provide feedback to the user
if (score === questions.length) {
alert("Congratulations! You answered all questions correctly.");
} else {
alert("Your final score is: " + score + " out of " + questions.length);
}
//script. -- make this a script closing tag