-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgame.js
More file actions
862 lines (716 loc) · 31.5 KB
/
game.js
File metadata and controls
862 lines (716 loc) · 31.5 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
import * as THREE from 'three';
import { Player } from './player.js';
import { DirectModelEnvironment } from './direct-model-environment.js';
import { ObstacleManager } from './obstacles.js';
import { CollectableManager } from './collectables.js';
import { PowerUpManager } from './powerups.js';
import { UIManager } from './ui.js';
import { InputManager } from './input.js';
import { GAME_CONFIG, SCORING, SPAWN_CONFIG, PHYSICS, COUNTDOWN_CONFIG } from './constants.js';
import { GameStateManager, STATES } from './game-state.js';
import { LeaderboardManager } from './leaderboard.js';
import { PlayerRegistration } from './player-registration.js';
export class Game {
constructor() {
// Core Three.js components
this.scene = null;
this.camera = null;
this.renderer = null;
// Game managers
this.player = null;
this.environment = null;
this.obstacleManager = null;
this.collectableManager = null;
this.powerUpManager = null;
this.uiManager = null;
this.inputManager = null;
// New managers for state & leaderboard
this.stateManager = new GameStateManager();
this.leaderboardManager = new LeaderboardManager();
// Performance optimization: Cache playing state to avoid checking every frame
this.isCurrentlyPlaying = false;
// Game state
this.gameActive = true;
this.gamePaused = false; // Add pause state
this.gameSpeed = { value: GAME_CONFIG.INITIAL_SPEED }; // Using object for reference
// State management
this.stateManager = new GameStateManager();
this.leaderboardManager = new LeaderboardManager();
this.playerRegistration = null;
// Countdown state
this.countdownActive = false;
this.countdownTimeoutId = null;
this.animationId = null;
this.initPromise = this.init();
}
async init() { // Make init async
this.setupThreeJS();
await this.createManagers(); // Await manager creation
this.setupInputManager();
// Check player registration BEFORE starting game
this.checkPlayerRegistration();
}
setupThreeJS() {
// Scene setup
this.scene = new THREE.Scene();
// Camera setup
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
this.camera.position.z = 5;
this.camera.position.y = 2;
this.camera.lookAt(0, 0, 0);
// Enhanced renderer setup with mobile optimization
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
const rendererOptions = {
antialias: !isMobile, // Disable antialiasing on mobile for better performance
alpha: false,
stencil: false,
powerPreference: isMobile ? 'low-power' : 'high-performance'
};
this.renderer = new THREE.WebGLRenderer(rendererOptions);
// Set proper pixel ratio for crisp rendering on high-DPI displays
const pixelRatio = Math.min(window.devicePixelRatio, isMobile ? 2 : 3); // Limit to 2 on mobile
this.renderer.setPixelRatio(pixelRatio);
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.shadowMap.enabled = false;
// Set output color space for better color accuracy
this.renderer.outputColorSpace = THREE.SRGBColorSpace;
// Add canvas styles for proper mobile display
this.renderer.domElement.style.display = 'block';
this.renderer.domElement.style.touchAction = 'none'; // Prevent scrolling on touch
document.getElementById('game-container').appendChild(this.renderer.domElement);
// Store mobile flag for later use
this.isMobile = isMobile;
}
async createManagers() { // Make createManagers async
// Create managers in dependency order
this.environment = new DirectModelEnvironment(this.scene);
this.player = new Player(this.scene);
await this.player.initialize(); // Await player initialization
this.obstacleManager = new ObstacleManager(this.scene);
this.collectableManager = new CollectableManager(this.scene);
await this.collectableManager.initializeModelLoading(); // Await model loading before game starts
this.powerUpManager = new PowerUpManager(this.scene, this.player);
this.uiManager = new UIManager(this);
// Set game controller references so managers can access current game state
this.environment.setGameController(this);
this.obstacleManager.setGameController(this);
this.collectableManager.setGameController(this);
this.uiManager.setGameController(this);
// Set game speed reference for power-ups
this.powerUpManager.setGameSpeedReference(this.gameSpeed);
// Set collectable manager reference for power-ups (to remove aerial stars)
this.powerUpManager.setCollectableManager(this.collectableManager);
// Set obstacle manager reference for power-ups (for water pipe targeting)
this.powerUpManager.setObstacleManager(this.obstacleManager);
// Setup resize handling
this.setupResizeHandling();
}
setupInputManager() {
// Cleanup existing input manager if it exists
if (this.inputManager && typeof this.inputManager.destroy === 'function') {
this.inputManager.destroy();
}
this.inputManager = new InputManager(this.player, this);
// Optional: Enable mobile controls
this.inputManager.setupMobileControls();
}
// ------------------------------------------------------------------
// STATE & UI EVENT HANDLERS
// ------------------------------------------------------------------
setupStateHandlers() {
// React to state changes
this.stateManager.onStateChange((state) => {
// Performance optimization: Cache playing state
this.isCurrentlyPlaying = (state === STATES.PLAYING);
switch (state) {
case STATES.SPLASH:
this.uiManager.showSplash();
break;
case STATES.START_MENU:
this.uiManager.hideSplash();
this.uiManager.hideLeaderboard();
this.uiManager.hideUserInfo();
this.uiManager.showStartMenu();
// Pause game logic
this.gameActive = false;
break;
case STATES.PLAYING:
this.uiManager.hideStartMenu();
this.uiManager.hideLeaderboard();
this.uiManager.hideUserInfo();
this.restartGame(); // Ensure fresh run
this.gameActive = true;
break;
case STATES.USER_INFO:
this.uiManager.showUserInfo();
break;
case STATES.LEADERBOARD:
// Update table then show
this.uiManager.updateLeaderboard(this.leaderboardManager.getScores());
this.uiManager.hideUserInfo();
this.uiManager.showLeaderboard();
// Stop gameplay until menu
this.gameActive = false;
break;
}
});
// Wire UI events
this.uiManager.onStartButtonClicked = () => this.handleStartGame();
this.uiManager.onUserInfoSubmitted = (name) => this.handleUserInfo(name);
this.uiManager.onLeaderboardBack = () => this.stateManager.returnToMenu();
}
handleStartGame() {
this.stateManager.startGame(); // Triggers PLAYING state
}
handleUserInfo(name) {
// Save info into state manager
this.stateManager.saveUserInfo(name);
// Persist to leaderboard
this.leaderboardManager.addScore(this.stateManager.getPlayerData());
// Show leaderboard
this.stateManager.showLeaderboard();
}
getGameSpeed() {
return this.gameSpeed.value;
}
// Public methods for managers to access current game state
// getPlayerPosition() is already defined below
// isGameActive() is already defined below
startSpawning() {
this.obstacleManager.startSpawning();
this.environment.startSpawning();
this.collectableManager.startSpawning();
}
updateGameLogic() {
if (!this.gameActive || this.gamePaused) return;
// Pause most game logic if player is stumbling
if (this.player.isStumbling) {
// Only update player position to handle stumble animation, but pause everything else
this.player.updatePosition(
this.powerUpManager.getFlyingStatus(),
this.powerUpManager.getWaterSlideObjects(),
this.gameSpeed.value
);
return; // Skip all other game logic during stumble
}
// Update player position
this.player.updatePosition(
this.powerUpManager.getFlyingStatus(),
this.powerUpManager.getWaterSlideObjects(),
this.gameSpeed.value // Pass game speed for animation state management
);
// Update all objects
this.updateAllObjects();
// Check collisions
this.checkCollisions();
// NEW: Fair power-up spawning system (like Subway Surfers)
if (this.collectableManager.shouldSpawnPowerUp()) {
const playerZ = this.player.getPosition().z;
const obstacles = this.obstacleManager.getObstacles();
this.collectableManager.createPowerUp(playerZ, obstacles);
this.collectableManager.markPowerUpSpawned();
}
// Handle aerial collectibles when flying
if (this.powerUpManager.getFlyingStatus() && Math.random() < SPAWN_CONFIG.AERIAL_SPAWN_CHANCE) {
this.collectableManager.createAerialCollectable(this.player.getPosition());
}
// Handle solar orbs when solar boost is active
if (this.powerUpManager.getSolarBoostStatus() && Math.random() < SPAWN_CONFIG.SOLAR_ORB_SPAWN_CHANCE) {
this.collectableManager.createSolarOrb(this.player.getPosition());
}
// Update camera
this.updateCamera();
// Update game speed and score
this.updateGameSpeed();
// Update power-up timers
const frameTime = 1000 / 60; // Assuming 60 FPS
this.powerUpManager.updateTimers(frameTime);
// Update UI timers with same deltaTime
this.uiManager.updatePowerUpTimers(frameTime);
// Apply magnet effect if solar boost is active
if (this.powerUpManager.getSolarBoostStatus()) {
this.collectableManager.applyMagnetEffect(
this.player.getPosition(),
PHYSICS.MAGNET_RADIUS,
PHYSICS.MAGNET_PULL_SPEED
);
}
}
updateAllObjects() {
// Update obstacles and gain score for passed obstacles
const obstacleScore = this.obstacleManager.updateObstacles(
this.gameSpeed.value,
this.camera.position.z,
this.gameActive
);
this.uiManager.updateScore(obstacleScore);
// Update buildings
this.environment.updateBuildings(this.gameSpeed.value, this.camera.position.z);
// Update collectables
this.collectableManager.updateCollectables(this.gameSpeed.value, this.camera.position.z);
// Update environment
this.environment.updateGround(this.camera.position.z);
// Update water slide if active
this.powerUpManager.updateWaterSlidePosition(this.gameSpeed.value);
}
checkCollisions() {
const playerBox = this.player.getCollisionBox();
// Check obstacle collisions (if not invincible, not stumbling, and not flying)
if (!this.powerUpManager.getInvincibilityStatus() && !this.player.isStumbling && !this.powerUpManager.getFlyingStatus()) {
const collision = this.obstacleManager.checkCollisions(
playerBox,
this.powerUpManager.getWaterSlideObjects(),
this.powerUpManager.getWaterSlideStatus()
);
if (collision) {
// Collision detected with obstacle
// Player stumbling state checked
// Try to trigger stumble animation with game over callback
// Attempting to trigger stumble animation
const stumbleTriggered = this.player.triggerStumble(() => this.gameOver());
// Stumble trigger result processed
if (!stumbleTriggered) {
// If stumble animation not available, immediate game over
// Stumble animation not available - Game Over
this.gameOver();
return;
}
// Stumble was successfully triggered, continue playing
// Player stumbled but continues playing
return;
}
}
// Check collectable collisions
const collectedItems = this.collectableManager.checkCollisions(playerBox);
this.handleCollectedItems(collectedItems);
}
handleCollectedItems(collectedItems) {
for (const itemType of collectedItems) {
// Item collected successfully
switch (itemType) {
// Regular collectibles
case 'blueprint':
this.uiManager.updateCollectables('blueprint', SCORING.BLUEPRINT);
break;
case 'waterDrop':
this.uiManager.updateCollectables('waterDrop', SCORING.WATER_DROP);
break;
case 'energyCell':
this.uiManager.updateCollectables('energyCell', SCORING.ENERGY_CELL);
break;
case 'aerialStar':
this.uiManager.updateScore(SCORING.AERIAL_STAR);
// Collected aerial star bonus
break;
case 'solarOrb':
this.uiManager.updateScore(SCORING.SOLAR_ORB);
// Collected solar orb bonus
break;
// Power-ups
case 'hardHat':
this.uiManager.updateScore(SCORING.POWER_UP);
this.powerUpManager.activateInvincibility();
this.uiManager.addPowerUpToUI('🛡️ Hard Hat Shield', 5);
this.collectableManager.markPowerUpSpawned(); // Reset fair spawning timer
break;
case 'helicopter':
this.uiManager.updateScore(SCORING.POWER_UP);
this.powerUpManager.activateHelicopter();
this.uiManager.addPowerUpToUI('Jetpack', 10);
this.collectableManager.markPowerUpSpawned(); // Reset fair spawning timer
break;
case 'solarPower':
this.uiManager.updateScore(SCORING.POWER_UP);
this.powerUpManager.activateSolarPower();
this.uiManager.addPowerUpToUI('🌟 Solar Power Boost', 8);
this.collectableManager.markPowerUpSpawned(); // Reset fair spawning timer
break;
case 'windPower':
this.uiManager.updateScore(SCORING.POWER_UP);
this.powerUpManager.activateWindPower();
this.uiManager.addPowerUpToUI('💨 Wind Power', 15);
this.collectableManager.markPowerUpSpawned(); // Reset fair spawning timer
break;
case 'waterPipeline':
this.uiManager.updateScore(SCORING.POWER_UP);
this.powerUpManager.activateWaterSlide();
this.uiManager.addPowerUpToUI('fire-hydrant', 12);
this.collectableManager.markPowerUpSpawned(); // Reset fair spawning timer
break;
}
}
}
updateCamera() {
// Smoothly update camera's x position to follow the player
const cameraTargetX = this.player.getPosition().x;
this.camera.position.x += (cameraTargetX - this.camera.position.x) * GAME_CONFIG.CAMERA_FOLLOW_SPEED;
// Enhanced camera Y tracking - different behavior for flying vs. ground
let cameraTargetY;
if (this.powerUpManager && this.powerUpManager.getFlyingStatus()) {
// During flying: higher camera position with smoother tracking
cameraTargetY = this.player.getPosition().y + 1.0; // Closer to flying player
this.camera.position.y += (cameraTargetY - this.camera.position.y) * (GAME_CONFIG.CAMERA_FOLLOW_SPEED * 0.8); // Smoother for flying
} else {
// Normal ground tracking
cameraTargetY = this.player.getPosition().y + 1.5;
this.camera.position.y += (cameraTargetY - this.camera.position.y) * GAME_CONFIG.CAMERA_FOLLOW_SPEED;
}
// Move camera forward
this.camera.position.z -= this.gameSpeed.value;
this.player.setPosition(
this.player.getPosition().x,
this.player.getPosition().y,
this.camera.position.z - 5
);
}
updateGameSpeed() {
// Time-based speed increment to prevent frame rate affecting game speed
const now = performance.now();
if (!this.lastSpeedUpdate) {
this.lastSpeedUpdate = now;
}
const deltaTime = now - this.lastSpeedUpdate;
if (deltaTime >= 16.67) { // ~60fps equivalent (1000ms / 60fps = 16.67ms)
this.gameSpeed.value += GAME_CONFIG.SPEED_INCREMENT;
this.lastSpeedUpdate = now;
}
// Update score based on solar boost status
if (this.powerUpManager.getSolarBoostStatus()) {
this.uiManager.updateScore(SCORING.SOLAR_BOOST_RATE);
} else {
this.uiManager.updateScore(SCORING.BASE_RATE);
}
}
gameOver() {
this.gameActive = false;
const finalScore = this.uiManager.getScore();
const stats = this.uiManager.getCollectableStats();
// Update game state manager with final game stats
this.stateManager.setState(STATES.GAME_OVER);
this.stateManager.updateGameStats({
score: finalScore,
blueprints: stats.blueprints,
waterDrops: stats.waterDrops,
energyCells: stats.energyCells
});
// Show game over UI
this.uiManager.showGameOver();
// Game Over with final score
// Final game statistics recorded
}
restartGame() {
// STOP the existing animation loop to prevent multiple loops
this.stopAnimation();
// Reset game state completely
this.gameActive = true;
this.gameSpeed.value = GAME_CONFIG.INITIAL_SPEED;
this.lastSpeedUpdate = null; // Reset speed update timer
this.stateManager.resetGame();
// Reset camera position
this.camera.position.z = 5;
this.camera.position.x = 0;
this.camera.position.y = 2;
// Reset all managers completely
this.player.reset();
this.environment.reset();
this.obstacleManager.reset();
this.collectableManager.reset();
this.powerUpManager.reset();
this.uiManager.reset();
// Recreate input manager properly
this.setupInputManager();
// Start game immediately - no countdown on restart
this.stateManager.setState(STATES.PLAYING);
this.startSpawning();
// Only start animation if not already running
if (!this.animationId) {
this.animate();
}
// Game restarted completely
}
startNewGame() {
// Starting new game with user registration
// STOP the existing animation loop to prevent multiple loops
this.stopAnimation();
// Clear stored player data to force new registration
PlayerRegistration.clearStoredPlayerData();
// Reset game state completely
this.gameActive = false;
this.gameSpeed.value = GAME_CONFIG.INITIAL_SPEED;
this.stateManager.resetGame();
// Reset camera position
this.camera.position.z = 5;
this.camera.position.x = 0;
this.camera.position.y = 2;
// Reset all managers completely
this.player.reset();
this.environment.reset();
this.obstacleManager.reset();
this.collectableManager.reset();
this.powerUpManager.reset();
this.uiManager.reset();
this.inputManager.reset();
// Clear leaderboard data and state
this.leaderboardManager.clearPlayerData();
this.stateManager.clearPlayerData();
// Start the registration process
this.stateManager.setState(STATES.PLAYER_REGISTRATION);
this.showPlayerRegistration();
// New game started - showing registration form
}
setupResizeHandling() {
// Add event listeners for resize
window.addEventListener('resize', () => this.handleWindowResize());
window.addEventListener('orientationchange', () => {
// Add delay to handle orientation change properly
setTimeout(() => this.handleWindowResize(), 100);
});
}
handleWindowResize() {
// Update camera aspect ratio
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
// Update renderer size with proper pixel ratio
const pixelRatio = Math.min(window.devicePixelRatio, this.isMobile ? 2 : 3);
this.renderer.setPixelRatio(pixelRatio);
this.renderer.setSize(window.innerWidth, window.innerHeight);
// Force canvas to fill container properly
this.renderer.domElement.style.width = '100%';
this.renderer.domElement.style.height = '100%';
// Screen resized with new dimensions and pixel ratio
}
// Game pause/resume functionality
pauseGame() {
this.gamePaused = true;
// Game paused for onboarding
}
resumeGame() {
this.gamePaused = false;
// Game resumed after onboarding
}
// Public methods for managers to access current game state
isGameActive() {
return this.gameActive && !this.gamePaused;
}
getPlayerPosition() {
return this.player.getPosition();
}
getObstacles() {
return this.obstacleManager.getObstacles();
}
// Player registration methods
checkPlayerRegistration() {
// Checking player registration
try {
// Check if player data exists
const storedData = PlayerRegistration.getStoredPlayerData();
// Stored player data checked
if (storedData) {
// Player already registered, show countdown then start the game
// Player already registered, showing countdown
this.registerPlayer(storedData.playerName, storedData.email, storedData.organizationName);
this.showCountdown();
} else {
// Show registration form first
// No player data found, showing registration form
this.stateManager.setState(STATES.PLAYER_REGISTRATION);
this.showPlayerRegistration();
}
} catch (error) {
// Error in checkPlayerRegistration, using fallback
// Fallback: just show countdown and start the game
// Fallback: showing countdown without registration
this.showCountdown();
}
}
startGame() {
// Starting game directly (bypassing countdown)
try {
this.stateManager.setState(STATES.PLAYING);
this.gameActive = true;
this.startSpawning();
this.animate();
// Game started successfully
} catch (error) {
// Error starting game
}
}
showPlayerRegistration() {
// Showing player registration form
try {
// Disable input manager during registration
if (this.inputManager) {
this.inputManager.disable();
}
if (!this.playerRegistration) {
// Creating new PlayerRegistration instance
this.playerRegistration = new PlayerRegistration((name, email, organization) => {
// Player registration completed
this.registerPlayer(name, email, organization);
// Re-enable input manager
if (this.inputManager) {
this.inputManager.enable();
}
// NOW show countdown before starting the game
this.showCountdown();
});
}
// Showing registration form
this.playerRegistration.show();
} catch (error) {
// Error showing player registration
}
}
registerPlayer(name, email, organization) {
// Set player data in state manager
this.stateManager.setPlayerData(name, email, organization);
// Set player data in leaderboard manager
this.leaderboardManager.setPlayerData(name, email, organization);
// Player registered successfully
}
showCountdown() {
// Starting countdown
// Set state to getting ready
this.stateManager.setState(STATES.GETTING_READY);
this.countdownActive = true;
// Show countdown in UI
this.uiManager.showCountdown((skipped) => {
// Countdown completed or skipped
this.onCountdownComplete();
});
// Set up character ready animation
if (this.player && this.player.setReadyState) {
this.player.setReadyState(true);
}
}
onCountdownComplete() {
// Countdown complete, starting game
// Clear countdown state
this.countdownActive = false;
if (this.countdownTimeoutId) {
clearTimeout(this.countdownTimeoutId);
this.countdownTimeoutId = null;
}
// Reset character ready state
if (this.player && this.player.setReadyState) {
this.player.setReadyState(false);
}
// IMPORTANT: Reset environment again to ensure clean state
// This ensures all buildings and decorations are cleared and regenerated
this.environment.reset();
this.collectableManager.reset();
this.powerUpManager.reset();
// Reset game speed to initial value
this.gameSpeed.value = GAME_CONFIG.INITIAL_SPEED;
// Now actually start the game
this.stateManager.setState(STATES.PLAYING);
this.gameActive = true;
this.startSpawning();
// Only start animation if not already running
if (!this.animationId) {
this.animate();
}
// Game started after countdown
}
animate() {
// Make sure we don't have multiple animation loops running
if (this.animationId) {
cancelAnimationFrame(this.animationId);
}
this.animationId = requestAnimationFrame(() => {
// Clear the animation ID to avoid recursive issues
this.animationId = null;
this.animate();
});
this.updateGameLogic();
this.renderer.render(this.scene, this.camera);
}
stopAnimation() {
if (this.animationId) {
cancelAnimationFrame(this.animationId);
this.animationId = null;
}
}
cleanup() {
console.log('Starting comprehensive game cleanup');
// Stop the game
this.gameActive = false;
// Stop animation loop
this.stopAnimation();
// Cleanup input manager
if (this.inputManager && typeof this.inputManager.destroy === 'function') {
this.inputManager.destroy();
this.inputManager = null;
}
// Cleanup UI manager
if (this.uiManager && typeof this.uiManager.cleanup === 'function') {
this.uiManager.cleanup();
}
// Cleanup player registration
if (this.playerRegistration && typeof this.playerRegistration.destroy === 'function') {
this.playerRegistration.destroy();
this.playerRegistration = null;
}
// Cleanup WebGL renderer
if (this.renderer) {
try {
this.renderer.dispose();
this.renderer.forceContextLoss();
// Remove canvas if it exists
if (this.renderer.domElement && this.renderer.domElement.parentNode) {
this.renderer.domElement.parentNode.removeChild(this.renderer.domElement);
}
this.renderer = null;
} catch (error) {
console.warn('Error cleaning up renderer:', error);
}
}
// Clear scene
if (this.scene) {
this.scene.clear();
this.scene = null;
}
// Clear camera
this.camera = null;
console.log('Game cleanup completed');
}
}
// Game will be initialized by the loading manager or onboarding system
// No auto-initialization here
// Function to initialize game after onboarding
window.initializeGame = function() {
// Prevent multiple game instances - clean up any existing instance
if (window.gameInstance) {
console.log('Cleaning up existing game instance to prevent WebGL context leak');
// Call comprehensive cleanup method
if (typeof window.gameInstance.cleanup === 'function') {
window.gameInstance.cleanup();
} else {
// Fallback cleanup
window.gameInstance.gameActive = false;
// Clean up WebGL renderer if it exists
if (window.gameInstance.renderer) {
try {
window.gameInstance.renderer.dispose();
window.gameInstance.renderer.forceContextLoss();
// Remove canvas if it exists
if (window.gameInstance.renderer.domElement && window.gameInstance.renderer.domElement.parentNode) {
window.gameInstance.renderer.domElement.parentNode.removeChild(window.gameInstance.renderer.domElement);
}
} catch (error) {
console.warn('Error cleaning up renderer:', error);
}
}
}
// Clear the instance
window.gameInstance = null;
// Force garbage collection if available
if (window.gc) {
window.gc();
}
}
// Initializing new game instance after onboarding completion
console.log('Creating new game instance');
window.gameInstance = new Game();
return window.gameInstance;
};