-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
3664 lines (3190 loc) · 123 KB
/
Copy pathgame.js
File metadata and controls
3664 lines (3190 loc) · 123 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
//up to now just create functional game
// 0.01 humble beginnings
// 0.01 - 1.00 just create functional game first
// 1.1 time based animation
// 1.2 limit fire rate
// 1.3 enemies also shoot!
// 1.4 player hit and lives system
// 1.5 sound!
// 1.6 walls a bit bigger
// 1.6 use a vax to shoot at IBM
// 1.7 MUTE button
// 1.8 remove console log messages
// 1.9 1000 extra points when user finishes the level
// 2.0 touch screen support! (later removed again)
// 2.1 oh no! homing missiles from the evil empire!
// 2.2 fix missile logic, add assets and add favicon support
// 2.3 fix opening page and walls can now collapse!
// 2.4 vax bullets also deterioate walls
// 2.5 fix some sound issues
// 2.5.1 fix new level unexplained pause
// 2.5.2 also enable A for left and D for right move
// 2.5.3 show new level banner before continuing
// 2.6 fire rate slower while moving
// 2.7 avoid missed promise in sound playing
// 2.8 fix game over race condition
// 2.9 sometimes change explosion type for enemies to make more interesting
// 3.0 more sound effects
// 3.0.1 old bug of enemy reacching criticla position fix?
// 3.0.2 display game over when enmies reach critical position
// 3.0.3 aha! (?) only enemies alive can reach wall
// 3.1 catch bug when no more walls are around
// 3.2 defintely show game over when it's over
// 3.2.1 small parameter tune-ups
// 3.2.2 enemies fire more frequent as levels increase
// 3.2.3 version taken from the javascript file
// 3.24 change enemy explosions graphics a bit
// 3.2.5 clode clean up
// 3.3 touch support again !
// 3.4 columns of enemies respond to browser window size
// 3.5.1 touch controls now also fire bullets
// 3.6 monster on top of screen
// 3.6.1 the monster can shoot!
// 3.6.2 make monster shoot missiles from its position
// 3.6.3 restore walls when monster hit
// 3.6.4 fix collision detection regression with missiles...arghhh
// 3.6.5 Yannai fixed F11 race condition
// 3.6.6 Small tune ups (due to monster death regenerating walls again)
// 3.7 Show lives with space ships instead of just numbers
// 3.7.1 Show brief animation in lower right corner when life is list
// 3.8 Every 5th shot down missile, player gets a bonus
// 3.9 Firebirds opening screen, and walls protect from bullets
// 4.0 Every 7 bonus grants, player gets one life back!
// 4.0.1 Small fixes in restart logic (reset values)
// 4.1 With new life, user is informed thru life grand animation
// 4.2 Adjustements to canvas size, redo all html, and scale content
// 4.2.1 Some adjustements to positiongs and reset logic
// 4.2.2 Put enemies a bit further down
// 4.3 Make canvas always 1024x576, and center it on the screen
// 4.3.1 Scale up a bit more, and make bonusSound and new life grand silent if muted
// 4.4 AI mode with F1 !!!
// 4.4.1 Refine bullet and missile avoidance
// 4.4.2 better threat trajectory analysis
// 4.4.3 better bullets avoidance in lateral movement for AI mode
// 4.4 also look sideways for bullets when moving in AI mode
// 4.5 Use space background image instead of solid color
// 4.5.1 Fix player size
// 4.5.3 fix wall restoratin and re-initialization of game
// 4.5.4 wall damage handling
// 4.5.5 wall damage look nicer
// 4.5.6 revised sounds
// 4.6 first stable version with preloading of assets and sound
// 4.6.1 restrict certain locales, adjust monster position
// 4.6.2 only advance speed of enemies by 9% between levels to make it more playable
// 4.6.3 limit enemy firing rate in new levels to make game more playable
// 4.6.4 make bullets a bit bigger
// 4.7 various playability improvements (no bullets while player is hit)
// 4.8 kamikaze enemies!
// 4.8.1 better kamikaze artwork
// 4.9 hot streak message for player
// 4.9.1-6 fix various kamikaze small bugs
// 5.0 whole new game play!
// 5.1 monster starts to move down at end of a sceneshouldSlalom = enemies.length < KAMIKA
// 5.2.1-5 fix monster slalom mod and ipad game playing issues
// 5.3 new monster enemy with different behavior patterns
// 5.4 make a bit more playable and more monster2 patterns
// 5.5 code cleanup
// 5.6 put enemy explosions back in, change points system a bit, code cleanup
// 5.6 - 5.94 herustic AI mode
// 6.0 neural network inference engine AI mode
const VERSION = "v6.0.1"; // version showing in index.html
// keep right after the VERSION constant
if (document.getElementById('version-info')) {
document.getElementById('version-info').textContent = VERSION;
}
// canvas size!
const GAME_WIDTH = 1024;
const GAME_HEIGHT = 576;
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
// Set the fixed canvas size
canvas.width = GAME_WIDTH;
canvas.height = GAME_HEIGHT;
// Remove the solid background from canvas to let space background show through
canvas.style.position = 'absolute';
canvas.style.left = '0';
canvas.style.top = '0';
canvas.style.backgroundColor = 'transparent';
// Background styles for the body
document.body.style.margin = '0';
document.body.style.padding = '0';
document.body.style.width = '100vw';
document.body.style.height = '100vh';
document.body.style.overflow = 'hidden';
document.body.style.backgroundImage = 'url(space.jpg)';
document.body.style.backgroundSize = 'cover';
document.body.style.backgroundPosition = 'center';
document.body.style.backgroundRepeat = 'no-repeat';
// Update resize handler
window.addEventListener('resize', () => {
// No positioning updates needed
});
// streak related constants
const STREAK_MESSAGES = ["Rampage!", "Oh yeah!", "Unstoppable!", "Savage!", "Sweet!", "Legendary!"];
const HOT_STREAK_WINDOW = 15000; // measurement window for sterak msg
const HOT_STREAK_MESSAGE_DURATION = 3000; // 1 second in milliseconds
let currentKillCount = 0;
let previousKillCount = 0;
let lastStreakCheckTime = 0;
let showHotStreakMessage = false;
let hotStreakMessageTimer = 0;
let currentStreakMessage = "";
// streak related variables above
// ther monster constants
const MONSTER_SLALOM_SPEED = 170; // Speed during slalom movement
const MONSTER_SLALOM_AMPLITUDE = 350; // Increased from 200 to 350 for wider swings
const MONSTER_VERTICAL_SPEED = 60; // Reduced from 100 to 60 for slower descent
const MONSTER_SLALOM_FIRE_RATE = 1800; // Fire rate during slalom mode (2 seconds)
const MONSTER_MISSILE_INTERVAL = 500; // Time between monster's missile shots (500ms)
let lastMonsterMissileTime = 0;
// other state variables at the top
let lifeRemovalAnimation = null;
let vaxGoneImage = new Image();
vaxGoneImage.src = 'vax_gone.svg';
// state variables
let monster = null;
let monsterDirection = 1; // 1 for right, -1 for left
let lastMonsterTime = 0;
const MONSTER_INTERVAL = 6000; // seconds between monster appearances
const MONSTER2_INTERVAL = 10000; //econds between monster appearances
const MONSTER_SPEED = 175; // pixels per second
const MONSTER_WIDTH = 56; //
const MONSTER_HEIGHT = 56; //
const MONSTER_HIT_DURATION = 700; // 0.7 seconds
let monsterHit = false;
let monsterImage = new Image();
let monsterHitImage = new Image();
monsterImage.src = 'monster.svg';
monsterHitImage.src = 'monster_shot.svg';
// Kamikaze enemy settings
const KAMIKAZE_MIN_TIME = 6000; // Min time between kamikaze launches
const KAMIKAZE_MAX_TIME = 11000; // Max time between kamikaze launches
const KAMIKAZE_SPEED = 170; // Kamikaze movement speed (pixels per second)
const KAMIKAZE_FIRE_RATE = 900; // Fire rate in milliseconds
const KAMIKAZE_AGGRESSIVE_TIME = 4000; // Time between kamikazes when < 25 enemies
const KAMIKAZE_VERY_AGGRESSIVE_TIME = 2200; // Time between kamikazes when < 10 enemies
const KAMIKAZE_AGGRESSIVE_THRESHOLD = 26; // First threshold (25 enemies)
const KAMIKAZE_VERY_AGGRESSIVE_THRESHOLD = 11; // Second threshold in number of enemies
let lifeGrant = false;
const PLAYER_LIVES = 6; // starting lives
let bonusGrants = 0; // start with no bonus
const BONUS2LIVES = 5; // every n bonuses, player gets one life
const BULLET_SPEED = 300; // Player bullet speed (pixels per second)
const ENEMY_BULLET_SPEED = BULLET_SPEED / 3; // Enemy bullet speed (1/3 of player bullet speed)
const HIT_MESSAGE_DURATION = 900; // How long to show "HIT!" message in milliseconds
const PLAYER_HIT_ANIMATION_DURATION = 750; // Duration in milliseconds (0.5 seconds)
const MIN_MISSILE_INTERVAL = 3200; // 3 seconds
const MAX_MISSILE_INTERVAL = 7200; //
const MISSILE_SPEED = 170; // pixels per second
let shotCounter = 0; // during rapid fire, only sound every
let nextMissileTime = 0;
let homingMissiles = [];
let homingMissileHits = 0; // every 5th missile shot down we give bonus
let missileImage = new Image();
missileImage.src = 'missile.svg';
// monster-related constants
const MONSTER2_WIDTH = 56;
const MONSTER2_HEIGHT = 56;
const MONSTER2_SPEED = 220; // Slightly faster than monster1
const MONSTER2_SPIRAL_RADIUS = 100;
const MONSTER2_SPIRAL_SPEED = 3;
const MONSTER2_VERTICAL_SPEED = 40;
// image declarations
let monster2Image = new Image();
monster2Image.src = 'monster2.svg';
// onster state variables
let monster2 = null;
let lastMonster2Time = 0;
const MONSTER2_DISAPPEAR_TIME = 8000; // 8 seconds disappearance time
const MONSTER2_MIN_RETURN_TIME = 5000; // 5 seconds minimum return time
const MONSTER2_MAX_RETURN_TIME = 9000; // 9 seconds maximum return time
// other monster2 constants
const MONSTER2_PATTERNS = {
2: 'spiral', // Level 2: Spiral pattern
3: 'zigzag', // Level 3: Horizontal zigzag while descending
4: 'figure8', // Level 4: Figure 8 pattern
5: 'bounce', // Level 5: Bounce off screen edges
6: 'wave', // Level 6: Sinusoidal wave pattern
7: 'teleport', // Level 7: Random teleportation
8: 'chase', // Level 8: Chase player with prediction
9: 'random' // Level 9+: Random quick movements
};
let player = {
x: canvas.width / 2 - 37,
y: canvas.height - 30,
width: 48,
height: 48,
dx: 5,
lives: PLAYER_LIVES,
image: new Image(),
};
//let bonusgrants = 0; // tracks how many bonuses player got, every 7th lives++
let bullets = [];
let enemies = [];
let explosions = [];
let score = 0;
let enemyHitsToDestroy = 2; // how many times an enemy needs to be hit
let enemySpeed = 0.54; // Decreased from 0.55
let enemyDirection = 1; // 1 for right, -1 for left
let gamePaused = false;
let lastFireTime = 0;
let gameOverFlag = false;
let victoryFlag = false;
let lastTime = 0;
const PLAYER_SPEED = 300; // pixels per second
const ENEMY_SPEED = 50; // pixels per second
const FIRE_RATE = 0.16; // Time in seconds between shots (0.1 = 10 shots per second)
const ENEMY_FIRE_RATE = 0.72; // Time in seconds between enemy shots
let lastEnemyFireTime = 0;
let hitMessageTimer = 0;
let showHitMessage = false;
let playerHitTimer = 0;
let isPlayerHit = false;
let whilePlayerHit = false;
let playerNormalImage = new Image();
let playerExplosionImage = new Image();
playerNormalImage.src = "vax.svg";
playerExplosionImage.src = "player_explosion.svg";
player.image = playerNormalImage;
const KAMIKAZE_HITS_TO_DESTROY = 2; // Number of hits needed to destroy a kamikaze
let kamikazeExplosionImage = new Image();
kamikazeExplosionImage.src = 'explode_kamikaze.svg';
const keys = {
ArrowLeft: false,
ArrowRight: false,
KeyD: false,
KeyA: false,
Space: false,
P: false,
p: false,
R: false,
r: false,
KeyB: false,
};
let wallImage = new Image();
wallImage.src = 'wall.svg';
let chunkImage = new Image();
chunkImage.src = 'chunk.png';
const WALL_HITS_FROM_BELOW = 3; // hits needed for wall damage from player shots
const WALL_MAX_HITS_TOTAL = 11; // total hits before wall disappears
const WALL_MAX_MISSILE_HITS = 4; // hits from missiles before wall disappears
// Original wall positions with evenly spaced walls
const INITIAL_WALLS = [
{
x: canvas.width * 1/5 - 29, // First wall at 1/5
y: canvas.height - 75,
width: 58,
height: 23,
image: wallImage
},
{
x: canvas.width * 2/5 - 29, // Second wall at 2/5
y: canvas.height - 75,
width: 58,
height: 23,
image: wallImage
},
{
x: canvas.width * 3/5 - 29, // Third wall at 3/5
y: canvas.height - 75,
width: 58,
height: 23,
image: wallImage
},
{
x: canvas.width * 4/5 - 29, // Fourth wall at 4/5
y: canvas.height - 75,
width: 58,
height: 23,
image: wallImage
}
];
let walls = INITIAL_WALLS.map(wall => ({
...wall,
hitCount: 0,
missileHits: 0
}));
// Initialize wallHits array for all walls
let wallHits = walls.map(() => []);
//counter for tracking explosions
let explosionCounter = 0;
// At the start of the game where other assets are loaded
let explosionImg = new Image();
explosionImg.src = 'explosion.svg';
let explosionAdditionalImg = new Image();
explosionAdditionalImg.src = 'explosion_additional.svg';
const BASE_FIRE_RATE = 0.190; // Base time in seconds between shots
let currentFireRate = BASE_FIRE_RATE; // Current fire rate that can be modified
// for enemies
const BASE_ENEMY_FIRE_RATE = 0.85; // Base time in seconds between enemy shots
const ENEMY_FIRE_RATE_INCREASE = 0.10;// % increase per level
let currentEnemyFireRate = BASE_ENEMY_FIRE_RATE;
// other initialization code
let isTouchDevice = false;
let isTablet = false;
// Detect if device is a tablet
function detectTablet() {
// Check if touch device
isTouchDevice = ('ontouchstart' in window) ||
(navigator.maxTouchPoints > 0) ||
(navigator.msMaxTouchPoints > 0);
// Check if tablet based on screen size
isTablet = isTouchDevice &&
Math.min(window.innerWidth, window.innerHeight) >= 768 &&
Math.max(window.innerWidth, window.innerHeight) <= 1366;
// Show/hide touch controls based on device
const touchControls = document.getElementById('touch-controls');
if (touchControls) {
touchControls.style.display = isTablet ? 'block' : 'none';
}
}
// Initialize touch controls
function initTouchControls() {
detectTablet();
if (!isTablet) return;
const touchStart = document.getElementById('touch-start');
const touchLeft = document.getElementById('touch-left');
const touchRight = document.getElementById('touch-right');
const touchFireLeft = document.getElementById('touch-fire-left');
const touchFireRight = document.getElementById('touch-fire-right');
// Start button
touchStart.addEventListener('click', () => {
startGame();
touchStart.style.display = 'none';
});
// Movement controls
touchLeft.addEventListener('touchstart', (e) => {
e.preventDefault();
keys.ArrowLeft = true;
});
touchLeft.addEventListener('touchend', () => {
keys.ArrowLeft = false;
});
touchRight.addEventListener('touchstart', (e) => {
e.preventDefault();
keys.ArrowRight = true;
});
touchRight.addEventListener('touchend', () => {
keys.ArrowRight = false;
});
// Modified fire controls
function handleFireStart(e) {
e.preventDefault();
keys.Space = true;
spaceKeyPressTime = Date.now();
// bullet creation here
if (!gamePausedt && Date.now() - lastFireTime > currentFireRate * 1000) {
bullets.push({
x: player.x + player.width / 2 - 2.5,
y: player.y,
isEnemyBullet: false
});
lastFireTime = Date.now();
playSoundWithCleanup(() => playerShotSound);
}
}
function handleFireEnd(e) {
e.preventDefault();
keys.Space = false;
stopMachineGunSound();
}
// touchstart and click events for better response
touchFireLeft.addEventListener('touchstart', handleFireStart);
touchFireLeft.addEventListener('touchend', handleFireEnd);
touchFireRight.addEventListener('touchstart', handleFireStart);
touchFireRight.addEventListener('touchend', handleFireEnd);
}
// handler to update tablet detection
window.addEventListener('resize', detectTablet);
// Initialize touch controls when the window loads
window.addEventListener('load', initTouchControls);
function createExplosion(x, y) {
explosionCounter++;
if (explosionCounter % 2 === 0) {
playSoundWithCleanup(createExplosionSound);
}
score += 30;
const isAdditionalExplosion = explosionCounter % (Math.random() < 0.5 ? 2 : 3) === 0;
const newExplosion = {
x: x,
y: y,
frame: 0,
img: new Image(),
width: isAdditionalExplosion ? 170 : 96, // Regular explosion now 96 (32 * 3)
height: isAdditionalExplosion ? 170 : 96, // Regular explosion now 96 (32 * 3)
};
// Set the source first, then push to array
newExplosion.img.src = isAdditionalExplosion ? 'explosion_additional.svg' : 'explosion.svg';
explosions.push(newExplosion);
}
function createEnemies() {
const rows = 5;
// Calculate number of columns based on window width
const minCols = 4; // Minimum number of columns
const maxCols = 12; // Maximum number of columns
const enemyWidth = 43; // Increased from 38
const padding = 16; // Increased from 14
const minTotalWidth = (enemyWidth + padding) * minCols;
// Calculate how many columns can fit in the current window width
let cols = Math.floor((canvas.width - 60) / (enemyWidth + padding)); // 60 is total side padding
cols = Math.max(minCols, Math.min(maxCols, cols)); // Clamp between min and max
const enemyHeight = 43; // Increased from 38
// Calculate the optimal starting position based on canvas height
// Use a percentage of canvas height instead of fixed pixels
const maxOffsetTop = 35; // minimum starting position
const desiredOffsetTop = Math.min(canvas.height * 0.2, maxOffsetTop); // 20% of canvas height or 70px, whichever is smaller
// Calculate the ideal gap between enemies and walls
const idealGapToWalls = canvas.height * 0.3; // 30% of canvas height
const wallY = walls[0]?.y || (canvas.height - 75); // fallback if no walls
// Calculate where the bottom row of enemies should end
const bottomRowY = wallY - idealGapToWalls;
// Calculate total height needed for all rows
const totalEnemyHeight = rows * (enemyHeight + padding);
// Calculate final offsetTop to position enemies properly
const offsetTop = Math.max(desiredOffsetTop, bottomRowY - totalEnemyHeight);
// Center the enemies horizontally
const offsetLeft = (canvas.width - (cols * (enemyWidth + padding))) / 2;
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
let color = ["red", "orange", "yellow", "green", "blue"][r % 5];
enemies.push({
x: c * (enemyWidth + padding) + offsetLeft,
y: r * (enemyHeight + padding) + offsetTop,
width: enemyWidth,
height: enemyHeight,
hits: 0,
image: new Image(),
});
enemies[enemies.length - 1].image.src = `enemy-ship-${color}.svg`;
}
}
}
function drawPlayer() {
if (isPlayerHit) {
bullets = bullets.filter(b => !b.isEnemyBullet); // remove enemy bullets
bullets = bullets.filter(b => b.isEnemyBullet); // remove player bullets
whilePlayerHit = true; // flag player is in hit mode and during this time we don't allow bullets
if (Date.now() - playerHitTimer > PLAYER_HIT_ANIMATION_DURATION) {
isPlayerHit = false;
player.image = playerNormalImage;
player.width = 48;
player.height = 48;
} else {
player.image = playerExplosionImage;
player.width = 25 * 2;
player.height = 25 * 2;
// Only draw if image is loaded
if (player.image.complete) {
ctx.drawImage(
player.image,
player.x - (player.width / 2),
player.y - (player.height / 2),
48,
48
);
}
return;
}
whilePlayerHit = false; // flag player is not in hit mode
}
// Only draw if image is loaded
if (player.image.complete) {
ctx.drawImage(player.image, player.x, player.y, player.width, player.height);
}
}
function drawEnemies() {
enemies.forEach((enemy) => {
if (enemy.image.complete) {
ctx.drawImage(enemy.image, enemy.x, enemy.y, enemy.width, enemy.height);
} else {
ctx.fillStyle = 'red';
ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);
enemy.image.onload = () => {
ctx.drawImage(enemy.image, enemy.x, enemy.y, enemy.width, enemy.height);
};
}
});
}
function drawBullets() {
bullets.forEach((bullet) => {
if (bullet.isEnemyBullet) {
if (bullet.isMonster2Bullet) {
ctx.fillStyle = "#ff0000"; // Bright red for monster2 bullets
} else {
ctx.fillStyle = "#39ff14"; // Original neon green for other enemy bullets
}
} else {
ctx.fillStyle = "white"; // Player bullets
}
ctx.fillRect(bullet.x, bullet.y, 3.4, 5.9);
});
}
function drawWalls() {
walls.forEach((wall, index) => {
// Save the current context state
ctx.save();
// First draw the wall
ctx.drawImage(wall.image, wall.x, wall.y, wall.width, wall.height);
// Set up compositing to "cut out" the damage spots
ctx.globalCompositeOperation = 'destination-out';
// Draw the damage holes (they will create transparent areas)
if (wallHits[index]) {
wallHits[index].forEach(hit => {
ctx.save();
ctx.translate(wall.x + hit.x + 10, wall.y + hit.y);
ctx.rotate(hit.rotation);
// Create circular/oval holes instead of drawing chunk images
ctx.beginPath();
if (hit.fromEnemy) {
// Elongated oval for enemy hits
ctx.ellipse(0, 0, 10, 7, 0, 0, Math.PI * 2);
} else {
// Circular hole for player hits
ctx.arc(0, 0, 10, 0, Math.PI * 2);
}
ctx.fill();
ctx.restore();
});
}
// Restore the original context state
ctx.restore();
});
}
function drawExplosions() {
explosions.forEach((explosion) => {
ctx.drawImage(
explosion.img,
explosion.x,
explosion.y,
explosion.width,
explosion.height,
);
});
explosions = explosions.filter(
(explosion) => Date.now() - explosion.startTime < 500,
); // Remove after 500ms
}
function movePlayer(deltaTime) {
// Only allow movement if player is not in hit animation
if (!isPlayerHit) {
if ((keys.ArrowLeft || keys.KeyA) && player.x > 0) {
player.x -= PLAYER_SPEED * deltaTime;
}
if ((keys.ArrowRight || keys.KeyD) && player.x < canvas.width - player.width) {
player.x += PLAYER_SPEED * deltaTime;
}
}
}
function moveBullets(deltaTime) {
bullets.forEach((bullet) => {
if (bullet.isEnemyBullet) {
if (!whilePlayerHit) bullet.y += ENEMY_BULLET_SPEED * deltaTime; // Slower enemy bullets
} else {
if (!whilePlayerHit) bullet.y -= BULLET_SPEED * deltaTime; // no bullets during player hit
}
});
bullets = bullets.filter((bullet) =>
bullet.y > 0 && bullet.y < canvas.height
);
}
function moveEnemies(deltaTime) {
// safety check for large deltaTime values
if (deltaTime > 0.1) deltaTime = 0.1; // Cap maximum deltaTime at 100ms
// First check if there are any enemies at all
if (enemies.length === 0) {
if (!gameOverFlag) {
gamePaused = true;
victory();
}
return;
}
const currentEnemySpeed = (ENEMY_SPEED * enemySpeed) * deltaTime;
let needsToMoveDown = false;
// First check if any enemy needs to change direction
enemies.forEach((enemy) => {
// Skip any null or undefined enemies
if (!enemy) return;
// Skip any "dead" enemies that might still be in the array
if (enemy.hits >= enemyHitsToDestroy) return;
enemy.x += currentEnemySpeed * enemyDirection;
if (enemy.x + enemy.width > canvas.width || enemy.x < 0) {
needsToMoveDown = true;
enemy.x = Math.max(0, Math.min(canvas.width - enemy.width, enemy.x));
}
});
// Then handle direction change and moving down as a separate step
if (needsToMoveDown) {
enemyDirection *= -1;
const moveDownAmount = 20;
enemies.forEach((enemy) => {
// Skip any null or undefined enemies
if (!enemy) return;
// Only check active enemies
if (enemy.hits < enemyHitsToDestroy) {
enemy.y += moveDownAmount;
// Check if there are any walls before checking position
const wallY = walls.length > 0 ? walls[0].y - 20 : canvas.height * 0.90;
if (enemy.y + enemy.height >= wallY) {
gameOverFlag = true;
gameOver();
}
}
});
}
// Clean up any destroyed enemies
enemies = enemies.filter(enemy => enemy && enemy.hits < enemyHitsToDestroy);
if (enemies.length === 0 && !gameOverFlag) {
gamePaused = true;
victory();
}
}
function detectCollisions() {
// Check bullet collisions with walls
bullets.forEach((bullet, bulletIndex) => {
// kamikaze-bullet collision detection
if (!bullet.isEnemyBullet) {
kamikazeEnemies.forEach((kamikaze, kIndex) => {
if (bullet.x < kamikaze.x + kamikaze.width &&
bullet.x + 5 > kamikaze.x &&
bullet.y < kamikaze.y + kamikaze.height &&
bullet.y + 10 > kamikaze.y) {
// Remove bullet
bullets.splice(bulletIndex, 1);
// Increment hit counter
kamikaze.hits++;
// Check if kamikaze is destroyed
if (kamikaze.hits >= KAMIKAZE_HITS_TO_DESTROY) {
// Create special kamikaze explosion
explosions.push({
x: kamikaze.x - 20, // Offset to center the explosion
y: kamikaze.y - 20,
frame: 0,
img: kamikazeExplosionImage,
width: kamikaze.width * 2.2, // Make explosion bigger than the kamikaze
height: kamikaze.height * 2,
startTime: Date.now()
});
// kamikaze is killed, add points and increase kill count
kamikazeEnemies.splice(kIndex, 1);
score += 300;
currentKillCount++; // kill count
// Play kamikaze explosion sound
if (!isMuted) {
kamikazeExplosionSound.currentTime = 0;
kamikazeExplosionSound.play().catch(error => {
console.log("Error playing kamikaze explosion sound:", error);
});
}
}
else {
// Player bullets hitting enemies
enemies.forEach((enemy, eIndex) => {
if (bullet.x < enemy.x + enemy.width &&
bullet.x + 5 > enemy.x &&
bullet.y < enemy.y + enemy.height &&
bullet.y + 10 > enemy.y) {
enemy.hits++;
if (enemy.hits >= enemyHitsToDestroy) {
createExplosion(enemy.x, enemy.y);
enemies.splice(eIndex, 1);
score += 10;
}
bullets.splice(bIndex, 1);
}
});
}
return;
}
});
}
// Existing wall collision check
walls.forEach((wall, wallIndex) => {
if (bullet.x < wall.x + wall.width &&
bullet.x + 5 > wall.x &&
bullet.y < wall.y + wall.height &&
bullet.y + 10 > wall.y) {
// chunk at bullet impact point with rotation info
wallHits[wallIndex].push({
x: bullet.x - wall.x - 10,
y: bullet.isEnemyBullet ?
bullet.y - wall.y + 10 : // Moved enemy bullet impact much lower
bullet.y - wall.y, // Player bullet position unchanged
timeCreated: Date.now(),
rotation: bullet.isEnemyBullet ? 0 : Math.PI
});
// Update wall damage
if (!bullet.isEnemyBullet) {
wall.hitCount++;
} else {
wall.missileHits++;
}
bullets.splice(bulletIndex, 1);
return;
}
});
});
// kamikaze-player and kamikaze-wall collision detection
if (!isPlayerHit) {
kamikazeEnemies.forEach((kamikaze, kIndex) => {
// Check wall collisions first
let hitWall = false;
walls.forEach((wall) => {
if (kamikaze.x < wall.x + wall.width &&
kamikaze.x + kamikaze.width > wall.x &&
kamikaze.y < wall.y + wall.height &&
kamikaze.y + kamikaze.height > wall.y) {
createExplosion(kamikaze.x, kamikaze.y);
kamikazeEnemies.splice(kIndex, 1);
hitWall = true;
return;
}
});
// If didn't hit wall, check player collision
if (!hitWall &&
kamikaze.x < player.x + player.width &&
kamikaze.x + kamikaze.width > player.x &&
kamikaze.y < player.y + player.height &&
kamikaze.y + kamikaze.height > player.y) {
kamikazeEnemies.splice(kIndex, 1);
handlePlayerHit();
createExplosion(kamikaze.x, kamikaze.y);
}
});
}
// missile-player collision detection
if (!isPlayerHit) {
homingMissiles.forEach((missile, mIndex) => {
const dx = (missile.x) - (player.x + player.width / 2);
const dy = (missile.y) - (player.y + player.height / 2);
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < (player.width / 2 + missile.width / 4)) {
homingMissiles.splice(mIndex, 1);
handlePlayerHit();
isPlayerHit = true;
playerHitTimer = Date.now();
player.image = playerExplosionImage;
playerExplosionSound.currentTime = 0;
playerExplosionSound.play();
bullets = bullets.filter(b => !b.isEnemyBullet);
homingMissiles = [];
if (player.lives <= 0) {
gameOverFlag = true;
gameOverSound.currentTime = 0;
gameOverSound.play();
}
}
});
}
// enemy bullet collision with walls
bullets.forEach((bullet, bIndex) => {
if (bullet.isEnemyBullet) { // Check only enemy bullets
walls.forEach((wall, wallIndex) => {
if (bullet.x >= wall.x &&
bullet.x <= wall.x + wall.width &&
bullet.y >= wall.y &&
bullet.y <= wall.y + wall.height) {
// Remove the enemy bullet
bullets.splice(bIndex, 1);
// damage mark
wallHits[wallIndex].push({
x: bullet.x - wall.x,
y: bullet.y - wall.y
});
// Count hits for this wall
wall.hitCount = (wall.hitCount || 0) + 1;
// Remove wall if total hits exceeded
if (wall.hitCount >= WALL_MAX_HITS_TOTAL) {
playSoundWithCleanup(createWallGoneSound);
walls.splice(wallIndex, 1);
wallHits.splice(wallIndex, 1);
}
}
});
}
});
// Update missile collision with walls
homingMissiles.forEach((missile, mIndex) => {
walls.forEach((wall, wallIndex) => {
if (missile.x >= wall.x &&
missile.x <= wall.x + wall.width &&
missile.y >= wall.y &&
missile.y <= wall.y + wall.height) {
wallHits[wallIndex].push({
x: missile.x - wall.x,
y: missile.y - wall.y
});
homingMissiles.splice(mIndex, 1);
// Count missile hits separately
wall.missileHits = (wall.missileHits || 0) + 1;
if (wall.missileHits >= WALL_MAX_MISSILE_HITS) {
walls.splice(wallIndex, 1);
wallHits.splice(wallIndex, 1);
}
}
});
});
// Bullet collisions with missiles
for (let bIndex = bullets.length - 1; bIndex >= 0; bIndex--) {
const bullet = bullets[bIndex];
if (!bullet.isEnemyBullet) {
for (let mIndex = homingMissiles.length - 1; mIndex >= 0; mIndex--) {
const missile = homingMissiles[mIndex];
const dx = bullet.x - missile.x;
const dy = bullet.y - missile.y;
const distance = Math.sqrt(dx * dx + dy * dy);
// homing missile is hit by player bullet ?
if (distance < (missile.width / 2 + 5)) {
homingMissileHits++;
missileBoomSound.currentTime = 0;
if (!isMuted) {
missileBoomSound.play();
setTimeout(() => {
missileBoomSound.pause();
missileBoomSound.currentTime = 0;
}, 800);
}
if (homingMissileHits % 4 === 0) {
score += 500; // bonus for every 4th missile shot down
if (!isMuted) bonusSound.play(); // normal bonus sound
/* every BONUS2LIVES (7 normally) bonus, lives++ but
not over PLAYER_LIVES max defined by programmer */
bonusGrants++;
if (bonusGrants >= BONUS2LIVES) { // normally 7
player.lives++; // every nth bonus grants player gets one life back!
if (player.lives > PLAYER_LIVES) {
player.lives = PLAYER_LIVES; // don't go over max
} else {
if (!isMuted) {
newLifeSound.volume = 1.0; // max volume
newLifeSound.play();
}
// Initialize the animation properties with debug logging
//console.log('Starting life grant animation');
lifeGrant = true;
animations.lifeGrant = {
startTime: Date.now(),
startX: canvas.width / 2,
startY: canvas.height - 100 // Start a bit higher for better visibility