-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
3227 lines (2711 loc) · 95.5 KB
/
game.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as THREE from 'three';
import { FontLoader } from 'three/addons/loaders/FontLoader.js';
import { TextGeometry } from 'three/addons/geometries/TextGeometry.js';
import { VRButton } from 'three/addons/webxr/VRButton.js';
import { XRControllerModelFactory } from 'three/addons/webxr/XRControllerModelFactory.js';
const supportsXR = 0; // Disabled because its buggy
// Ensure that you have the necessary event listeners and variables in place
let controllerMoveCooldown = 0;
let controllerRotateCooldown = 0;
// Initialize variables
let scene, camera, renderer;
let wellSize = {
x: 6,
y: 12,
z: 6
}; // Smaller square playfield
let well = []; // 3D array representing the well
let currentPiece, shadowPiece, nextPiece;
let blockSize = 1;
let baseFallingSpeed = 0.005; // Slower initial falling speed
let fallingSpeed = baseFallingSpeed;
let gameOver = false;
let score = 0;
let layersCleared = 0;
let level = 1;
let isFastDropping = false;
let rotationQueue = [];
let isRotating = false; // New variable to track rotation state
let rotationCooldown = 0;
let piecesPlaced = 0; // Counter for pieces placed
let highScore = 0;
let introMusicPlayed = false;
let totalResources = 0;
let resourcesLoaded = 0;
let backgroundMesh, backgroundGeometry, backgroundMaterial;
let clock;
// Game state variables
let gameState = 'title'; // 'title', 'menu', 'game', 'gameover', 'story'
// Game mode variables
let gameMode = 'arcade'; // 'arcade' or 'story'
let canProceed = true;
// Define game actions
const gameActions = [
'Left',
'Right',
'Forward',
'Backward',
'Rotate X Positive',
'Rotate X Negative',
'Rotate Y Positive',
'Rotate Y Negative',
'Rotate Z Positive',
'Rotate Z Negative',
'Fast Drop',
'Drop Piece',
'Confirm',
'Cancel'
];
// Default key bindings
const defaultKeyBindings = {
'Left': 'ArrowLeft',
'Right': 'ArrowRight',
'Forward': 'ArrowUp',
'Backward': 'ArrowDown',
'Rotate Y Negative': 'KeyQ', // Rotate left around Y-axis
'Rotate Y Positive': 'KeyE', // Rotate right around Y-axis
'Rotate X Negative': 'KeyA', // Rotate left around X-axis
'Rotate X Positive': 'KeyD', // Rotate right around X-axis
'Rotate Z Negative': 'KeyW', // Rotate left around Z-axis
'Rotate Z Positive': 'KeyS', // Rotate right around Z-axis
'Fast Drop': 'KeyF',
'Drop Piece': 'Space',
'Confirm': 'Enter',
'Cancel': 'Escape'
};
let keyBindings = {}; // To store current key bindings
let keyToActionMap = {}; // Reverse map for quick lookup
let keyConfigOptions = gameActions; // Use the game actions defined earlier
let selectedKeyConfigOption = 0;
let waitingForKeyBinding = false;
// Story mode variables
let storySegments = [{
text: [
"Hey! I bet I can beat you at this puzzle game today!",
"Don't worry, I'll share a few tricks along the way.\nJust know I'm not going easy on you."
],
background: "images/background1.png",
character1: "images/character1.png",
character2: "images/player.png",
opponentHP: 25,
timeLimit: 90,
storyMusic: 'story1',
gameMusic: 'game1'
},
{
text: [
"Well, well! Ready to get schooled? I may not be the best, but I’m no beginner either.",
"Bring on the next round!"
],
background: "images/background2.png",
character1: "images/character2.png",
character2: "images/player.png",
opponentHP: 50,
timeLimit: 140,
storyMusic: 'story2',
gameMusic: 'game2'
},
{
text: [
"I’ve heard of you, Boy. But reputation means nothing here.",
"Understand this ——I don’t play for fun, and I certainly don’t lose.",
"Only one of us leaves this game victorious, and I have no intention of it being you."
],
background: "images/background3.png",
character1: "images/character3.png",
character2: "images/player.png",
opponentHP: 75,
timeLimit: 200,
storyMusic: 'story3',
gameMusic: 'game3'
},
{
text: ["Congratulations!", "You've completed your journey!"],
background: "images/background3.png",
character1: "images/character3.png",
character2: "images/player.png",
opponentHP: 0,
timeLimit: 0
}
];
let currentStorySegment = 0;
let opponentHP = 100;
let timeRemaining = 120;
let initialTimeLimit = 120;
// Typewriter effect variables
let currentLine = 0;
let currentCharIndex = 0;
let isTyping = false;
let typewriterInterval;
// Mouse controls
let isMouseDown = false;
let prevMouse = {
x: 0,
y: 0
};
let rotationSpeed = 0.005;
let verticalAngle = Math.PI / 4; // Initial vertical angle
let minVerticalAngle = 0.1; // Can't look below horizontal
let maxVerticalAngle = Math.PI / 2 - 0.1; // Can't look directly down
let horizontalAngle = 0; // Initial horizontal angle
// Smooth rotation variables
let targetRotation = {
x: 0,
y: 0,
z: 0
};
let rotationStep = Math.PI / 20; // Controls the smoothness of rotation
// Screen shake variables
let shakeDuration = 0;
let shakeIntensity = 0;
// Font for 3D text
let font;
// Label group
let labelGroup;
// Menu variables
let menuOptions = ['Story Mode', 'Arcade Mode', 'Reconfigure Keys'];
let selectedOption = 0;
// Audio variables
let bgm; // Background music
let sfx; // Sound effects
let voiceOver; // Voice overs
let introMusic; // Intro music
let allResourcesLoadedCalled = false;
// Add these global variables
let isVRMode = false;
let interactiveObjects = []; // For menu interactions
let tempMatrix = new THREE.Matrix4();
let leftController = null;
let rightController = null;
// Touch Controls Variables
let touchControlsVisible = false;
let joystick = {
base: null,
thumb: null,
centerX: 0,
centerY: 0,
maxDistance: 60,
onMove: function(dx, dy) {},
};
function isMobileDevice() {
return 'ontouchstart' in window || navigator.maxTouchPoints > 0;
//return 1;
}
let isMobile = isMobileDevice(); // Add this at the top of your script or inside init()
init();
//animate();
renderer.setAnimationLoop(animate);
function init() {
// Check if the device is mobile
isMobile = isMobileDevice();
// Initialize touch controls if on mobile
if (isMobile) {
initTouchControls();
}
// Show the loading screen
document.getElementById('loading-screen').style.display = 'flex';
// Initialize audio
initAudio();
// Count the total number of resources to load
countTotalResources();
// Load font
loadFont();
// Preload images
preloadImages();
// Preload videos
preloadVideos();
clock = new THREE.Clock();
// Add event listeners
addEventListeners();
loadKeyBindings();
// Create VR button only if WebXR Is poss
if (supportsXR)
{
document.body.appendChild( VRButton.createButton( renderer ) );
}
// Set up the scene
scene = new THREE.Scene();
// Set up the camera
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
// Improved default viewpoint
let centerX = (wellSize.x * blockSize) / 2 - blockSize / 2;
let centerY = (wellSize.y * blockSize) / 2 - blockSize / 2;
let centerZ = (wellSize.z * blockSize) / 2 - blockSize / 2;
let radius = 20; // Distance from the center
updateCameraPosition();
// Set up the renderer
renderer = new THREE.WebGPURenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
if (supportsXR)
{
renderer.xr.enabled = true;
// Event listeners to track VR mode
renderer.xr.addEventListener('sessionstart', () => { isVRMode = true; });
renderer.xr.addEventListener('sessionend', () => { isVRMode = false; });
// Create VR controllers
const controllerModelFactory = new XRControllerModelFactory();
// Left controller for movement
leftController = renderer.xr.getController(0);
leftController.addEventListener('connected', (event) => setupController(event, 'left'));
leftController.addEventListener('disconnected', () => clearController('left'));
leftController.addEventListener('selectstart', onSelectStart);
leftController.addEventListener('selectend', onSelectEnd);
scene.add(leftController);
const leftControllerGrip = renderer.xr.getControllerGrip(0);
leftControllerGrip.add(controllerModelFactory.createControllerModel(leftControllerGrip));
scene.add(leftControllerGrip);
// Right controller for rotation
rightController = renderer.xr.getController(1);
rightController.addEventListener('connected', (event) => setupController(event, 'right'));
rightController.addEventListener('disconnected', () => clearController('right'));
rightController.addEventListener('selectstart', onSelectStart);
rightController.addEventListener('selectend', onSelectEnd);
scene.add(rightController);
const rightControllerGrip = renderer.xr.getControllerGrip(1);
rightControllerGrip.add(controllerModelFactory.createControllerModel(rightControllerGrip));
scene.add(rightControllerGrip);
}
else
{
document.body.appendChild( getFullscreenButton( renderer ) );
// Reference to the fullscreen button
const fullscreenButton = document.getElementById('fullscreen-button');
// Function to hide the fullscreen button with transition
function hideFullscreenButton() {
fullscreenButton.classList.add('hidden');
fullscreenButton.classList.remove('visible');
}
// Function to show the fullscreen button with transition
function showFullscreenButton() {
fullscreenButton.classList.add('visible');
fullscreenButton.classList.remove('hidden');
}
// Initialize the button as visible
fullscreenButton.classList.add('visible');
// Listen for fullscreen change events
document.addEventListener('fullscreenchange', () => {
if (document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement) {
hideFullscreenButton();
} else {
showFullscreenButton();
}
});
}
}
/* Touchscreen controls */
function initTouchControls() {
const touchControls = document.getElementById('touch-controls');
// Initialize D-pad buttons
const dpadButtons = document.querySelectorAll('.dpad-button');
dpadButtons.forEach(button => {
button.addEventListener('touchstart', onDpadButtonPress, false);
button.addEventListener('touchend', onDpadButtonRelease, false);
});
// Action buttons event listeners
const rotateButtons = document.getElementsByClassName('rotate-button');
for (let button of rotateButtons) {
button.addEventListener('touchstart', onActionButtonPress, false);
button.addEventListener('touchend', onActionButtonRelease, false);
}
const fastDropButton = document.getElementById('fast-drop-button');
fastDropButton.addEventListener('touchstart', onActionButtonPress, false);
fastDropButton.addEventListener('touchend', onActionButtonRelease, false);
const dropPieceButton = document.getElementById('drop-piece-button');
dropPieceButton.addEventListener('touchstart', onActionButtonPress, false);
dropPieceButton.addEventListener('touchend', onActionButtonRelease, false);
// Initialize Camera Controls
const cameraControls = document.getElementById('camera-controls');
cameraControls.addEventListener('touchstart', onCameraTouchStart, false);
cameraControls.addEventListener('touchmove', onCameraTouchMove, false);
cameraControls.addEventListener('touchend', onCameraTouchEnd, false);
}
// Existing Camera Control Handlers
let isCameraTouching = false;
let lastCameraTouchX = 0;
let lastCameraTouchY = 0;
let cameraRotationSpeed = 0.005; // Adjust rotation sensitivity as needed
function onCameraTouchStart(event) {
if (isVRMode) return; // Disable camera touch controls in VR mode
if (event.touches.length === 1) { // Single touch
isCameraTouching = true;
lastCameraTouchX = event.touches[0].clientX;
lastCameraTouchY = event.touches[0].clientY;
// Prevent touch event from propagating to other elements
event.preventDefault();
event.stopPropagation();
}
}
function onCameraTouchMove(event) {
if (isVRMode) return; // Disable camera touch controls in VR mode
if (isCameraTouching && event.touches.length === 1) {
let touch = event.touches[0];
let deltaX = touch.clientX - lastCameraTouchX;
let deltaY = touch.clientY - lastCameraTouchY;
// Update horizontal and vertical angles based on touch movement
horizontalAngle -= deltaX * cameraRotationSpeed;
verticalAngle += deltaY * cameraRotationSpeed;
// Clamp vertical angle to prevent flipping
verticalAngle = Math.max(minVerticalAngle, Math.min(maxVerticalAngle, verticalAngle));
// Update camera position based on new angles
updateCameraPosition();
// Update last touch positions
lastCameraTouchX = touch.clientX;
lastCameraTouchY = touch.clientY;
// Prevent touch event from propagating to other elements
event.preventDefault();
event.stopPropagation();
}
}
function onCameraTouchEnd(event) {
if (isVRMode) return; // Disable camera touch controls in VR mode
isCameraTouching = false;
// Prevent touch event from propagating to other elements
event.preventDefault();
event.stopPropagation();
}
let lastActionTime = 0;
const actionCooldown = 60; // 6 cooldown
function handleActionWithThrottle(action, callback) {
const currentTime = Date.now();
if (currentTime - lastActionTime > actionCooldown) {
callback();
lastActionTime = currentTime;
}
}
// Usage within touch event handlers
function onActionButtonPress(event) {
event.preventDefault();
event.stopPropagation();
const action = event.target.getAttribute('data-action');
handleActionWithThrottle(action, () => handleTouchAction(action, true));
}
function onActionButtonRelease(event) {
event.preventDefault();
event.stopPropagation();
const action = event.target.getAttribute('data-action');
handleTouchAction(action, false);
}
// D-Pad Event Handlers remain unchanged
function onDpadButtonPress(event) {
event.preventDefault();
const direction = event.target.getAttribute('data-direction');
handleDpadAction(direction, true);
}
function onDpadButtonRelease(event) {
event.preventDefault();
const direction = event.target.getAttribute('data-direction');
handleDpadAction(direction, false);
}
// Function to handle D-pad actions
function handleDpadAction(direction, isPressed) {
if (isPressed) {
switch(direction) {
case 'up':
handleMovement('Forward');
break;
case 'down':
handleMovement('Backward');
break;
case 'left':
handleMovement('Left');
break;
case 'right':
handleMovement('Right');
break;
}
}
}
function handleTouchAction(action, isPressed) {
if (isPressed) {
if (action === 'Fast Drop') {
isFastDropping = true;
} else if (action === 'Drop Piece') {
dropPieceToBottom();
} else {
// Rotation actions
let rotation = { x: 0, y: 0, z: 0 };
switch (action) {
case 'Rotate X Positive':
rotation.x = Math.PI / 2;
break;
case 'Rotate X Negative':
rotation.x = -Math.PI / 2;
break;
case 'Rotate Y Positive':
rotation.y = Math.PI / 2;
break;
case 'Rotate Y Negative':
rotation.y = -Math.PI / 2;
break;
case 'Rotate Z Positive':
rotation.z = Math.PI / 2;
break;
case 'Rotate Z Negative':
rotation.z = -Math.PI / 2;
break;
}
handleRotation(rotation);
}
} else {
if (action === 'Fast Drop') {
isFastDropping = false;
}
}
}
function handleJoystickMovement() {
if (!currentPiece) return;
let deltaPosition = new THREE.Vector3();
const threshold = 0.3; // Deadzone threshold
const moveX = joystick.normalizedX || 0;
const moveY = joystick.normalizedY || 0;
if (moveX > threshold) {
deltaPosition.x = blockSize;
} else if (moveX < -threshold) {
deltaPosition.x = -blockSize;
}
if (moveY > threshold) {
deltaPosition.z = blockSize;
} else if (moveY < -threshold) {
deltaPosition.z = -blockSize;
}
// Apply movement if any
if (deltaPosition.lengthSq() > 0) {
currentPiece.position.add(deltaPosition);
// Check collision after movement
if (checkMovementCollision()) {
// Revert movement if collision detected
currentPiece.position.sub(deltaPosition);
} else {
updateShadowPiece();
playSFX('move'); // Optional: Play move sound effect
}
}
}
function showTouchControls() {
if (!isMobile) return; // Only show on mobile devices
const touchControls = document.getElementById('touch-controls');
touchControls.classList.remove('hidden');
touchControlsVisible = true;
}
function hideTouchControls() {
const touchControls = document.getElementById('touch-controls');
touchControls.classList.add('hidden');
touchControlsVisible = false;
}
/* End Virtual touchscreen */
// Setup controller function
function setupController(event, hand) {
const controller = event.target;
controller.userData.inputSource = event.data; // Store the inputSource
controller.userData.gamepad = event.data.gamepad; // Store the gamepad
if (hand === 'left') leftController = controller;
if (hand === 'right') rightController = controller;
}
function clearController(hand) {
if (hand === 'left') leftController = null;
if (hand === 'right') rightController = null;
}
function getFullscreenButton(renderer) {
var button = document.createElement('button');
button.id = 'fullscreen-button'; // Assign an ID for easy reference
button.style.position = 'absolute';
button.style.right = '20px';
button.style.bottom = '20px';
button.style.width = '100px';
button.style.border = '0';
button.style.padding = '8px';
button.style.cursor = 'pointer';
button.style.backgroundColor = '#000';
button.style.color = '#fff';
button.style.fontFamily = 'sans-serif';
button.style.fontSize = '13px';
button.style.fontStyle = 'normal';
button.style.textAlign = 'center';
button.style.zIndex = '999';
button.textContent = 'FULLSCREEN';
button.onclick = function() {
let fullscreenElement = document.getElementById('main-container');
if (!document.fullscreenElement) {
if (fullscreenElement.requestFullscreen) {
fullscreenElement.requestFullscreen();
}
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
}
}
};
return button;
}
function loadKeyBindings() {
let storedBindings = localStorage.getItem('keyBindings');
if (storedBindings) {
keyBindings = JSON.parse(storedBindings);
} else {
keyBindings = {
...defaultKeyBindings
};
}
buildKeyToActionMap();
}
function saveKeyBindings() {
localStorage.setItem('keyBindings', JSON.stringify(keyBindings));
}
function buildKeyToActionMap() {
keyToActionMap = {};
for (let action in keyBindings) {
keyToActionMap[keyBindings[action]] = action;
}
}
function addEventListeners() {
// Add event listeners
window.addEventListener('resize', onWindowResize, false);
document.addEventListener('keydown', onDocumentKeyDown, false);
document.addEventListener('keyup', onDocumentKeyUp, false);
document.addEventListener('mousedown', onDocumentMouseDown, false);
document.addEventListener('mousemove', onDocumentMouseMove, false);
document.addEventListener('mouseup', onDocumentMouseUp, false);
}
function loadFont() {
let fontLoader = new FontLoader();
fontLoader.load(
'https://threejs.org/examples/fonts/helvetiker_regular.typeface.json',
function(loadedFont) {
font = loadedFont;
resourceLoaded(); // Call when font is loaded
},
undefined,
function(err) {
console.error('An error happened while loading the font.');
}
);
}
function preloadImages() {
storySegments.forEach(segment => {
if (segment.background) {
let img = new Image();
img.src = segment.background;
img.onload = resourceLoaded;
}
if (segment.character1) {
let img = new Image();
img.src = segment.character1;
img.onload = resourceLoaded;
}
if (segment.character2) {
let img = new Image();
img.src = segment.character2;
img.onload = resourceLoaded;
}
});
}
function preloadVideos() {
const introVideo = document.getElementById('intro-video');
introVideo.addEventListener('loadeddata', resourceLoaded, {
once: true
});
const cutsceneVideo = document.getElementById('cutscene-video');
cutsceneVideo.addEventListener('loadeddata', resourceLoaded, {
once: true
});
}
function resourceLoaded() {
resourcesLoaded++;
console.log(`Resource Loaded: ${resourcesLoaded}/${totalResources}`);
updateLoadingBar();
if (resourcesLoaded >= totalResources && !allResourcesLoadedCalled) {
allResourcesLoadedCalled = true;
console.log('All resources loaded. Calling onAllResourcesLoaded()');
// Hide the loading bar
let loadingBarContainer = document.getElementById('loading-bar-container');
if (loadingBarContainer) {
loadingBarContainer.style.display = 'none';
}
onAllResourcesLoaded();
}
}
function updateLoadingBar() {
let percentage = Math.round((resourcesLoaded / totalResources) * 100);
let loadingBar = document.getElementById('loading-bar');
loadingBar.style.width = percentage + '%';
}
function onAllResourcesLoaded() {
// Update the loading screen to prompt for user interaction
let loadingContent = document.getElementById('loading-content');
loadingContent.innerHTML += `
<p style="font-size: 24px;">Click, tap, or press any key to continue</p>
`;
// Add event listeners for user interaction
function onUserInteraction() {
// Remove the event listeners to prevent multiple triggers
document.removeEventListener('keydown', onUserInteraction);
document.removeEventListener('mousedown', onUserInteraction);
document.removeEventListener('touchstart', onUserInteraction);
// Hide the loading screen
document.getElementById('loading-screen').style.display = 'none';
// Proceed to play the intro
playIntro();
}
document.addEventListener('keydown', onUserInteraction);
document.addEventListener('mousedown', onUserInteraction);
document.addEventListener('touchstart', onUserInteraction);
}
function countTotalResources() {
totalResources = 0; // Initialize to zero
// Count fonts
totalResources += 1;
// Count audio files
for (let key in bgm) {
if (Array.isArray(bgm[key])) {
totalResources += bgm[key].length;
} else if (bgm[key] instanceof Howl) {
totalResources += 1;
} else if (typeof bgm[key] === 'object') {
for (let subKey in bgm[key]) {
if (bgm[key][subKey] instanceof Howl) {
totalResources += 1;
}
}
}
}
for (let segment in voiceOver) {
totalResources += voiceOver[segment].length;
}
// Count images in story segments
storySegments.forEach(segment => {
if (segment.background) totalResources += 1;
if (segment.character1) totalResources += 1;
if (segment.character2) totalResources += 1;
});
totalResources += 6;
console.log(`Total Resources to Load: ${totalResources}`);
}
function initAudio() {
// Background music
bgm = {
title: new Howl({
src: ['audio/title.mp3'],
loop: true,
onload: resourceLoaded
}),
menu: new Howl({
src: ['audio/menu.mp3'],
loop: true,
onload: resourceLoaded
}),
story: new Howl({
src: ['audio/default_story.mp3'],
loop: true,
onload: resourceLoaded
}),
game: [
new Howl({
src: ['audio/default_game1.mp3'],
loop: true,
onload: resourceLoaded
}),
new Howl({
src: ['audio/default_game2.mp3'],
loop: true,
onload: resourceLoaded
})
],
win: new Howl({
src: ['audio/win.mp3'],
loop: false,
volume: 0.7,
onload: resourceLoaded
}),
// New properties for specific tracks
storyTracks: {
story1: new Howl({
src: ['audio/story1_music.mp3'],
loop: true,
volume: 0.25,
onload: resourceLoaded
}),
story2: new Howl({
src: ['audio/story2_music.mp3'],
loop: true,
volume: 0.25,
onload: resourceLoaded
}),
story3: new Howl({
src: ['audio/story3_music.mp3'],
loop: true,
volume: 0.25,
onload: resourceLoaded
}),
// Add more story tracks as needed
},
gameTracks: {
game1: new Howl({
src: ['audio/game1.mp3'],
loop: true,
onload: resourceLoaded
}),
game2: new Howl({
src: ['audio/game2.mp3'],
loop: true,
onload: resourceLoaded
}),
game3: new Howl({
src: ['audio/game3.mp3'],
loop: true,
onload: resourceLoaded
}),
}
};
// Sound effects (no changes needed here)
sfx = {
clearLine: new Howl({
src: ['audio/clearline.mp3'],
onload: resourceLoaded
}),
rotate: new Howl({
src: ['audio/rotate.mp3'],
onload: resourceLoaded
}),
move: new Howl({
src: ['audio/move.mp3'],
onload: resourceLoaded
}),
drop: new Howl({
src: ['audio/drop.mp3'],
onload: resourceLoaded
}),
explosion: new Howl({
src: ['audio/explosion.mp3'],
onload: resourceLoaded
})
};
// Voice overs
voiceOver = {
segment0: [
new Howl({
src: ['audio/story1_v1.mp3'],
onload: resourceLoaded
}),
new Howl({
src: ['audio/story1_v2.mp3'],
onload: resourceLoaded
})
],
segment1: [
new Howl({
src: ['audio/story2_v1.mp3'],
onload: resourceLoaded
}),
new Howl({
src: ['audio/story2_v2.mp3'],
onload: resourceLoaded
})
],
segment2: [
new Howl({
src: ['audio/story3_v1.mp3'],
onload: resourceLoaded
}),
new Howl({
src: ['audio/story3_v2.mp3'],
onload: resourceLoaded
}),
new Howl({
src: ['audio/story3_v3.mp3'],
onload: resourceLoaded
})
],
// Add more segments as needed
};
// Winning music
bgm.win = new Howl({
src: ['audio/win.mp3'],
loop: false,
volume: 0.7,
onload: resourceLoaded
});
// Intro music
introMusic = new Howl({
src: ['audio/intromusic.mp3'],
loop: true,
volume: 0.5,
onload: resourceLoaded
});
}