-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1107 lines (944 loc) · 48.7 KB
/
index.html
File metadata and controls
1107 lines (944 loc) · 48.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
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
<!DOCTYPE html>
<html lang="es">
<head>
<title>CPR</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Babylon.js -->
<script src="https://cdn.babylonjs.com/babylon.js"></script>
<script src="https://cdn.babylonjs.com/loaders/babylonjs.loaders.min.js"></script>
<script src="https://cdn.babylonjs.com/materialsLibrary/babylonjs.materials.min.js"></script>
<script src="https://cdn.babylonjs.com/postProcessesLibrary/babylonjs.postProcess.min.js"></script>
<script src="https://cdn.babylonjs.com/proceduralTexturesLibrary/babylonjs.proceduralTextures.min.js"></script>
<script src="https://cdn.babylonjs.com/gui/babylon.gui.min.js"></script>
<style>
/* Variables CSS personalizadas para mantener compatibilidad */
:root {
--background-dark: #0a0a0a;
--hud-background-dark: #1f1f1f;
--main-border-color: #AECAD2;
}
/* Animaciones personalizadas */
@keyframes hudPulseFlat {
0%, 100% {
transform: scale(1);
background-color: var(--hud-background-dark);
color: white;
}
50% {
transform: scale(1.05);
background-color: #FFECB3;
color: black;
}
}
@keyframes fadeInOut {
0% { opacity: 0; transform: translate(-50%, -50%) scale(0.8); }
50% { opacity: 1; transform: translate(-50%, -50%) scale(1); }
100% { opacity: 0; transform: translate(-50%, -50%) scale(1.2); }
}
/* Clases utilitarias adicionales */
.animate-hud-pulse {
animation: hudPulseFlat 0.3s ease-out forwards;
}
.animate-fade-in-out {
animation: fadeInOut 2s ease-out forwards;
}
/* Asegurar que el canvas de Babylon ocupe toda la pantalla */
#renderCanvas {
width: 100%;
height: 100%;
display: block;
outline: none;
}
</style>
</head>
<body class="bg-black text-white font-sans overflow-hidden m-0 p-0 w-screen h-screen">
<!-- Canvas de Babylon.js -->
<canvas id="renderCanvas" class="absolute top-0 left-0 w-full h-full z-0"></canvas>
<!-- HUD del juego -->
<div id="hud" class="absolute top-5 left-0 w-full flex flex-wrap gap-4 justify-center z-10">
<div class="hud-item bg-gray-800 bg-opacity-90 px-4 py-2 rounded-lg text-white text-lg backdrop-blur-sm border border-white border-opacity-15 shadow-lg transition-all duration-200">
Puntuación: <span id="score">0</span>
</div>
<div class="hud-item bg-gray-800 bg-opacity-90 px-4 py-2 rounded-lg text-white text-lg backdrop-blur-sm border border-white border-opacity-15 shadow-lg transition-all duration-200">
BPM: <span id="bpm">0</span>
</div>
<div class="hud-item bg-gray-800 bg-opacity-90 px-4 py-2 rounded-lg text-white text-lg backdrop-blur-sm border border-white border-opacity-15 shadow-lg transition-all duration-200">
Precisión: <span id="accuracy">100%</span>
</div>
<div class="hud-item bg-gray-800 bg-opacity-90 px-4 py-2 rounded-lg text-white text-lg backdrop-blur-sm border border-white border-opacity-15 shadow-lg transition-all duration-200">
Combo: <span id="combo">0</span>
</div>
</div>
<!-- Menú principal -->
<div id="startMenu" class="absolute inset-0 flex flex-col items-center justify-center bg-gray-800 bg-opacity-95 z-20">
<h1 class="text-4xl md:text-6xl font-bold mb-8 text-white">CPR</h1>
<button id="playButton" class="bg-green-300 text-gray-900 border-4 border-blue-200 rounded-xl cursor-pointer transition-all duration-300 hover:bg-blue-200 hover:text-white hover:border-pink-200 transform hover:scale-105 font-bold text-lg md:text-xl px-8 py-4 my-2 w-64 max-w-full">
Jugar
</button>
<button id="settingsButton" class="bg-green-300 text-gray-900 border-4 border-blue-200 rounded-xl cursor-pointer transition-all duration-300 hover:bg-blue-200 hover:text-white hover:border-pink-200 transform hover:scale-105 font-bold text-lg md:text-xl px-8 py-4 my-2 w-64 max-w-full">
Configuración
</button>
<button id="aboutButton" class="bg-green-300 text-gray-900 border-4 border-blue-200 rounded-xl cursor-pointer transition-all duration-300 hover:bg-blue-200 hover:text-white hover:border-pink-200 transform hover:scale-105 font-bold text-lg md:text-xl px-8 py-4 my-2 w-64 max-w-full">
Acerca de
</button>
<p class="text-gray-300 mt-5 text-sm md:text-base">Presiona SPACE para jugar</p>
</div>
<!-- Menú de configuración -->
<div id="settingsMenu" class="absolute inset-0 bg-gray-800 bg-opacity-95 z-20 hidden overflow-y-auto py-10">
<div class="container mx-auto px-4 max-w-4xl">
<h1 class="text-4xl md:text-6xl font-bold mb-8 text-white text-center">Configuración</h1>
<div class="bg-gray-700 bg-opacity-70 p-6 rounded-xl border border-white border-opacity-10 shadow-lg mb-6">
<h2 class="text-xl md:text-2xl font-bold mb-4 text-white">Renderizado</h2>
<div class="flex flex-wrap gap-2 justify-center">
<button id="rendererStandard" class="bg-gray-600 text-white border-2 border-gray-500 px-4 py-2 rounded-lg cursor-pointer transition-all duration-200 hover:bg-gray-500 active:bg-green-300 active:text-gray-900 active:border-blue-200">
Estándar
</button>
<button id="rendererEnhanced" class="bg-gray-600 text-white border-2 border-gray-500 px-4 py-2 rounded-lg cursor-pointer transition-all duration-200 hover:bg-gray-500 active:bg-green-300 active:text-gray-900 active:border-blue-200">
Mejorado
</button>
</div>
</div>
<div class="bg-gray-700 bg-opacity-70 p-6 rounded-xl border border-white border-opacity-10 shadow-lg mb-6">
<h2 class="text-xl md:text-2xl font-bold mb-4 text-white">Calidad Gráfica</h2>
<div class="flex flex-wrap gap-2 justify-center">
<button id="graphicsLow" class="bg-gray-600 text-white border-2 border-gray-500 px-4 py-2 rounded-lg cursor-pointer transition-all duration-200 hover:bg-gray-500 active:bg-green-300 active:text-gray-900 active:border-blue-200">
Baja
</button>
<button id="graphicsMedium" class="bg-green-300 text-gray-900 border-2 border-blue-200 px-4 py-2 rounded-lg cursor-pointer transition-all duration-200">
Media
</button>
<button id="graphicsHigh" class="bg-gray-600 text-white border-2 border-gray-500 px-4 py-2 rounded-lg cursor-pointer transition-all duration-200 hover:bg-gray-500 active:bg-green-300 active:text-gray-900 active:border-blue-200">
Alta
</button>
</div>
</div>
<div class="bg-gray-700 bg-opacity-70 p-6 rounded-xl border border-white border-opacity-10 shadow-lg mb-6">
<h2 class="text-xl md:text-2xl font-bold mb-4 text-white">Dificultad</h2>
<div class="flex flex-wrap gap-2 justify-center">
<button id="difficultyEasy" class="bg-gray-600 text-white border-2 border-gray-500 px-4 py-2 rounded-lg cursor-pointer transition-all duration-200 hover:bg-gray-500 active:bg-green-300 active:text-gray-900 active:border-blue-200">
Fácil
</button>
<button id="difficultyNormal" class="bg-green-300 text-gray-900 border-2 border-blue-200 px-4 py-2 rounded-lg cursor-pointer transition-all duration-200">
Normal
</button>
<button id="difficultyHard" class="bg-gray-600 text-white border-2 border-gray-500 px-4 py-2 rounded-lg cursor-pointer transition-all duration-200 hover:bg-gray-500 active:bg-green-300 active:text-gray-900 active:border-blue-200">
Difícil
</button>
</div>
</div>
<div class="bg-gray-700 bg-opacity-70 p-6 rounded-xl border border-white border-opacity-10 shadow-lg mb-6">
<h2 class="text-xl md:text-2xl font-bold mb-4 text-white">Efectos</h2>
<div class="flex flex-wrap gap-2 justify-center">
<button id="shaderOff" class="bg-green-300 text-gray-900 border-2 border-blue-200 px-4 py-2 rounded-lg cursor-pointer transition-all duration-200">
Off
</button>
<button id="shaderBloom" class="bg-gray-600 text-white border-2 border-gray-500 px-4 py-2 rounded-lg cursor-pointer transition-all duration-200 hover:bg-gray-500 active:bg-green-300 active:text-gray-900 active:border-blue-200">
Bloom
</button>
<button id="shaderGlow" class="bg-gray-600 text-white border-2 border-gray-500 px-4 py-2 rounded-lg cursor-pointer transition-all duration-200 hover:bg-gray-500 active:bg-green-300 active:text-gray-900 active:border-blue-200">
Glow
</button>
</div>
</div>
<div class="bg-gray-700 bg-opacity-70 p-6 rounded-xl border border-white border-opacity-10 shadow-lg mb-6">
<h2 class="text-xl md:text-2xl font-bold mb-4 text-white">Modo de Color</h2>
<div class="flex flex-wrap gap-2 justify-center">
<button id="colorModePerRound" class="bg-gray-600 text-white border-2 border-gray-500 px-4 py-2 rounded-lg cursor-pointer transition-all duration-200 hover:bg-gray-500 active:bg-green-300 active:text-gray-900 active:border-blue-200">
Por Ronda
</button>
<button id="colorModeRainbow" class="bg-green-300 text-gray-900 border-2 border-blue-200 px-4 py-2 rounded-lg cursor-pointer transition-all duration-200">
Arcoíris
</button>
<button id="colorModeMonochromatic" class="bg-gray-600 text-white border-2 border-gray-500 px-4 py-2 rounded-lg cursor-pointer transition-all duration-200 hover:bg-gray-500 active:bg-green-300 active:text-gray-900 active:border-blue-200">
Monocromático
</button>
</div>
</div>
<div class="text-center mt-8">
<button id="backToMainMenuButton" class="bg-green-300 text-gray-900 border-4 border-blue-200 rounded-xl cursor-pointer transition-all duration-300 hover:bg-blue-200 hover:text-white hover:border-pink-200 transform hover:scale-105 font-bold text-lg md:text-xl px-8 py-4 my-2 w-64 max-w-full">
Volver
</button>
</div>
</div>
</div>
<!-- Menú de pausa -->
<div id="pauseMenu" class="absolute inset-0 flex flex-col items-center justify-center bg-gray-800 bg-opacity-95 z-20 hidden">
<h1 class="text-4xl md:text-6xl font-bold mb-8 text-white">Juego Pausado</h1>
<button id="continueButton" class="bg-green-300 text-gray-900 border-4 border-blue-200 rounded-xl cursor-pointer transition-all duration-300 hover:bg-blue-200 hover:text-white hover:border-pink-200 transform hover:scale-105 font-bold text-lg md:text-xl px-8 py-4 my-2 w-64 max-w-full">
Continuar
</button>
<button id="restartButton" class="bg-green-300 text-gray-900 border-4 border-blue-200 rounded-xl cursor-pointer transition-all duration-300 hover:bg-blue-200 hover:text-white hover:border-pink-200 transform hover:scale-105 font-bold text-lg md:text-xl px-8 py-4 my-2 w-64 max-w-full">
Reiniciar
</button>
<button id="exitToMenuButton" class="bg-green-300 text-gray-900 border-4 border-blue-200 rounded-xl cursor-pointer transition-all duration-300 hover:bg-blue-200 hover:text-white hover:border-pink-200 transform hover:scale-105 font-bold text-lg md:text-xl px-8 py-4 my-2 w-64 max-w-full">
Salir al Menú Principal
</button>
</div>
<!-- Pantalla de puntuación -->
<div id="scoreScreen" class="absolute inset-0 flex flex-col items-center justify-center bg-gray-800 bg-opacity-95 z-20 hidden">
<h1 class="text-4xl md:text-6xl font-bold mb-8 text-white">Resultados Finales</h1>
<p class="text-xl md:text-3xl mb-4">Puntuación: <span id="finalScore">0</span></p>
<p class="text-xl md:text-3xl mb-4">Precisión: <span id="finalAccuracy">0%</span></p>
<p class="text-xl md:text-3xl mb-8">Clasificación: <span id="finalRank">E</span></p>
<button id="playAgainButton" class="bg-green-300 text-gray-900 border-4 border-blue-200 rounded-xl cursor-pointer transition-all duration-300 hover:bg-blue-200 hover:text-white hover:border-pink-200 transform hover:scale-105 font-bold text-lg md:text-xl px-8 py-4 my-2 w-64 max-w-full">
Jugar de Nuevo
</button>
</div>
<!-- Texto informativo del juego -->
<div class="info-text absolute bottom-5 w-full text-center text-gray-400 text-sm md:text-base z-10">
Presiona SPACE o toca cuando los círculos coincidan
</div>
<!-- Texto de animación de introducción -->
<div id="introAnimationText" class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 text-4xl md:text-6xl text-white text-center z-30 opacity-0 pointer-events-none">
¡Prepárate!
</div>
<!-- Modal de alerta personalizado -->
<div id="customAlertModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-40 hidden">
<div class="bg-gray-800 p-8 rounded-xl border-4 border-blue-200 shadow-2xl max-w-md w-4/5 text-center">
<h2 id="customAlertTitle" class="text-2xl font-bold mb-4 text-white"></h2>
<p id="customAlertMessage" class="text-gray-300 mb-6"></p>
<button id="customAlertCloseButton" class="bg-green-300 text-gray-900 border-2 border-blue-200 rounded-lg cursor-pointer px-6 py-2 font-bold transition-all duration-200 hover:bg-blue-200 hover:text-white">
OK
</button>
</div>
</div>
<!-- Advertencia de orientación -->
<div id="orientationWarning" class="fixed inset-0 bg-black flex flex-col items-center justify-center z-50 p-5 hidden">
<p class="text-xl md:text-3xl text-white text-center mb-4">
Para una mejor experiencia de juego, por favor, rota tu dispositivo a orientación vertical.
</p>
<p class="text-lg md:text-xl text-gray-300 text-center">
(O asegúrate de que tu pantalla no sea demasiado ancha en modo horizontal)
</p>
</div>
<script>
// --- Constantes y Configuración ---
const BASE_PRECISION = {
NANO: { threshold: 1.0, score: 350, color: '#AECAD2', text: 'NANO!' },
PERFECT: { threshold: 2.5, score: 300, color: '#C3F8B7', text: 'PERFECT!' },
BEST: { threshold: 5, score: 150, color: '#FFFACD', text: 'BEST!' },
GOOD: { threshold: 8, score: 75, color: '#FFD1DC', text: 'GOOD' },
BAD: { threshold: 12, score: 25, color: '#D5B8FF', text: 'BAD' },
MISS: { threshold: Infinity, score: 0, color: '#FF7F7F', text: 'MISS' }
};
const DIFFICULTY_MULTIPLIERS = {
'easy': 1.5,
'normal': 1.0,
'hard': 0.7
};
const GRAPHICS_SETTINGS = {
'low': { particles: 10, effects: false },
'medium': { particles: 35, effects: true },
'high': { particles: 100, effects: true }
};
const PASTEL_COLORS = [
'#FFD1DC', // Pastel Pink
'#BCE2E8', // Pastel Blue
'#FFFACD', // Pastel Yellow
'#C3F8B7', // Pastel Green
'#D5B8FF', // Pastel Lavender
'#FFECB3' // Pastel Peach
];
// Rounds del juego
const rounds = [
{ bpm: 60, notes: [90, 270], beatsPerRotation: 2 },
{ bpm: 90, notes: [0, 120, 240], beatsPerRotation: 3 },
{ bpm: 120, notes: [45, 135, 225, 315], beatsPerRotation: 4 },
{ bpm: 150, notes: [0, 72, 144, 216, 288], beatsPerRotation: 5 }
];
// --- Variables Globales de Babylon.js ---
let engine, scene, camera, canvasElem;
let mainCircleMesh, playerMesh, markerMeshes = [];
let particleSystems = [];
let currentRoundIndex = 0;
let currentColorIndex = 0;
// --- Estado del Juego ---
let gameState = {
phase: 'menu', // 'menu', 'introAnimation', 'playing', 'ended', 'settings', 'paused', 'scoreScreen'
score: 0,
totalHits: 0,
totalAttempts: 0,
combo: 0,
activeMarkers: [],
currentDifficulty: 'normal',
currentGraphicsQuality: 'medium',
activeShader: 'none',
colorMode: 'rainbow',
playerAngle: 0,
centralReelPulseScale: 1,
rotationsCompletedThisRound: 0,
lastCheckedRotationAngle: 0,
globalTime: 0
};
// --- Elementos DOM ---
const elements = {
score: document.getElementById('score'),
bpm: document.getElementById('bpm'),
accuracy: document.getElementById('accuracy'),
combo: document.getElementById('combo'),
startMenu: document.getElementById('startMenu'),
playButton: document.getElementById('playButton'),
settingsButton: document.getElementById('settingsButton'),
aboutButton: document.getElementById('aboutButton'),
settingsMenu: document.getElementById('settingsMenu'),
backToMainMenuButton: document.getElementById('backToMainMenuButton'),
pauseMenu: document.getElementById('pauseMenu'),
continueButton: document.getElementById('continueButton'),
restartButton: document.getElementById('restartButton'),
exitToMenuButton: document.getElementById('exitToMenuButton'),
scoreScreen: document.getElementById('scoreScreen'),
finalScore: document.getElementById('finalScore'),
finalAccuracy: document.getElementById('finalAccuracy'),
finalRank: document.getElementById('finalRank'),
playAgainButton: document.getElementById('playAgainButton'),
introAnimationText: document.getElementById('introAnimationText'),
customAlertModal: document.getElementById('customAlertModal'),
customAlertTitle: document.getElementById('customAlertTitle'),
customAlertMessage: document.getElementById('customAlertMessage'),
customAlertCloseButton: document.getElementById('customAlertCloseButton'),
orientationWarning: document.getElementById('orientationWarning'),
// Botones de configuración
rendererStandard: document.getElementById('rendererStandard'),
rendererEnhanced: document.getElementById('rendererEnhanced'),
graphicsLow: document.getElementById('graphicsLow'),
graphicsMedium: document.getElementById('graphicsMedium'),
graphicsHigh: document.getElementById('graphicsHigh'),
difficultyEasy: document.getElementById('difficultyEasy'),
difficultyNormal: document.getElementById('difficultyNormal'),
difficultyHard: document.getElementById('difficultyHard'),
shaderOff: document.getElementById('shaderOff'),
shaderBloom: document.getElementById('shaderBloom'),
shaderGlow: document.getElementById('shaderGlow'),
colorModePerRound: document.getElementById('colorModePerRound'),
colorModeRainbow: document.getElementById('colorModeRainbow'),
colorModeMonochromatic: document.getElementById('colorModeMonochromatic')
};
// --- Funciones de Utilidad ---
function customAlert(title, message) {
elements.customAlertTitle.textContent = title;
elements.customAlertMessage.textContent = message;
elements.customAlertModal.classList.remove('hidden');
}
function hideCustomAlert() {
elements.customAlertModal.classList.add('hidden');
}
function hexToRgb(hex) {
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
return { r, g, b };
}
function getAccuracyRank(accuracyPercentage) {
if (accuracyPercentage === 100) return 'SX';
if (accuracyPercentage >= 95) return 'S';
if (accuracyPercentage >= 90) return 'A';
if (accuracyPercentage >= 80) return 'B';
if (accuracyPercentage >= 70) return 'C';
return 'E';
}
function updateHUD() {
elements.score.textContent = gameState.score;
const accuracy = gameState.totalAttempts === 0 ? 100 :
(gameState.totalHits / gameState.totalAttempts * 100).toFixed(1);
elements.accuracy.textContent = `${accuracy}%`;
elements.combo.textContent = gameState.combo;
}
function calculatePrecision(angleDiff) {
const difficultyMultiplier = DIFFICULTY_MULTIPLIERS[gameState.currentDifficulty];
for (const key in BASE_PRECISION) {
const precisionLevel = BASE_PRECISION[key];
if (precisionLevel.threshold !== Infinity && angleDiff <= precisionLevel.threshold * difficultyMultiplier) {
return precisionLevel;
}
}
return BASE_PRECISION.MISS;
}
// --- Funciones de Babylon.js ---
function initBabylon() {
// Obtener el canvas
canvasElem = document.getElementById('renderCanvas');
// Crear el motor de Babylon.js
engine = new BABYLON.Engine(canvasElem, true, {
preserveDrawingBuffer: true,
stencil: true
});
// Crear la escena
scene = new BABYLON.Scene(engine);
// Crear una cámara
camera = new BABYLON.ArcRotateCamera("camera", -Math.PI / 2, Math.PI / 2, 10, BABYLON.Vector3.Zero(), scene);
camera.attachControl(canvasElem, true);
camera.inputs.attached.keyboard.detachControl(); // Deshabilitar controles de teclado de la cámara
// Crear luz
const light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0), scene);
light.intensity = 0.7;
// Configurar el entorno
setupGameScene();
// Iniciar el bucle de renderizado
engine.runRenderLoop(() => {
scene.render();
updateGame();
});
// Manejar redimensionamiento de ventana
window.addEventListener('resize', () => {
engine.resize();
});
}
function setupGameScene() {
// Limpiar escena si ya existe
if (mainCircleMesh) mainCircleMesh.dispose();
if (playerMesh) playerMesh.dispose();
markerMeshes.forEach(mesh => mesh.dispose());
markerMeshes = [];
particleSystems.forEach(system => system.dispose());
particleSystems = [];
// Crear el círculo principal (anillo)
mainCircleMesh = BABYLON.MeshBuilder.CreateTorus("mainCircle", {
diameter: 5,
thickness: 0.2,
tessellation: 60
}, scene);
mainCircleMesh.rotation.x = Math.PI / 2;
// Crear el jugador (esfera)
playerMesh = BABYLON.MeshBuilder.CreateSphere("player", {
diameter: 0.3
}, scene);
// Material para el círculo principal
const mainCircleMaterial = new BABYLON.StandardMaterial("mainCircleMaterial", scene);
mainCircleMaterial.diffuseColor = new BABYLON.Color3(1, 1, 1);
mainCircleMaterial.emissiveColor = new BABYLON.Color3(0.2, 0.2, 0.2);
mainCircleMesh.material = mainCircleMaterial;
// Material para el jugador
const playerMaterial = new BABYLON.StandardMaterial("playerMaterial", scene);
playerMaterial.diffuseColor = new BABYLON.Color3.FromHexString(PASTEL_COLORS[currentColorIndex]);
playerMaterial.emissiveColor = new BABYLON.Color3.FromHexString(PASTEL_COLORS[currentColorIndex]);
playerMesh.material = playerMaterial;
// Crear marcadores iniciales
createMarkers();
// Configurar efectos post-procesamiento según la configuración
setupPostProcessing();
}
function createMarkers() {
// Limpiar marcadores existentes
markerMeshes.forEach(mesh => mesh.dispose());
markerMeshes = [];
const round = rounds[currentRoundIndex];
if (!round) return;
// Crear marcadores para esta ronda
round.notes.forEach((angle, index) => {
const marker = BABYLON.MeshBuilder.CreateSphere(`marker-${index}`, {
diameter: 0.4
}, scene);
const markerMaterial = new BABYLON.StandardMaterial(`markerMaterial-${index}`, scene);
markerMaterial.diffuseColor = new BABYLON.Color3.FromHexString(PASTEL_COLORS[(currentColorIndex + 2) % PASTEL_COLORS.length]);
markerMaterial.emissiveColor = new BABYLON.Color3.FromHexString(PASTEL_COLORS[(currentColorIndex + 2) % PASTEL_COLORS.length]);
marker.material = markerMaterial;
markerMeshes.push(marker);
gameState.activeMarkers.push({
angle,
hit: false,
originalAngle: angle,
mesh: marker
});
});
// Actualizar BPM en el HUD
elements.bpm.textContent = round.bpm;
}
function updateMarkers() {
const radius = 2.5;
gameState.activeMarkers.forEach((marker, index) => {
if (marker.hit) {
// Si el marcador fue golpeado, hacerlo más transparente
marker.mesh.material.alpha = 0.3;
return;
}
// Calcular posición del marcador
const radian = marker.angle * Math.PI / 180;
const x = Math.cos(radian) * radius;
const z = Math.sin(radian) * radius;
marker.mesh.position.set(x, 0, z);
});
}
function updatePlayer() {
const round = rounds[currentRoundIndex];
if (!round) return;
// Actualizar ángulo del jugador basado en BPM
const degreesPerBeat = 180 / round.beatsPerRotation;
const angleIncrease = (degreesPerBeat * (round.bpm / 60)) * (engine.getDeltaTime() / 1000);
const previousAngle = gameState.playerAngle;
gameState.playerAngle += angleIncrease;
// Actualizar posición del jugador
const radius = 2.5;
const radian = gameState.playerAngle * Math.PI / 180;
const x = Math.cos(radian) * radius;
const z = Math.sin(radian) * radius;
playerMesh.position.set(x, 0, z);
// Actualizar color según el modo
updatePlayerColor();
// Verificar rotaciones completadas
const currentTotalRotations = Math.floor(gameState.playerAngle / 360);
const lastTotalRotations = Math.floor(previousAngle / 360);
if (currentTotalRotations > lastTotalRotations) {
gameState.rotationsCompletedThisRound += (currentTotalRotations - lastTotalRotations);
}
// Verificar si se completó la ronda
if (gameState.rotationsCompletedThisRound >= 1) {
completeRound();
}
}
function updatePlayerColor() {
if (gameState.colorMode === 'rainbow') {
const anglePerColor = 360 / PASTEL_COLORS.length;
const currentAngleNormalized = (gameState.playerAngle % 360 + 360) % 360;
currentColorIndex = Math.floor(currentAngleNormalized / anglePerColor) % PASTEL_COLORS.length;
}
// Aplicar color al jugador
const playerMaterial = playerMesh.material;
playerMaterial.diffuseColor = new BABYLON.Color3.FromHexString(PASTEL_COLORS[currentColorIndex]);
playerMaterial.emissiveColor = new BABYLON.Color3.FromHexString(PASTEL_COLORS[currentColorIndex]);
}
function createParticles(angle, color, count = 10) {
if (gameState.currentGraphicsQuality === 'low') return;
const particleSystem = new BABYLON.ParticleSystem("particles", count, scene);
const radius = 2.5;
const radian = angle * Math.PI / 180;
const x = Math.cos(radian) * radius;
const z = Math.sin(radian) * radius;
particleSystem.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", scene);
particleSystem.emitter = new BABYLON.Vector3(x, 0, z);
particleSystem.minEmitBox = new BABYLON.Vector3(0, 0, 0);
particleSystem.maxEmitBox = new BABYLON.Vector3(0, 0, 0);
const rgb = hexToRgb(color);
particleSystem.color1 = new BABYLON.Color4(rgb.r / 255, rgb.g / 255, rgb.b / 255, 1.0);
particleSystem.color2 = new BABYLON.Color4(rgb.r / 255, rgb.g / 255, rgb.b / 255, 1.0);
particleSystem.colorDead = new BABYLON.Color4(0, 0, 0, 0.0);
particleSystem.minSize = 0.1;
particleSystem.maxSize = 0.3;
particleSystem.minLifeTime = 0.3;
particleSystem.maxLifeTime = 1.5;
particleSystem.emitRate = count;
particleSystem.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
particleSystem.minEmitPower = 1;
particleSystem.maxEmitPower = 3;
particleSystem.updateSpeed = 0.005;
particleSystem.start();
particleSystems.push(particleSystem);
// Detener el sistema de partículas después de un tiempo
setTimeout(() => {
particleSystem.stop();
const index = particleSystems.indexOf(particleSystem);
if (index > -1) {
particleSystems.splice(index, 1);
}
setTimeout(() => {
particleSystem.dispose();
}, 2000);
}, 100);
}
function setupPostProcessing() {
// Limpiar efectos anteriores
scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline("Standard", camera);
if (gameState.activeShader === 'bloom') {
// Pipeline de Bloom
const pipeline = new BABYLON.DefaultRenderingPipeline("Standard", true, scene, [camera]);
pipeline.bloomEnabled = true;
pipeline.bloomThreshold = 0.8;
pipeline.bloomWeight = 0.5;
pipeline.bloomKernel = 64;
pipeline.bloomScale = 0.5;
} else if (gameState.activeShader === 'glow') {
// Pipeline de Glow (usando LDR glow)
const pipeline = new BABYLON.DefaultRenderingPipeline("Standard", true, scene, [camera]);
pipeline.glowLayerEnabled = true;
pipeline.glowLayerIntensity = 1.0;
}
}
// --- Lógica del Juego ---
function startRound(roundIndex) {
if (roundIndex >= rounds.length) {
showScoreScreen();
return;
}
currentRoundIndex = roundIndex;
gameState.activeMarkers = [];
gameState.playerAngle = 0;
gameState.rotationsCompletedThisRound = 0;
gameState.lastCheckedRotationAngle = 0;
// Si el modo de color es "Por Ronda", elegir un color aleatorio
if (gameState.colorMode === 'per_round') {
currentColorIndex = Math.floor(Math.random() * PASTEL_COLORS.length);
}
createMarkers();
elements.bpm.textContent = rounds[roundIndex].bpm;
}
function completeRound() {
// Crear texto de ronda completada
createRoundCompleteText(`RONDA ${currentRoundIndex + 1} COMPLETADA!`);
// Avanzar a la siguiente ronda después de un retraso
setTimeout(() => {
currentRoundIndex++;
startRound(currentRoundIndex);
}, 2000);
}
function checkHit() {
const currentAngle = (gameState.playerAngle % 360 + 360) % 360;
gameState.totalAttempts++;
let bestPrecision = BASE_PRECISION.MISS;
let hitMarkerIndex = -1;
let closestDiff = Infinity;
gameState.activeMarkers.forEach((marker, index) => {
if (!marker.hit) {
const angleDiff = Math.min(
Math.abs(currentAngle - marker.angle),
Math.abs(currentAngle - (marker.angle + 360)),
Math.abs(currentAngle - (marker.angle - 360))
);
if (angleDiff < closestDiff) {
closestDiff = angleDiff;
hitMarkerIndex = index;
}
}
});
if (hitMarkerIndex !== -1) {
const marker = gameState.activeMarkers[hitMarkerIndex];
bestPrecision = calculatePrecision(closestDiff);
if (bestPrecision.score > 0) {
gameState.score += bestPrecision.score;
gameState.totalHits++;
marker.hit = true;
// Crear partículas y efecto visual
createParticles(marker.originalAngle, bestPrecision.color);
createHitFeedbackText(bestPrecision.text, bestPrecision.color);
// Incrementar combo
gameState.combo++;
if (gameState.combo > 1 && gameState.combo % 5 === 0) {
createComboFeedbackText(`COMBO ${gameState.combo}!`);
}
// Efecto de pulso en el círculo central
gameState.centralReelPulseScale = 1.1;
} else {
// Reiniciar combo si es un golpe MALO o FALLO
gameState.combo = 0;
createHitFeedbackText(bestPrecision.text, BASE_PRECISION.MISS.color);
createComboFeedbackText('COMBO BROKEN!');
}
} else {
// Si no se golpeó ningún marcador, reiniciar combo
gameState.combo = 0;
createHitFeedbackText(BASE_PRECISION.MISS.text, BASE_PRECISION.MISS.color);
createComboFeedbackText('COMBO BROKEN!');
}
updateHUD();
// Animación del HUD
document.querySelectorAll('.hud-item').forEach(item => {
item.classList.add('animate-hud-pulse');
setTimeout(() => item.classList.remove('animate-hud-pulse'), 300);
});
}
function createHitFeedbackText(text, color) {
// En una implementación completa, esto usaría BABYLON.GUI para mostrar texto en 3D
// Por simplicidad, usaremos un enfoque simplificado aquí
console.log(`Hit: ${text}`);
}
function createComboFeedbackText(text) {
console.log(`Combo: ${text}`);
}
function createRoundCompleteText(text) {
console.log(`Round Complete: ${text}`);
}
function showScoreScreen() {
gameState.phase = 'scoreScreen';
elements.finalScore.textContent = gameState.score;
const accuracy = gameState.totalAttempts === 0 ? 100 :
(gameState.totalHits / gameState.totalAttempts * 100);
elements.finalAccuracy.textContent = `${accuracy.toFixed(1)}%`;
elements.finalRank.textContent = getAccuracyRank(accuracy);
elements.scoreScreen.classList.remove('hidden');
}
function resetGameStats() {
gameState.score = 0;
gameState.totalHits = 0;
gameState.totalAttempts = 0;
gameState.combo = 0;
updateHUD();
}
function restartGame() {
elements.pauseMenu.classList.add('hidden');
elements.scoreScreen.classList.add('hidden');
// Mostrar animación de introducción
elements.introAnimationText.classList.remove('hidden');
elements.introAnimationText.classList.add('animate-fade-in-out');
gameState.phase = 'introAnimation';
gameState.globalTime = 0;
// Iniciar juego después de la animación
setTimeout(() => {
elements.introAnimationText.classList.remove('animate-fade-in-out');
elements.introAnimationText.classList.add('hidden');
gameState.phase = 'playing';
resetGameStats();
startRound(0);
}, 2000);
}
// --- Actualización del Juego ---
function updateGame() {
if (gameState.phase !== 'playing') return;
gameState.globalTime += engine.getDeltaTime();
// Actualizar elementos del juego
updatePlayer();
updateMarkers();
// Actualizar efecto de pulso del círculo central
if (gameState.centralReelPulseScale > 1) {
gameState.centralReelPulseScale -= (gameState.centralReelPulseScale - 1) * 0.3;
if (gameState.centralReelPulseScale < 1.005) gameState.centralReelPulseScale = 1;
// Aplicar escala al círculo principal
mainCircleMesh.scaling.set(
gameState.centralReelPulseScale,
gameState.centralReelPulseScale,
gameState.centralReelPulseScale
);
}
}
// --- Configuración de Eventos ---
function setupEventListeners() {
// Teclado
document.addEventListener('keydown', handleKeyDown);
document.addEventListener('keyup', handleKeyUp);
// Touch
document.body.addEventListener('touchstart', handleTouch);
// Botones del menú principal
attachButtonListeners(elements.playButton, () => {
elements.startMenu.classList.add('hidden');
restartGame();
});
attachButtonListeners(elements.settingsButton, () => {
elements.startMenu.classList.add('hidden');
elements.settingsMenu.classList.remove('hidden');
gameState.phase = 'settings';
});
attachButtonListeners(elements.aboutButton, () => {
customAlert('Acerca de', 'Juego de Ritmo Psico Minimalista\nDesarrollado con Babylon.js y Tailwind CSS\nPor RetrogisusDEV\nv1.0.0');
});
// Botón volver al menú principal
attachButtonListeners(elements.backToMainMenuButton, () => {
elements.settingsMenu.classList.add('hidden');
elements.startMenu.classList.remove('hidden');
gameState.phase = 'menu';
});
// Botones del menú de pausa
attachButtonListeners(elements.continueButton, () => {
gameState.phase = 'playing';
elements.pauseMenu.classList.add('hidden');
});
attachButtonListeners(elements.restartButton, () => {
restartGame();
});
attachButtonListeners(elements.exitToMenuButton, () => {
elements.pauseMenu.classList.add('hidden');
elements.startMenu.classList.remove('hidden');
gameState.phase = 'menu';
resetGameStats();
});
// Botón jugar de nuevo
attachButtonListeners(elements.playAgainButton, () => {
elements.scoreScreen.classList.add('hidden');
elements.startMenu.classList.remove('hidden');
gameState.phase = 'menu';
resetGameStats();
});
// Botón cerrar alerta
attachButtonListeners(elements.customAlertCloseButton, hideCustomAlert);
// Botones de configuración
attachButtonListeners(elements.graphicsLow, () => setGraphicsQuality('low'));
attachButtonListeners(elements.graphicsMedium, () => setGraphicsQuality('medium'));
attachButtonListeners(elements.graphicsHigh, () => setGraphicsQuality('high'));
attachButtonListeners(elements.difficultyEasy, () => setDifficulty('easy'));
attachButtonListeners(elements.difficultyNormal, () => setDifficulty('normal'));
attachButtonListeners(elements.difficultyHard, () => setDifficulty('hard'));
attachButtonListeners(elements.shaderOff, () => setShaderEffect('none'));
attachButtonListeners(elements.shaderBloom, () => setShaderEffect('bloom'));
attachButtonListeners(elements.shaderGlow, () => setShaderEffect('glow'));
attachButtonListeners(elements.colorModePerRound, () => setColorMode('per_round'));
attachButtonListeners(elements.colorModeRainbow, () => setColorMode('rainbow'));
attachButtonListeners(elements.colorModeMonochromatic, () => setColorMode('monochromatic'));
}
function attachButtonListeners(buttonElement, handlerFunction) {
buttonElement.addEventListener('click', handlerFunction);
buttonElement.addEventListener('touchstart', (e) => {
e.preventDefault();
handlerFunction(e);
});
}
function handleKeyDown(e) {
if (e.code === 'Escape') {
if (gameState.phase === 'playing') {
gameState.phase = 'paused';
elements.pauseMenu.classList.remove('hidden');
} else if (gameState.phase === 'paused') {
gameState.phase = 'playing';
elements.pauseMenu.classList.add('hidden');
}
return;
}
if (e.code === 'Space') {
if (gameState.phase === 'menu') {
elements.startMenu.classList.add('hidden');
restartGame();
} else if (gameState.phase === 'playing') {
checkHit();
}
e.preventDefault();
}
}
function handleKeyUp(e) {
// Implementar si es necesario
}
function handleTouch(e) {
if (gameState.phase === 'playing') {
e.preventDefault();
checkHit();
}
}
// --- Funciones de Configuración ---
function setGraphicsQuality(quality) {
gameState.currentGraphicsQuality = quality;
updateSettingsUI();
saveSettings();
}
function setDifficulty(difficulty) {
gameState.currentDifficulty = difficulty;
updateSettingsUI();
saveSettings();
}
function setShaderEffect(effect) {
gameState.activeShader = effect;
setupPostProcessing();
updateSettingsUI();
saveSettings();
}
function setColorMode(mode) {
gameState.colorMode = mode;
updateSettingsUI();
saveSettings();
}
function updateSettingsUI() {
// Actualizar botones de calidad gráfica
elements.graphicsLow.classList.toggle('bg-green-300', gameState.currentGraphicsQuality === 'low');
elements.graphicsLow.classList.toggle('text-gray-900', gameState.currentGraphicsQuality === 'low');
elements.graphicsLow.classList.toggle('border-blue-200', gameState.currentGraphicsQuality === 'low');
elements.graphicsLow.classList.toggle('bg-gray-600', gameState.currentGraphicsQuality !== 'low');
elements.graphicsLow.classList.toggle('text-white', gameState.currentGraphicsQuality !== 'low');
elements.graphicsLow.classList.toggle('border-gray-500', gameState.currentGraphicsQuality !== 'low');
elements.graphicsMedium.classList.toggle('bg-green-300', gameState.currentGraphicsQuality === 'medium');
elements.graphicsMedium.classList.toggle('text-gray-900', gameState.currentGraphicsQuality === 'medium');
elements.graphicsMedium.classList.toggle('border-blue-200', gameState.currentGraphicsQuality === 'medium');
elements.graphicsMedium.classList.toggle('bg-gray-600', gameState.currentGraphicsQuality !== 'medium');
elements.graphicsMedium.classList.toggle('text-white', gameState.currentGraphicsQuality !== 'medium');
elements.graphicsMedium.classList.toggle('border-gray-500', gameState.currentGraphicsQuality !== 'medium');
elements.graphicsHigh.classList.toggle('bg-green-300', gameState.currentGraphicsQuality === 'high');
elements.graphicsHigh.classList.toggle('text-gray-900', gameState.currentGraphicsQuality === 'high');
elements.graphicsHigh.classList.toggle('border-blue-200', gameState.currentGraphicsQuality === 'high');
elements.graphicsHigh.classList.toggle('bg-gray-600', gameState.currentGraphicsQuality !== 'high');
elements.graphicsHigh.classList.toggle('text-white', gameState.currentGraphicsQuality !== 'high');
elements.graphicsHigh.classList.toggle('border-gray-500', gameState.currentGraphicsQuality !== 'high');
// Actualizar botones de dificultad
elements.difficultyEasy.classList.toggle('bg-green-300', gameState.currentDifficulty === 'easy');
elements.difficultyEasy.classList.toggle('text-gray-900', gameState.currentDifficulty === 'easy');
elements.difficultyEasy.classList.toggle('border-blue-200', gameState.currentDifficulty === 'easy');
elements.difficultyEasy.classList.toggle('bg-gray-600', gameState.currentDifficulty !== 'easy');
elements.difficultyEasy.classList.toggle('text-white', gameState.currentDifficulty !== 'easy');
elements.difficultyEasy.classList.toggle('border-gray-500', gameState.currentDifficulty !== 'easy');
elements.difficultyNormal.classList.toggle('bg-green-300', gameState.currentDifficulty === 'normal');
elements.difficultyNormal.classList.toggle('text-gray-900', gameState.currentDifficulty === 'normal');