-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
1483 lines (1253 loc) · 55.5 KB
/
script.js
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const questions = {}; // 문제들을 저장할 객체
let score = 0; // 사용자 점수 저장
let selectedDifficulty = ""; // 선택된 난이도 저장
let displayedAnswers = []; // 현재 질문에서 보여진 답변 목록 저장
let selectedDifficulties = []; // 사용자가 선택한 난이도 저장
let totalQuestions = 0; // 전체 문제 수 저장
// UI 요소 초기 상태 설정
function resetElements() {
console.log("");
console.log("[SYSTEM] UI 요소 초기 상태 설정");
// 메인 화면 캐릭터 이미지 표시
document.querySelector(".partner-image-container").style.display = "block";
document.querySelector(".partner-image").src = "./asm_partner_01_base.png";
// 칠판 이미지 위치 조절
document.getElementById("chalkboardImage").style.top = "50%";
// 체크박스 초기화
document.getElementById("JLPT N1").checked = false;
document.getElementById("JLPT N2").checked = false;
document.getElementById("JLPT N3").checked = false;
document.getElementById("JLPT N4").checked = false;
document.getElementById("JLPT N5").checked = false;
document.getElementById("필수기초단어").checked = false;
// 텍스트박스 초기화
document.getElementById("questionCountInput").value = "";
document.getElementById("customQuestionCountInput").value = "";
// 발음 기호 표시 체크박스 초기화
document.getElementById("showPronunciation").checked = false;
document.getElementById("customshowPronunciation").checked = false;
// 출제 문제수 기준 설정 라디오 버튼 체크박스 초기화
document.getElementById("customQuestionOption1").checked = false;
document.getElementById("customQuestionOption2").checked = true;
// Confetti 중지
StopConfetti(); // Confetti.js 함수 호출
// 특정 날짜 확인 함수에 지정한 날짜에만 작동
if (isTodaySpecialDate()) {
InitializeConfetti(); // Confetti.js 함수 호출
console.log("[SYSTEM] Confetti.js 실행");
console.log("[Developer] ☆★캬루의 생일을 축하합니다!★☆"); // 개발자 축하 메시지
}
}
// 로딩 화면을 보여주는 함수
const showLoadingScreen = () => {
const loadingScreen = document.getElementById("loading-screen");
loadingScreen.style.opacity = "1"; // 투명도 변경
loadingScreen.style.display = "flex"; // 로딩 화면을 보이게 함
};
// 로딩 화면을 숨기는 함수
const hideLoadingScreen = () => {
return new Promise((resolve) => {
const loadingScreen = document.getElementById("loading-screen");
loadingScreen.classList.remove("hidden"); // 숨김 클래스 제거
setTimeout(() => {
loadingScreen.style.opacity = "0"; // 투명도 변경
setTimeout(() => {
loadingScreen.style.display = "none"; // 최종적으로 숨김
resolve();
}, 500); // 애니메이션 시간과 같게 설정
}, 300); // 대기 시간
});
};
// CSV 파일에서 문제 로딩 함수
async function loadQuestions() {
try {
const response = await fetch("Questions.csv");
if (!response.ok) {
console.log("");
console.erorr(
"[SYSTEM] 네트워크 문제 발생(서버 응답이 HTTP 200~299 범위가 아님)"
);
throw new Error("네트워크 응답이 올바르지 않습니다."); // 서버 응답이 HTTP 200~299 범위가 아닐 경우 실행
}
const csvText = await response.text();
// PapaParse를 사용하여 CSV 파싱
Papa.parse(csvText, {
header: true,
skipEmptyLines: true,
complete: (results) => {
results.data.forEach((row) => {
const { difficulty, question, pronunciation, answers, correct } = row;
if (!questions[difficulty]) {
questions[difficulty] = [];
}
questions[difficulty].push({
question,
answers: answers.split(";"), // 답변 목록은 세미콜론으로 분리되었다고 가정
correct,
pronunciation,
});
});
},
});
} catch (error) {
console.log("");
console.error("[SYSTEM] Error loading questions:", error);
console.log("[SYSTEM] 문제 데이터(Questions.csv) 로딩 실패");
alert("문제 데이터(Questions.csv)를 불러오는 데 실패했습니다.");
}
}
// 특정 날짜 확인 함수
function isTodaySpecialDate() {
const today = new Date();
const specialDate = new Date(today.getFullYear(), 8, 2); // 9월 2일, Month는 0부터 시작(1월 = 0, 12월 = 11)
console.log("");
console.log("[SYSTEM] 현재 시스템 날짜:", today.toLocaleDateString()); // 현재 시스템 날짜
console.log("[SYSTEM] 특정 날짜:", specialDate.toLocaleDateString()); // 특정 날짜
return (
today.getDate() === specialDate.getDate() &&
today.getMonth() === specialDate.getMonth()
);
}
// 페이지가 로드될 때 필수 리소스 로드
window.onload = async () => {
console.log("[SYSTEM] 로딩 화면 표시 중...");
showLoadingScreen(); // 로딩 화면 표시
// 폰트 로드
const fontPromises = [
document.fonts.load("400 1em 'Noto Sans KR'"),
document.fonts.load("400 1em 'Allison'"),
document.fonts.load("400 1em 'Noto Serif KR'"),
];
// 이미지 로드
const partnerImage = new Image();
partnerImage.src = "./asm_partner_01_base.png";
const listenButtonImage = new Image();
listenButtonImage.src = "./pronunciationListenButton.png";
// 폰트 및 이미지 로드 대기
await Promise.all([
new Promise((resolve, reject) => {
console.log("[SYSTEM] 폰트 로딩 중...");
document.querySelector("#loading-screen p").innerText = "폰트 로딩 중...";
Promise.all(fontPromises)
.then(() => {
console.log("[SYSTEM] 폰트 로딩 완료");
document.querySelector("#loading-screen p").innerText =
"폰트 로딩 완료";
resolve();
})
.catch((error) => {
console.error("[SYSTEM] 폰트 로딩 실패", error);
reject();
});
}),
new Promise((resolve, reject) => {
console.log("[SYSTEM] 이미지 로딩 중...");
document.querySelector("#loading-screen p").innerText =
"이미지 로딩 중...";
let loadedImages = 0;
const checkComplete = () => {
loadedImages++;
if (loadedImages === 2) {
console.log("[SYSTEM] 이미지 로딩 완료");
document.querySelector("#loading-screen p").innerText =
"이미지 로딩 완료";
resolve();
}
};
partnerImage.onload = checkComplete;
partnerImage.onerror = () => {
console.error("[SYSTEM] 메인 화면 캐릭터 이미지 로딩 실패");
reject();
};
listenButtonImage.onload = checkComplete;
listenButtonImage.onerror = () => {
console.error("[SYSTEM] 정오표 발음 버튼 이미지 로딩 실패");
reject();
};
}),
]);
// 문제 데이터 로드
console.log("[SYSTEM] 문제 데이터(Questions.csv) 로딩 중...");
document.querySelector("#loading-screen p").innerText =
"문제 데이터 로딩 중...";
await loadQuestions();
console.log("[SYSTEM] 문제 데이터(Questions.csv) 로딩 완료");
document.querySelector("#loading-screen p").innerText =
"문제 데이터 로딩 완료";
// 모든 리소스 로딩 완료 메시지 표시
console.log("[SYSTEM] 모든 리소스 로딩 완료");
document.querySelector("#loading-screen p").innerText =
"모든 리소스 로딩 완료";
// 페이지가 로드된 후 0.5초 대기 후 로딩 화면 숨기기
await new Promise((resolve) => setTimeout(resolve, 500)); // 0.5초 대기
await hideLoadingScreen();
console.log("[SYSTEM] 로딩 화면 숨김");
// 나머지 초기화 작업
resetElements();
console.log("[SYSTEM] 초기화 작업 완료");
};
// 난이도 선택 확인 팝업 창 표시 함수
function showConfirmation(difficulty) {
console.log("");
console.log("[SYSTEM] 난이도 선택 확인 팝업 창 표시");
selectedDifficulty = difficulty;
const confirmationMessage = `난이도 '${difficulty}'을(를) 선택하셨습니다.<br><br>계속 하시겠습니까?`;
document.getElementById("confirmationMessage").innerHTML =
confirmationMessage;
document.getElementById("menu").style.display = "none";
const confirmationContainer = document.getElementById(
"confirmationContainer"
);
confirmationContainer.style.display = "block";
confirmationContainer.classList.add("show");
}
// 난이도 선택 확인 팝업 창에서 예/아니오 버튼 클릭 시 처리 함수
function confirmSelection(confirm) {
const confirmationContainer = document.getElementById(
"confirmationContainer"
);
if (confirm) {
console.log("[SYSTEM] 난이도 선택 확인 팝업 창에서 '예' 버튼 클릭");
// 선택된 난이도 배열을 초기화하고 새 난이도만 추가
selectedDifficulties = [selectedDifficulty];
confirmationContainer.classList.remove("show");
setTimeout(() => {
confirmationContainer.style.display = "none";
showQuestionCountInput(); // 문제 수 입력 창 표시
}, 120);
} else {
confirmationContainer.classList.remove("show");
console.log("[SYSTEM] 난이도 선택 확인 팝업 창에서 '아니요' 버튼 클릭");
setTimeout(() => {
confirmationContainer.style.display = "none";
document.getElementById("menu").style.display = "flex"; // 메뉴 표시
}, 120);
}
}
// 문제 수 입력 팝업 창 표시 함수
function showQuestionCountInput() {
console.log("");
console.log("[SYSTEM] 문제 수 입력 팝업 창 표시");
const questionCountContainer = document.getElementById(
"questionCountContainer"
);
const difficultyInfo = document.getElementById("difficultyInfo");
// 현재 선택된 난이도와 전체 문제 수 표시
totalQuestions = questions[selectedDifficulty]
? questions[selectedDifficulty].length
: 0;
difficultyInfo.innerHTML = `선택된 난이도: ${selectedDifficulty}<br>전체 문제 수: ${totalQuestions}개`;
questionCountContainer.style.display = "block";
questionCountContainer.classList.add("show");
}
// 문제 수 입력 후 확인 함수
function confirmQuestionCount() {
console.log("[SYSTEM] 문제 수 입력 팝업 창에서 '확인' 버튼 클릭");
const input = document.getElementById("questionCountInput").value;
let count = parseInt(input, 10);
// 입력 값이 숫자가 아닌 경우
if (isNaN(count)) {
console.log("[SYSTEM] 입력 값이 숫자가 아님");
alert("올바른 숫자(정수)를 입력해 주세요.");
return;
}
// 입력 값이 1보다 작은 경우
if (count < 1) {
console.log("[SYSTEM] 입력 값이 1보다 작음");
alert("최소 1 이상의 값을 입력하세요.");
document.getElementById("questionCountInput").value = ""; // 수정된 값을 입력 필드에 반영
return;
}
// 선택된 난이도의 전체 문제 수를 초과하는 경우
if (count > totalQuestions) {
count = totalQuestions;
document.getElementById("questionCountInput").value = count;
console.log("[SYSTEM] 선택된 난이도의 전체 문제 수 초과");
alert(
`선택된 난이도의 전체 문제 수를 초과했습니다.\n` +
`최대 ${totalQuestions}개의 문제로 자동 설정됩니다.`
);
console.log("[SYSTEM] 선택된 난이도의 전체 문제 수로 설정");
return;
}
console.log(`[SYSTEM] 문제 수: ${count}`);
document.querySelector("#loading-screen p").innerText =
"문제를 불러오는 중...";
console.log("[SYSTEM] 문제 불러오는 중...");
console.log("[SYSTEM] 로딩 화면 표시 중...");
showLoadingScreen(); // 로딩 화면 표시
// 로딩 화면 표시된 후 대기 시간 설정
setTimeout(() => {
hideLoadingScreen(); // 로딩 화면 숨김
console.log("[SYSTEM] 로딩 화면 숨김");
questionCount = count;
document.getElementById("questionCountContainer").classList.remove("show");
// 퀴즈 시작
setTimeout(() => {
document.getElementById("questionCountContainer").style.display = "none";
startQuiz(selectedDifficulty);
}, 120);
}, 100); // 로딩 화면이 표시된 후 0.1초 대기
}
// 문제 수 입력 취소 함수
function cancelQuestionCount() {
console.log("[SYSTEM] 문제 수 입력 팝업 창에서 '취소' 버튼 클릭");
document.getElementById("questionCountContainer").classList.remove("show");
setTimeout(() => {
document.getElementById("questionCountContainer").style.display = "none";
document.getElementById("menu").style.display = "flex";
document.getElementById("progressContainer").style.display = "none"; // 진행 상태 막대 숨기기
resetElements();
}, 120);
}
// 사용자 지정 문제 확인 팝업 창 표시 함수
function startCustomQuiz() {
console.log("");
console.log("[SYSTEM] 사용자 지정 문제 확인 팝업 창 표시");
// 확인 메시지 설정
const confirmationMessage = `사용자 지정 문제 을(를) 선택하셨습니다.<br><br>계속 하시겠습니까?`;
document.getElementById("customQuizConfirmationMessage").innerHTML =
confirmationMessage;
// 메뉴 숨기기
document.getElementById("menu").style.display = "none";
const customQuizConfirmationContainer = document.getElementById(
"customQuizConfirmationContainer"
);
customQuizConfirmationContainer.style.display = "block";
customQuizConfirmationContainer.classList.add("show");
}
// 사용자 지정 문제 확인 팝업 창에서 '예' 또는 '아니오' 버튼 클릭 시 호출되는 함수
function handleCustomQuizConfirmation(confirm) {
const customQuizConfirmationContainer = document.getElementById(
"customQuizConfirmationContainer"
);
if (confirm) {
console.log("[SYSTEM] 사용자 지정 문제 확인 팝업 창에서 '예' 버튼 클릭");
customQuizConfirmationContainer.classList.remove("show");
setTimeout(() => {
customQuizConfirmationContainer.style.display = "none";
showCustomQuestionCountInput();
}, 120);
} else {
console.log(
"[SYSTEM] 사용자 지정 문제 확인 팝업 창에서 '아니요' 버튼 클릭"
);
customQuizConfirmationContainer.classList.remove("show");
setTimeout(() => {
customQuizConfirmationContainer.style.display = "none";
document.getElementById("menu").style.display = "flex";
}, 120);
}
}
// 사용자 지정 문제 설정 팝업 창 표시 함수
function showCustomQuestionCountInput() {
console.log("");
console.log("[SYSTEM] 사용자 지정 문제 설정 팝업 창 표시");
const customQuestionCountContainer = document.getElementById(
"customQuestionCountContainer"
);
customQuestionCountContainer.style.display = "block";
customQuestionCountContainer.classList.add("show");
updateDifficultyInfo(); // 체크박스 상태와 문제 수를 업데이트
}
// 사용자 지정 문제 설정 팝업 창에서 '확인' 버튼 클릭 시 호출되는 함수
function confirmCustomQuestionCount() {
console.log("[SYSTEM] 사용자 지정 문제 설정 팝업 창에서 '확인' 버튼 클릭");
questionCount = document.getElementById("customQuestionCountInput").value;
// 난이도가 선택되지 않은 경우
if (selectedDifficulties.length === 0) {
console.log("[SYSTEM] 난이도가 선택 되지 않음");
alert("하나 이상의 난이도를 선택해 주세요.");
return;
}
// 숫자가 아닌 경우
if (isNaN(questionCount)) {
console.log("[SYSTEM] 입력 값이 숫자가 아님");
alert("올바른 숫자(정수)를 입력해 주세요.");
return;
}
// 1보다 작은 경우
if (questionCount < 1) {
console.log("[SYSTEM] 입력 값이 1보다 작음");
alert("최소 1 이상의 값을 입력하세요.");
document.getElementById("customQuestionCountInput").value = "";
return;
}
// 선택된 난이도의 전체 문제 수 계산
let totalQuestions = 0;
selectedDifficulties.forEach((difficulty) => {
if (questions[difficulty]) {
totalQuestions += questions[difficulty].length;
}
});
// 전체 문제 수를 초과하는 경우
if (questionCount > totalQuestions) {
count = totalQuestions;
document.getElementById("customQuestionCountInput").value = count; // 문제 수를 최대값으로 조정
console.log("[SYSTEM] 선택된 난이도의 전체 문제 수 초과");
alert(
`선택된 난이도의 전체 문제 수를 초과했습니다.\n` +
`최대 ${totalQuestions}개의 문제로 자동 설정됩니다.`
);
console.log("[SYSTEM] 선택된 난이도의 전체 문제 수로 설정");
return;
}
console.log(`[SYSTEM] 문제 수: ${questionCount}`);
// 입력 창 숨기기
const customQuestionCountContainer = document.getElementById(
"customQuestionCountContainer"
);
document.querySelector("#loading-screen p").innerText =
"사용자 지정 문제를 불러오는 중...";
console.log("[SYSTEM] 사용자 지정 문제 불러오는 중...");
console.log("[SYSTEM] 로딩 화면 표시 중...");
showLoadingScreen(); // 로딩 화면 표시
// 로딩 화면 표시된 후 대기 시간 설정
setTimeout(() => {
hideLoadingScreen();
console.log("[SYSTEM] 로딩 화면 숨김");
customQuestionCountContainer.classList.remove("show");
// 퀴즈 시작
setTimeout(() => {
customQuestionCountContainer.style.display = "none";
startQuiz(); // 퀴즈 시작 함수 호출
}, 120);
}, 100); // 로딩 화면이 표시된 후 0.1초 대기
}
// 사용자 지정 문제 설정 팝업 창에서 '취소' 버튼 클릭 시 호출되는 함수
function cancelCustomQuestionCount() {
console.log("[SYSTEM] 사용자 지정 문제 설정 팝업 창에서 '취소' 버튼 클릭");
// 입력 창 숨기기
const customQuestionCountContainer = document.getElementById(
"customQuestionCountContainer"
);
customQuestionCountContainer.classList.remove("show");
setTimeout(() => {
customQuestionCountContainer.style.display = "none";
document.getElementById("menu").style.display = "flex";
resetElements();
}, 120);
}
// 사용자 지정 문제 설정 팝업 창에서 체크박스 상태와 문제 수를 업데이트하는 함수
function updateDifficultyInfo() {
// 체크박스 요소를 선택
const checkboxes = document.querySelectorAll(
'#difficultyCheckboxContainer input[type="checkbox"]'
);
selectedDifficulties = [];
// 체크된 체크박스의 값을 수집
checkboxes.forEach((checkbox) => {
if (checkbox.checked) {
selectedDifficulties.push(checkbox.value);
}
});
// 선택된 난이도에 따른 문제 수 계산
totalQuestions = 0;
selectedDifficulties.forEach((difficulty) => {
if (questions[difficulty]) {
totalQuestions += questions[difficulty].length;
}
});
// 문제 수 정보를 표시할 문자열 생성
const infoText = `선택된 난이도의 전체 문제 수: ${totalQuestions}`;
// `<p id="customDifficultyInfo"></p>` 요소에 문자열을 설정
document.getElementById("customDifficultyInfo").innerHTML = infoText;
}
// 사용자 지정 문제 체크박스와 문제 수 입력의 변화를 감지하여 `updateDifficultyInfo`를 호출
document
.querySelectorAll('#difficultyCheckboxContainer input[type="checkbox"]')
.forEach((checkbox) => {
checkbox.addEventListener("change", updateDifficultyInfo);
});
document
.getElementById("customQuestionCountInput")
.addEventListener("input", updateDifficultyInfo);
// 입력 필드에서 점(`.`) 자동 삭제 및 마우스 휠로 숫자 증가, 감소 기능을 처리하는 함수
function setupInputHandling(inputId) {
const inputField = document.getElementById(inputId);
// 점(`.`) 자동 삭제
inputField.addEventListener("input", function (event) {
const input = event.target;
input.value = input.value.replace(/\./g, "");
});
// 마우스 휠로 숫자 증가, 감소
inputField.addEventListener("wheel", function (event) {
const input = event.target;
let value = parseInt(input.value.replace(/\D/g, ""), 10) || 0;
// 문제 수의 최소값 설정
const minValue = 1;
// 선택된 난이도에 따른 최대값 설정
const maxValue = selectedDifficulties.reduce((total, difficulty) => {
if (questions[difficulty]) {
return total + questions[difficulty].length;
}
return total;
}, 0);
if (event.deltaY < 0) {
// 값을 증가시키되 최대값을 초과하지 않도록
value = Math.min(value + 1, maxValue);
} else if (event.deltaY > 0) {
// 값을 감소시키되 최소값보다 작아지지 않도록
value = Math.max(value - 1, minValue);
}
// 값 업데이트
input.value = value;
// 기본 스크롤 동작 방지
event.preventDefault();
});
}
// 문제 수 입력 필드 설정
setupInputHandling("questionCountInput");
// 사용자 지정 문제 수 입력 필드 설정
setupInputHandling("customQuestionCountInput");
// 퀴즈 시작 함수
function startQuiz() {
console.log("");
console.log("[SYSTEM] 퀴즈 시작");
StopConfetti();
console.log("[SYSTEM] Confetti.js 중지");
// 문제 출제 옵션 선택
const mode = document.querySelector(
'input[name="customQuestionMode"]:checked'
).value;
selectedDifficulties.push(mode); // 선택한 난이도를 배열에 추가 (* 상장 다운로드시 사용)
// 문제 데이터를 숨기고, 퀴즈 컨테이너 표시
document.getElementById("confirmationContainer").style.display = "none";
document.getElementById("questionCountContainer").style.display = "none";
document.getElementById("quizContainer").style.display = "grid";
document.getElementById("menu").style.display = "none";
console.log("[SYSTEM] 진행 상태 막대 표시");
document.getElementById("progressContainer").style.display = "block"; // 진행 상태 막대 표시
// 메인 화면 캐릭터 이미지 숨김
console.log("[SYSTEM] 메인 화면 캐릭터 이미지 숨김");
document.querySelector(".partner-image-container").style.display = "none";
// 칠판 이미지 위치 조절
console.log("[SYSTEM] 칠판 이미지 위치 조절");
document.getElementById("chalkboardImage").style.top = "45%";
if (mode === "byDifficulty") {
// 난이도별 문제 수 지정
console.log("[SYSTEM] 난이도별 문제 수 지정");
selectedQuestions = [];
selectedDifficulties.forEach((difficulty) => {
if (questions[difficulty] && questions[difficulty].length > 0) {
selectedQuestions.push(
...shuffleArray(questions[difficulty]).slice(0, questionCount)
);
}
});
// 선택된 문제의 개수가 questionCount보다 적을 경우 처리
if (selectedQuestions.length < questionCount) {
console.log("[SYSTEM] 선택 된 문제 수가 지정된 수 보다 적음");
alert("문제의 수가 지정된 개수보다 적습니다.");
return;
}
} else if (mode === "totalRandom") {
// 선택된 난이도에서 총 문제를 무작위로 추출
console.log("[SYSTEM] 선택 된 난이도에서 총 문제 무작위로 추출");
let allQuestions = [];
selectedDifficulties.forEach((difficulty) => {
if (questions[difficulty] && questions[difficulty].length > 0) {
allQuestions.push(...questions[difficulty]);
}
});
// 문제가 없는 경우 처리
if (allQuestions.length === 0) {
console.log("[SYSTEM] 선택한 난이도 문제 없음");
alert("선택한 난이도에 해당하는 문제가 없습니다.");
return;
}
// 문제를 무작위로 섞고, 지정된 개수만큼 선택합니다.
console.log("[SYSTEM] 문제 무작위로 섞은 후 지정된 수 만큼 선택");
selectedQuestions = shuffleArray(allQuestions).slice(0, questionCount);
}
// 초기화
currentQuestionIndex = 0;
score = 0;
answersChosen = [];
// 문제 표시
displayQuestion();
}
// 문제 표시 함수
function displayQuestion() {
console.log("");
console.log("[SYSTEM] 문제 표시");
if (currentQuestionIndex >= selectedQuestions.length) {
showResult();
return;
}
const question = selectedQuestions[currentQuestionIndex];
const showPronunciation =
document.getElementById("showPronunciation").checked;
const customshowPronunciation = document.getElementById(
"customshowPronunciation"
).checked;
let questionText = question.question;
if (
(showPronunciation && question.pronunciation) ||
(customshowPronunciation && question.pronunciation)
) {
questionText = `<span class="questionPronunciation">(${question.pronunciation})</span><br>${questionText}`; // 발음 기호를 먼저 표시
console.log(`[SYSTEM] 발음 기호 표시: YES`);
} else {
questionText = `<br>${questionText}`; // 발음 기호를 먼저 표시
console.log(`[SYSTEM] 발음 기호 표시: NO`);
}
document.getElementById("questionText").innerHTML = questionText;
// 현재 문제의 정답을 포함한 선택지 생성
const allAnswers = [question.correct];
// 다른 문제에서 정답을 무작위로 선택
const allQuestions = Object.values(questions)
.flat()
.filter((q) => q.correct !== question.correct);
const randomAnswers = shuffleArray(allQuestions.map((q) => q.correct)).slice(
0,
3
);
allAnswers.push(...randomAnswers);
// 총 4개의 선택지 배열 생성
const shuffledAnswers = shuffleArray(allAnswers);
// 선택지 버튼 생성
const answersContainer = document.getElementById("answers");
answersContainer.innerHTML = "";
// 문제에서 보여진 답변 저장
displayedAnswers[currentQuestionIndex] = shuffledAnswers.slice(0, 4);
shuffledAnswers.forEach((answer) => {
const displayAnswer = answer.replace(/\\n/g, "<br>"); // \\n을 <br>로 대체
const button = document.createElement("button");
button.innerHTML = displayAnswer; // HTML을 사용하여 줄 바꿈 적용
button.classList.add("answer-button");
button.addEventListener("click", () => selectAnswer(answer)); // 원본 값을 사용
answersContainer.appendChild(button);
});
updateProgress(); // 진행 상태 업데이트
}
// 배열을 무작위로 섞는 함수 (피셔-예이츠 알고리즘)
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
// 사용자가 선택한 답변 처리 함수
function selectAnswer(selectedAnswer) {
const question = selectedQuestions[currentQuestionIndex];
console.log("[SYSTEM] 선택된 답변:", selectedAnswer);
if (selectedAnswer === question.correct) {
score += 1; // 문제당 1점
}
answersChosen[currentQuestionIndex] = selectedAnswer;
currentQuestionIndex++;
displayQuestion();
}
// 문제 푸는 중 문제 건너뛰기 버튼 처리 함수
function skipQuestion() {
console.log("[SYSTEM] 문제 푸는 중 '건너뛰기' 버튼 클릭");
answersChosen[currentQuestionIndex] = null;
currentQuestionIndex++;
displayQuestion();
}
// 문제 푸는 중 처음으로 돌아가기 버튼 클릭 시 확인 팝업 창 표시 함수
function showRestartConfirmation() {
console.log(
"[SYSTEM] 문제 푸는 중 처음으로 돌아가기 버튼 클릭 시 팝업 창 표시"
);
document.getElementById("quizContainer").style.display = "none";
const restartConfirmationContainer = document.getElementById(
"restartConfirmationContainer"
);
restartConfirmationContainer.style.display = "block";
restartConfirmationContainer.classList.add("show");
}
// 문제 푸는 중 처음으로 돌아가기 버튼 누른 후 확인 팝업 창에서 예/아니오 버튼 클릭 시 처리 함수
function confirmRestart(confirm) {
const restartConfirmationContainer = document.getElementById(
"restartConfirmationContainer"
);
if (confirm) {
console.log(
"[SYSTEM] 문제 푸는 중 처음으로 돌아가기 팝업 창에서 '예' 버튼 클릭"
);
restartConfirmationContainer.classList.remove("show");
setTimeout(() => {
restartConfirmationContainer.style.display = "none";
restartQuiz();
}, 120);
} else {
console.log(
"[SYSTEM] 문제 푸는 중 처음으로 돌아가기 팝업 창에서 '아니요' 버튼 클릭"
);
restartConfirmationContainer.classList.remove("show");
setTimeout(() => {
restartConfirmationContainer.style.display = "none";
document.getElementById("quizContainer").style.display = "grid";
}, 120);
}
}
// 진행 상태 업데이트 함수
function updateProgress() {
const progressBar = document.getElementById("progressBar");
const progressText = document.getElementById("progressText");
console.log("[SYSTEM] 진행 상태 막대 업데이트");
// 현재 진행 상황을 백분율로 계산
const progressPercentage =
((currentQuestionIndex + 1) / selectedQuestions.length) * 100;
// 진행 상태 막대 업데이트
progressBar.style.width = `${progressPercentage}%`;
progressText.innerText = `문제: ${currentQuestionIndex + 1}/${
selectedQuestions.length
}`;
}
// 결과 표시 함수
function showResult() {
const maxScore = selectedQuestions.length; // 총 문제 수를 최대 점수로 설정
const percentageScore = (score / maxScore) * 100; // 점수를 백분율로 변환
const formattedScore = percentageScore.toFixed(2); // 소수 둘째 자리까지 포맷팅
console.log("");
console.log("[SYSTEM] 결과 불러오는 중...");
document.querySelector("#loading-screen p").innerText =
"결과를 불러오는 중...";
console.log("[SYSTEM] 로딩 화면 표시 중...");
showLoadingScreen(); // 로딩 화면 표시
// 메인 화면 캐릭터 이미지 표시
console.log("[SYSTEM] 메인 화면 캐릭터 이미지 표시");
document.querySelector(".partner-image-container").style.display = "block";
// 칠판 이미지 위치 조절
console.log("[SYSTEM] 칠판 이미지 위치 조절");
document.getElementById("chalkboardImage").style.top = "50%";
// 로딩 화면 표시된 후 대기 시간 설정
setTimeout(() => {
console.log("[SYSTEM] 로딩 화면 숨김"); // 로딩 화면 숨김 로그
let resultText = "";
let resultImageURL = ""; // 이미지 URL 변수를 추가
if (percentageScore === 0) {
console.log("[SYSTEM] 점수 0점");
resultImageURL = "./asm_partner_01_base_face_06.png";
} else if (percentageScore < 10) {
console.log("[SYSTEM] 점수 0점 이상, 10점 미만");
resultImageURL = "./asm_partner_01_base_face_06.png";
} else if (percentageScore < 20) {
console.log("[SYSTEM] 점수 10점 이상, 20점 미만");
resultImageURL = "./asm_partner_01_base_face_03.png";
} else if (percentageScore < 30) {
console.log("[SYSTEM] 점수 20점 이상, 30점 미만");
resultImageURL = "./asm_partner_01_base_face_09.png";
} else if (percentageScore < 40) {
console.log("[SYSTEM] 점수 30점 이상, 40점 미만");
resultImageURL = "./asm_partner_01_base_face_10.png";
} else if (percentageScore < 50) {
console.log("[SYSTEM] 점수 40점 이상, 50점 미만");
resultImageURL = "./asm_partner_01_base_face_07.png";
} else if (percentageScore < 60) {
console.log("[SYSTEM] 점수 50점 이상, 60점 미만");
resultImageURL = "./asm_partner_01_base_face_01.png";
} else if (percentageScore < 70) {
console.log("[SYSTEM] 점수 60점 이상, 70점 미만");
resultImageURL = "./asm_partner_01_base_face_08.png";
} else if (percentageScore < 80) {
console.log("[SYSTEM] 점수 70점 이상, 80점 미만");
resultImageURL = "./asm_partner_01_base_face_02.png";
} else if (percentageScore < 90) {
console.log("[SYSTEM] 점수 80점 이상, 90점 미만");
resultImageURL = "./asm_partner_01_base_face_05.png";
} else if (percentageScore <= 100) {
console.log("[SYSTEM] 점수 90점 이상, 100점 이하");
InitializeConfetti(); // confetti.js 함수 호출
console.log("[SYSTEM] Confetti.js 실행");
resultImageURL = "./asm_partner_01_base_face_04.png";
} else {
console.log("[SYSTEM] 올바르지 않은 접근으로 결과 표시 화면 접근");
resultText =
"(오류) 올바르지 않은 접근입니다.<br><br>메인 화면으로 이동하십시오.";
}
document.getElementById(
"resultText"
).innerHTML = `총 점수: ${formattedScore}점<br><br>${resultText}`;
// 상장 다운로드 버튼 표시
console.log(
"[SYSTEM] 점수 90점 이상이면서 선택한 난이도의 전체 문제수 80% 이상일 때 상장 다운로드 버튼 표시"
);
console.log(
"[SYSTEM] (* 전체 문제 수의 80% 계산 시 소수점은 반내림하여 정수로 처리))"
);
console.log(`[SYSTEM] 점수: ${percentageScore}`);
console.log(`[SYSTEM] 문제 수: ${questionCount}`);
console.log(
`[SYSTEM] 필요 최소 문제 수: ${Math.floor(totalQuestions * 0.8)}`
);
if (
percentageScore >= 90 &&
questionCount >= Math.floor(totalQuestions * 0.8)
) {
console.log("[SYSTEM] 조건 충족으로 상장 다운로드 버튼 표시");
// 상장 다운로드 버튼 표시
document.getElementById("downloadCertificateButton").style.display =
"block";
document.getElementById("downloadCertificateButton").onclick =
generateCertificate;
} else {
console.log("[SYSTEM] 조건 불충족으로 상장 다운로드 버튼 숨김");
document.getElementById("downloadCertificateButton").style.display =
"none";
}
// 이미지를 로드하고 나서 로딩 화면을 숨김
const img = new Image();
img.src = resultImageURL; // 점수에 맞는 이미지 로딩
img.onload = () => {
document.querySelector(".partner-image").src = resultImageURL; // 이미지 변경
hideLoadingScreen(); // 로딩 화면 숨김
console.log("[SYSTEM] 로딩 화면 숨김"); // 로딩 화면 숨김 로그
document.getElementById("quizContainer").style.display = "none";
document.getElementById("resultContainer").style.display = "flex";
console.log("[SYSTEM] 진행 상태 막대 숨김");
document.getElementById("progressContainer").style.display = "none"; // 진행 상태 막대 숨기기
};
}, 500); // 로딩 화면이 표시된 후 0.5초 대기
}
// 상장 다운로드 버튼 클릭 이벤트
async function generateCertificate() {
console.log("");
console.log("[SYSTEM] 상장 다운로드 버튼 클릭");
const canvas = document.getElementById("Certificate_Canvas");
const ctx = canvas.getContext("2d");
const image = document.getElementById("Certificate_Image");
// 월 이름 배열
const months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
const name = prompt("상장에 추가할 이름을 입력하세요:");
if (name) {
await document.fonts.ready; // 모든 폰트 로딩 완료 대기
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0);
// 난이도
const filteredDifficulties = selectedDifficulties.filter(
(difficulty) =>