Repository navigation
Expand file tree
/
Copy pathoptimized-game.js
More file actions
815 lines (666 loc) · 27.9 KB
/
Copy pathoptimized-game.js
File metadata and controls
815 lines (666 loc) · 27.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
// Optimized Game Controller with Modern Performance Systems
import * as THREE from 'three';
import { Player } from './player.js';
import { DirectModelEnvironment } from './direct-model-environment.js';
import { OptimizedObstacleManager } from './optimized-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 } from './constants.js';
import { GameStateManager, STATES } from './game-state.js';
import { LeaderboardManager } from './leaderboard.js';
import { PlayerRegistration } from './player-registration.js';
import {
PerformanceMonitor,
AdaptiveQualityManager,
FrustumCullingManager,
ObjectPool
} from './performance-manager.js';
import { GamepadInputIntegration } from './gamepad-manager.js';
export class OptimizedGame {
constructor() {
// Performance monitoring
this.performanceMonitor = new PerformanceMonitor();
this.adaptiveQuality = null;
this.frustumCuller = null;
// Core Three.js components
this.scene = null;
this.camera = null;
this.renderer = null;
// Game managers (will be optimized versions)
this.player = null;
this.environment = null;
this.obstacleManager = null;
this.collectableManager = null;
this.powerUpManager = null;
this.uiManager = null;
this.inputManager = null;
this.gamepadIntegration = null;
// State management
this.stateManager = new GameStateManager();
this.leaderboardManager = new LeaderboardManager();
this.playerRegistration = null;
// Performance optimization flags
this.isCurrentlyPlaying = false;
this.enableInstancedRendering = true;
this.enableFrustumCulling = true;
this.enableAdaptiveQuality = true;
// Game state
this.gameActive = true;
this.gameSpeed = { value: GAME_CONFIG.INITIAL_SPEED };
// Performance metrics tracking
this.frameCounter = 0;
this.lastPerformanceReport = 0;
this.performanceReportInterval = 5000; // Report every 5 seconds
// Countdown state
this.countdownActive = false;
this.countdownTimeoutId = null;
this.animationId = null;
this.init();
}
async init() {
await this.setupOptimizedThreeJS();
await this.createOptimizedManagers();
this.setupInputSystems();
this.setupStateHandlers();
this.setupPerformanceMonitoring();
this.startSpawning();
this.animate();
// Start game flow with player registration
this.checkPlayerRegistration();
}
async setupOptimizedThreeJS() {
// Scene setup
this.scene = new THREE.Scene();
this.scene.fog = new THREE.Fog(0x87CEEB, 50, 200); // Add fog for depth
// Camera setup with optimized settings
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 500);
this.camera.position.set(0, 2, 5);
this.camera.lookAt(0, 0, 0);
// Optimized renderer with fallback support
this.renderer = await this.createOptimalRenderer();
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.shadowMap.enabled = true;
this.renderer.shadowMap.type = THREE.PCFSoftShadowMap; // Better quality shadows
this.renderer.outputColorSpace = THREE.SRGBColorSpace;
// Performance optimizations
this.renderer.info.autoReset = false; // Manual reset for better performance tracking
document.getElementById('game-container').appendChild(this.renderer.domElement);
// Initialize adaptive quality system
if (this.enableAdaptiveQuality) {
this.adaptiveQuality = new AdaptiveQualityManager(this.renderer);
}
// Initialize frustum culling
if (this.enableFrustumCulling) {
this.frustumCuller = new FrustumCullingManager(this.camera);
}
}
async createOptimalRenderer() {
// Try WebGPU first (future-ready), fallback to WebGL2, then WebGL1
if (navigator.gpu && window.WebGPURenderer) {
try {
const webgpuRenderer = new window.WebGPURenderer({ antialias: true });
await webgpuRenderer.init();
return webgpuRenderer;
} catch (e) {
}
}
// WebGL with optimized settings
const context = document.createElement('canvas').getContext('webgl2') ||
document.createElement('canvas').getContext('webgl');
const webglVersion = context instanceof WebGL2RenderingContext ? 'WebGL2' : 'WebGL1';
return new THREE.WebGLRenderer({
antialias: true,
alpha: false,
stencil: false,
depth: true,
preserveDrawingBuffer: false,
powerPreference: 'high-performance'
});
}
async createOptimizedManagers() {
// Environment (keep existing for now)
this.environment = new DirectModelEnvironment(this.scene);
this.environment.setGameController(this);
// Player with enhanced physics
this.player = new Player(this.scene);
await this.player.initialize();
// Optimized obstacle manager with modern techniques
this.obstacleManager = new OptimizedObstacleManager(this.scene, this.performanceMonitor);
this.obstacleManager.setGameController(this);
// Collectables (TODO: Optimize this next)
this.collectableManager = new CollectableManager(this.scene);
this.collectableManager.setGameController(this);
// Power-ups
this.powerUpManager = new PowerUpManager(this.scene, this.player);
this.powerUpManager.setGameSpeedReference(this.gameSpeed);
this.powerUpManager.setCollectableManager(this.collectableManager);
// UI Manager
this.uiManager = new UIManager();
}
setupInputSystems() {
// Cleanup existing input manager if it exists
if (this.inputManager && typeof this.inputManager.destroy === 'function') {
this.inputManager.destroy();
}
// Original input manager
this.inputManager = new InputManager(this.player, this);
this.inputManager.setupMobileControls();
// Gamepad integration
this.gamepadIntegration = new GamepadInputIntegration(this.inputManager);
// Enhanced input processing
this.inputManager.originalUpdate = this.inputManager.update;
this.inputManager.update = () => {
// Original input processing
if (this.inputManager.originalUpdate) {
this.inputManager.originalUpdate();
}
// Add gamepad input
const gamepadCommands = this.gamepadIntegration.updateGamepadInput();
// Process gamepad commands
for (const command of gamepadCommands) {
this.processInputCommand(command);
}
};
}
processInputCommand(command) {
if (!this.isCurrentlyPlaying || !this.gameActive) return;
switch (command) {
case 'jump':
this.player.jump();
this.gamepadIntegration.onJump();
break;
case 'moveLeft':
this.player.moveLeft();
break;
case 'moveRight':
this.player.moveRight();
break;
case 'restart':
if (!this.gameActive) {
this.restartGame();
}
break;
}
}
setupPerformanceMonitoring() {
// Performance metrics callback
this.performanceMonitor.onMetricsUpdate((metrics) => {
// Update adaptive quality based on performance
if (this.adaptiveQuality) {
this.adaptiveQuality.updateFPS(metrics.frameTime / 1000);
}
// Log performance warnings
if (metrics.fps < 30) {
}
if (metrics.memoryUsage > 150) {
}
});
// Window resize optimization
window.addEventListener('resize', () => {
this.handleWindowResize();
});
}
setupStateHandlers() {
// Enhanced state management with performance considerations
this.stateManager.onStateChange((state) => {
this.isCurrentlyPlaying = (state === STATES.PLAYING);
switch (state) {
case STATES.SPLASH:
this.uiManager.showSplash();
this.pausePerformanceIntensiveOperations();
break;
case STATES.START_MENU:
this.uiManager.hideSplash();
this.uiManager.hideLeaderboard();
this.uiManager.hideUserInfo();
this.uiManager.showStartMenu();
this.gameActive = false;
this.pausePerformanceIntensiveOperations();
break;
case STATES.PLAYING:
this.uiManager.hideStartMenu();
this.uiManager.hideLeaderboard();
this.uiManager.hideUserInfo();
this.restartGame();
this.gameActive = true;
this.resumePerformanceIntensiveOperations();
break;
case STATES.USER_INFO:
this.uiManager.showUserInfo();
this.pausePerformanceIntensiveOperations();
break;
case STATES.LEADERBOARD:
this.uiManager.updateLeaderboard(this.leaderboardManager.getScores());
this.uiManager.hideUserInfo();
this.uiManager.showLeaderboard();
this.gameActive = false;
this.pausePerformanceIntensiveOperations();
break;
}
});
// UI event handlers
this.uiManager.onStartButtonClicked = () => this.handleStartGame();
this.uiManager.onUserInfoSubmitted = (name) => this.handleUserInfo(name);
this.uiManager.onLeaderboardBack = () => this.stateManager.returnToMenu();
}
pausePerformanceIntensiveOperations() {
// Reduce rendering quality during menu states
if (this.adaptiveQuality) {
this.adaptiveQuality.forceQuality = 'low';
}
}
resumePerformanceIntensiveOperations() {
// Resume normal rendering quality
if (this.adaptiveQuality) {
this.adaptiveQuality.forceQuality = null;
}
}
updateGameLogic() {
// Performance optimization: Use cached playing state
if (!this.isCurrentlyPlaying || !this.gameActive) return;
// Update performance monitoring
const deltaTime = this.performanceMonitor.update(this.renderer);
// Frame counter for performance reporting
this.frameCounter++;
// Pause game logic if player is stumbling
if (this.player.isStumbling) {
this.player.updatePosition(
this.powerUpManager.getFlyingStatus(),
this.powerUpManager.getWaterSlideObjects(),
this.gameSpeed.value
);
return;
}
// Update player
this.player.updatePosition(
this.powerUpManager.getFlyingStatus(),
this.powerUpManager.getWaterSlideObjects(),
this.gameSpeed.value
);
// Update input systems
this.inputManager.update();
// Update all game objects
this.updateAllObjects();
// Update frustum culling
if (this.frustumCuller) {
this.frustumCuller.update();
}
// Check collisions
this.checkCollisions();
// Enhanced power-up spawning
this.handlePowerUpSpawning();
// Handle special collectibles
this.handleSpecialCollectibles();
// Update camera
this.updateCamera();
// Update game speed and score
this.updateGameSpeed();
// Update power-up timers
this.powerUpManager.updateTimers(deltaTime);
this.uiManager.updatePowerUpTimers(deltaTime);
// Apply magnet effect
this.applyMagnetEffect();
// Performance reporting
this.reportPerformanceMetrics();
}
updateAllObjects() {
// Update obstacles with performance tracking
const obstacleScore = this.obstacleManager.updateObstacles(
this.gameSpeed.value,
this.camera.position.z,
this.gameActive
);
this.uiManager.updateScore(obstacleScore);
// Update environment
this.environment.updateBuildings(this.gameSpeed.value, this.camera.position.z);
this.environment.updateGround(this.camera.position.z);
// Update collectables
this.collectableManager.updateCollectables(this.gameSpeed.value, this.camera.position.z);
// Update power-up effects
this.powerUpManager.updateWaterSlidePosition(this.gameSpeed.value);
}
checkCollisions() {
const playerBox = this.player.getCollisionBox();
// Enhanced collision detection
if (!this.powerUpManager.getInvincibilityStatus() &&
!this.player.isStumbling &&
!this.powerUpManager.getFlyingStatus()) {
const collision = this.obstacleManager.checkCollisions(
playerBox,
this.powerUpManager.getWaterSlideObjects(),
this.powerUpManager.getWaterSlideStatus()
);
if (collision) {
// Trigger haptic feedback
this.gamepadIntegration.onCollision();
const stumbleTriggered = this.player.triggerStumble(() => this.gameOver());
if (!stumbleTriggered) {
this.gameOver();
return;
}
return;
}
}
// Check collectable collisions
const collectedItems = this.collectableManager.checkCollisions(playerBox);
this.handleCollectedItems(collectedItems);
}
handleCollectedItems(collectedItems) {
for (const itemType of collectedItems) {
// Trigger haptic feedback for power-ups
if (['hardHat', 'helicopter', 'solarPower', 'windPower', 'waterPipeline'].includes(itemType)) {
this.gamepadIntegration.onPowerUp();
}
// Process collection (same as original)
switch (itemType) {
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);
break;
case 'solarOrb':
this.uiManager.updateScore(SCORING.SOLAR_ORB);
break;
case 'hardHat':
this.uiManager.updateScore(SCORING.POWER_UP);
this.powerUpManager.activateInvincibility();
this.uiManager.addPowerUpToUI('🛡️ Hard Hat Shield', 5);
this.collectableManager.markPowerUpSpawned();
break;
case 'helicopter':
this.uiManager.updateScore(SCORING.POWER_UP);
this.powerUpManager.activateHelicopter();
this.uiManager.addPowerUpToUI('🚁 Helicopter Ride', 10);
this.collectableManager.markPowerUpSpawned();
break;
case 'solarPower':
this.uiManager.updateScore(SCORING.POWER_UP);
this.powerUpManager.activateSolarPower();
this.uiManager.addPowerUpToUI('🌟 Solar Power Boost', 8);
this.collectableManager.markPowerUpSpawned();
break;
case 'windPower':
this.uiManager.updateScore(SCORING.POWER_UP);
this.powerUpManager.activateWindPower();
this.uiManager.addPowerUpToUI('💨 Wind Power', 15);
this.collectableManager.markPowerUpSpawned();
break;
case 'waterPipeline':
this.uiManager.updateScore(SCORING.POWER_UP);
this.powerUpManager.activateWaterSlide();
this.uiManager.addPowerUpToUI('🚰 Water Pipeline', 12);
this.collectableManager.markPowerUpSpawned();
break;
}
}
}
handlePowerUpSpawning() {
if (this.collectableManager.shouldSpawnPowerUp()) {
const playerZ = this.player.getPosition().z;
const obstacles = this.obstacleManager.getObstacles();
this.collectableManager.createPowerUp(playerZ, obstacles);
this.collectableManager.markPowerUpSpawned();
}
}
handleSpecialCollectibles() {
// Aerial collectibles when flying
if (this.powerUpManager.getFlyingStatus() && Math.random() < SPAWN_CONFIG.AERIAL_SPAWN_CHANCE) {
this.collectableManager.createAerialCollectable(this.player.getPosition());
}
// 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());
}
}
applyMagnetEffect() {
if (this.powerUpManager.getSolarBoostStatus()) {
this.collectableManager.applyMagnetEffect(
this.player.getPosition(),
PHYSICS.MAGNET_RADIUS,
PHYSICS.MAGNET_PULL_SPEED
);
}
}
updateCamera() {
// Enhanced camera system with smooth following
const cameraTargetX = this.player.getPosition().x;
this.camera.position.x += (cameraTargetX - this.camera.position.x) * GAME_CONFIG.CAMERA_FOLLOW_SPEED;
// Dynamic camera Y positioning
let cameraTargetY;
if (this.powerUpManager && this.powerUpManager.getFlyingStatus()) {
cameraTargetY = this.player.getPosition().y + 1.0;
this.camera.position.y += (cameraTargetY - this.camera.position.y) * (GAME_CONFIG.CAMERA_FOLLOW_SPEED * 0.8);
} else {
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() {
this.gameSpeed.value += GAME_CONFIG.SPEED_INCREMENT;
// Update score with boost consideration
if (this.powerUpManager.getSolarBoostStatus()) {
this.uiManager.updateScore(SCORING.SOLAR_BOOST_RATE);
} else {
this.uiManager.updateScore(SCORING.BASE_RATE);
}
}
reportPerformanceMetrics() {
const now = Date.now();
if (now - this.lastPerformanceReport > this.performanceReportInterval) {
const metrics = this.performanceMonitor.getMetrics();
const obstacleStats = this.obstacleManager.getPerformanceStats();
const gamepadStats = this.gamepadIntegration.getStats();
if (this.adaptiveQuality) {
const qualityStats = this.adaptiveQuality.getStats();
}
this.lastPerformanceReport = now;
}
}
// Game state methods
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();
}
restartGame() {
// STOP the existing animation loop to prevent multiple loops
this.stopAnimation();
// Cleanup existing input manager to prevent event listener accumulation
if (this.inputManager && typeof this.inputManager.destroy === 'function') {
this.inputManager.destroy();
}
// Reset game state
this.gameActive = true;
this.gameSpeed.value = GAME_CONFIG.INITIAL_SPEED;
this.stateManager.resetGame();
// Reset camera
this.camera.position.set(0, 2, 5);
// Reset all managers
this.player.reset();
this.environment.reset();
this.obstacleManager.reset();
this.collectableManager.reset();
this.powerUpManager.reset();
this.uiManager.reset();
this.inputManager.reset();
// Position player at safe starting location ahead of obstacle spawn zone
// Obstacles spawn at playerZ - 50, so position player ahead to ensure safety
const safeStartZ = this.camera.position.z - 5;
this.player.setPosition(0, this.player.getPosition().y, safeStartZ);
// Reset performance counters
this.frameCounter = 0;
this.lastPerformanceReport = Date.now();
// Start game immediately - no countdown on restart
this.stateManager.setState(STATES.PLAYING);
this.gameActive = true;
this.startSpawning();
this.animate();
}
startSpawning() {
this.obstacleManager.startSpawning();
this.environment.startSpawning();
this.collectableManager.startSpawning();
}
handleWindowResize() {
const newAspect = window.innerWidth / window.innerHeight;
this.camera.aspect = newAspect;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
// Notify adaptive quality system
if (this.adaptiveQuality) {
this.adaptiveQuality.onResize(window.innerWidth, window.innerHeight);
}
}
// Event handlers
handleStartGame() {
this.stateManager.startGame();
}
handleUserInfo(name) {
this.stateManager.saveUserInfo(name);
this.leaderboardManager.addScore(this.stateManager.getPlayerData());
this.stateManager.showLeaderboard();
}
// Player registration methods
checkPlayerRegistration() {
// Check if player data exists
const storedData = PlayerRegistration.getStoredPlayerData();
if (storedData) {
// Player already registered, set up the game
this.registerPlayer(storedData.playerName, storedData.email, storedData.organizationName);
this.stateManager.setState(STATES.MENU);
} else {
// Show registration form
this.stateManager.setState(STATES.PLAYER_REGISTRATION);
this.showPlayerRegistration();
}
}
showPlayerRegistration() {
try {
if (!this.playerRegistration) {
this.playerRegistration = new PlayerRegistration((name, email, organization) => {
this.registerPlayer(name, email, organization);
this.stateManager.setState(STATES.MENU);
});
}
this.playerRegistration.show();
} catch (error) {
}
}
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);
}
// Public interface methods
getGameSpeed() {
return this.gameSpeed.value;
}
isGameActive() {
return this.gameActive;
}
getPlayerPosition() {
return this.player.getPosition();
}
getObstacles() {
return this.obstacleManager.getObstacles();
}
showCountdown() {
// Clear countdown state first
this.countdownActive = true;
if (this.countdownTimeoutId) {
clearTimeout(this.countdownTimeoutId);
this.countdownTimeoutId = null;
}
// Position player at safe starting location ahead of obstacle spawn zone
// Obstacles spawn at playerZ - 50, so position player ahead to ensure safety
const safeStartZ = this.camera.position.z - 5;
this.player.setPosition(0, this.player.getPosition().y, safeStartZ);
// Show countdown in UI
this.uiManager.showCountdown((skipped) => {
this.onCountdownComplete();
});
// Set up character ready animation
if (this.player && this.player.setReadyState) {
this.player.setReadyState(true);
}
}
onCountdownComplete() {
// 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.obstacleManager.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();
this.uiManager.updateScoreDisplay && this.uiManager.updateScoreDisplay();
}
// Main animation loop
animate() {
this.animationId = requestAnimationFrame(() => this.animate());
this.updateGameLogic();
// Manual reset renderer info for accurate performance tracking
this.renderer.info.reset();
this.renderer.render(this.scene, this.camera);
}
stopAnimation() {
if (this.animationId) {
cancelAnimationFrame(this.animationId);
this.animationId = null;
}
}
// Cleanup
destroy() {
if (this.gamepadIntegration) {
this.gamepadIntegration.gamepadManager.destroy();
}
if (this.renderer) {
this.renderer.dispose();
}
}
}
// Initialize the optimized game when the page loads
document.addEventListener('DOMContentLoaded', () => {
window.optimizedGame = new OptimizedGame();
});