-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgame.js
More file actions
4605 lines (4073 loc) · 221 KB
/
game.js
File metadata and controls
4605 lines (4073 loc) · 221 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
/* --- SESSION TOKEN FOR SCORE SUBMISSION --- */
let sessionToken = null; // Holds the session token for this game session
async function fetchSessionToken() {
try {
const response = await fetch('/start-session', { method: 'POST' });
if (!response.ok) throw new Error('Failed to get session token');
const data = await response.json();
sessionToken = data.sessionToken;
console.log('Session token acquired:', sessionToken);
} catch (e) {
sessionToken = null;
console.error('Session token error:', e);
// Optionally: disable score submission UI here
}
}
// --- PWA Install Prompt Variables ---
let deferredPrompt; // To store the event
const installButton = document.getElementById('installPwaButton');
// --- Event Listener for beforeinstallprompt ---
window.addEventListener('beforeinstallprompt', (e) => {
// Prevent the mini-infobar from appearing on mobile
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
// Update UI notify the user they can install the PWA
console.log('`beforeinstallprompt` event fired.');
if (installButton) {
installButton.style.display = 'block'; // Show the install button
} else {
console.warn('Install button not found.');
}
});
// --- Click Handler for the Install Button ---
if (installButton) {
installButton.addEventListener('click', async () => {
// Hide the app provided install promotion
installButton.style.display = 'none';
// Show the install prompt
if (deferredPrompt) {
deferredPrompt.prompt();
// Wait for the user to respond to the prompt
const { outcome } = await deferredPrompt.userChoice;
console.log(`User response to the install prompt: ${outcome}`);
// We've used the prompt, and can't use it again, discard it
deferredPrompt = null;
} else {
console.log('No deferred prompt available to show.');
}
});
} else {
console.warn('Install button not found, cannot add click listener.');
}
// --- Optional: Listener for appinstalled event ---
window.addEventListener('appinstalled', () => {
// Hide the install button
if (installButton) {
installButton.style.display = 'none';
}
// Clear the deferredPrompt so it can be garbage collected
deferredPrompt = null;
console.log('PWA was installed');
// Optionally, send analytics event
});
// --- Canvas, Context, UI Elements ---
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreDisplay = document.getElementById('score');
const highScoreDisplay = document.getElementById('highScore');
const waveDisplay = document.getElementById('wave');
const citiesLeftDisplay = document.getElementById('citiesLeft');
const multiplierDisplay = document.getElementById('multiplier');
const restartButton = document.getElementById('restartButton');
const pauseButton = document.getElementById('pauseButton');
const screenshotButton = document.getElementById('screenshotButton');
const messageBox = document.getElementById('messageBox');
const messageTitle = document.getElementById('messageTitle');
const messageText = document.getElementById('messageText');
const messageSubText = document.getElementById('messageSubText');
const messageBonusText = document.getElementById('messageBonusText');
const statsContainer = document.getElementById('statsContainer');
const pauseOverlay = document.getElementById('pauseOverlay');
const uiContainer = document.getElementById('uiContainer');
const controlsContainer = document.getElementById('controlsContainer');
const difficultySelectionDiv = document.getElementById('difficultySelection');
const startMenuContainer = document.getElementById('startMenuContainer');
const startHighScoreDisplay = document.getElementById('startHighScore');
const actualStartButton = document.getElementById('actualStartButton');
const bonusIndicator = document.getElementById('bonusIndicator');
const goToStoreButton = document.getElementById('goToStoreButton');
const skipStoreButton = document.getElementById('skipStoreButton');
const storeModal = document.getElementById('storeModal');
const storeScoreDisplay = document.getElementById('storeScore');
const stockSatelliteDisplay = document.getElementById('stockSatellite');
const stockBaseDisplay = document.getElementById('stockBase');
const stockCityDisplay = document.getElementById('stockCity');
const stockShieldDisplay = document.getElementById('stockShield');
const stockSatShieldDisplay = document.getElementById('stockSatShield');
const stockSonicWaveDisplay = document.getElementById('stockSonicWave');
const stockBombDisplay = document.getElementById('stockBomb');
const buySatelliteButton = document.getElementById('buySatelliteButton');
const buyBaseButton = document.getElementById('buyBaseButton');
const buyCityButton = document.getElementById('buyCityButton');
const buyShieldButton = document.getElementById('buyShieldButton');
const buySatShieldButton = document.getElementById('buySatShieldButton');
const buySonicWaveButton = document.getElementById('buySonicWaveButton');
const buyBombButton = document.getElementById('buyBombButton');
const buySonicWave10Button = document.getElementById('buySonicWave10Button');
const buyBomb10Button = document.getElementById('buyBomb10Button');
const storeContinueButton = document.getElementById('storeContinueButton');
const specialWeaponsUIDiv = document.getElementById('specialWeaponsUI');
const sonicWaveControl = document.getElementById('sonicWaveControl');
const sonicWaveCountDisplay = document.getElementById('sonicWaveCount');
const bombControl = document.getElementById('bombControl');
const bombCountDisplay = document.getElementById('bombCount');
const canvasContainer = document.getElementById('canvasContainer');
const costFasterMissileDisplay = document.getElementById('costFasterMissile');
const levelFasterMissileDisplay = document.getElementById('levelFasterMissile');
const buyFasterMissileButton = document.getElementById('buyFasterMissileButton');
const costWiderExplosionDisplay = document.getElementById('costWiderExplosion');
const levelWiderExplosionDisplay = document.getElementById('levelWiderExplosion');
const buyWiderExplosionButton = document.getElementById('buyWiderExplosionButton');
// --- ADDED: Audio Elements ---
const muteMusicButton = document.getElementById('muteMusicButton');
const muteSfxButton = document.getElementById('muteSfxButton');
const musicVolumeSlider = document.getElementById('musicVolumeSlider'); // NEW
const sfxVolumeSlider = document.getElementById('sfxVolumeSlider'); // NEW
// --- NEW: Leaderboard Elements ---
const leaderboardContainer = document.getElementById('leaderboardContainer');
const leaderboardList = document.getElementById('leaderboardList');
const leaderboardLoading = document.getElementById('leaderboardLoading');
const leaderboardViewMoreContainer = document.getElementById('leaderboardViewMoreContainer');
const leaderboardViewMoreLink = document.getElementById('leaderboardViewMoreLink');
const scoreSubmissionDiv = document.getElementById('scoreSubmission');
const playerNameInput = document.getElementById('playerNameInput');
const submitScoreButton = document.getElementById('submitScoreButton');
const submissionStatus = document.getElementById('submissionStatus');
// --- Game Constants & State Variables ---
const INTERNAL_WIDTH = 800;
const INTERNAL_HEIGHT = 600;
const GROUND_HEIGHT_RATIO = 10 / INTERNAL_HEIGHT;
const BASE_WIDTH_RATIO = 40 / INTERNAL_WIDTH;
const BASE_HEIGHT_RATIO = 40 / INTERNAL_HEIGHT;
const CITY_WIDTH_RATIO = 50 / INTERNAL_WIDTH;
const CITY_HEIGHT_RATIO = 30 / INTERNAL_HEIGHT;
const SATELLITE_WIDTH_RATIO = 35 / INTERNAL_WIDTH;
const SATELLITE_HEIGHT_RATIO = 25 / INTERNAL_HEIGHT;
const SATELLITE_Y_POS_RATIO = (INTERNAL_HEIGHT * 0.55) / INTERNAL_HEIGHT;
const MISSILE_SPEED_PLAYER_BASE = 5;
const MISSILE_SPEED_ENEMY_BASE = 0.4;
const MAX_ENEMY_MISSILE_SPEED = 3.25;
const EXPLOSION_RADIUS_START = 13;
const EXPLOSION_RADIUS_MAX_BASE = 65;
const EXPLOSION_DURATION = 60;
const POINTS_PER_MISSILE = 100;
const POINTS_PER_CITY = 1000;
const POINTS_PER_AMMO = 10;
const BONUS_FIRE_SPREAD = 8;
const BASE_SHIELD_RADIUS_MULTIPLIER = 2.45;
const SHIELD_STRENGTH_START = 150;
const SHIELD_DAMAGE_PER_HIT = 10;
const SHIELD_COLOR_FULL = 'rgba(0, 150, 255, 0.6)';
const SHIELD_COLOR_75 = 'rgba(0, 255, 150, 0.6)';
const SHIELD_COLOR_50 = 'rgba(255, 255, 0, 0.6)';
const SHIELD_COLOR_25 = 'rgba(255, 100, 0, 0.6)';
const SHIELD_FLASH_COLOR = 'rgba(255, 255, 255, 0.8)';
const SHIELD_FLASH_DURATION = 5;
const BOMB_EXPLOSION_RADIUS_MULTIPLIER = 5.5;
const BOMB_EXPLOSION_DURATION_MULTIPLIER = 1.5;
const SONIC_WAVE_SPEED = 3.5;
const SONIC_WAVE_HEIGHT = 10;
const SONIC_WAVE_COLOR = 'rgba(200, 0, 255, 0.5)';
const ACCURACY_BONUS_THRESHOLD = 20;
const ACCURACY_BONUS_POINTS = 25;
const MULTIPLIER_INCREASE_INTERVAL = 5;
const MULTIPLIER_MAX = 5.0;
const COST_FASTER_MISSILE_BASE = 10000;
const COST_WIDER_EXPLOSION_BASE = 10000;
const UPGRADE_COST_MULTIPLIER = 1.55;
const MAX_UPGRADE_LEVEL = 15;
const MISSILE_SPEED_INCREASE_PER_LEVEL = 0.9;
const EXPLOSION_RADIUS_INCREASE_PER_LEVEL = 8;
const SMART_BOMB_CHANCE = 0.05;
const SMART_BOMB_SPLIT_ALTITUDE_MIN = INTERNAL_HEIGHT * 0.45;
const SMART_BOMB_SPLIT_ALTITUDE_MAX = INTERNAL_HEIGHT * 0.65;
const SMART_BOMB_SPLIT_COUNT = 3;
const SMART_BOMB_SPLIT_SPEED_FACTOR = 0.7;
const SMART_BOMB_SPLIT_COLOR = '#ff8800';
const MIRV_CHANCE = 0.10;
const MIRV_SPLIT_ALTITUDE = INTERNAL_HEIGHT * 0.35;
const MIRV_WARHEAD_COUNT = 4;
const MIRV_WARHEAD_SPEED_FACTOR = 0.9;
const MIRV_WARHEAD_COLOR = '#ff4444';
const COMBO_BONUS_POINTS_PER_EXTRA_KILL = 15; // Points per extra kill in a combo
const PLANE_SPEED_INCREASE_PER_WAVE = 0.05;
const PLANE_VARIANT_CHANCE = 0.2;
const MAX_ACTIVE_SATELLITES = 3;
const COST_SATELLITE = 100000;
const MAX_STOCK_SATELLITE = 100;
const COST_BASE = 50000;
const MAX_STOCK_BASE = 100;
const COST_CITY = 100000;
const MAX_STOCK_CITY = 100;
const COST_SHIELD = 50000;
const MAX_STOCK_SHIELD = 100;
const COST_SAT_SHIELD = 50000;
const MAX_STOCK_SAT_SHIELD = 100;
const COST_SONIC_WAVE = 20000;
const MAX_STOCK_SONIC_WAVE = 100;
const COST_BOMB = 10000;
const MAX_STOCK_BOMB = 100;
const PLANE_SPEED_BASE = 1.5;
const PLANE_WIDTH = 50;
const PLANE_HEIGHT = 20;
const PLANE_BONUS_SCORE = 2000;
const PLANE_BOMB_POINTS = 10;
const PLANE_BOMB_SPEED = 1.0;
const BASE_BOMBS_PER_PLANE = 20;
const BOMBS_INCREASE_PER_WAVE = 1;
const PLANE_SPAWN_CHANCE = 0.025;
const PLANE_MIN_Y = INTERNAL_HEIGHT * 0.1;
const PLANE_MAX_Y = INTERNAL_HEIGHT * 0.3;
const PLANE_BOMB_DROP_INTERVAL_MIN = 75;
const PLANE_BOMB_DROP_INTERVAL_MAX = 150;
const PLANE_BOMB_COLOR = '#FFA500';
const PLANE_BOMB_TRAIL_COLOR = 'rgba(255, 165, 0, 0.4)';
// Game State Variables
let stars = [];
let gameStartTimestamp = 0;
let score = 0;
let gameTotalScore = 0;
let highScore = 0;
let currentWave = 0;
let cities = [];
let bases = [];
let incomingMissiles = [];
let playerMissiles = [];
let explosions = [];
let isGameOver = true;
let gameLoopId = null;
let transitioningWave = false;
let isPaused = false;
let gameHasStarted = false;
let difficultySelected = false;
let selectedDifficultyName = '';
let selectedDifficultyAmmo = 50;
let difficultyScoreMultiplier = 1.0;
let bonusMissileCount = 0;
let storeStockSatellite = MAX_STOCK_SATELLITE;
let storeStockBase = MAX_STOCK_BASE;
let storeStockCity = MAX_STOCK_CITY;
let storeStockShield = MAX_STOCK_SHIELD;
let storeStockSatShield = MAX_STOCK_SAT_SHIELD;
let storeStockSonicWave = MAX_STOCK_SONIC_WAVE;
let storeStockBomb = MAX_STOCK_BOMB;
let satelliteBases = [];
let baseShields = [null, null, null];
let inventorySonicWave = 0;
let inventoryBomb = 0;
let isBombArmed = false;
let activeSonicWave = null;
let consecutiveIntercepts = 0;
let scoreMultiplier = 1.0;
let playerMissileSpeedLevel = 0;
let explosionRadiusLevel = 0;
let accuracyBonusMessageTimer = 0;
let comboMessageTimer = 0; // NEW: Timer for combo message display
let statsMissilesFired = 0;
let statsEnemyMissilesDestroyed = 0;
let statsPlaneBombsDestroyed = 0;
let statsPlanesDestroyed = 0;
let statsCitiesLost = 0;
let statsBasesLost = 0;
let statsAccuracyBonusHits = 0;
let planes = [];
let planeBombs = [];
let statsShieldBombsDestroyed = 0;
let gameClickData = [];
let storeActions = [];
let scoreSubmitted = false; // Track if score has been submitted
const waveDefinitions = defineWaves();
let currentWaveConfig = {};
let waveTimer = 0;
let waveEnemiesSpawned = 0;
let waveEnemiesRequired = 0;
let submittedPlayerNameThisSession = null; // ADDED: Track submitted name for the current session
// ADDED: Duration tracking variables
let waveStartTime = 0;
let totalGameDurationSeconds = 0;
let waveAllSpawnedTimestamp = 0; // NEW: Timestamp when all enemies for the wave are spawned
let waveStats = []; // NEW: Array to store stats per wave [{ spawnToCompletionMs: 12345 }, ...]
// NEW: Keyboard control variables
let keyboardSelectedBaseIndex = -1; // -1 = none, 0-2 ground, 3-5 satellite
let reticleX = INTERNAL_WIDTH / 2;
let reticleY = INTERNAL_HEIGHT / 2;
let keyboardTargetingActive = false; // Flag to show reticle
const RETICLE_SPEED = 8;
// ADDED: Variables for performance tracking
let lastFrameTime = 0;
let frameCount = 0;
let frameTimes = [];
const FRAME_SAMPLE_SIZE = 60; // Number of frames to sample for performance
// ADDED: Debug logging flag
window.enableDebugLogging = false;
// NEW: Kill counting control variable
let useDeferredKillCounting = true; // Set to true to use new method, false for old
// --- ADDED: Web Audio API Setup ---
let audioContext;
let masterGainNode;
let musicGainNode;
let sfxGainNode;
let musicBuffer = null;
let launchBuffer = null;
let explosionBuffer = null;
let musicSourceNode = null; // To keep track of the playing music source
let isMusicMuted = true; // Start muted by default
let isSfxMuted = false;
let audioInitialized = false;
const audioFilePaths = {
music: 'audio/music-lowest.mp3', // Placeholder
launch: 'audio/launch.mp3', // Placeholder - Changed to mp3
explosion: 'audio/explosion.mp3' // Placeholder - Changed to mp3
};
function initializeStars() {
stars = []; // Clear any existing stars
const groundY = canvas.height - (canvas.height * GROUND_HEIGHT_RATIO);
const numStars = Math.floor(canvas.width * canvas.height / 5000);
for (let i = 0; i < numStars; i++) {
stars.push({
x: Math.random() * canvas.width,
y: Math.random() * groundY,
radius: 0.3 + Math.random() * 1.2, // Base radius between 0.3 and 1.5
twinkleSpeed: 0.3 + Math.random() * 0.7, // Random speed for twinkling
twinkleOffset: Math.random() * Math.PI * 2 // Random starting phase
});
}
}
// Function to initialize AudioContext (must be called after user interaction)
function initAudioContext() {
if (!audioContext) {
try {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
masterGainNode = audioContext.createGain();
musicGainNode = audioContext.createGain();
sfxGainNode = audioContext.createGain();
// Set initial volumes from sliders
musicGainNode.gain.value = parseFloat(musicVolumeSlider.value); // NEW
sfxGainNode.gain.value = parseFloat(sfxVolumeSlider.value); // NEW
musicGainNode.connect(masterGainNode);
sfxGainNode.connect(masterGainNode);
masterGainNode.connect(audioContext.destination);
console.log("AudioContext initialized successfully.");
loadAllSounds(); // Start loading sounds once context is ready
} catch (e) {
console.error("Web Audio API is not supported in this browser", e);
// Disable sound buttons if context fails
if (muteMusicButton) muteMusicButton.disabled = true;
if (muteSfxButton) muteSfxButton.disabled = true;
}
}
// Resume context if it was suspended
if (audioContext && audioContext.state === 'suspended') {
audioContext.resume();
}
}
// Function to load a single sound file
async function loadSound(url) {
if (!audioContext) return null;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status} for ${url}`);
}
const arrayBuffer = await response.arrayBuffer();
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
console.log(`Sound loaded successfully: ${url}`);
return audioBuffer;
} catch (error) {
console.error(`Error loading sound ${url}:`, error);
// Display a user-friendly message or disable related features
// For now, just log the error. You might want to show a message in the UI.
return null; // Return null to indicate failure
}
}
// Function to load all sounds
async function loadAllSounds() {
if (!audioContext) return;
console.log("Loading all sounds...");
[musicBuffer, launchBuffer, explosionBuffer] = await Promise.all([
loadSound(audioFilePaths.music),
loadSound(audioFilePaths.launch),
loadSound(audioFilePaths.explosion)
]);
console.log("Sound loading process finished.");
// ADDED: Attempt to play music now if conditions are right
if (gameHasStarted && !isGameOver && !isPaused && !isMusicMuted && musicBuffer && !musicSourceNode) {
console.log("Attempting to play music after loading sounds.");
playMusic();
}
// Optionally, enable sound-related UI elements here if they were disabled
}
// Function to play a sound effect
function playSfx(buffer) {
if (!audioContext || !buffer || isSfxMuted) return;
// Resume context if needed (e.g., after inactivity)
if (audioContext.state === 'suspended') {
audioContext.resume();
}
const source = audioContext.createBufferSource();
source.buffer = buffer;
source.connect(sfxGainNode);
source.start(0);
}
// Function to play background music (loops)
function playMusic() {
if (!audioContext || !musicBuffer || musicSourceNode || isMusicMuted) return;
// Resume context if needed
if (audioContext.state === 'suspended') {
audioContext.resume();
}
musicSourceNode = audioContext.createBufferSource();
musicSourceNode.buffer = musicBuffer;
musicSourceNode.loop = true;
musicSourceNode.connect(musicGainNode);
musicSourceNode.start(0);
console.log("Music started.");
}
// Function to stop background music
function stopMusic() {
if (musicSourceNode) {
musicSourceNode.stop(0);
musicSourceNode.disconnect();
musicSourceNode = null;
console.log("Music stopped.");
}
}
// --- MODIFIED: Function to toggle music mute (works with slider) ---
function toggleMusicMute() {
if (!audioContext) return;
isMusicMuted = !isMusicMuted;
if (isMusicMuted) {
musicGainNode.gain.setValueAtTime(0, audioContext.currentTime); // Mute immediately
muteMusicButton.textContent = 'Unmute Music';
musicVolumeSlider.disabled = true; // Disable slider when muted
stopMusic(); // Stop current playback when muting
} else {
// Restore volume to slider value
musicGainNode.gain.setValueAtTime(parseFloat(musicVolumeSlider.value), audioContext.currentTime);
muteMusicButton.textContent = 'Mute Music';
musicVolumeSlider.disabled = false; // Enable slider
// Optionally restart music if the game is running
if (gameHasStarted && !isGameOver && !isPaused) {
playMusic();
}
}
console.log("Music Muted:", isMusicMuted);
}
// --- MODIFIED: Function to toggle SFX mute (works with slider) ---
function toggleSfxMute() {
if (!audioContext) return;
isSfxMuted = !isSfxMuted;
if (isSfxMuted) {
sfxGainNode.gain.setValueAtTime(0, audioContext.currentTime); // Mute immediately
muteSfxButton.textContent = 'Unmute SFX';
sfxVolumeSlider.disabled = true; // Disable slider when muted
} else {
// Restore volume to slider value
sfxGainNode.gain.setValueAtTime(parseFloat(sfxVolumeSlider.value), audioContext.currentTime);
muteSfxButton.textContent = 'Mute SFX';
sfxVolumeSlider.disabled = false; // Enable slider
}
console.log("SFX Muted:", isSfxMuted);
}
// --- NEW: Function to handle music volume change ---
function handleMusicVolumeChange(event) {
if (!audioContext || isMusicMuted) return; // Don't change if muted
const volume = parseFloat(event.target.value);
musicGainNode.gain.setValueAtTime(volume, audioContext.currentTime);
console.log("Music Volume:", volume);
}
// --- NEW: Function to handle SFX volume change ---
function handleSfxVolumeChange(event) {
if (!audioContext || isSfxMuted) return; // Don't change if muted
const volume = parseFloat(event.target.value);
sfxGainNode.gain.setValueAtTime(volume, audioContext.currentTime);
console.log("SFX Volume:", volume);
// Optionally play a test sound
// playSfx(launchBuffer);
}
// --- END Web Audio API Setup ---
// --- Utility Functions ---
function distance(x1, y1, x2, y2) { const dx = x1 - x2; const dy = y1 - y2; return Math.sqrt(dx * dx + dy * dy); }
function getRandomTarget(avoidX = -1, avoidRadius = 0) {
const aliveCities = cities.filter(c => c.alive);
const aliveBases = bases.filter(b => b.alive);
const aliveSatellites = satelliteBases.filter(s => s.alive);
let possibleTargets = [...aliveCities, ...aliveBases, ...aliveSatellites];
if (avoidX !== -1) {
possibleTargets = possibleTargets.filter(t => {
const targetCenterX = t.x + (t.width / 2);
return distance(targetCenterX, t.y, avoidX, 0) > avoidRadius;
});
}
const groundY = canvas.height - (canvas.height * GROUND_HEIGHT_RATIO);
if (possibleTargets.length === 0) {
let targetGroundX = canvas.width / 2 + (Math.random() - 0.5) * canvas.width * 0.4;
if (avoidX !== -1 && Math.abs(targetGroundX - avoidX) < avoidRadius) {
targetGroundX = avoidX + (Math.sign(targetGroundX - avoidX) || 1) * (avoidRadius + Math.random() * 50);
targetGroundX = Math.max(0, Math.min(canvas.width, targetGroundX));
}
return { x: targetGroundX, y: groundY };
}
const target = possibleTargets[Math.floor(Math.random() * possibleTargets.length)];
return { x: target.x + (target.width / 2), y: target.y };
}
function getCurrentPlayerMissileSpeed() { return MISSILE_SPEED_PLAYER_BASE + (playerMissileSpeedLevel * MISSILE_SPEED_INCREASE_PER_LEVEL); }
function getCurrentPlayerExplosionRadius() { return EXPLOSION_RADIUS_MAX_BASE + (explosionRadiusLevel * EXPLOSION_RADIUS_INCREASE_PER_LEVEL); }
function calculateUpgradeCost(baseCost, level) { return Math.floor(baseCost * Math.pow(UPGRADE_COST_MULTIPLIER, level)); }
// --- Game Object Factories ---
function createCity(xRatio) {
const cityWidth = canvas.width * CITY_WIDTH_RATIO;
const cityHeight = canvas.height * CITY_HEIGHT_RATIO;
const groundY = canvas.height - (canvas.height * GROUND_HEIGHT_RATIO);
const cityX = xRatio * canvas.width;
const cityY = groundY - cityHeight;
const buildings = [];
const numBuildings = 3 + Math.floor(Math.random() * 3);
let currentX = cityX;
const totalBuildingWidth = cityWidth * 0.9;
const baseBuildingWidth = totalBuildingWidth / numBuildings;
for (let i = 0; i < numBuildings; i++) {
const buildingHeight = (cityHeight * 0.6) + (Math.random() * cityHeight * 0.4);
const buildingWidth = baseBuildingWidth * (0.8 + Math.random() * 0.4);
const gap = (baseBuildingWidth - buildingWidth) / 2;
buildings.push({ x: currentX + gap, y: groundY - buildingHeight, w: buildingWidth, h: buildingHeight, color: `hsl(180, 100%, ${35 + Math.random() * 15}%)` });
currentX += baseBuildingWidth;
}
return {
x: cityX, y: cityY, width: cityWidth, height: cityHeight, alive: true, buildings: buildings,
draw() {
if (!this.alive) return;
this.buildings.forEach(b => {
ctx.fillStyle = b.color; ctx.fillRect(b.x, b.y, b.w, b.h);
ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
const windowSize = Math.min(b.w, b.h) * 0.15;
const cols = Math.floor(b.w / (windowSize * 2.5)); const rows = Math.floor(b.h / (windowSize * 3));
if (cols > 0 && rows > 0) {
const xSpacing = b.w / cols; const ySpacing = b.h / rows;
for (let r = 0; r < rows; r++) { for (let c = 0; c < cols; c++) { ctx.fillRect(b.x + xSpacing * (c + 0.5) - windowSize / 2, b.y + ySpacing * (r + 0.5) - windowSize / 2, windowSize, windowSize); } }
}
ctx.strokeStyle = '#006666'; ctx.lineWidth = 1; ctx.strokeRect(b.x, b.y, b.w, b.h);
});
}
};
}
function createBase(xRatio) {
const baseWidth = canvas.width * BASE_WIDTH_RATIO;
const baseHeight = canvas.height * BASE_HEIGHT_RATIO;
const groundY = canvas.height - (canvas.height * GROUND_HEIGHT_RATIO);
const baseX = (xRatio * canvas.width) - (baseWidth / 2);
const baseY = groundY - baseHeight;
return {
x: baseX, y: baseY, width: baseWidth, height: baseHeight, color: '#dddd00', outlineColor: '#aaaa00', launcherColor: '#999999', alive: true, ammo: selectedDifficultyAmmo, isSatellite: false,
draw() {
if (!this.alive) return;
// Ground platform
ctx.fillStyle = '#556b2f'; // Dark olive green
ctx.fillRect(this.x, this.y + this.height * 0.8, this.width, this.height * 0.2);
// Central command building - made taller
const buildingWidth = this.width * 0.4;
const buildingX = this.x + (this.width - buildingWidth) / 2;
const buildingHeight = this.height * 0.8; // Increased from 0.7
const buildingY = this.y + this.height * 0.8 - buildingHeight;
// Main building
ctx.fillStyle = '#5a5a5a';
ctx.fillRect(buildingX, buildingY, buildingWidth, buildingHeight);
// Building top
ctx.fillStyle = '#4a4a4a';
ctx.fillRect(buildingX + buildingWidth * 0.1, buildingY, buildingWidth * 0.8, buildingHeight * 0.1);
// Building windows - adjusted for taller building
ctx.fillStyle = '#88ccff';
const windowSize = buildingWidth * 0.1;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) { // Added an extra row of windows
ctx.fillRect(
buildingX + buildingWidth * 0.2 + i * buildingWidth * 0.3,
buildingY + buildingHeight * 0.15 + j * buildingHeight * 0.25,
windowSize, windowSize
);
}
}
// Missile silos - adjusted positions
const siloWidth = this.width * 0.15;
const siloLeftX = this.x + this.width * 0.1;
const siloRightX = this.x + this.width * 0.75;
const siloY = this.y + this.height * 0.75;
const siloHeight = this.height * 0.4; // Increased from 0.35
// Silo bases
ctx.fillStyle = '#777777';
ctx.fillRect(siloLeftX, siloY - siloHeight * 0.2, siloWidth, siloHeight * 0.2);
ctx.fillRect(siloRightX, siloY - siloHeight * 0.2, siloWidth, siloHeight * 0.2);
// Draw missiles in silos - made taller
const missileWidth = siloWidth * 0.6;
const missileLeftX = siloLeftX + (siloWidth - missileWidth) / 2;
const missileRightX = siloRightX + (siloWidth - missileWidth) / 2;
// Draw left missile
ctx.fillStyle = '#cccccc';
ctx.fillRect(missileLeftX, siloY - siloHeight * 0.8, missileWidth, siloHeight * 0.6);
// Left missile tip
ctx.fillStyle = '#ff3333';
ctx.beginPath();
ctx.moveTo(missileLeftX, siloY - siloHeight * 0.8);
ctx.lineTo(missileLeftX + missileWidth / 2, siloY - siloHeight);
ctx.lineTo(missileLeftX + missileWidth, siloY - siloHeight * 0.8);
ctx.closePath();
ctx.fill();
// Draw right missile
ctx.fillStyle = '#cccccc';
ctx.fillRect(missileRightX, siloY - siloHeight * 0.7, missileWidth, siloHeight * 0.5);
// Right missile tip
ctx.fillStyle = '#ff3333';
ctx.beginPath();
ctx.moveTo(missileRightX, siloY - siloHeight * 0.7);
ctx.lineTo(missileRightX + missileWidth / 2, siloY - siloHeight * 0.9);
ctx.lineTo(missileRightX + missileWidth, siloY - siloHeight * 0.7);
ctx.closePath();
ctx.fill();
// Small antenna on command building
ctx.strokeStyle = '#aaaaaa';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(buildingX + buildingWidth / 2, buildingY);
ctx.lineTo(buildingX + buildingWidth / 2, buildingY - buildingHeight * 0.15);
ctx.stroke();
ctx.beginPath();
ctx.arc(buildingX + buildingWidth / 2, buildingY - buildingHeight * 0.15, buildingWidth * 0.05, 0, Math.PI * 2);
ctx.stroke();
// Ammo display
ctx.fillStyle = '#ffffff';
const fontSize = Math.max(8, Math.min(12, Math.floor(this.width * 0.25)));
ctx.font = `${fontSize}px "Press Start 2P"`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(this.ammo, this.x + this.width / 2, this.y + this.height * 0.9);
}
};
}
function createSatelliteBase(xRatio, yRatio) {
const satWidth = canvas.width * SATELLITE_WIDTH_RATIO;
const satHeight = canvas.height * SATELLITE_HEIGHT_RATIO;
const satX = (xRatio * canvas.width) - (satWidth / 2);
const satY = yRatio * canvas.height;
return {
x: satX, y: satY, width: satWidth, height: satHeight, bodyColor: '#b0b0b0', panelColor: '#3333cc', panelHighlight: '#6666ff', outlineColor: '#777777', antennaColor: '#dddddd', lightColor: '#ff0000', alive: true, ammo: selectedDifficultyAmmo, isSatellite: true, shield: null,
draw() {
if (!this.alive) return;
// Main satellite body (central platform)
const bodyW = this.width * 0.6;
const bodyH = this.height * 0.7;
const bodyX = this.x + (this.width - bodyW) / 2;
const bodyY = this.y + (this.height - bodyH) / 2;
// Central command module (matching the land base's command building)
ctx.fillStyle = '#5a5a5a';
ctx.beginPath();
ctx.moveTo(bodyX, bodyY + bodyH * 0.2);
ctx.lineTo(bodyX + bodyW * 0.1, bodyY);
ctx.lineTo(bodyX + bodyW * 0.9, bodyY);
ctx.lineTo(bodyX + bodyW, bodyY + bodyH * 0.2);
ctx.lineTo(bodyX + bodyW, bodyY + bodyH * 0.8);
ctx.lineTo(bodyX + bodyW * 0.9, bodyY + bodyH);
ctx.lineTo(bodyX + bodyW * 0.1, bodyY + bodyH);
ctx.lineTo(bodyX, bodyY + bodyH * 0.8);
ctx.closePath();
ctx.fill();
// Command module outline
ctx.strokeStyle = '#444444';
ctx.lineWidth = 1;
ctx.stroke();
// Solar panels - left and right (similar layout to the land base silos)
const panelW = this.width * 0.25;
const panelH = this.height * 0.8;
const panelY = this.y + (this.height - panelH) / 2;
// Left panel
ctx.fillStyle = '#336699'; // Blue panels (like windows in command center)
ctx.fillRect(this.x, panelY, panelW, panelH);
// Right panel
ctx.fillRect(this.x + this.width - panelW, panelY, panelW, panelH);
// Panel details - grid lines
ctx.strokeStyle = '#88ccff';
ctx.lineWidth = 1;
// Left panel grid
for (let i = 0; i < 3; i++) {
ctx.beginPath();
ctx.moveTo(this.x, panelY + panelH * (i + 1) / 4);
ctx.lineTo(this.x + panelW, panelY + panelH * (i + 1) / 4);
ctx.stroke();
}
for (let i = 0; i < 1; i++) {
ctx.beginPath();
ctx.moveTo(this.x + panelW * (i + 1) / 2, panelY);
ctx.lineTo(this.x + panelW * (i + 1) / 2, panelY + panelH);
ctx.stroke();
}
// Right panel grid
for (let i = 0; i < 3; i++) {
ctx.beginPath();
ctx.moveTo(this.x + this.width - panelW, panelY + panelH * (i + 1) / 4);
ctx.lineTo(this.x + this.width, panelY + panelH * (i + 1) / 4);
ctx.stroke();
}
for (let i = 0; i < 1; i++) {
ctx.beginPath();
ctx.moveTo(this.x + this.width - panelW * (i + 1) / 2, panelY);
ctx.lineTo(this.x + this.width - panelW * (i + 1) / 2, panelY + panelH);
ctx.stroke();
}
// Windows on command module (matching land base)
ctx.fillStyle = '#88ccff';
const windowSize = bodyW * 0.1;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 2; j++) {
ctx.fillRect(
bodyX + bodyW * 0.2 + i * bodyW * 0.3,
bodyY + bodyH * 0.25 + j * bodyH * 0.3,
windowSize, windowSize
);
}
}
// Missile launchers (top and bottom, similar to land base's dual launchers)
const launcherW = bodyW * 0.15;
const launcherH = this.height * 0.15;
// Top launcher
ctx.fillStyle = '#777777';
ctx.fillRect(bodyX + (bodyW - launcherW) / 2, bodyY - launcherH * 0.6, launcherW, launcherH * 0.6);
// Top missile
const missileW = launcherW * 0.6;
ctx.fillStyle = '#cccccc';
ctx.fillRect(bodyX + (bodyW - missileW) / 2, bodyY - launcherH * 1.5, missileW, launcherH * 0.9);
// Missile tip
ctx.fillStyle = '#ff3333';
ctx.beginPath();
ctx.moveTo(bodyX + (bodyW - missileW) / 2, bodyY - launcherH * 1.5);
ctx.lineTo(bodyX + bodyW / 2, bodyY - launcherH * 1.8);
ctx.lineTo(bodyX + (bodyW + missileW) / 2, bodyY - launcherH * 1.5);
ctx.closePath();
ctx.fill();
// Bottom launcher
ctx.fillStyle = '#777777';
ctx.fillRect(bodyX + (bodyW - launcherW) / 2, bodyY + bodyH, launcherW, launcherH * 0.6);
// Bottom missile
ctx.fillStyle = '#cccccc';
ctx.fillRect(bodyX + (bodyW - missileW) / 2, bodyY + bodyH + launcherH * 0.6, missileW, launcherH * 0.9);
// Bottom missile tip
ctx.fillStyle = '#ff3333';
ctx.beginPath();
ctx.moveTo(bodyX + (bodyW - missileW) / 2, bodyY + bodyH + launcherH * 1.5);
ctx.lineTo(bodyX + bodyW / 2, bodyY + bodyH + launcherH * 1.8);
ctx.lineTo(bodyX + (bodyW + missileW) / 2, bodyY + bodyH + launcherH * 1.5);
ctx.closePath();
ctx.fill();
// Communication antenna (matching land base)
ctx.strokeStyle = '#aaaaaa';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(bodyX + bodyW * 0.8, bodyY);
ctx.lineTo(bodyX + bodyW * 0.8, bodyY - bodyH * 0.3);
ctx.stroke();
ctx.beginPath();
ctx.arc(bodyX + bodyW * 0.8, bodyY - bodyH * 0.3, bodyW * 0.05, 0, Math.PI * 2);
ctx.stroke();
// Status light
ctx.fillStyle = this.lightColor;
if (Math.floor(Date.now() / 500) % 2 === 0) {
ctx.beginPath();
ctx.arc(bodyX + bodyW * 0.2, bodyY + bodyH * 0.5, bodyW * 0.03, 0, Math.PI * 2);
ctx.fill();
}
// Ammo display
ctx.fillStyle = '#ffff00';
const fontSize = Math.max(7, Math.min(10, Math.floor(this.width * 0.25)));
ctx.font = `${fontSize}px "Press Start 2P"`;
ctx.textAlign = 'center';
ctx.textBaseline = 'top';
ctx.fillText(this.ammo, this.x + this.width / 2, this.y + this.height + 3);
}
};
}
function createIncomingMissile(config = {}) {
const startX = config.startX !== undefined ? config.startX : Math.random() * canvas.width;
const startY = config.startY !== undefined ? config.startY : 0;
const target = config.target || getRandomTarget();
let baseSpeed = MISSILE_SPEED_ENEMY_BASE + (currentWave * 0.08);
baseSpeed = Math.min(baseSpeed, MAX_ENEMY_MISSILE_SPEED);
const speed = config.speed || baseSpeed * (config.speedFactor || 1.0);
const angle = Math.atan2(target.y - startY, target.x - startX);
const groundY = canvas.height - (canvas.height * GROUND_HEIGHT_RATIO);
const waveSmartBombChance = SMART_BOMB_CHANCE * (1 + currentWave * 0.05);
const waveMIRVChance = MIRV_CHANCE * (1 + currentWave * 0.03);
let isSmartBomb = config.isSmartBomb !== undefined ? config.isSmartBomb : (!config.isMIRV && !config.isSplit && Math.random() < waveSmartBombChance);
let isMIRV = config.isMIRV !== undefined ? config.isMIRV : (!isSmartBomb && !config.isSplit && Math.random() < waveMIRVChance);
let isSplit = config.isSplit || false;
let color = '#ff0000'; let trailColor = 'rgba(255, 100, 100, 0.5)';
if (isMIRV) { color = MIRV_WARHEAD_COLOR; trailColor = 'rgba(255, 150, 150, 0.5)'; }
if (isSmartBomb) { color = SMART_BOMB_SPLIT_COLOR; trailColor = 'rgba(255, 200, 100, 0.5)'; }
if (isSplit) { color = config.color || color; trailColor = config.trailColor || trailColor; }
// Add the ignoreEnemyObjectsWhenExploding flag, default to false
const ignoreEnemyObjectsWhenExploding = config.ignoreEnemyObjectsWhenExploding || false;
return {
x: startX, y: startY, targetX: target.x, targetY: target.y, dx: Math.cos(angle) * speed, dy: Math.sin(angle) * speed, speed: speed, color: color, trailColor: trailColor, alive: true, trail: [{x: startX, y: startY}], isPlaneBomb: false, isSmartBomb: isSmartBomb, isMIRV: isMIRV, isSplit: isSplit, hasSplit: false, wavePartType: config.wavePartType, ignoreEnemyObjectsWhenExploding: ignoreEnemyObjectsWhenExploding, countedAsDestroyed: false, // NEW: Flag for deferred counting
update() {
if (!this.alive) return;
this.x += this.dx; this.y += this.dy; this.trail.push({x: this.x, y: this.y}); if (this.trail.length > 15) { this.trail.shift(); }
if (this.isMIRV && !this.hasSplit && this.y >= MIRV_SPLIT_ALTITUDE) {
this.alive = false; this.hasSplit = true;
// Create an explosion that ignores enemy objects
createExplosion(this.x, this.y, EXPLOSION_RADIUS_START * 0.5, this.color, null, null, true);
for (let i = 0; i < MIRV_WARHEAD_COUNT; i++) {
// Use getBaseOrCityTarget for MIRV splits instead of getRandomTarget
const warheadTarget = getBaseOrCityTarget();
incomingMissiles.push(createIncomingMissile({
startX: this.x,
startY: this.y,
target: warheadTarget,
speed: this.speed * MIRV_WARHEAD_SPEED_FACTOR,
isSplit: true,
isMIRV: false,
isSmartBomb: false,
color: MIRV_WARHEAD_COLOR,
trailColor: 'rgba(255, 150, 150, 0.5)',
ignoreEnemyObjectsWhenExploding: true,
wavePartType: this.wavePartType
}));
}
return;
}
const splitAltitude = SMART_BOMB_SPLIT_ALTITUDE_MIN + Math.random() * (SMART_BOMB_SPLIT_ALTITUDE_MAX - SMART_BOMB_SPLIT_ALTITUDE_MIN);
if (this.isSmartBomb && !this.hasSplit && this.y >= splitAltitude) {
this.alive = false; this.hasSplit = true;
// Create an explosion that ignores enemy objects
createExplosion(this.x, this.y, EXPLOSION_RADIUS_START * 0.4, this.color, null, null, true);
for (let i = 0; i < SMART_BOMB_SPLIT_COUNT; i++) {
// Use getBaseOrCityTarget for smart bomb splits instead of getRandomTarget
const splitTarget = getBaseOrCityTarget();
incomingMissiles.push(createIncomingMissile({
startX: this.x,
startY: this.y,
target: splitTarget,
speed: this.speed * SMART_BOMB_SPLIT_SPEED_FACTOR,
isSplit: true,
isMIRV: false,
isSmartBomb: false,
color: SMART_BOMB_SPLIT_COLOR,
trailColor: 'rgba(255, 200, 100, 0.5)',
ignoreEnemyObjectsWhenExploding: true,
wavePartType: this.wavePartType
}));
}
return;
}
if (this.y >= this.targetY || this.y >= groundY) {
this.alive = false; const impactY = Math.min(this.targetY, groundY); const explosionSizeFactor = this.isSplit ? 0.6 : 1.0;
createExplosion(this.x, impactY, (EXPLOSION_RADIUS_MAX_BASE / 2) * explosionSizeFactor, this.color, null, null, this.ignoreEnemyObjectsWhenExploding);
checkObjectImpact(this.x, impactY, this.isPlaneBomb);
}
},
draw() {
if (!this.alive) return; ctx.strokeStyle = this.trailColor; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(this.trail[0].x, this.trail[0].y); for (let i = 1; i < this.trail.length; i++) { ctx.lineTo(this.trail[i].x, this.trail[i].y); } ctx.stroke();
const size = (this.isMIRV || this.isSmartBomb) && !this.hasSplit ? 5 : 4; ctx.fillStyle = this.color; ctx.fillRect(this.x - size/2, this.y - size/2, size, size); if ((this.isMIRV || this.isSmartBomb) && !this.hasSplit && Math.floor(Date.now() / 200) % 2 === 0) { ctx.fillStyle = 'rgba(255, 255, 255, 0.5)'; ctx.fillRect(this.x - size/2 - 1, this.y - size/2 - 1, size + 2, size + 2); }
}
};
}
function createPlayerMissile(startX, startY, targetX, targetY) {
const currentSpeed = getCurrentPlayerMissileSpeed(); const angle = Math.atan2(targetY - startY, targetX - startX); statsMissilesFired++;
playSfx(launchBuffer); // ADDED: Play launch sound
return {
x: startX, y: startY, targetX: targetX, targetY: targetY, dx: Math.cos(angle) * currentSpeed, dy: Math.sin(angle) * currentSpeed, speed: currentSpeed, color: '#00ff00', trailColor: 'rgba(100, 255, 100, 0.5)', alive: true, trail: [{x: startX, y: startY}],
update() {
if (!this.alive) return; this.x += this.dx; this.y += this.dy; this.trail.push({x: this.x, y: this.y}); if (this.trail.length > 10) { this.trail.shift(); } const distToTarget = distance(this.x, this.y, this.targetX, this.targetY); if (distToTarget < this.speed || (this.dx * (this.targetX - this.x) + this.dy * (this.targetY - this.y)) < 0) { this.alive = false; const currentExplosionRadius = getCurrentPlayerExplosionRadius(); createExplosion(this.targetX, this.targetY, EXPLOSION_RADIUS_START, this.color, currentExplosionRadius); }
},
draw() { if (!this.alive) return; ctx.strokeStyle = this.trailColor; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(this.trail[0].x, this.trail[0].y); for (let i = 1; i < this.trail.length; i++) { ctx.lineTo(this.trail[i].x, this.trail[i].y); } ctx.stroke(); ctx.fillStyle = this.color; ctx.fillRect(this.x - 1, this.y - 1, 3, 3); }
};
}
function getBaseOrCityTarget() {
const aliveCities = cities.filter(c => c.alive);
const aliveBases = [...bases.filter(b => b.alive), ...satelliteBases.filter(s => s.alive)];
let possibleTargets = [...aliveCities, ...aliveBases];
const groundY = canvas.height - (canvas.height * GROUND_HEIGHT_RATIO);
if (possibleTargets.length === 0) {
// If no cities or bases are alive, target a random ground position
let targetGroundX = canvas.width / 2 + (Math.random() - 0.5) * canvas.width * 0.4;
return { x: targetGroundX, y: groundY };
}
// Select a random city or base
const target = possibleTargets[Math.floor(Math.random() * possibleTargets.length)];
return { x: target.x + (target.width / 2), y: target.y };
}
function createExplosion(x, y, startRadius, color, maxRadius = EXPLOSION_RADIUS_MAX_BASE, duration = EXPLOSION_DURATION, ignoreEnemyObjectsWhenExploding = false) {
const effectiveMaxRadius = maxRadius || getCurrentPlayerExplosionRadius();
if (typeof color !== 'string' || (!color.startsWith('#') && !color.startsWith('rgba'))) { color = '#888888'; }
playSfx(explosionBuffer); // ADDED: Play explosion sound
explosions.push({
x: x, y: y, radius: startRadius, maxRadius: effectiveMaxRadius, duration: duration, currentFrame: 0, color: color, alive: true, collidedMissiles: new Set(), collidedBombs: new Set(), collidedPlanes: new Set(), ignoreEnemyObjectsWhenExploding: ignoreEnemyObjectsWhenExploding, killCount: 0, // NEW: Initialize kill count for combo
update() { if (!this.alive) return; this.currentFrame++; const expansionPhase = this.duration * 0.6; if (this.currentFrame <= expansionPhase) { this.radius = startRadius + (this.maxRadius - startRadius) * (this.currentFrame / expansionPhase); } else { this.radius = this.maxRadius - (this.maxRadius * ((this.currentFrame - expansionPhase) / (this.duration - expansionPhase))); } this.radius = Math.max(0, this.radius); if (this.currentFrame >= this.duration) { this.alive = false; } if (this.currentFrame < expansionPhase) { checkExplosionCollisions(this); } },
draw() { if (!this.alive) return; ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2); const intensity = Math.sin((this.currentFrame / this.duration) * Math.PI); let r = 180, g = 180, b = 180; try { if (this.color.startsWith('#') && this.color.length >= 7) { r = parseInt(this.color.slice(1, 3), 16); g = parseInt(this.color.slice(3, 5), 16); b = parseInt(this.color.slice(5, 7), 16); } else if (this.color.startsWith('rgba')) { const parts = this.color.match(/(\d+),\s*(\d+),\s*(\d+)/); if (parts) { r = parseInt(parts[1]); g = parseInt(parts[2]); b = parseInt(parts[3]); } } } catch (e) { console.warn("Could not parse explosion color:", this.color, e); r = 180; g = 180; b = 180; } ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${0.3 + intensity * 0.6})`; ctx.fill(); ctx.beginPath(); ctx.arc(this.x, this.y, this.radius * 0.3 * intensity, 0, Math.PI * 2); ctx.fillStyle = `rgba(255, 255, 255, ${intensity * 0.8})`; ctx.fill(); }
});
}
function createPlane() {
const startY = PLANE_MIN_Y + Math.random() * (PLANE_MAX_Y - PLANE_MIN_Y); const bombsToDrop = BASE_BOMBS_PER_PLANE + Math.floor(currentWave / 3) * BOMBS_INCREASE_PER_WAVE; const isVariant = Math.random() < PLANE_VARIANT_CHANCE; const speedMultiplier = isVariant ? 1.4 : 1.0; const planeSpeed = (PLANE_SPEED_BASE + currentWave * PLANE_SPEED_INCREASE_PER_WAVE) * speedMultiplier; const bodyColor = isVariant ? '#A9A9A9' : '#B0C4DE'; const wingColor = isVariant ? '#696969' : '#778899';
return {
x: canvas.width + PLANE_WIDTH, y: startY, width: PLANE_WIDTH, height: PLANE_HEIGHT, speed: planeSpeed, alive: true, bombsLeft: bombsToDrop, bombDropTimer: PLANE_BOMB_DROP_INTERVAL_MIN + Math.random() * (PLANE_BOMB_DROP_INTERVAL_MAX - PLANE_BOMB_DROP_INTERVAL_MIN), bodyColor: bodyColor, wingColor: wingColor, tailColor: '#708090', cockpitColor: '#1E90FF', engineColor: '#555555', isVariant: isVariant, wavePartType: 'plane',
update() { if (!this.alive) return; this.x -= this.speed; this.bombDropTimer--; if (this.bombDropTimer <= 0 && this.bombsLeft > 0) { this.dropBomb(); this.bombsLeft--; this.bombDropTimer = PLANE_BOMB_DROP_INTERVAL_MIN + Math.random() * (PLANE_BOMB_DROP_INTERVAL_MAX - PLANE_BOMB_DROP_INTERVAL_MIN); } if (this.x < -this.width * 1.5) { this.alive = false; } },
dropBomb() { const bombStartX = this.x + this.width / 2; const bombStartY = this.y + this.height * 0.7; planeBombs.push(createBomb(bombStartX, bombStartY)); },
draw() { if (!this.alive) return; const w = this.width; const h = this.height; const x = this.x; const y = this.y; ctx.save(); ctx.translate(x, y); ctx.fillStyle = this.bodyColor; ctx.beginPath(); ctx.moveTo(w * 0.1, h * 0.3); ctx.lineTo(w * 0.85, h * 0.15); ctx.quadraticCurveTo(w, h * 0.5, w * 0.85, h * 0.85); ctx.lineTo(w * 0.1, h * 0.7); ctx.quadraticCurveTo(0, h * 0.5, w * 0.1, h * 0.3); ctx.closePath(); ctx.fill(); ctx.strokeStyle = '#666'; ctx.lineWidth = 1; ctx.stroke(); ctx.fillStyle = this.cockpitColor; ctx.beginPath(); ctx.moveTo(w * 0.7, h * 0.25); ctx.lineTo(w * 0.9, h * 0.4); ctx.lineTo(w * 0.9, h * 0.6); ctx.lineTo(w * 0.7, h * 0.75); ctx.closePath(); ctx.fill(); ctx.fillStyle = this.wingColor; ctx.beginPath(); ctx.moveTo(w * 0.3, h * 0.3); ctx.lineTo(w * 0.6, h * -0.1); ctx.lineTo(w * 0.7, h * 0.1); ctx.lineTo(w * 0.45, h * 0.4); ctx.closePath(); ctx.fill(); ctx.beginPath(); ctx.moveTo(w * 0.3, h * 0.7); ctx.lineTo(w * 0.6, h * 1.1); ctx.lineTo(w * 0.7, h * 0.9); ctx.lineTo(w * 0.45, h * 0.6); ctx.closePath(); ctx.fill(); ctx.strokeStyle = '#555'; ctx.stroke(); ctx.fillStyle = this.tailColor; ctx.beginPath(); ctx.moveTo(w * 0.05, h * 0.3); ctx.lineTo(w * 0.2, h * -0.1); ctx.lineTo(w * 0.25, h * 0.1); ctx.lineTo(w * 0.1, h * 0.4); ctx.closePath(); ctx.fill(); ctx.stroke(); ctx.fillStyle = this.wingColor; ctx.beginPath(); ctx.moveTo(w * 0.05, h * 0.3); ctx.lineTo(w * 0.2, h * 0.1); ctx.lineTo(w * 0.25, h * 0.2); ctx.closePath(); ctx.fill(); ctx.beginPath(); ctx.moveTo(w * 0.05, h * 0.7); ctx.lineTo(w * 0.2, h * 0.9); ctx.lineTo(w * 0.25, h * 0.8); ctx.closePath(); ctx.fill(); ctx.fillStyle = this.engineColor; ctx.fillRect(w * 0.4, h * 0.6, w * 0.25, h * 0.3); ctx.fillRect(w * 0.4, h * 0.1, w * 0.25, h * 0.3); ctx.restore(); }
};
}
function createBomb(startX, startY) {
const target = getRandomTarget(); const angle = Math.atan2(target.y - startY, target.x - startX); const groundY = canvas.height - (canvas.height * GROUND_HEIGHT_RATIO); const speed = PLANE_BOMB_SPEED + (currentWave * 0.03);
return {
x: startX, y: startY, targetX: target.x, targetY: target.y, dx: Math.cos(angle) * speed, dy: Math.sin(angle) * speed, color: PLANE_BOMB_COLOR, trailColor: PLANE_BOMB_TRAIL_COLOR, alive: true, trail: [{x: startX, y: startY}], isPlaneBomb: true,
update() { if (!this.alive) return; this.x += this.dx; this.y += this.dy; this.trail.push({x: this.x, y: this.y}); if (this.trail.length > 12) { this.trail.shift(); } if (this.y >= this.targetY || this.y >= groundY) { this.alive = false; const impactY = Math.min(this.targetY, groundY); createExplosion(this.x, impactY, EXPLOSION_RADIUS_START * 0.8, this.color, EXPLOSION_RADIUS_MAX_BASE * 0.6); checkObjectImpact(this.x, impactY, this.isPlaneBomb); } },
draw() { if (!this.alive) return; ctx.strokeStyle = this.trailColor; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(this.trail[0].x, this.trail[0].y); for (let i = 1; i < this.trail.length; i++) { ctx.lineTo(this.trail[i].x, this.trail[i].y); } ctx.stroke(); ctx.fillStyle = this.color; ctx.beginPath(); ctx.arc(this.x, this.y, 3, 0, Math.PI * 2); ctx.fill(); }
};
}