-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
375 lines (320 loc) · 10.4 KB
/
app.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
// 필요한 변수들 선언
let score = 0;
let timeLeft = 30; // 30초 제한시간
let currentRecipe = null;
let selectedCards = [];
let isPlaying = false;
let timerInterval; // 타이머 인터벌 저장용 변수 추가
// recipes.json 불러오기
async function loadRecipes() {
try {
const response = await fetch("recipes.json");
const recipes = await response.json();
// console.log(recipes.recipes[1].name);
return recipes.recipes;
} catch (error) {
console.error("레시피를 불러오는데 실패했습니다:", error);
return [];
}
}
// 랜덤 레시피 선택
function getRandomRecipe(recipes) {
const randomIndex = Math.floor(Math.random() * recipes.length);
return recipes[randomIndex];
}
// 게임 초기화
async function initGame() {
const popup = document.getElementById("resultPopup");
popup.classList.remove("show");
selectedCards = [];
// 지우기 버튼 보이기
const backspaceBtn = document.getElementById("backspaceBtn");
if (backspaceBtn) backspaceBtn.style.display = "block";
loadRecipes().then((recipes) => {
currentRecipe = getRandomRecipe(recipes);
setupGameCards(currentRecipe);
startTimer();
});
}
// 배열을 랜덤하게 섞는 함수
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 setupGameCards(recipe) {
const ingredientContainer = document.getElementById(
"ingredient-card-container"
);
const quantityContainer = document.getElementById("quantity-card-container");
const actionContainer = document.getElementById("action-card-container");
const recipeTrack = document.getElementById("recipe-track");
// 컨테이너 초기화
ingredientContainer.innerHTML = "";
quantityContainer.innerHTML = "";
actionContainer.innerHTML = "";
recipeTrack.innerHTML = "";
// 뒤로가기 버튼 이벤트 리스너 설정
const backspaceBtn = document.getElementById("backspaceBtn");
backspaceBtn.onclick = removeLastCard;
backspaceBtn.style.display = "block";
// 레시피에서 각 타입별로 고유한 값만 추출
let ingredients = [
...new Set(
recipe.recipe
.filter((item) => item.type === "ingredient")
.map((item) => item.value)
),
];
let quantities = [
...new Set(
recipe.recipe
.filter((item) => item.type === "quantity")
.map((item) => item.value)
),
];
let actions = [
...new Set(
recipe.recipe
.filter((item) => item.type === "action")
.map((item) => item.value)
),
];
// 각 배열을 랜덤하게 섞기
ingredients = shuffleArray(ingredients);
quantities = shuffleArray(quantities);
actions = shuffleArray(actions);
// 섞인 카드들을 컨테이너에 추가
ingredients.forEach((ingredient) => {
const card = createCard("ingredient", ingredient);
ingredientContainer.appendChild(card);
});
quantities.forEach((quantity) => {
const card = createCard("quantity", quantity);
quantityContainer.appendChild(card);
});
actions.forEach((action) => {
const card = createCard("action", action);
actionContainer.appendChild(card);
});
// 레시피 이름 표시
document.getElementById("recipe-name").textContent = recipe.name;
// 다음 문제 버튼 숨기기
document.getElementById("nextButton").style.display = "none";
// 레시피 트랙 초기화
document.getElementById("recipe-track").innerHTML = "";
selectedCards = [];
}
// 카드 생성
function createCard(type, value) {
const card = document.createElement("div");
card.className = `${type}-card`;
card.textContent = value;
card.dataset.type = type;
card.dataset.value = value;
card.addEventListener("click", () => handleCardClick(card));
return card;
}
// 카드 클릭 처리
function handleCardClick(card) {
const recipeTrack = document.getElementById("recipe-track");
const newCard = card.cloneNode(true);
recipeTrack.appendChild(newCard);
selectedCards.push({
type: card.dataset.type,
value: card.dataset.value,
});
// 카드 추가 후에 실행할 코드
recipeTrack.scrollLeft = recipeTrack.scrollWidth;
// 선택된 카드 수가 현재 레시피의 스텝 수와 같아지면 정답 체크
if (selectedCards.length === currentRecipe.recipe.length) {
checkAnswer();
}
}
// 점수 업데이트 함수 수정
function updateScore(newScore) {
const scoreElement = document.getElementById("score-container");
const oldScore = score;
score = newScore;
// 점수 증가 애니메이션
if (newScore > oldScore) {
scoreElement.style.transform = "scale(1.2)";
scoreElement.style.color = "#4CAF50";
setTimeout(() => {
scoreElement.style.transform = "scale(1)";
scoreElement.style.color = "";
}, 500);
}
scoreElement.textContent = `Score: ${score}`;
}
// 팝업 표시 함수 수정
function showResultPopup(isCorrect) {
const popup = document.getElementById("resultPopup");
const resultText = popup.querySelector(".result-text");
const scoreChange = popup.querySelector(".score-change");
const nextButton = document.getElementById("nextButton");
const backspaceBtn = document.getElementById("backspaceBtn");
clearInterval(timerInterval);
// 지우기 버튼 숨기기
if (backspaceBtn) backspaceBtn.style.display = "none";
if (isCorrect) {
resultText.textContent = "정답입니다!";
resultText.className = "result-text correct";
scoreChange.textContent = "+10점";
popup.classList.add("show");
setTimeout(() => {
popup.classList.remove("show");
initGame();
}, 1500);
} else {
resultText.textContent = "틀렸습니다!";
resultText.className = "result-text incorrect";
scoreChange.textContent = "";
popup.classList.add("show");
setTimeout(() => {
popup.classList.remove("show");
}, 1000);
// 다음 문제 버튼 표시
nextButton.style.display = "block";
}
}
// 정답 체크 함수 수정
function checkAnswer() {
const isCorrect = selectedCards.every(
(card, index) =>
card.type === currentRecipe.recipe[index].type &&
card.value === currentRecipe.recipe[index].value
);
if (isCorrect) {
updateScore(score + 10);
showResultPopup(true);
} else {
showResultPopup(false);
showCorrectAnswer();
}
}
// 다음 버튼 이벤트 리스너 수정
document.getElementById("nextButton").addEventListener("click", () => {
initGame();
});
// 정답 보여주기 함수 수정
function showCorrectAnswer() {
const recipeTrack = document.getElementById("recipe-track");
recipeTrack.innerHTML = "";
// 정답 컨테이너 생성
const answerContainer = document.createElement("div");
answerContainer.className = "correct-answer-container";
// 정답 문자열 생성
let answerText = "정답: ";
currentRecipe.recipe.forEach((step, index) => {
if (step.type === "ingredient") {
answerText += step.value;
} else if (step.type === "quantity") {
answerText += ` ${step.value}`;
} else if (step.type === "action") {
answerText += ` (${step.value})`;
}
// 마지막 항목이 아니면 쉼표 추가
if (index < currentRecipe.recipe.length - 1) {
answerText += " → ";
}
});
answerContainer.textContent = answerText;
recipeTrack.appendChild(answerContainer);
}
// 타이머 함수 수정
function startTimer() {
if (timerInterval) {
clearInterval(timerInterval);
}
timeLeft = 30;
updateTimerLine();
timerInterval = setInterval(() => {
timeLeft--;
updateTimerLine();
if (timeLeft <= 0) {
clearInterval(timerInterval);
showResultPopup(false);
showCorrectAnswer();
document.getElementById("nextButton").style.display = "block";
}
}, 1000);
}
// 타이머 라인 업데이트 함수 추가
function updateTimerLine() {
const timerLine = document.querySelector(".timer-line");
const percentage = (timeLeft / 30) * 100; // 30초 기준으로 계산
timerLine.style.width = `${percentage}%`;
}
// 시작 화면 관련 코드 추가
document.getElementById("startButton").addEventListener("click", function () {
document.getElementById("startScreen").classList.add("hidden");
playBackgroundMusic();
initGame();
});
// playBackgroundMusic 함수 수정
function playBackgroundMusic() {
bgMusic.volume = 0.3;
// 음악이 끝나면 게임 종료
bgMusic.addEventListener("ended", endGame);
// 음악 컨트롤 버튼 추가
const musicControl = document.createElement("button");
musicControl.innerHTML = "🔊";
musicControl.style.position = "fixed";
musicControl.style.top = "10px";
musicControl.style.right = "10px";
musicControl.style.zIndex = "1000";
musicControl.style.padding = "5px 10px";
musicControl.style.fontSize = "20px";
musicControl.style.cursor = "pointer";
musicControl.addEventListener("click", function () {
if (bgMusic.paused) {
bgMusic.play();
this.innerHTML = "🔊";
} else {
bgMusic.pause();
this.innerHTML = "🔈";
}
});
document.body.appendChild(musicControl);
bgMusic.play();
}
// 게임 종료 함수 추가
function endGame() {
clearInterval(timerInterval);
// 게임 종료 팝업 생성
const endGamePopup = document.createElement("div");
endGamePopup.className = "end-game-popup";
endGamePopup.innerHTML = `
<div class="end-game-content">
<h2>게임 종료!</h2>
<p>최종 점수: ${score}점</p>
<button id="restartButton">다시 하기</button>
</div>
`;
document.body.appendChild(endGamePopup);
// 다시 하기 버튼 이벤트 리스너
document.getElementById("restartButton").addEventListener("click", () => {
score = 0;
updateScore(0);
endGamePopup.remove();
document.getElementById("startScreen").classList.remove("hidden");
bgMusic.currentTime = 0;
});
}
// 마지막 카드 제거 함수 추가
function removeLastCard() {
const recipeTrack = document.getElementById("recipe-track");
if (selectedCards.length > 0) {
selectedCards.pop(); // 배열에서 마지막 카드 제거
recipeTrack.removeChild(recipeTrack.lastChild); // DOM에서 마지막 카드 제거
}
}
// 페이지 로드 시 초기 설정
document.addEventListener("DOMContentLoaded", function () {
const backspaceBtn = document.getElementById("backspaceBtn");
backspaceBtn.style.display = "none"; // 초기에는 버튼 숨기기
});