Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
475 lines (409 loc) · 18.5 KB
/
Copy pathscript.js
File metadata and controls
475 lines (409 loc) · 18.5 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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
class MathGame {
constructor() {
this.state = {
totalQuestions: 10,
currentQuestionIndex: 0,
score: 0,
questions: [],
results: [], // { question: "3x4", userAnswer: 12, correctAnswer: 12, time: 1.2, isCorrect: true }
questionStartTime: 0,
settings: {
operations: [],
ranges: {
op1: { min: 0, max: 9 },
op2: { min: 0, max: 9 }
}
}
};
this.elements = {
screens: {
start: document.getElementById('start-screen'),
game: document.getElementById('game-screen'),
result: document.getElementById('result-screen')
},
inputs: {
questionCount: document.getElementById('question-count'),
answer: document.getElementById('answer-input'),
op1Min: document.getElementById('op1-min'),
op1Max: document.getElementById('op1-max'),
op2Min: document.getElementById('op2-min'),
op2Max: document.getElementById('op2-max'),
operations: document.querySelectorAll('input[name="operation"]')
},
display: {
questionCounter: document.getElementById('question-counter'),
progressFill: document.getElementById('progress-fill'),
factor1: document.getElementById('factor1'),
operator: document.querySelector('.operator'),
factor2: document.getElementById('factor2'),
feedback: document.getElementById('feedback'),
avgTime: document.getElementById('avg-time'),
scoreText: document.getElementById('score-text'),
wrongAnswersList: document.getElementById('wrong-answers-list'),
wrongAnswersSection: document.getElementById('wrong-answers-section')
},
buttons: {
start: document.getElementById('start-btn'),
restart: document.getElementById('restart-btn'),
shareToggle: document.getElementById('share-toggle-btn'),
shareMailto: document.getElementById('share-mailto-btn'),
shareFormContainer: document.getElementById('share-form-container'),
netlifyForm: document.getElementById('netlify-form'),
formFeedback: document.getElementById('form-feedback'),
reportMessage: document.getElementById('report-message'),
themeToggle: document.getElementById('theme-toggle')
}
};
this.init();
}
init() {
this.elements.buttons.start.addEventListener('click', () => this.startGame());
this.elements.buttons.restart.addEventListener('click', () => this.resetGame());
this.elements.buttons.shareToggle.addEventListener('click', () => this.showShareForm());
this.elements.buttons.shareMailto.addEventListener('click', () => this.shareViaMailto());
this.elements.buttons.netlifyForm.addEventListener('submit', (e) => this.handleFormSubmit(e));
this.elements.buttons.themeToggle.addEventListener('click', () => this.toggleTheme());
this.elements.inputs.answer.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
this.handleAnswer();
}
});
// Prevent non-numeric input (extra safety)
this.elements.inputs.answer.addEventListener('input', (e) => {
e.target.value = e.target.value.replace(/[^0-9-]/g, '');
});
// Load saved theme
const savedTheme = localStorage.getItem('theme');
if (savedTheme === 'dark' || (!savedTheme && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
document.body.classList.add('dark-mode');
this.updateThemeIcon(true);
} else {
this.updateThemeIcon(false);
}
}
toggleTheme() {
document.body.classList.toggle('dark-mode');
const isDark = document.body.classList.contains('dark-mode');
localStorage.setItem('theme', isDark ? 'dark' : 'light');
this.updateThemeIcon(isDark);
}
updateThemeIcon(isDark) {
const sunIcon = this.elements.buttons.themeToggle.querySelector('.sun-icon');
const moonIcon = this.elements.buttons.themeToggle.querySelector('.moon-icon');
if (isDark) {
sunIcon.classList.remove('hidden');
moonIcon.classList.add('hidden');
} else {
sunIcon.classList.add('hidden');
moonIcon.classList.remove('hidden');
}
}
startGame() {
// Get Settings
let count = parseInt(this.elements.inputs.questionCount.value);
if (isNaN(count) || count < 1) {
count = 50; // default override
this.elements.inputs.questionCount.value = 50;
}
const selectedOps = Array.from(this.elements.inputs.operations)
.filter(cb => cb.checked)
.map(cb => cb.value);
if (selectedOps.length === 0) {
alert('Lütfen en az bir işlem seçin.');
return;
}
this.state.settings.operations = selectedOps;
this.state.settings.ranges.op1.min = parseInt(this.elements.inputs.op1Min.value) || 0;
this.state.settings.ranges.op1.max = parseInt(this.elements.inputs.op1Max.value) || 9;
this.state.settings.ranges.op2.min = parseInt(this.elements.inputs.op2Min.value) || 0;
this.state.settings.ranges.op2.max = parseInt(this.elements.inputs.op2Max.value) || 9;
// Validate Ranges
if (this.state.settings.ranges.op1.min > this.state.settings.ranges.op1.max) {
[this.state.settings.ranges.op1.min, this.state.settings.ranges.op1.max] = [this.state.settings.ranges.op1.max, this.state.settings.ranges.op1.min];
}
if (this.state.settings.ranges.op2.min > this.state.settings.ranges.op2.max) {
[this.state.settings.ranges.op2.min, this.state.settings.ranges.op2.max] = [this.state.settings.ranges.op2.max, this.state.settings.ranges.op2.min];
}
this.state.totalQuestions = count;
this.state.currentQuestionIndex = 0;
this.state.score = 0;
this.state.results = [];
this.generateQuestions(count);
this.switchScreen('game');
this.showNextQuestion();
}
generateQuestions(count) {
this.state.questions = [];
const { operations, ranges } = this.state.settings;
for (let i = 0; i < count; i++) {
const op = operations[Math.floor(Math.random() * operations.length)];
let n1, n2;
if (op === '/') {
// Division: Result should be integer. n1 = n2 * result.
let valid = false;
let attempts = 0;
while (!valid && attempts < 100) {
// Avoid division by zero
let min2 = Math.max(1, ranges.op2.min);
let max2 = Math.max(1, ranges.op2.max);
if (min2 > max2) min2 = max2;
n2 = Math.floor(Math.random() * (max2 - min2 + 1)) + min2;
// Estimate max result to keep n1 within max op1 range
const maxResult = Math.floor(ranges.op1.max / n2);
const minResult = Math.ceil(ranges.op1.min / n2);
if (maxResult >= minResult) {
const result = Math.floor(Math.random() * (maxResult - minResult + 1)) + minResult;
n1 = n2 * result;
valid = true;
}
attempts++;
}
// Fallback if generation fails
if (!valid) {
n2 = Math.floor(Math.random() * 9) + 1;
n1 = n2 * (Math.floor(Math.random() * 9) + 1);
}
} else if (op === '-') {
// Subtraction: n1 >= n2
let valid = false;
let attempts = 0;
while (!valid && attempts < 100) {
n1 = Math.floor(Math.random() * (ranges.op1.max - ranges.op1.min + 1)) + ranges.op1.min;
n2 = Math.floor(Math.random() * (ranges.op2.max - ranges.op2.min + 1)) + ranges.op2.min;
if (n1 >= n2) valid = true;
attempts++;
}
if (!valid) {
// Force valid
n1 = 10; n2 = 5;
}
} else {
// Addition and Multiplication
n1 = Math.floor(Math.random() * (ranges.op1.max - ranges.op1.min + 1)) + ranges.op1.min;
n2 = Math.floor(Math.random() * (ranges.op2.max - ranges.op2.min + 1)) + ranges.op2.min;
}
this.state.questions.push({ n1, n2, op });
}
}
showNextQuestion() {
if (this.state.currentQuestionIndex >= this.state.totalQuestions) {
this.endGame();
return;
}
const q = this.state.questions[this.state.currentQuestionIndex];
// Update UI
this.elements.display.factor1.textContent = q.n1;
this.elements.display.factor2.textContent = q.n2;
let opSymbol = '';
switch (q.op) {
case '+': opSymbol = '+'; break;
case '-': opSymbol = '-'; break;
case '*': opSymbol = '×'; break;
case '/': opSymbol = '÷'; break;
}
this.elements.display.operator.textContent = opSymbol;
this.elements.display.questionCounter.textContent = `Soru ${this.state.currentQuestionIndex + 1}/${this.state.totalQuestions}`;
const progressPercent = (this.state.currentQuestionIndex / this.state.totalQuestions) * 100;
this.elements.display.progressFill.style.width = `${progressPercent}%`;
// Reset Input
this.elements.inputs.answer.value = '';
this.elements.inputs.answer.focus();
// Clear feedback
this.elements.display.feedback.textContent = '';
this.elements.display.feedback.style.opacity = '0';
// Start Timer
this.state.questionStartTime = performance.now();
}
handleAnswer() {
const inputVal = this.elements.inputs.answer.value;
if (inputVal === '') return;
const userAnswer = parseInt(inputVal);
const currentQ = this.state.questions[this.state.currentQuestionIndex];
let correctAnswer;
switch (currentQ.op) {
case '+': correctAnswer = currentQ.n1 + currentQ.n2; break;
case '-': correctAnswer = currentQ.n1 - currentQ.n2; break;
case '*': correctAnswer = currentQ.n1 * currentQ.n2; break;
case '/': correctAnswer = currentQ.n1 / currentQ.n2; break;
}
const isCorrect = userAnswer === correctAnswer;
const timeTaken = (performance.now() - this.state.questionStartTime) / 1000; // seconds
// Record Result
let opSymbol = '';
switch (currentQ.op) {
case '+': opSymbol = '+'; break;
case '-': opSymbol = '-'; break;
case '*': opSymbol = '×'; break;
case '/': opSymbol = '÷'; break;
}
this.state.results.push({
question: `${currentQ.n1} ${opSymbol} ${currentQ.n2}`,
userAnswer,
correctAnswer,
time: timeTaken,
isCorrect
});
this.state.currentQuestionIndex++;
if (isCorrect) {
this.state.score++;
this.showFeedback(true);
setTimeout(() => {
this.showNextQuestion();
}, 500);
} else {
this.showFeedback(false, correctAnswer);
// Longer delay for wrong answers to read the feedback
setTimeout(() => {
this.showNextQuestion();
}, 2000);
}
}
showFeedback(isCorrect, correctAnswer = null) {
const feedbackEl = this.elements.display.feedback;
feedbackEl.style.opacity = '1';
if (isCorrect) {
feedbackEl.textContent = 'Doğru!';
feedbackEl.className = 'feedback-message correct';
} else {
feedbackEl.textContent = `Yanlış! Doğru cevap: ${correctAnswer}`;
feedbackEl.className = 'feedback-message wrong';
}
// Hide feedback when moving to next (handled by showNextQuestion resetting UI or just fade out)
// actually showNextQuestion doesn't clear feedback, let's clear it there or timeout here
}
endGame() {
// Calculate Stats
const correctAnswers = this.state.results.filter(r => r.isCorrect);
const totalTime = correctAnswers.reduce((sum, r) => sum + r.time, 0);
const avgTime = correctAnswers.length > 0 ? (totalTime / correctAnswers.length).toFixed(1) : '0.0';
// Update Result Screen
this.elements.display.avgTime.textContent = `${avgTime}s`;
this.elements.display.scoreText.textContent = `${this.state.score}/${this.state.totalQuestions}`;
// Wrong Answers
const wrongAnswers = this.state.results.filter(r => !r.isCorrect);
this.elements.display.wrongAnswersList.innerHTML = '';
if (wrongAnswers.length > 0) {
this.elements.display.wrongAnswersSection.classList.remove('hidden');
wrongAnswers.forEach(r => {
const item = document.createElement('div');
item.className = 'wrong-item';
item.innerHTML = `
<span class="question">${r.question}</span>
<div>
<span class="user-ans">${r.userAnswer}</span>
<span class="correct-ans">${r.correctAnswer}</span>
</div>
`;
this.elements.display.wrongAnswersList.appendChild(item);
});
} else {
this.elements.display.wrongAnswersSection.classList.add('hidden');
}
this.elements.buttons.shareFormContainer.classList.add('hidden'); // Ensure form is hidden on restart
this.switchScreen('result');
}
resetGame() {
this.switchScreen('start');
}
switchScreen(screenName) {
Object.values(this.elements.screens).forEach(el => {
el.classList.add('hidden');
el.classList.remove('active');
});
const target = this.elements.screens[screenName];
target.classList.remove('hidden');
// Small timeout to allow display:block to apply before opacity transition
setTimeout(() => {
target.classList.add('active');
}, 10);
}
generateReportBody() {
const correctAnswers = this.state.results.filter(r => r.isCorrect);
const total = this.state.totalQuestions;
const score = correctAnswers.length;
const totalTime = correctAnswers.reduce((sum, r) => sum + r.time, 0);
const avgTime = correctAnswers.length > 0 ? (totalTime / correctAnswers.length).toFixed(1) : '0.0';
let body = `Matematik Alıştırması Sonuç Raporu\n`;
body += `Tarih: ${new Date().toLocaleDateString('tr-TR')} ${new Date().toLocaleTimeString('tr-TR')}\n`;
body += `Toplam Soru: ${total}\n`;
body += `Doğru Sayısı: ${score}\n`;
body += `Ortalama Süre: ${avgTime} saniye\n\n`;
const wrongAnswers = this.state.results.filter(r => !r.isCorrect);
if (wrongAnswers.length > 0) {
body += `Hatalı Cevaplar (${wrongAnswers.length}):\n`;
wrongAnswers.forEach(r => {
body += `${r.question} = ${r.correctAnswer} (Cevap: ${r.userAnswer})\n`;
});
} else {
body += `Tebrikler! Hata yapılmadı. 🎉\n`;
}
return body;
}
showShareForm() {
// Toggle Form Visibility
const formContainer = this.elements.buttons.shareFormContainer;
const feedbackEl = this.elements.buttons.formFeedback;
if (!formContainer.classList.contains('hidden')) {
formContainer.classList.add('hidden');
return;
}
// Hide previous feedback
feedbackEl.classList.add('hidden');
feedbackEl.textContent = '';
// Generate Report
const body = this.generateReportBody();
// Populate Textarea and Show Form
this.elements.buttons.reportMessage.value = body;
formContainer.classList.remove('hidden');
// Scroll to form
formContainer.scrollIntoView({ behavior: 'smooth' });
}
shareViaMailto() {
const body = this.generateReportBody();
const subject = encodeURIComponent('Matematik Alıştırması Sonuçları');
const mailtoLink = `mailto:?subject=${subject}&body=${encodeURIComponent(body)}`;
const confirmed = confirm('Rapor hazırlandı. Cihazınızdaki e-posta uygulaması açılsın mı?');
if (confirmed) {
window.location.href = mailtoLink;
}
}
handleFormSubmit(e) {
e.preventDefault();
const form = e.target;
const feedbackEl = this.elements.buttons.formFeedback;
const submitBtn = form.querySelector('button[type="submit"]');
submitBtn.disabled = true;
submitBtn.textContent = 'Gönderiliyor...';
const formData = new FormData(form);
fetch('/', {
method: 'POST',
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(formData).toString()
})
.then(() => {
feedbackEl.textContent = 'Rapor başarıyla gönderildi! ✅';
feedbackEl.style.backgroundColor = '#d1fae5'; // light green
feedbackEl.style.color = '#065f46';
feedbackEl.classList.remove('hidden');
form.reset();
setTimeout(() => {
this.elements.buttons.shareFormContainer.classList.add('hidden');
}, 3000);
})
.catch((error) => {
console.error(error);
feedbackEl.textContent = 'Gönderim sırasında bir hata oluştu. ❌';
feedbackEl.style.backgroundColor = '#fee2e2'; // light red
feedbackEl.style.color = '#991b1b';
feedbackEl.classList.remove('hidden');
})
.finally(() => {
submitBtn.disabled = false;
submitBtn.textContent = 'Raporu Gönder';
});
}
}
// Initialize
document.addEventListener('DOMContentLoaded', () => {
new MathGame();
});