-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
409 lines (371 loc) · 15.3 KB
/
Copy pathscript.js
File metadata and controls
409 lines (371 loc) · 15.3 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
const { useState, useEffect, useCallback } = React;
// ============================================
// 📚 QUIZ DATA - Array of question objects
// ============================================
// Each object contains: question text, options array, correct answer
const quizData = [
{
question: "What is HTML?",
options: ["Programming Language", "Markup Language", "Database", "Operating System"],
answer: "Markup Language"
},
{
question: "What does CSS stand for?",
options: ["Computer Style Sheets", "Cascading Style Sheets", "Creative Style System", "Colorful Style Sheets"],
answer: "Cascading Style Sheets"
},
{
question: "What is React JS?",
options: ["A Database", "A JavaScript Library", "An Operating System", "A Programming Language"],
answer: "A JavaScript Library"
},
{
question: "Which keyword is used to declare a constant in JavaScript?",
options: ["var", "let", "const", "constant"],
answer: "const"
},
{
question: "What is the virtual DOM in React?",
options: ["A real DOM copy", "A lightweight JavaScript object", "A CSS framework", "A server"],
answer: "A lightweight JavaScript object"
},
{
question: "Which hook is used for side effects in React?",
options: ["useState", "useEffect", "useContext", "useReducer"],
answer: "useEffect"
},
{
question: "What does API stand for?",
options: ["Application Programming Interface", "Advanced Program Integration", "Automated Protocol Interface", "Application Process Integration"],
answer: "Application Programming Interface"
}
];
// ============================================
// 🎯 TIMER COMPONENT
// ============================================
// Displays countdown timer for each question
function Timer({ timeLeft, totalTime, onTimeUp }) {
// Calculate percentage for progress bar
const percentage = (timeLeft / totalTime) * 100;
const isWarning = timeLeft <= 5; // Warning when 5 seconds or less
// useEffect runs when timeLeft changes
useEffect(() => {
if (timeLeft === 0) {
onTimeUp(); // Call parent function when timer hits zero
}
}, [timeLeft, onTimeUp]);
return (
<div className="mb-6 fade-in">
{/* Timer label */}
<div className="flex justify-between text-sm text-white mb-2">
<span>⏱️ Time Remaining</span>
<span className={isWarning ? "text-yellow-300 font-bold timer-warning" : ""}>
{timeLeft}s
</span>
</div>
{/* Progress bar */}
<div className="w-full bg-white/30 rounded-full h-3 overflow-hidden">
<div
className={`h-full rounded-full transition-all duration-1000 ${
isWarning ? 'bg-red-500' : 'bg-green-400'
}`}
style={{ width: `${percentage}%` }}
/>
</div>
</div>
);
}
// ============================================
// 📝 QUESTION CARD COMPONENT
// ============================================
// Displays the current question and options
function QuestionCard({
question,
options,
questionNumber,
totalQuestions,
onAnswerSelect,
selectedAnswer,
showResult,
isCorrect
}) {
return (
<div className="fade-in">
{/* Progress indicator */}
<div className="flex justify-between items-center mb-4">
<span className="bg-white/20 text-white px-4 py-1 rounded-full text-sm">
Question {questionNumber} of {totalQuestions}
</span>
<div className="w-1/2 bg-white/30 rounded-full h-2">
<div
className="bg-purple-400 h-2 rounded-full transition-all duration-500"
style={{ width: `${(questionNumber / totalQuestions) * 100}%` }}
/>
</div>
</div>
{/* Question text */}
<h2 className="text-2xl font-bold text-white mb-8 text-center">
{question}
</h2>
{/* Options container */}
<div className="space-y-3">
{/* Map through options and create button for each */}
{options.map((option, index) => {
// Determine button style based on state
let btnClass = "option-btn bg-white/90 hover:bg-white text-gray-800";
if (showResult && selectedAnswer === option) {
// Show green for correct, red for wrong
btnClass = isCorrect
? "option-btn bg-green-500 text-white"
: "option-btn bg-red-500 text-white shake";
} else if (showResult && option === question.answer) {
// Highlight correct answer when showing result
btnClass = "option-btn bg-green-500/50 text-white border-2 border-green-400";
} else if (selectedAnswer === option) {
// Show selected state
btnClass = "option-btn bg-purple-500 text-white";
}
return (
<button
key={index} // Unique key for React
onClick={() => !showResult && onAnswerSelect(option)}
disabled={showResult} // Disable after answering
className={`w-full p-4 rounded-xl text-left font-medium ${btnClass} slide-in`}
style={{ animationDelay: `${index * 0.1}s` }}
>
<span className="inline-block w-8 h-8 bg-purple-500 text-white rounded-lg text-center leading-8 mr-3">
{String.fromCharCode(65 + index)}
</span>
{option}
</button>
);
})}
</div>
</div>
);
}
// ============================================
// 🏆 RESULT SCREEN COMPONENT
// ============================================
// Displays final score and restart option
function ResultScreen({ score, total, onRestart, timeTaken }) {
// Calculate percentage
const percentage = Math.round((score / total) * 100);
// Determine message based on score
let message = "";
let emoji = "";
if (percentage >= 80) {
message = "🎉 Excellent! You're a pro!";
emoji = "🏆";
} else if (percentage >= 60) {
message = "👍 Good job! Keep practicing!";
emoji = "⭐";
} else if (percentage >= 40) {
message = "📚 Not bad, but room for improvement!";
emoji = "📖";
} else {
message = "💪 Keep learning, you'll get better!";
emoji = "🎯";
}
return (
<div className="text-center fade-in">
<div className="text-8xl mb-4 bounce">{emoji}</div>
<h2 className="text-4xl font-bold text-white mb-4">Quiz Completed!</h2>
{/* Score circle */}
<div className="relative w-40 h-40 mx-auto mb-6">
<svg className="w-full h-full transform -rotate-90">
<circle
cx="80"
cy="80"
r="70"
stroke="rgba(255,255,255,0.3)"
strokeWidth="10"
fill="none"
/>
<circle
cx="80"
cy="80"
r="70"
stroke={percentage >= 60 ? "#4ade80" : "#f87171"}
strokeWidth="10"
fill="none"
strokeDasharray={`${percentage * 4.4} 440`}
strokeLinecap="round"
className="transition-all duration-1000"
/>
</svg>
<div className="absolute inset-0 flex items-center justify-center">
<span className="text-4xl font-bold text-white">{percentage}%</span>
</div>
</div>
{/* Score details */}
<div className="bg-white/20 rounded-2xl p-6 mb-6">
<p className="text-2xl text-white mb-2">
You scored <span className="font-bold">{score}</span> out of <span className="font-bold">{total}</span>
</p>
<p className="text-white/80">
⏱️ Total time: {Math.floor(timeTaken / 60)}:{(timeTaken % 60).toString().padStart(2, '0')}
</p>
<p className="text-lg text-white mt-3 font-medium">{message}</p>
</div>
{/* Restart button */}
<button
onClick={onRestart}
className="bg-white text-purple-600 px-8 py-4 rounded-xl font-bold text-lg hover:scale-105 transition-transform pulse"
>
🔄 Play Again
</button>
</div>
);
}
// ============================================
// 🎮 MAIN QUIZ APP COMPONENT
// ============================================
// Main component that manages quiz state
function QuizApp() {
// ============ STATE VARIABLES ============
// currentQuestion: Index of current question (starts at 0)
const [currentQuestion, setCurrentQuestion] = useState(0);
// score: Number of correct answers
const [score, setScore] = useState(0);
// selectedAnswer: The answer user clicked for current question
const [selectedAnswer, setSelectedAnswer] = useState(null);
// showResult: Whether to show correct/wrong feedback
const [showResult, setShowResult] = useState(false);
// quizComplete: Whether the entire quiz is finished
const [quizComplete, setQuizComplete] = useState(false);
// timeLeft: Timer countdown for current question
const [timeLeft, setTimeLeft] = useState(15);
// totalTime: Total time spent on quiz
const [totalTimeTaken, setTotalTimeTaken] = useState(0);
// ============ TIMER EFFECT ============
// useEffect runs when currentQuestion or timeLeft changes
useEffect(() => {
// Reset timer when moving to new question
if (!quizComplete && !showResult) {
setTimeLeft(15);
}
}, [currentQuestion, quizComplete, showResult]);
// Countdown timer - runs every second
useEffect(() => {
if (!quizComplete && !showResult && timeLeft > 0) {
const timer = setInterval(() => {
setTimeLeft(prev => prev - 1); // Decrease time by 1
}, 1000); // 1000ms = 1 second
// Cleanup function - clears interval when component unmounts
return () => clearInterval(timer);
}
}, [quizComplete, showResult, timeLeft]);
// Track total time
useEffect(() => {
if (!quizComplete) {
const timer = setInterval(() => {
setTotalTimeTaken(prev => prev + 1);
}, 1000);
return () => clearInterval(timer);
}
}, [quizComplete]);
// ============ ANSWER HANDLER ============
const handleAnswerSelect = useCallback((answer) => {
if (showResult) return; // Prevent multiple selections
setSelectedAnswer(answer); // Store selected answer
setShowResult(true); // Show result feedback
// Check if answer is correct
const currentQ = quizData[currentQuestion];
if (answer === currentQ.answer) {
setScore(prev => prev + 1); // Increment score if correct
}
// Auto-advance after showing result
setTimeout(() => {
if (currentQuestion < quizData.length - 1) {
// Go to next question
setCurrentQuestion(prev => prev + 1);
setSelectedAnswer(null);
setShowResult(false);
} else {
// Quiz complete
setQuizComplete(true);
}
}, 2000); // Wait 2 seconds before next question
}, [currentQuestion, showResult]);
// ============ TIME UP HANDLER ============
const handleTimeUp = useCallback(() => {
if (showResult || quizComplete) return;
setSelectedAnswer("Time's up!");
setShowResult(true);
// Auto-advance after timeout
setTimeout(() => {
if (currentQuestion < quizData.length - 1) {
setCurrentQuestion(prev => prev + 1);
setSelectedAnswer(null);
setShowResult(false);
} else {
setQuizComplete(true);
}
}, 2000);
}, [currentQuestion, showResult, quizComplete]);
// ============ RESTART QUIZ ============
const handleRestart = () => {
setCurrentQuestion(0);
setScore(0);
setSelectedAnswer(null);
setShowResult(false);
setQuizComplete(false);
setTimeLeft(15);
setTotalTimeTaken(0);
};
// ============ RENDER ============
return (
<div className="bg-white/10 backdrop-blur-lg rounded-3xl p-8 shadow-2xl w-full max-w-2xl">
{/* Show quiz completion screen */}
{quizComplete ? (
<ResultScreen
score={score}
total={quizData.length}
onRestart={handleRestart}
timeTaken={totalTimeTaken}
/>
) : (
/* Show current question */
<>
{/* Timer component */}
<Timer
timeLeft={timeLeft}
totalTime={15}
onTimeUp={handleTimeUp}
/>
{/* Question card component */}
<QuestionCard
question={quizData[currentQuestion].question}
options={quizData[currentQuestion].options}
questionNumber={currentQuestion + 1}
totalQuestions={quizData.length}
onAnswerSelect={handleAnswerSelect}
selectedAnswer={selectedAnswer}
showResult={showResult}
isCorrect={selectedAnswer === quizData[currentQuestion].answer}
currentQuestionData={quizData[currentQuestion]}
/>
{/* Feedback message */}
{showResult && (
<div className={`mt-4 text-center text-lg font-bold fade-in ${
selectedAnswer === quizData[currentQuestion].answer
? "text-green-300"
: "text-red-300"
}`}>
{selectedAnswer === quizData[currentQuestion].answer
? "✅ Correct!"
: `❌ Wrong! Answer: ${quizData[currentQuestion].answer}`}
</div>
)}
</>
)}
</div>
);
}
// ============================================
// 🚀 RENDER REACT APP
// ============================================
// Create root and render QuizApp component
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<QuizApp />);