-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
619 lines (539 loc) · 18.7 KB
/
Copy pathscript.js
File metadata and controls
619 lines (539 loc) · 18.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
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
const state = {
defaults: {
a: { num: 3, den: 4 },
b: { num: 2, den: 6 },
shape: "circle",
},
a: { num: 3, den: 4 },
b: { num: 2, den: 6 },
shape: "circle",
unitMode: false,
selectedAnswer: null,
quiz: {
active: false,
difficulty: "normal",
questions: [],
currentIndex: 0,
score: 0,
checkedCurrent: false,
},
};
const els = {
aDen: document.getElementById("aDen"),
aNum: document.getElementById("aNum"),
bDen: document.getElementById("bDen"),
bNum: document.getElementById("bNum"),
aDenValue: document.getElementById("aDenValue"),
aNumValue: document.getElementById("aNumValue"),
bDenValue: document.getElementById("bDenValue"),
bNumValue: document.getElementById("bNumValue"),
formulaA: document.getElementById("formulaA"),
formulaB: document.getElementById("formulaB"),
canvasA: document.getElementById("canvasA"),
canvasB: document.getElementById("canvasB"),
mergeText: document.getElementById("mergeText"),
checkBtn: document.getElementById("checkBtn"),
startQuizBtn: document.getElementById("startQuizBtn"),
nextBtn: document.getElementById("nextBtn"),
stopQuizBtn: document.getElementById("stopQuizBtn"),
difficulty: document.getElementById("difficulty"),
quizProgress: document.getElementById("quizProgress"),
quizResult: document.getElementById("quizResult"),
unitMode: document.getElementById("unitMode"),
comparisonSummary: document.getElementById("comparisonSummary"),
modelTextA: document.getElementById("modelTextA"),
modelTextB: document.getElementById("modelTextB"),
quizAnswerButtons: Array.from(document.querySelectorAll(".quiz-buttons button")),
shapeOptions: Array.from(document.querySelectorAll('input[name="shape"]')),
};
const shapeLabels = {
circle: "원형 모델",
bar: "막대 모델",
};
function syncSliders(group) {
const denInput = group === "a" ? els.aDen : els.bDen;
const numInput = group === "a" ? els.aNum : els.bNum;
const den = Number(denInput.value);
numInput.max = String(den);
if (Number(numInput.value) > den) {
numInput.value = String(den);
}
}
function readState() {
syncSliders("a");
syncSliders("b");
state.a.den = Number(els.aDen.value);
state.b.den = Number(els.bDen.value);
if (state.unitMode) {
els.aNum.value = "1";
els.bNum.value = "1";
}
state.a.num = Number(els.aNum.value);
state.b.num = Number(els.bNum.value);
}
function updateLabels() {
els.aDenValue.textContent = String(state.a.den);
els.aNumValue.textContent = String(state.a.num);
els.bDenValue.textContent = String(state.b.den);
els.bNumValue.textContent = String(state.b.num);
els.formulaA.textContent = `${state.a.num}/${state.a.den}`;
els.formulaB.textContent = `${state.b.num}/${state.b.den}`;
}
function getComparisonLabel(correct) {
if (correct === "A") return "분수 A가 더 큽니다";
if (correct === "B") return "분수 B가 더 큽니다";
return "두 분수가 같습니다";
}
function updateModelDescriptions() {
els.modelTextA.textContent = `${state.a.den}조각 중 ${state.a.num}조각이 색칠되었습니다.`;
els.modelTextB.textContent = `${state.b.den}조각 중 ${state.b.num}조각이 색칠되었습니다.`;
}
function updateComparisonSummary() {
const correct = compareFractions(state.a, state.b);
els.comparisonSummary.textContent = `A ${state.a.num}/${state.a.den}, B ${state.b.num}/${state.b.den} · ${getComparisonLabel(correct)}.`;
}
function updateCanvasLabels() {
const shapeLabel = shapeLabels[state.shape] || "분수 모델";
els.canvasA.setAttribute(
"aria-label",
`분수 A: ${state.a.num}/${state.a.den}, ${shapeLabel}에서 ${state.a.den}개 중 ${state.a.num}개가 칠해졌습니다.`,
);
els.canvasB.setAttribute(
"aria-label",
`분수 B: ${state.b.num}/${state.b.den}, ${shapeLabel}에서 ${state.b.den}개 중 ${state.b.num}개가 칠해졌습니다.`,
);
}
function drawCircle(ctx, num, den, color) {
const cx = 130;
const cy = 110;
const r = 82;
ctx.clearRect(0, 0, 260, 220);
for (let i = 0; i < den; i += 1) {
const start = -Math.PI / 2 + (i / den) * Math.PI * 2;
const end = -Math.PI / 2 + ((i + 1) / den) * Math.PI * 2;
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.arc(cx, cy, r, start, end);
ctx.closePath();
ctx.fillStyle = i < num ? color : "#f3f6f9";
ctx.fill();
ctx.strokeStyle = "#2f3e46";
ctx.lineWidth = 2;
ctx.stroke();
}
}
function drawBar(ctx, num, den, color) {
ctx.clearRect(0, 0, 260, 220);
const x = 20;
const y = 80;
const w = 220;
const h = 60;
const segment = w / den;
for (let i = 0; i < den; i += 1) {
ctx.beginPath();
ctx.rect(x + i * segment, y, segment, h);
ctx.fillStyle = i < num ? color : "#f3f6f9";
ctx.fill();
ctx.strokeStyle = "#2f3e46";
ctx.lineWidth = 2;
ctx.stroke();
}
}
function drawFraction(canvas, fraction, color) {
const ctx = canvas.getContext("2d");
if (!ctx) {
return;
}
if (state.shape === "circle") {
drawCircle(ctx, fraction.num, fraction.den, color);
} else {
drawBar(ctx, fraction.num, fraction.den, color);
}
}
function simplify(num, den) {
const divisor = getGreatestCommonDivisor(num, den);
return { num: num / divisor, den: den / divisor };
}
function getGreatestCommonDivisor(x, y) {
let a = Math.abs(x);
let b = Math.abs(y);
while (b !== 0) {
const t = b;
b = a % b;
a = t;
}
return a;
}
function getLeastCommonMultiple(x, y) {
return (x * y) / getGreatestCommonDivisor(x, y);
}
function updateMergeHint() {
const remain = state.a.den - state.a.num;
const reduced = simplify(remain, state.a.den);
if (remain === 0) {
els.mergeText.innerHTML = "분수 A는 이미 <strong>1(전체)</strong>예요! 아주 잘했어요.";
return;
}
els.mergeText.innerHTML = `분수 A와 더해 1이 되려면 <strong>${reduced.num}/${reduced.den}</strong> 조각이 더 필요해요.`;
}
function compareFractions(x, y) {
const left = x.num * y.den;
const right = y.num * x.den;
if (left > right) return "A";
if (left < right) return "B";
return "E";
}
function getAnswerLabel(answer) {
if (answer === "A") return "분수 A";
if (answer === "B") return "분수 B";
return "같다";
}
function getComparisonExplanation(correct) {
if (state.a.den === state.b.den) {
if (correct === "E") {
return `같은 크기의 조각 ${state.a.den}개 중 둘 다 ${state.a.num}조각이 색칠되어 같아요.`;
}
return `같은 크기의 조각 ${state.a.den}개 중 분수 A는 ${state.a.num}조각, 분수 B는 ${state.b.num}조각이 색칠되었어요. 더 많이 색칠된 ${getAnswerLabel(correct)}가 더 커요.`;
}
if (state.a.num === 1 && state.b.num === 1) {
if (correct === "E") {
return `두 분수는 같은 단위분수예요. 전체를 같은 수로 나누어 한 조각 크기가 같아요.`;
}
const largerFractionDen = correct === "A" ? state.a.den : state.b.den;
const otherDen = correct === "A" ? state.b.den : state.a.den;
return `두 분수는 한 조각만 색칠한 단위분수예요. ${getAnswerLabel(correct)}는 전체를 ${largerFractionDen}조각으로 나눈 한 조각이고, 다른 분수는 전체를 ${otherDen}조각으로 나눈 한 조각이에요. 같은 전체라면 더 적게 나눌수록 한 조각이 더 커요. 그래서 ${getAnswerLabel(correct)}가 더 커요.`;
}
const commonDenominator = getLeastCommonMultiple(state.a.den, state.b.den);
const aPieces = state.a.num * (commonDenominator / state.a.den);
const bPieces = state.b.num * (commonDenominator / state.b.den);
if (correct === "E") {
return `전체를 ${commonDenominator}개의 같은 크기 조각으로 다시 나눠 보면, 분수 A도 ${aPieces}조각, 분수 B도 ${bPieces}조각이 색칠된 것과 같아요. 그래서 두 분수는 같아요.`;
}
return `전체를 ${commonDenominator}개의 같은 크기 조각으로 다시 나눠 보면, 분수 A는 ${aPieces}조각, 분수 B는 ${bPieces}조각이 색칠된 것과 같아요. 더 많이 색칠된 ${getAnswerLabel(correct)}가 더 커요.`;
}
function buildFeedback(isCorrect, correct, activeQuiz) {
const explanation = getComparisonExplanation(correct);
if (isCorrect) {
const lead = activeQuiz ? "정답! 아주 잘했어요." : "정답! 분수의 크기를 정확히 비교했어요.";
return `${lead} ${explanation}`;
}
return `아쉬워요. 정답은 "${getAnswerLabel(correct)}"예요. ${explanation}`;
}
function resetQuizMessage() {
els.quizResult.textContent = "";
els.quizResult.className = "result-text";
}
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function makeRandomFraction(minDen, maxDen) {
const den = randomInt(minDen, maxDen);
const num = randomInt(1, den);
return { num, den };
}
function simplifyPair(fraction) {
return simplify(fraction.num, fraction.den);
}
function makeEquivalentFraction(fraction, maxDen) {
const maxFactor = Math.floor(maxDen / fraction.den);
if (maxFactor < 2) {
return { num: fraction.num, den: fraction.den };
}
const factor = randomInt(2, maxFactor);
return { num: fraction.num * factor, den: fraction.den * factor };
}
function generateQuestion(difficulty) {
const config =
difficulty === "easy"
? { minDen: 2, maxDen: 6, sameDenChance: 0.65, equalChance: 0.1 }
: difficulty === "hard"
? { minDen: 4, maxDen: 12, sameDenChance: 0.2, equalChance: 0.15 }
: { minDen: 2, maxDen: 9, sameDenChance: 0.35, equalChance: 0.2 };
for (let attempt = 0; attempt < 100; attempt += 1) {
const a = makeRandomFraction(config.minDen, config.maxDen);
let b = makeRandomFraction(config.minDen, config.maxDen);
if (Math.random() < config.sameDenChance) {
b.den = a.den;
b.num = randomInt(1, b.den);
}
if (Math.random() < config.equalChance) {
b = makeEquivalentFraction(a, config.maxDen);
}
if (difficulty === "hard" && Math.random() < 0.5) {
const closeDen = Math.min(config.maxDen, Math.max(config.minDen, a.den + randomInt(-2, 2)));
b.den = closeDen;
b.num = randomInt(1, closeDen);
}
const aSimple = simplifyPair(a);
const bSimple = simplifyPair(b);
const equivalent = aSimple.num === bSimple.num && aSimple.den === bSimple.den;
if (difficulty === "easy" && !equivalent && Math.abs(a.num - b.num) <= 1 && a.den === b.den) {
continue;
}
return { a, b };
}
return { a: { num: 1, den: 2 }, b: { num: 1, den: 3 } };
}
function generateQuizSet(difficulty, count) {
const set = [];
for (let i = 0; i < count; i += 1) {
set.push(generateQuestion(difficulty));
}
return set;
}
function setControlsLocked(locked) {
els.aDen.disabled = locked;
els.aNum.disabled = locked || state.unitMode;
els.bDen.disabled = locked;
els.bNum.disabled = locked || state.unitMode;
els.unitMode.disabled = locked;
[els.aDen, els.aNum, els.bDen, els.bNum, els.unitMode].forEach((input) => {
const block = input.closest(".control-block");
if (!block) return;
block.classList.toggle("locked", locked);
});
}
function clearSelectedAnswer() {
state.selectedAnswer = null;
syncAnswerButtons();
}
function syncAnswerButtons() {
els.quizAnswerButtons.forEach((button, index) => {
const selected = button.dataset.answer === state.selectedAnswer;
button.classList.toggle("primary", selected);
button.setAttribute("role", "radio");
button.setAttribute("aria-checked", selected ? "true" : "false");
button.setAttribute("tabindex", selected || (!state.selectedAnswer && index === 0) ? "0" : "-1");
});
}
function selectAnswer(answer, shouldFocus = false) {
state.selectedAnswer = answer;
syncAnswerButtons();
if (shouldFocus) {
const button = els.quizAnswerButtons.find((item) => item.dataset.answer === answer);
if (button) {
button.focus();
}
}
}
function moveAnswerSelection(currentButton, direction) {
const currentIndex = els.quizAnswerButtons.indexOf(currentButton);
if (currentIndex < 0) return;
const lastIndex = els.quizAnswerButtons.length - 1;
const nextIndex =
direction === "first"
? 0
: direction === "last"
? lastIndex
: (currentIndex + direction + els.quizAnswerButtons.length) % els.quizAnswerButtons.length;
selectAnswer(els.quizAnswerButtons[nextIndex].dataset.answer, true);
}
function applyQuestion(question) {
els.aDen.value = String(question.a.den);
els.aNum.value = String(question.a.num);
els.bDen.value = String(question.b.den);
els.bNum.value = String(question.b.num);
render();
}
function updateQuizProgressText() {
if (!state.quiz.active) {
return;
}
const current = state.quiz.currentIndex + 1;
const total = state.quiz.questions.length;
els.quizProgress.textContent = `${current}/${total}문제 | 현재 점수: ${state.quiz.score}점`;
}
function startQuiz() {
state.quiz.difficulty = els.difficulty.value;
state.quiz.questions = generateQuizSet(state.quiz.difficulty, 10);
state.quiz.currentIndex = 0;
state.quiz.score = 0;
state.quiz.active = true;
state.quiz.checkedCurrent = false;
state.unitMode = false;
els.unitMode.checked = false;
clearSelectedAnswer();
resetQuizMessage();
setControlsLocked(true);
applyQuestion(state.quiz.questions[0]);
updateQuizProgressText();
els.startQuizBtn.textContent = "랜덤 10문제 다시 시작";
els.nextBtn.disabled = true;
els.checkBtn.disabled = false;
}
function finishQuiz() {
state.quiz.active = false;
state.quiz.checkedCurrent = false;
setControlsLocked(false);
clearSelectedAnswer();
els.nextBtn.disabled = true;
els.quizProgress.textContent = `완료! 총점: ${state.quiz.score}/10점`;
els.quizResult.textContent = "10문제가 끝났어요. 난이도를 바꿔 다시 도전해 보세요.";
els.quizResult.className = "result-text ok";
}
function resetToHome() {
state.quiz.active = false;
state.quiz.checkedCurrent = false;
state.quiz.questions = [];
state.quiz.currentIndex = 0;
state.quiz.score = 0;
state.selectedAnswer = null;
state.unitMode = false;
state.shape = state.defaults.shape;
els.aDen.value = String(state.defaults.a.den);
els.aNum.value = String(state.defaults.a.num);
els.bDen.value = String(state.defaults.b.den);
els.bNum.value = String(state.defaults.b.num);
els.unitMode.checked = false;
els.shapeOptions.forEach((opt) => {
opt.checked = opt.value === state.defaults.shape;
});
setControlsLocked(false);
clearSelectedAnswer();
resetQuizMessage();
els.startQuizBtn.textContent = "랜덤 10문제 시작";
els.quizProgress.textContent = "대기 중: 시작 버튼을 눌러 주세요.";
els.nextBtn.disabled = true;
els.checkBtn.disabled = false;
render();
}
function goNextQuestion() {
if (!state.quiz.active) {
return;
}
if (!state.quiz.checkedCurrent) {
els.quizResult.textContent = "정답 확인 후 다음 문제로 넘어갈 수 있어요.";
els.quizResult.className = "result-text bad";
return;
}
if (state.quiz.currentIndex >= state.quiz.questions.length - 1) {
finishQuiz();
return;
}
state.quiz.currentIndex += 1;
state.quiz.checkedCurrent = false;
clearSelectedAnswer();
resetQuizMessage();
applyQuestion(state.quiz.questions[state.quiz.currentIndex]);
updateQuizProgressText();
els.nextBtn.disabled = true;
}
function render() {
readState();
updateLabels();
updateModelDescriptions();
updateComparisonSummary();
updateCanvasLabels();
drawFraction(els.canvasA, state.a, "#ff7b89");
drawFraction(els.canvasB, state.b, "#5ec2f7");
updateMergeHint();
}
function bindEvents() {
[els.aDen, els.aNum, els.bDen, els.bNum].forEach((input) => {
input.addEventListener("input", () => {
clearSelectedAnswer();
resetQuizMessage();
render();
});
});
els.shapeOptions.forEach((option) => {
option.addEventListener("change", () => {
state.shape = option.value;
clearSelectedAnswer();
render();
});
});
els.unitMode.addEventListener("change", () => {
state.unitMode = els.unitMode.checked;
els.aNum.disabled = state.unitMode;
els.bNum.disabled = state.unitMode;
if (state.unitMode) {
els.aNum.value = "1";
els.bNum.value = "1";
}
clearSelectedAnswer();
resetQuizMessage();
render();
});
els.startQuizBtn.addEventListener("click", () => {
startQuiz();
});
els.nextBtn.addEventListener("click", () => {
goNextQuestion();
});
els.stopQuizBtn.addEventListener("click", () => {
resetToHome();
});
els.quizAnswerButtons.forEach((btn) => {
btn.addEventListener("click", () => {
selectAnswer(btn.dataset.answer);
});
btn.addEventListener("keydown", (event) => {
if (["ArrowDown", "ArrowRight"].includes(event.key)) {
event.preventDefault();
moveAnswerSelection(btn, 1);
return;
}
if (["ArrowUp", "ArrowLeft"].includes(event.key)) {
event.preventDefault();
moveAnswerSelection(btn, -1);
return;
}
if (event.key === "Home") {
event.preventDefault();
moveAnswerSelection(btn, "first");
return;
}
if (event.key === "End") {
event.preventDefault();
moveAnswerSelection(btn, "last");
return;
}
if (event.key === " " || event.key === "Enter") {
event.preventDefault();
selectAnswer(btn.dataset.answer);
}
});
});
els.checkBtn.addEventListener("click", () => {
if (!state.selectedAnswer) {
els.quizResult.textContent = "먼저 답을 골라 주세요!";
els.quizResult.className = "result-text bad";
return;
}
if (state.quiz.active) {
if (state.quiz.checkedCurrent) {
els.quizResult.textContent = "이미 확인한 문제예요. 다음 문제로 넘어가세요.";
els.quizResult.className = "result-text bad";
return;
}
readState();
const correct = compareFractions(state.a, state.b);
if (state.selectedAnswer === correct) {
state.quiz.score += 1;
els.quizResult.textContent = buildFeedback(true, correct, true);
els.quizResult.className = "result-text ok";
} else {
els.quizResult.textContent = buildFeedback(false, correct, true);
els.quizResult.className = "result-text bad";
}
state.quiz.checkedCurrent = true;
updateQuizProgressText();
els.nextBtn.disabled = false;
return;
}
readState();
const correct = compareFractions(state.a, state.b);
if (state.selectedAnswer === correct) {
els.quizResult.textContent = buildFeedback(true, correct, false);
els.quizResult.className = "result-text ok";
} else {
els.quizResult.textContent = buildFeedback(false, correct, false);
els.quizResult.className = "result-text bad";
}
});
}
bindEvents();
els.nextBtn.disabled = true;
syncAnswerButtons();
render();