-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbinaryquiz.html
More file actions
370 lines (338 loc) · 13.7 KB
/
binaryquiz.html
File metadata and controls
370 lines (338 loc) · 13.7 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
<!DOCTYPE html>
<html>
<head>
<title>Conversion Quiz</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.question {
margin-top: 20px;
}
.choices {
margin-top: 10px;
}
.result, .high-score, .timer, .correct-count {
margin-top: 20px;
font-weight: bold;
}
.share-button {
margin-top: 10px;
padding: 10px 20px;
font-size: 16px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
.share-button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<h2>Conversion Quiz</h2>
<div id="levelContainer">
<label for="level">Select Level:</label>
<select id="level">
<option value="easy">Easy (0-15)</option>
<option value="medium">Medium (0-255)</option>
<option value="hard">Hard (Two's Complement)</option>
<option value="extreme">Extreme (Mixed Conversions)</option>
</select>
<br>
<label for="mode">Select Mode:</label>
<select id="mode">
<option value="timed">Timed</option>
<option value="untimed">Untimed</option>
</select>
<br>
<button onclick="startQuiz()">Start Quiz</button>
</div>
<div id="quizContainer" style="display:none;">
<div class="question" id="question"></div>
<div class="choices" id="choices"></div>
<button onclick="nextQuestion()">Next Question</button>
</div>
<div class="result" id="result"></div>
<div class="timer" id="timer"></div>
<div class="correct-count" id="correctCount"></div>
<div class="high-score" id="highScore" style="display:none;"></div>
<button id="playAgainBtn" style="display:none;" onclick="playAgain()">Play Again</button>
<button id="shareBtn" class="share-button" style="display:none;" onclick="shareResults()">Share Your Score</button>
<script>
const quizContainer = document.getElementById("quizContainer");
const levelContainer = document.getElementById("levelContainer");
const questionElement = document.getElementById("question");
const choicesElement = document.getElementById("choices");
const resultElement = document.getElementById("result");
const timerElement = document.getElementById("timer");
const correctCountElement = document.getElementById("correctCount");
const highScoreElement = document.getElementById("highScore");
const playAgainBtn = document.getElementById("playAgainBtn");
let currentQuestion = {};
let score = 0;
let initialScore = 0;
let questionCount = 0;
let correctCount = 0;
let highScore = localStorage.getItem('highScore') ? parseInt(localStorage.getItem('highScore')) : 0;
let level = 'easy';
let mode = 'timed';
let timer;
let timeLeft = 200;
let scoreBreakdown = [];
let hasPenalty = false;
function setLevel() {
level = document.getElementById("level").value;
}
function setMode() {
mode = document.getElementById("mode").value;
}
function startQuiz() {
setLevel();
setMode();
levelContainer.style.display = "none";
quizContainer.style.display = "block";
timerElement.style.display = mode === 'timed' ? 'block' : 'none';
correctCountElement.style.display = "block";
correctCountElement.innerText = `Correct Answers: 0`;
score = 0;
correctCount = 0;
questionCount = 0;
scoreBreakdown = [];
hasPenalty = false;
if (mode === 'timed') {
timeLeft = 200;
startTimer();
}
generateQuestion();
}
function startTimer() {
timer = setInterval(function() {
if (timeLeft <= 0) {
clearInterval(timer);
endQuiz();
} else {
timerElement.innerText = `Time Left: ${timeLeft} seconds`;
timeLeft--;
}
}, 1000);
}
function generateRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getBinary(value) {
return value.toString(2).padStart(8, '0');
}
function getHexadecimal(value) {
return value.toString(16).toUpperCase().padStart(2, '0');
}
function generateQuestion() {
let decimalValue, binaryValue, hexadecimalValue, questionText, operator, num1, num2;
if (level === 'easy') {
decimalValue = generateRandomNumber(0, 15);
initialScore = 1;
} else if (level === 'medium') {
decimalValue = generateRandomNumber(0, 255);
initialScore = 5;
} else if (level === 'hard') {
decimalValue = generateRandomNumber(-128, 127);
initialScore = 10;
} else if (level === 'extreme') {
initialScore = 20;
const isMixedConversion = Math.random() > 0.5;
if (isMixedConversion) {
num1 = generateRandomNumber(0, 255);
num2 = generateRandomNumber(0, 255);
const format1 = Math.random() > 0.5 ? 'hex' : 'bin';
const format2 = format1 === 'hex' ? 'bin' : 'hex';
operator = Math.random() > 0.5 ? '+' : '-';
decimalValue = operator === '+' ? num1 + num2 : num1 - num2;
questionText = `Convert ${format1 === 'hex' ? getHexadecimal(num1) : getBinary(num1)} (${format1}) ${operator} ${format2 === 'hex' ? getHexadecimal(num2) : getBinary(num2)} (${format2}):`;
if (decimalValue < 0 || decimalValue > 255) {
currentQuestion = {
question: questionText,
correctAnswer: 'Overflow',
choices: generateChoices('Overflow', 'decimal')
};
displayQuestion();
return;
}
} else {
decimalValue = generateRandomNumber(0, 255);
}
}
binaryValue = getBinary((decimalValue + 256) % 256); // Ensure it's always 8-bit
hexadecimalValue = getHexadecimal((decimalValue + 256) % 256);
const conversionTypes = level === 'extreme' && questionText ? [questionText] : ["Decimal to Binary", "Decimal to Hexadecimal", "Binary to Decimal", "Hexadecimal to Decimal"];
if (level === 'hard') {
conversionTypes.splice(conversionTypes.indexOf("Decimal to Hexadecimal"), 1);
conversionTypes.splice(conversionTypes.indexOf("Hexadecimal to Decimal"), 1);
}
const selectedConversion = conversionTypes[Math.floor(Math.random() * conversionTypes.length)];
switch (selectedConversion) {
case "Decimal to Binary":
currentQuestion = {
question: `Convert ${decimalValue} (Decimal) to Binary:`,
correctAnswer: binaryValue,
choices: generateChoices(binaryValue, "binary")
};
break;
case "Decimal to Hexadecimal":
currentQuestion = {
question: `Convert ${decimalValue} (Decimal) to Hexadecimal:`,
correctAnswer: hexadecimalValue,
choices: generateChoices(hexadecimalValue, "hexadecimal")
};
break;
case "Binary to Decimal":
currentQuestion = {
question: `Convert ${binaryValue} (Binary) to Decimal:`,
correctAnswer: decimalValue.toString(),
choices: generateChoices(decimalValue.toString(), "decimal")
};
break;
case "Hexadecimal to Decimal":
currentQuestion = {
question: `Convert ${hexadecimalValue} (Hexadecimal) to Decimal:`,
correctAnswer: decimalValue.toString(),
choices: generateChoices(decimalValue.toString(), "decimal")
};
break;
default:
currentQuestion = {
question: questionText,
correctAnswer: decimalValue.toString(),
choices: generateChoices(decimalValue.toString(), "decimal")
};
break;
}
displayQuestion();
}
function displayQuestion() {
questionElement.innerText = currentQuestion.question;
choicesElement.innerHTML = "";
currentQuestion.choices.forEach(choice => {
const button = document.createElement("button");
button.innerText = choice;
button.onclick = () => checkAnswer(choice);
choicesElement.appendChild(button);
});
}
function generateChoices(correctAnswer, type) {
const choices = new Set();
choices.add(correctAnswer);
while (choices.size < 4) {
let choice;
if (level === 'extreme' && choices.size === 3) {
choice = 'Overflow';
} else {
switch (type) {
case "binary":
choice = getBinary(generateRandomNumber(0, 255));
break;
case "hexadecimal":
choice = getHexadecimal(generateRandomNumber(0, 255));
break;
case "decimal":
choice = generateRandomNumber(0, 255).toString();
break;
}
}
choices.add(choice);
}
return Array.from(choices).sort(() => Math.random() - 0.5);
}
function checkAnswer(selectedChoice) {
if (selectedChoice === currentQuestion.correctAnswer) {
score += initialScore;
correctCount++;
resultElement.innerText = "Correct!";
scoreBreakdown.push({ question: currentQuestion.question, points: initialScore, timeBonus: 0 });
} else {
resultElement.innerText = `Incorrect. The correct answer is ${currentQuestion.correctAnswer}.`;
if (mode === 'timed') {
scoreBreakdown.push({ question: currentQuestion.question, points: 0, timeBonus: -initialScore * timeLeft });
hasPenalty = true;
} else {
scoreBreakdown.push({ question: currentQuestion.question, points: 0, timeBonus: 0 });
}
}
correctCountElement.innerText = `Correct Answers: ${correctCount}`;
questionCount++;
setTimeout(nextQuestion, 2000);
}
function nextQuestion() {
resultElement.innerText = "";
if (questionCount < 10) {
generateQuestion();
} else {
if (mode === 'timed') {
clearInterval(timer);
}
endQuiz();
}
}
function endQuiz() {
if (mode === 'timed') {
let totalBonus = Math.max(timeLeft, 0);
scoreBreakdown.forEach(entry => {
if (!hasPenalty || entry.points > 0) {
entry.timeBonus = entry.points * totalBonus;
}
});
score += scoreBreakdown.reduce((sum, entry) => sum + entry.timeBonus, 0);
}
if (score > highScore) {
highScore = score;
localStorage.setItem('highScore', highScore);
}
displayResults();
}
function displayResults() {
quizContainer.style.display = "none";
playAgainBtn.style.display = "block";
highScoreElement.style.display = "block";
document.getElementById("shareBtn").style.display = "block";
let breakdownHTML = `<h3>Quiz Over! You scored ${score} points.</h3>`;
breakdownHTML += `<p>High Score: ${highScore}</p>`;
if (mode === 'timed') {
breakdownHTML += `<p>Time Bonus: ${Math.max(timeLeft, 0)}</p>`;
}
breakdownHTML += `<h4>Score Breakdown:</h4><ul>`;
scoreBreakdown.forEach(entry => {
breakdownHTML += `<li>${entry.question} - Points: ${entry.points}, Time Bonus: ${entry.timeBonus}</li>`;
});
breakdownHTML += `</ul>`;
resultElement.innerHTML = breakdownHTML;
}
function playAgain() {
score = 0;
questionCount = 0;
correctCount = 0;
resultElement.innerText = "";
playAgainBtn.style.display = "none";
quizContainer.style.display = "none";
levelContainer.style.display = "block";
timerElement.innerText = "";
correctCountElement.innerText = "";
highScoreElement.style.display = "none";
document.getElementById("shareBtn").style.display = "none";
}
function shareResults() {
const shareText = `I scored ${score} points in the Conversion Quiz! Can you beat my high score of ${highScore}?`;
const url = window.location.href; // Get the current URL
const twitterShare = `https://twitter.com/intent/tweet?text=${encodeURIComponent(shareText)}&url=${encodeURIComponent(url)}`;
const facebookShare = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(url)}"e=${encodeURIComponent(shareText)}`;
const linkedInShare = `https://www.linkedin.com/shareArticle?mini=true&url=${encodeURIComponent(url)}&title=Conversion Quiz&summary=${encodeURIComponent(shareText)}`;
// Open share dialogs (for simplicity, we're opening Twitter share here, you can add more)
window.open(twitterShare, '_blank');
}
generateQuestion();
</script>
<script async defer src="https://scripts.simpleanalyticscdn.com/latest.js"></script>
<noscript><img src="https://queue.simpleanalyticscdn.com/noscript.gif" alt="" referrerpolicy="no-referrer-when-downgrade" /></noscript>
</body>
</html>