Project: Quiz Game
Let's build an interactive quiz game! This project combines arrays, objects, conditionals, and user interaction.
Features:
- Multiple choice questions
- Score tracking
- Immediate feedback
- Question navigation
- Results screen
Step 1: Question Data Structure
⚡ javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Array of question objects
const questions = [
{
question: 'What is 2 + 2?',
options: ['3', '4', '5', '6'],
correct: 1 // Index of correct answer
},
{
question: 'What color is the sky?',
options: ['Red', 'Blue', 'Green', 'Yellow'],
correct: 1
},
{
question: 'How many days in a week?',
options: ['5', '6', '7', '8'],
correct: 2
}
]
// Game state
let currentQuestion = 0
let score = 0Step 2: Check Answer Logic
⚡ javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function checkAnswer(selectedIndex) {
const question = questions[currentQuestion]
if (selectedIndex === question.correct) {
score++
console.log('Correct!')
return true
} else {
console.log('Wrong! The correct answer was: ' +
question.options[question.correct])
return false
}
}
function nextQuestion() {
if (currentQuestion < questions.length - 1) {
currentQuestion++
return true // More questions
} else {
return false // Quiz complete
}
}Step 3: Complete Game Flow
⚡ javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Display current question
function displayQuestion() {
const q = questions[currentQuestion]
console.log(\`Question \${currentQuestion + 1} of \${questions.length}\`)
console.log(q.question)
q.options.forEach((option, index) => {
console.log(\`\${index + 1}. \${option}\`)
})
}
// Main game flow
function playQuiz() {
displayQuestion()
// User selects answer (0-3)
const answer = getUserInput()
const correct = checkAnswer(answer)
if (nextQuestion()) {
playQuiz() // Recursive call for next question
} else {
showResults()
}
}
function showResults() {
console.log('Quiz Complete!')
console.log(\`Score: \${score}/\${questions.length}\`)
const percentage = (score / questions.length) * 100
if (percentage >= 80) {
console.log('Excellent!')
} else if (percentage >= 60) {
console.log('Good job!')
} else {
console.log('Keep practicing!')
}
}Play the Quiz!
Question 1 of 3Score: 0