-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
869 lines (793 loc) · 30.9 KB
/
index.html
File metadata and controls
869 lines (793 loc) · 30.9 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
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
<!DOCTYPE html>
<html lang="pt">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>MazeRush</title>
<link rel="icon" href="favicon.ico" type="C:\Users\bruno\source\repos\MazeRush-Game\favicon.ico" />
<link rel="stylesheet" href="style.css" />
<link
href="https://fonts.googleapis.com/css2?family=Orbitron:wght@500;700&display=swap"
rel="stylesheet"
/>
</head>
<body>
<!-- === CONTAINER DO MENU PRINCIPAL === -->
<div id="main-page" class="mazerush-menu">
<h1 class="mazerush-title">MazeRush</h1>
<div class="current-profile">
<span id="profile-name-main">Jogador</span>
</div>
<div class="mazerush-grid" id="main-menu">
<a href="#" class="mazerush-card mazerush-play" onclick="openLevels()">
<svg viewBox="0 0 24 24"><path d="M8 5v14l11-7z" /></svg>
<span>Jogar</span>
</a>
<a href="#" class="mazerush-card" onclick="openProfileMenu()">
<svg viewBox="0 0 24 24">
<path
d="M12 12c2.7 0 5-2.3 5-5s-2.3-5-5-5-5 2.3-5 5 2.3 5 5 5zm0 2c-3.3 0-10 1.7-10 5v3h20v-3c0-3.3-6.7-5-10-5z"
/>
</svg>
<span>Perfil</span>
</a>
<a href="#" class="mazerush-card" onclick="openSettingsMenu()">
<svg viewBox="0 0 24 24">
<path
d="M19.14 12.94c.04-.3.07-.61.07-.94s-.03-.64-.07-.94l2.03-1.58a.5.5 0 0 0 .11-.64l-1.91-3.32a.5.5 0 0 0-.6-.22l-2.39.96a7.007 7.007 0 0 0-1.62-.94L14 2.5a.5.5 0 0 0-.5-.5h-3a.5.5 0 0 0-.5.5l-.38 2.56c-.6.23-1.15.54-1.62.94l-2.39-.96a.5.5 0 0 0-.6.22l-1.91 3.32a.5.5 0 0 0 .11.64l2.03 1.58c-.04.3-.07.61-.07.94s.03.64.07.94L2.86 14.52a.5.5 0 0 0-.11.64l1.91 3.32c.14.24.44.34.7.22l2.39-.96c.47.4 1.02.72 1.62.94l.38 2.56a.5.5 0 0 0 .5.5h3c.25 0 .46-.18.5-.42l.38-2.56c.6-.23 1.15-.54 1.62-.94l2.39.96c.26.1.56 0 .7-.22l1.91-3.32a.5.5 0 0 0-.11-.64l-2.03-1.58zM12 15.5A3.5 3.5 0 1 1 15.5 12 3.5 3.5 0 0 1 12 15.5z"
/>
</svg>
<span>Definições</span>
</a>
<a href="#" class="mazerush-card" onclick="openCustomizeMenu()">
<svg viewBox="0 0 24 24">
<path d="M4 17h16v2H4v-2zm0-5h16v2H4v-2zm0-5h16v2H4V7z" />
</svg>
<span>Personalizar</span>
</a>
</div>
<div class="mazerush-footer">MazeRush version 1.0</div>
</div>
<!-- === SUBMENU PERFIS === -->
<div id="profile-list" class="profile-panel hidden">
<h2 class="profile-heading">Perfis</h2>
<div id="profiles-container"></div>
<div
class="profile-buttons"
style="justify-content: space-between; margin-bottom: 1rem"
>
<button id="btn-import-progress">Importar progresso</button>
<button onclick="closeProfileMenu()">← Voltar</button>
</div>
</div>
<!-- === POPUP EXPORT TOKEN === -->
<div id="token-export" class="profile-panel hidden">
<h2 class="profile-heading">Token de Exportação</h2>
<textarea
id="export-token-text"
readonly
style="
width: 100%;
height: 6em;
background: var(--verde-escuro);
color: var(--quase-branco);
border: none;
border-radius: 8px;
padding: 8px;
font-family: monospace;
"
></textarea>
<div class="profile-buttons">
<button onclick="closeTokenExport()">← Voltar</button>
<button onclick="copyExportToken()">Copiar</button>
</div>
</div>
<!-- === POPUP IMPORT TOKEN === -->
<div id="token-import" class="profile-panel hidden">
<h2 class="profile-heading">Importar via Token</h2>
<textarea
id="import-token-text"
placeholder="Cole aqui o token…"
style="
width: 100%;
height: 6em;
background: var(--verde-escuro);
color: var(--quase-branco);
border: none;
border-radius: 8px;
padding: 8px;
font-family: monospace;
"
></textarea>
<div class="profile-buttons">
<button onclick="closeTokenImport()">← Voltar</button>
<button onclick="confirmImportToken()">Importar</button>
</div>
</div>
<!-- === POPUP EDIÇÃO PERFIL === -->
<div id="profile-popup" class="profile-panel hidden">
<div
style="
display: flex;
justify-content: space-between;
align-items: center;
"
>
<h2 class="profile-heading" style="margin-bottom: 0">Nome</h2>
<button
id="delete-profile"
onclick="deleteProfile()"
title="Eliminar Perfil"
style="
background: none;
border: none;
color: var(--quase-branco);
font-size: 1.4rem;
cursor: pointer;
"
>
🗑️
</button>
</div>
<div style="display: flex; justify-content: center; margin: 12px 0">
<input type="text" id="nickname" maxlength="12" value="Jogador" />
</div>
<p
style="
font-size: 0.9rem;
margin: 10px 0 20px;
color: var(--quase-branco);
opacity: 0.8;
"
>
Escolha um nome para a tabela de classificação.
</p>
<div class="profile-buttons" style="justify-content: center; gap: 1rem">
<button id="btn-export">Exportar progresso</button>
<button id="confirm-profile" onclick="confirmEdit()">Ok</button>
</div>
</div>
<!-- === SUBMENU: DEFINIÇÕES === -->
<div id="settings-menu" class="profile-panel hidden">
<h2 class="profile-heading">Definições</h2>
<div class="setting-item">
<label class="toggle-label"
><input type="checkbox" id="toggle-sound" /><span
class="toggle-slider"
></span
></label>
<span>Som</span>
</div>
<input type="range" id="volume-sound" min="0" max="100" />
<div class="setting-item">
<label class="toggle-label"
><input type="checkbox" id="toggle-music" /><span
class="toggle-slider"
></span
></label>
<span>Música</span>
</div>
<input type="range" id="volume-music" min="0" max="100" />
<div class="profile-buttons" style="justify-content: center">
<button onclick="closeSettingsMenu()">← Voltar</button>
</div>
</div>
<!-- === SUBMENU: PERSONALIZAR === -->
<div id="customize-page" class="hidden">
<header class="levels-header">
<button onclick="closeCustomizeMenu()" class="back-button">← Voltar</button>
<h1 class="levels-title">
MazeRush <span style="opacity:0.6">— Personalizar</span>
</h1>
</header>
<div id="customize-container"></div>
<div id="color-ui">
<div class="picker">
<label for="color-primary">Primário</label>
<input type="color" id="color-primary" value="#603441" />
</div>
<div class="picker">
<label for="color-secondary">Secundário</label>
<input type="color" id="color-secondary" value="#ffffff" />
</div>
<div class="picker">
<label for="color-structure">Estrutura</label>
<input type="color" id="color-structure" value="#131313" />
</div>
<div class="picker">
<label for="color-wheels">Aros</label>
<input type="color" id="color-wheels" value="#666666" />
</div>
</div>
</div>
<!-- === SUBMENU: NÍVEIS === -->
<div id="levels-page" class="hidden">
<header class="levels-header">
<button onclick="closeLevels()" class="back-button">Voltar</button>
<h1 class="levels-title">
MazeRush <span style="opacity: 0.6">— Níveis</span>
</h1>
<button id="reset-btn" class="reset-button">Reiniciar</button>
</header>
<main class="categories">
<div class="section-heading">
<h2>Campanha</h2>
<div class="section-line"></div>
</div>
<div id="levels-container" class="levels-grid"></div>
</main>
</div>
<!-- === SUBMENU DE DETALHES DO NÍVEL (full-screen) === -->
<aside id="level-detail" class="hidden">
<div class="detail-content">
<button class="detail-close" onclick="closeLevelDetail()">×</button>
<div class="detail-body">
<!-- coluna 1: leaderboard -->
<section class="detail-leaderboard">
<h3>Tabela de Classificação</h3>
<div class="table-wrap">
<table id="detail-table">
<thead>
<tr>
<th>#</th>
<th>Jogador</th>
<th>Tempo</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</section>
<!-- coluna 2: preview + big “Melhor Pessoal” + botão -->
<aside class="detail-info">
<h2 id="detail-title">Nível X</h2>
<div id="detail-map"></div>
<div class="best-line">Melhor Pessoal: <span id="detail-best">–</span></div>
<button id="detail-play">▶ Jogar</button>
</aside>
</div>
</div>
</aside>
<!-- === CONTEÚDO DO JOGO === -->
<div id="game-page" class="hidden">
<div id="pause-overlay"></div>
<!-- Botão para alternar câmaras -->
<button id="camera-toggle-btn" class="cam-btn" title="Mudar câmara">
<svg viewBox="0 0 24 24" width="20" height="20">
<path
fill="currentColor"
d="M12 5a5 5 0 100 10 5 5 0 000-10zm0-3c1.1 0 2 .9 2 2h4c1.1 0 2 .9 2 2v10a2
2 0 01-2 2H6a2 2 0 01-2-2V6c0-1.1.9-2 2-2h4a2 2 0 012-2z"
/>
</svg>
</button>
<!-- Controles de luz -->
<div id="light-controls">
<label><input type="checkbox" id="toggleAmbient" checked /> Luz Ambiente</label>
<label><input type="checkbox" id="toggleDirectional" checked /> Luz Direcional</label>
<label><input type="checkbox" id="togglePoint" checked /> Luz Pontual</label>
</div>
<!-- Canvas do Jogo -->
<div id="game-container"></div>
<div id="preview-text">Decora o labirinto!</div>
<!-- Modal de Fim de Nível -->
<div id="level-complete-modal">
<div class="modal-content">
<div class="leaderboard-panel">
<h3>Top 5 deste nível</h3>
<table id="leaderboard-table">
<thead>
<tr>
<th>#</th>
<th>Jogador</th>
<th>Tempo</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="3">Carregando…</td>
</tr>
</tbody>
</table>
</div>
<div class="modal-body">
<h2>Nível Concluído!</h2>
<p class="time-display"></p>
<div class="button-group">
<button id="menu-btn">Regressar ao Menu</button>
<button id="retry-btn">Tentar Novamente</button>
</div>
<button id="next-level-btn">Próximo Nível</button>
</div>
</div>
</div>
<!-- Submenu Pausa -->
<div id="pause-menu">
<h2>Menu de Pausa</h2>
<button class="pause-button" id="resume-btn">▶ Continuar</button>
<button class="pause-button" id="restart-btn">↻ Reiniciar</button>
<button class="pause-button" id="exit-btn">⏴ Voltar ao Menu</button>
<div class="mute-controls">
<button id="mute-sound-btn" class="pause-button mute-btn" title="Som">
🔊
</button>
<button
id="mute-music-btn"
class="pause-button mute-btn"
title="Música"
>
🎵
</button>
</div>
</div>
<!-- Minimap -->
<div id="minimap-container">
<canvas id="minimap" width="220" height="220"></canvas>
</div>
<!-- Velocímetro -->
<div id="speedometer">0 km/h</div>
<!-- Contador de moedas -->
<div id="coin-counter">
<img src="./assets/textures/coin.png" alt="Moeda" />
<span id="coin-count">0</span>
</div>
</div>
<!-- === SCRIPTS === -->
<script type="module">
import { db } from "./js/firebase.js";
import { doc, getDoc } from "https://www.gstatic.com/firebasejs/10.3.0/firebase-firestore.js";
import { updateAudioSettings, updateMuteIcons } from "./js/audio.js";
import { fetchLeaderboard } from "./js/leaderboard.js";
import { getCurrentUserId, getAllProfiles, getCurrentProfile, getActiveProfileId, setActiveProfileId, updateProfile,
saveAllProfiles,} from "./js/profileSystem.js";
import {
unlockLevel,
isLevelUnlocked,
resetProgress,
} from "./js/unlockSystem.js";
import {
exportProgress,
importProgressToken,
} from "./js/dataTransfer.js";
// — Elementos globais —
const currentProfileEl = document.querySelector(".current-profile");
const mainMenu = document.getElementById("main-menu");
const footer = document.querySelector(".mazerush-footer");
const profileList = document.getElementById("profile-list");
const profilesCt = document.getElementById("profiles-container");
const profilePopup = document.getElementById("profile-popup");
const nicknameIn = document.getElementById("nickname");
const confirmBtn = document.getElementById("confirm-profile");
const deleteBtn = document.getElementById("delete-profile");
const nameMain = document.getElementById("profile-name-main");
const settingsMenu = document.getElementById("settings-menu");
const toggleSound = document.getElementById("toggle-sound");
const toggleMusic = document.getElementById("toggle-music");
const volSound = document.getElementById("volume-sound");
const volMusic = document.getElementById("volume-music");
const muteSoundBtn = document.getElementById("mute-sound-btn");
const muteMusicBtn = document.getElementById("mute-music-btn");
const levelsPage = document.getElementById("levels-page");
const levelsCt = document.getElementById("levels-container");
const resetBtn = document.getElementById("reset-btn");
const mainPage = document.getElementById("main-page");
const gamePage = document.getElementById("game-page");
const pauseMenu = document.getElementById("pause-menu");
const resumeBtn = document.getElementById("resume-btn");
const restartBtn = document.getElementById("restart-btn");
// elementos do painel de detalhe
const detailPanel = document.getElementById("level-detail");
const detailTitle = document.getElementById("detail-title");
const detailBest = document.getElementById("detail-best");
const detailTable = document.getElementById("detail-table").querySelector("tbody");
const detailPlay = document.getElementById("detail-play");
const detailMapDiv = document.getElementById("detail-map");
// — Painéis de token —
const tokenExportPanel = document.getElementById("token-export");
const exportTextarea = document.getElementById("export-token-text");
const tokenImportPanel = document.getElementById("token-import");
const importTextarea = document.getElementById("import-token-text");
// — Botões de export/import —
const btnExport = document.getElementById("btn-export");
const btnImportMenu = document.getElementById("btn-import-progress");
const firestoreTimeout = (promise, ms = 3000) =>
Promise.race([
promise,
new Promise((_, reject) => setTimeout(() => reject(new Error('Firestore timeout')), ms))
]);
async function fetchLeaderboardSafe(levelId, n) {
try {
return await firestoreTimeout(fetchLeaderboard(levelId, n), 2500);
} catch {
console.warn('Leaderboard demorou demais – vou regressar logo');
return [];
}
}
function generateUUID() {
return ([1e7]+-1e3+-4e3+-8e3+-1e11)
.replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c/4)
.toString(16)
);
}
// — Helpers de UI —
function hideCommon() {
mainMenu.style.display = "none";
footer.style.display = "none";
currentProfileEl.style.display = "none";
}
function showCommon() {
mainMenu.style.display = "grid";
footer.style.display = "block";
currentProfileEl.style.display = "flex";
}
// — Exportar —
window.openTokenExport = () => {
// escondemos perfil-list e editor
profileList.classList.add("hidden");
profilePopup.classList.add("hidden");
hideCommon();
exportTextarea.value = exportProgress();
tokenExportPanel.classList.remove("hidden");
};
window.closeTokenExport = () => {
tokenExportPanel.classList.add("hidden");
// mostra de novo o submenu de perfis
profileList.classList.remove("hidden");
// remove o blur caso estivesse aplicado
profileList.classList.remove("blurred");
};
// — Importar —
window.openTokenImport = () => {
profileList.classList.add("hidden");
hideCommon();
importTextarea.value = "";
tokenImportPanel.classList.remove("hidden");
};
window.closeTokenImport = () => {
tokenImportPanel.classList.add("hidden");
profileList.classList.remove("hidden");
profileList.classList.remove("blurred");
};
// — Copiar para clipboard —
window.copyExportToken = () => {
exportTextarea.select();
document.execCommand("copy");
alert("Token copiado!");
};
// — Confirmar token de importação —
window.confirmImportToken = () => {
const token = importTextarea.value.trim();
if (!token) return alert("Cole o token primeiro.");
const res = importProgressToken(token);
if (res.success) {
buildProfilesList();
loadActiveProfileUI();
closeTokenImport();
return alert("Importado com sucesso!");
}
if (res.needsConfirm && confirm("Substituir perfil ativo?")) {
importProgressToken(token, true);
buildProfilesList();
loadActiveProfileUI();
closeTokenImport();
return alert("Perfil substituído!");
}
alert("Erro: " + res.message);
};
// — Ligações de botões —
btnExport?.addEventListener("click", openTokenExport);
btnImportMenu?.addEventListener("click", openTokenImport);
// — Menu de perfis —
window.openProfileMenu = () => {
buildProfilesList();
hideCommon();
profileList.classList.remove("hidden");
};
window.closeProfileMenu = () => {
profileList.classList.add("hidden");
showCommon();
};
// — Lista de perfis —
function buildProfilesList() {
profilesCt.innerHTML = "";
getAllProfiles().forEach((p) => {
const slot = document.createElement("div");
slot.className =
"profile-slot " +
(p.id === getActiveProfileId() ? "active" : "inactive");
slot.textContent = p.name || "Vazio";
slot.onclick = () => {
if (!p.name) {
setActiveProfileId(p.id);
openEditPopup();
} else if (p.id === getActiveProfileId()) {
hideCommon();
profileList.classList.add("blurred");
openEditPopup();
} else {
setActiveProfileId(p.id);
buildProfilesList();
loadActiveProfileUI();
updateAudioSettings();
}
};
profilesCt.append(slot);
});
}
// — Popup editar perfil —
function openEditPopup() {
const cur = getCurrentProfile();
nicknameIn.value = cur.name || "";
profilePopup.classList.remove("hidden");
profileList.classList.add("blurred");
}
function closeEditPopup() {
profilePopup.classList.add("hidden");
profileList.classList.remove("blurred");
}
window.openEditPopup = openEditPopup;
confirmBtn.onclick = () => {
const cur = getCurrentProfile();
cur.name = nicknameIn.value.trim() || cur.name;
if (!cur.unlockedLevels || !cur.unlockedLevels.length)
cur.unlockedLevels = ["level-1"];
if (cur.soundEnabled === undefined) cur.soundEnabled = true;
if (cur.musicEnabled === undefined) cur.musicEnabled = true;
if (cur.soundVolume === undefined) cur.soundVolume = 70;
if (cur.musicVolume === undefined) cur.musicVolume = 60;
updateProfile(cur);
buildProfilesList();
loadActiveProfileUI();
closeEditPopup();
updateAudioSettings();
};
window.deleteProfile = () => {
const cur = getCurrentProfile();
if (!confirm("Eliminar este perfil?")) return;
const all = getAllProfiles().filter(p => p.id !== cur.id);
// Criar novo perfil com novos IDs únicos
const newProfile = {
id: generateUUID(),
userId: generateUUID(),
name: "",
unlockedLevels: [],
soundEnabled: true,
musicEnabled: true,
soundVolume: 70,
musicVolume: 60,
coins: 0,
levelTimes: {},
carModels: {
0: { primary: "#603441", secondary: "#ffffff", structure: "#131313", wheels: "#666666" },
1: { primary: "#4B5320", secondary: "#A9A9A9", structure: "#2F4F4F", wheels: "#333333" },
2: { primary: "#ff0000", secondary: "#111111", structure: "#333333", wheels: "#222222" },
3: { primary: "#0000ff", secondary: "#eeeeee", structure: "#555555", wheels: "#444444" }
},
selectedModel: 0,
unlockedCars: [0]
};
all.push(newProfile);
saveAllProfiles(all);
setActiveProfileId(newProfile.id);
buildProfilesList();
loadActiveProfileUI();
closeEditPopup();
updateAudioSettings();
};
// — Definições de som/música —
const updateSetting = (key, value) => {
const cur = getCurrentProfile();
cur[key] = value;
updateProfile(cur);
updateAudioSettings();
muteSoundBtn.textContent = cur.soundEnabled ? "🔊" : "🔇";
muteMusicBtn.textContent = cur.musicEnabled ? "🎵" : "🚫🎵";
};
toggleSound.onchange = () =>
updateSetting("soundEnabled", toggleSound.checked);
toggleMusic.onchange = () =>
updateSetting("musicEnabled", toggleMusic.checked);
volSound.oninput = () => updateSetting("soundVolume", +volSound.value);
volMusic.oninput = () => updateSetting("musicVolume", +volMusic.value);
window.openSettingsMenu = () => {
const cur = getCurrentProfile();
hideCommon();
settingsMenu.classList.remove("hidden");
toggleSound.checked = cur.soundEnabled;
toggleMusic.checked = cur.musicEnabled;
volSound.value = cur.soundVolume;
volMusic.value = cur.musicVolume;
};
window.closeSettingsMenu = () => {
settingsMenu.classList.add("hidden");
showCommon();
};
// — Níveis —
window.openLevels = () => {
loadActiveProfileUI();
hideCommon();
levelsPage.classList.remove("hidden");
};
window.closeLevels = () => {
levelsPage.classList.add("hidden");
showCommon();
};
resetBtn.onclick = () => {
if (!confirm("Reiniciar progresso deste perfil?")) return;
const cur = getCurrentProfile();
cur.unlockedLevels = ["level-1"];
updateProfile(cur);
loadActiveProfileUI();
};
/* === Carregar e renderizar os cards de nível === */
function loadActiveProfileUI() {
const cur = getCurrentProfile();
nameMain.textContent = cur.name ? `Olá, ${cur.name}!` : "Olá, Perfil!";
levelsCt.innerHTML = "";
const labels = ["Nível 1","Nível 2","Nível 3","Nível 4","Nível 5","Nível 6"];
labels.forEach((lbl, i) => {
const n = i + 1;
const id = `level-${n}`;
const card = document.createElement("div");
card.className = "level-card";
card.setAttribute("data-level", n);
// ─── Somente o <span> com o texto “Nível X” (sem nenhum canvas) ───
const span = document.createElement("span");
span.textContent = lbl;
card.append(span);
// ─── Lógica de destravar ou bloquear ───
if (cur.unlockedLevels.includes(id)) {
card.classList.add("clickable");
card.addEventListener("click", () => openLevelDetail(n));
} else {
card.classList.add("locked");
const lock = document.createElement("div");
lock.className = "locked-button";
lock.textContent = "🔒 Bloqueado";
card.append(lock);
}
levelsCt.append(card);
});
}
async function drawLevelThumbnail(levelNumber, canvas) {
try {
// 1) Carrega o layout.json do nível
const resp = await fetch(`./assets/levels/level-${levelNumber}/layout.json`);
if (!resp.ok) throw new Error("Não encontrou layout.json para level-" + levelNumber);
const data = await resp.json();
const map = data.map;
const rows = map.length;
const cols = map[0].length;
const ctx = canvas.getContext("2d");
const W = canvas.width;
const H = canvas.height;
ctx.clearRect(0, 0, W, H);
// Cada célula terá W/cols × H/rows pixels
const cellW = W / cols;
const cellH = H / rows;
// Cores vindas do JSON (se não existir, usa default)
const colorWall = data.colors.wall || "#0F223D";
const colorFloor = data.colors.floor || "#D3CA79";
// Desenha retângulo para cada célula
for (let z = 0; z < rows; z++) {
for (let x = 0; x < cols; x++) {
ctx.fillStyle = (map[z][x] === 1) ? colorWall : colorFloor;
ctx.fillRect(x * cellW, z * cellH, cellW, cellH);
}
}
ctx.strokeStyle = "#444";
ctx.lineWidth = 1;
ctx.strokeRect(0, 0, W, H);
} catch (err) {
console.warn("Erro em drawLevelThumbnail:", err);
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#333";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#fff";
ctx.font = "12px sans-serif";
ctx.textAlign = "center";
ctx.fillText("Sem prévia", canvas.width/2, canvas.height/2);
}
}
// abre o detalhe de nível
async function openLevelDetail(n) {
const cur = getCurrentProfile();
const levelId = `level-${n}`;
// título
detailTitle.textContent = `Nível ${n}`;
// carregar leaderboard via tua função existente
detailTable.innerHTML = `<tr><td colspan="3">A carregar…</td></tr>`;
fetchLeaderboard(levelId, 5).then(rows => {
detailTable.innerHTML = "";
if (!rows.length) {
detailTable.innerHTML = `<tr><td colspan="3">Sem resultados</td></tr>`;
} else {
rows.forEach((r,i) => {
detailTable.innerHTML += `
<tr>
<td>${i+1}</td>
<td>${r.name}</td>
<td>${r.time.toFixed(2)}s</td>
</tr>
`;
});
}
}).catch(() => {
detailTable.innerHTML = `<tr><td colspan="3">Erro ao carregar</td></tr>`;
});
// 2) carrega o teu “Melhor Pessoal” direto da Firestore
detailBest.textContent = "–";
try {
const userId = getCurrentUserId();
const personalRef = doc(db, "levels", levelId, "leaderboard", userId);
const snap = await getDoc(personalRef);
if (snap.exists()) {
detailBest.textContent = snap.data().time.toFixed(2) + " s";
}
} catch (err) {
console.warn("Falha ao buscar melhor pessoal:", err);
}
// Limpa qualquer conteúdo anterior no #detail-map
detailMapDiv.innerHTML = "";
// Cria o <canvas> com 180×180 px (para caber no seu CSS #detail-map)
const canvas = document.createElement("canvas");
canvas.width = 180;
canvas.height = 180;
detailMapDiv.append(canvas);
// Chama a função que desenha o layout.json exatamente naquele canvas
drawLevelThumbnail(n, canvas);
// botão jogar
detailPlay.onclick = () => {
closeLevelDetail();
localStorage.setItem("selectedLevel", levelId);
closeLevels();
mainPage.classList.add("hidden");
gamePage.classList.remove("hidden");
import("./js/main.js").then(m => m.initLevel(n));
};
detailPanel.classList.remove("hidden");
}
// fecha o detalhe
function closeLevelDetail() {
detailPanel.classList.add("hidden");
}
window.openLevelDetail = openLevelDetail;
window.closeLevelDetail = closeLevelDetail;
// — Personalizar —
const customizePage = document.getElementById("customize-page");
const customizeContainer = document.getElementById("customize-container");
window.openCustomizeMenu = () => {
hideCommon();
// esconder outros submenus caso estejam abertos
levelsPage.classList.add("hidden");
settingsMenu.classList.add("hidden");
profileList.classList.add("hidden");
customizePage.classList.remove("hidden");
import("./js/customize.js")
.then(m => m.initCustomize(customizeContainer))
.catch(err => console.error("Erro a carregar customize.js:", err));
};
window.closeCustomizeMenu = () => {
customizePage.classList.add("hidden");
showCommon();
};
// — Início —
window.onload = () => {
buildProfilesList();
loadActiveProfileUI();
updateAudioSettings();
};
</script>
<script async src="https://unpkg.com/es-module-shims@1.6.3/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@v0.163.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@v0.163.0/examples/jsm/"
}
}
</script>
</body>
</html>