-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
342 lines (308 loc) · 14.1 KB
/
script.js
File metadata and controls
342 lines (308 loc) · 14.1 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
import { gameState } from './data.js';
/* ─── CONFIG ──────────────────────────────────────────────────────────────── */
const CONFIG = Object.freeze({
defaultCategory: 'animales',
pairsPerGame: 18,
flipDelay: 800,
storage: {
history: 'mem_history',
decks: 'mem_decks',
tutorial: 'mem_tut'
},
categoryColors: {
animales: '#f14343',
vegetales: '#22ac0a',
comida: '#ff8800',
eventos: '#ff00ff',
colegio: '#2196f3'
}
});
/* ─── STATE ───────────────────────────────────────────────────────────────── */
const State = {
flippedCards: [], moves: 0, timer: 0, interval: null, lock: false, matches: 0,
currentCategory: CONFIG.defaultCategory, totalPairs: 0,
history: {},
decks: {},
tutorialSeen: false, isMuted: false,
voices: { english: null, spanish: null }
};
/* ─── DOM ────────────────────────────────────────────────────────────────── */
const dom = {
board: document.getElementById('game-board'),
catNav: document.getElementById('cat-nav'),
scorePanel: document.getElementById('score-panel'),
progressBar: document.getElementById('progress-bar'),
timerDisplay: document.getElementById('timer'),
movesDisplay: document.getElementById('moves'),
pairsCount: document.getElementById('pairs-count'),
modal: document.getElementById('modal-overlay'),
modalBody: document.getElementById('modal-content'),
sideMenu: document.getElementById('side-menu'),
menuToggle: document.getElementById('menu-toggle'),
menuClose: document.getElementById('menu-close'),
menuOverlay: document.getElementById('menu-overlay'),
resetAll: document.getElementById('reset-all-btn'),
resetPanel: document.getElementById('reset-panel-btn'), // Asegúrate de que este ID existe en tu HTML
helpBtn: document.getElementById('help-btn'),
soundToggle: document.getElementById('sound-toggle')
};
/* ─── BOOTSTRAP ──────────────────────────────────────────────────────────── */
function bootstrap() {
const savedHistory = localStorage.getItem(CONFIG.storage.history);
State.history = savedHistory ? JSON.parse(savedHistory) : {};
State.decks = JSON.parse(localStorage.getItem(CONFIG.storage.decks) || '{}');
State.tutorialSeen = localStorage.getItem(CONFIG.storage.tutorial) === 'true';
bindEvents();
initVoices();
init(CONFIG.defaultCategory);
}
/* ─── LÓGICA DE VOZ ──────────────────────────────────────────────────────── */
function initVoices() {
const load = () => {
const v = window.speechSynthesis.getVoices();
if (v.length > 0) {
State.voices.english = v.find(x => x.lang.startsWith('en'));
State.voices.spanish = v.find(x => x.lang.startsWith('es'));
}
};
load();
if (window.speechSynthesis.onvoiceschanged !== undefined) window.speechSynthesis.onvoiceschanged = load;
}
function speak(t, lang) {
if (State.isMuted || !window.speechSynthesis) return;
window.speechSynthesis.cancel();
const ut = new SpeechSynthesisUtterance(t);
const v = lang === 'english' ? State.voices.english : State.voices.spanish;
if (v) ut.voice = v;
ut.lang = lang === 'english' ? 'en-US' : 'es-ES';
window.speechSynthesis.speak(ut);
}
/* ─── CORE JUEGO ─────────────────────────────────────────────────────────── */
function init(category) {
State.currentCategory = category;
State.flippedCards = []; State.lock = false; State.matches = 0;
State.timer = 0; State.moves = 0;
clearInterval(State.interval); State.interval = null;
dom.board.className = `board-grid ${category}`;
closeSideMenu();
updateMenuData();
renderStats();
if (State.history[category]) loadCompleted(category);
else loadNew(category);
}
function loadNew(cat) {
let deck = State.decks[cat];
if (!deck) {
const pool = [...gameState[cat]].sort(() => Math.random() - 0.5).slice(0, CONFIG.pairsPerGame);
deck = [];
pool.forEach(item => {
deck.push({ id: item.clave, text: item.languages.english, img: item.icono, type: 'english' });
deck.push({ id: item.clave, text: item.languages.spanish, img: item.icono, type: 'spanish' });
});
deck.sort(() => Math.random() - 0.5);
State.decks[cat] = deck;
localStorage.setItem(CONFIG.storage.decks, JSON.stringify(State.decks));
}
State.totalPairs = deck.length / 2;
renderBoard(deck, false);
setProgress(0, 0, State.totalPairs);
}
function loadCompleted(cat) {
const d = State.history[cat];
State.timer = d.timer; State.moves = d.moves; State.totalPairs = d.totalPairs; State.matches = d.totalPairs;
renderStats();
setProgress(100, d.totalPairs, d.totalPairs);
renderBoard(State.decks[cat], true);
}
function renderBoard(deck, isDone) {
dom.board.innerHTML = '';
deck.forEach(data => {
const card = el('div', null, `card${isDone ? ' flipped matched' : ''}`);
const inner = el('div', null, 'card-inner');
const front = el('div', null, `card-face card-front ${data.type}`);
const back = el('div', null, 'card-face card-back');
const imgWrapper = el('div', null, 'img-wrapper');
const img = el('img'); img.src = data.img; img.className = 'icon-img';
imgWrapper.appendChild(img);
front.append(imgWrapper, el('div', data.text, 'word-text'));
inner.append(back, front);
card.appendChild(inner);
card.onclick = () => handleCardClick(card, data);
dom.board.appendChild(card);
});
}
function handleCardClick(card, data) {
if (card.classList.contains('matched') || card.classList.contains('flipped') || State.lock) return;
if (!State.interval) startTimer();
speak(data.text, data.type);
card.classList.add('flipped');
State.flippedCards.push({ card, id: data.id });
if (State.flippedCards.length === 2) {
State.lock = true; State.moves++; renderStats(); checkMatch();
}
}
function checkMatch() {
const [c1, c2] = State.flippedCards;
if (c1.id === c2.id) {
[c1.card, c2.card].forEach(c => c.classList.add('matched'));
State.matches++; State.flippedCards = []; State.lock = false;
setProgress((State.matches / State.totalPairs) * 100, State.matches, State.totalPairs);
if (State.matches === State.totalPairs) handleWin();
} else {
setTimeout(() => {
[c1.card, c2.card].forEach(c => c.classList.remove('flipped'));
State.flippedCards = []; State.lock = false;
}, CONFIG.flipDelay);
}
}
/* ─── VICTORIA Y MODALES ────────────────────────────────────────────────── */
function handleWin() {
clearInterval(State.interval);
const finalTimeStr = dom.timerDisplay.textContent;
State.history[State.currentCategory] = {
moves: State.moves,
timer: State.timer,
totalPairs: State.totalPairs,
timeStr: finalTimeStr
};
localStorage.setItem(CONFIG.storage.history, JSON.stringify(State.history));
if (typeof confetti === 'function') {
confetti({ particleCount: 200, spread: 90, origin: { y: 0.7 }, zIndex: 10000 });
}
updateMenuData();
showPopup('victory');
}
function showPopup(type) {
dom.modalBody.innerHTML = '';
if (type === 'victory') {
const imgCont = el('div', null, 'modal-image-container');
const img = el('img'); img.src = "./assets/img/jirafa.png";
imgCont.appendChild(img);
const statsRow = el('div', null, 'modal-stats-row');
statsRow.append(createStatItem('TIEMPO', dom.timerDisplay.textContent), createStatItem('PASOS', State.moves.toString()));
const btn = el('button', 'SIGUIENTE NIVEL', 'btn-action primary');
btn.onclick = () => { dom.modal.classList.remove('active'); openSideMenu(); };
dom.modalBody.append(imgCont, el('h2', '¡GENIAL!', 'modal-title'), el('p', 'Nivel completado', 'modal-subtitle'), statsRow, btn);
} else {
const btn = el('button', '¡VAMOS!', 'btn-action secondary');
btn.onclick = () => dom.modal.classList.remove('active');
dom.modalBody.append(el('h4', 'TUTORIAL', 'modal-title-small'), el('p', 'Une las parejas de inglés y español.', 'modal-text'), btn);
}
dom.modal.classList.add('active');
}
// NUEVA FUNCIÓN PARA ALERTAS PERSONALIZADAS
function showConfirmModal(title, message, onConfirm) {
dom.modalBody.innerHTML = '';
const btnContainer = el('div', null, 'modal-btn-group');
const confirmBtn = el('button', 'SÍ, BORRAR', 'btn-action primary danger');
const cancelBtn = el('button', 'CANCELAR', 'btn-action secondary');
cancelBtn.onclick = () => dom.modal.classList.remove('active');
confirmBtn.onclick = () => {
onConfirm();
dom.modal.classList.remove('active');
};
btnContainer.append(confirmBtn, cancelBtn);
dom.modalBody.append(el('h4', title, 'modal-title-small'), el('p', message, 'modal-text'), btnContainer);
dom.modal.classList.add('active');
}
function createStatItem(label, value) {
const item = el('div', null, 'modal-stat-item');
item.append(el('span', label, 'stat-label'), el('span', value, 'stat-value'));
return item;
}
/* ─── UI HELPERS ────────────────────────────────────────────────────────── */
function el(tag, text, className) {
const e = document.createElement(tag);
if (text) e.textContent = text;
if (className) e.className = className;
return e;
}
function setProgress(pct, m, t) {
dom.progressBar.style.width = `${pct}%`;
dom.pairsCount.textContent = `${m}/${t}`;
}
function startTimer() { State.interval = setInterval(() => { State.timer++; renderStats(); }, 1000); }
function renderStats() {
const m = Math.floor(State.timer / 60).toString().padStart(2, '0');
const s = (State.timer % 60).toString().padStart(2, '0');
dom.timerDisplay.textContent = `${m}:${s}`;
dom.movesDisplay.textContent = State.moves;
}
function updateRecordsList() {
dom.scorePanel.innerHTML = '';
const records = Object.entries(State.history);
if (records.length === 0) {
dom.scorePanel.innerHTML = '<p class="empty-msg">Aún no tienes récords</p>';
return;
}
records.forEach(([cat, data]) => {
let displayTime = data.timeStr;
if (!displayTime && data.timer !== undefined) {
const m = Math.floor(data.timer / 60).toString().padStart(2, '0');
const s = (data.timer % 60).toString().padStart(2, '0');
displayTime = `${m}:${s}`;
}
const row = el('div', null, 'score-row');
row.innerHTML = `<span class="score-cat">${cat}</span><span class="score-data">⏱ ${displayTime || '--:--'} | 👟 ${data.moves || 0}</span>`;
dom.scorePanel.appendChild(row);
});
}
function updateMenuData() {
dom.catNav.innerHTML = '';
gameState.categoriasNames.forEach(name => {
const record = State.history[name];
const btn = el('button', name.toUpperCase() + (record ? ' ✓' : ''), `btn-cat${record ? ' completed' : ''}`);
btn.style.backgroundColor = CONFIG.categoryColors[name];
btn.onclick = () => init(name);
dom.catNav.appendChild(btn);
});
updateRecordsList();
}
function openSideMenu() { dom.sideMenu.classList.add('active'); dom.menuOverlay.classList.add('active'); }
function closeSideMenu() { dom.sideMenu.classList.remove('active'); dom.menuOverlay.classList.remove('active'); }
/* ─── EVENTOS ────────────────────────────────────────────────────────────── */
function bindEvents() {
dom.menuToggle.onclick = openSideMenu;
dom.menuClose.onclick = closeSideMenu;
dom.menuOverlay.onclick = closeSideMenu;
dom.helpBtn.onclick = () => showPopup('tutorial');
dom.soundToggle.onclick = () => {
State.isMuted = !State.isMuted;
dom.soundToggle.textContent = State.isMuted ? '🔇' : '🔊';
};
// BORRAR TODO (Con modal nuevo)
dom.resetAll.onclick = () => {
showConfirmModal(
'¿BORRAR TODO?',
'Se eliminarán todos tus récords y progresos permanentemente.',
() => {
localStorage.clear();
location.reload();
}
);
};
// BORRAR PANEL ACTUAL (Con modal nuevo)
if (dom.resetPanel) {
dom.resetPanel.onclick = () => {
showConfirmModal(
'¿REINICIAR PANEL?',
`Se borrará el récord de "${State.currentCategory}".`,
() => {
delete State.history[State.currentCategory];
delete State.decks[State.currentCategory];
localStorage.setItem(CONFIG.storage.history, JSON.stringify(State.history));
localStorage.setItem(CONFIG.storage.decks, JSON.stringify(State.decks));
init(State.currentCategory);
}
);
};
}
document.querySelectorAll('.accordion-header').forEach(h => {
h.onclick = () => {
h.classList.toggle('active');
const target = document.getElementById(h.dataset.target);
target.classList.toggle('open');
};
});
}
bootstrap();