-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
795 lines (705 loc) 路 17.5 KB
/
Copy pathindex.js
File metadata and controls
795 lines (705 loc) 路 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
import audio from './audio.js'
import spaceshipImage from './images/spaceship.png'
import invaderImage from './images/invader.png'
let score = 0
const scoreEl = document.querySelector('#scoreEl')
const canvas = document.querySelector('canvas')
const c = canvas.getContext('2d')
canvas.width = 1024
canvas.height = 576
// Player
class Player {
constructor() {
this.velocity = {
x: 0,
y: 0
}
this.position = {
x: canvas.width / 2,
y: canvas.height - 50
}
this.speed = 5
this.rotate = 0
this.opacity = 1
const image = new Image()
image.src = spaceshipImage
image.onload = () => {
const scale = 0.12
this.image = image
this.width = image.width * scale
this.height = image.height * scale
this.position = {
x: canvas.width / 2 - this.width / 2,
y: canvas.height - this.height - 20
}
}
}
draw() {
// c.fillStyle = "red";
// c.fillRect(this.position.x, this.position.y, this.width, this.height);
c.save()
c.globalAlpha = this.opacity
c.translate(
this.position.x + this.width / 2,
this.position.y + this.height / 2
)
c.rotate(this.rotate)
c.translate(
-this.position.x - this.width / 2,
-this.position.y - this.height / 2
)
c.drawImage(
this.image,
this.position.x,
this.position.y,
this.width,
this.height
)
c.restore()
}
move() {
if (this.image) {
this.draw()
this.position.x += this.velocity.x
this.position.y += this.velocity.y
}
}
}
class Projectiles {
constructor(position, velocity) {
this.position = position
this.velocity = velocity
this.radius = 4
// this.color = "white";
// this.width = 5;
// this.height = 5;
}
draw() {
c.beginPath()
c.arc(this.position.x, this.position.y, this.radius, 0, Math.PI * 2)
c.fillStyle = 'red'
c.fill()
c.closePath()
}
update() {
this.draw()
this.position.x += this.velocity.x
this.position.y += this.velocity.y
}
}
class Particle {
constructor({ position, velocity, radius, color, fades }) {
this.position = position
this.velocity = velocity
this.radius = radius
this.color = color
this.opacity = 1
this.fades = fades
}
draw() {
c.save()
c.globalAlpha = this.opacity
c.beginPath()
c.arc(this.position.x, this.position.y, this.radius, 0, Math.PI * 2)
c.fillStyle = this.color
c.fill()
c.closePath()
c.restore()
}
update() {
this.draw()
this.position.x += this.velocity.x
this.position.y += this.velocity.y
if (this.fades) this.opacity -= 0.01
}
}
class InvaderProjectile {
constructor({ position, velocity }) {
this.position = position || { x: 0, y: 0 }
this.velocity = velocity
this.width = 3
this.height = 10
}
draw() {
c.fillStyle = '#FF00FF'
c.fillRect(this.position.x, this.position.y, this.width, this.height)
}
update() {
this.draw()
this.position.x += this.velocity.x
this.position.y += this.velocity.y
}
}
class Invader {
constructor({ position }) {
this.velocity = {
x: 0,
y: 0
}
const image = new Image()
image.src = invaderImage
this.position = {
x: position.x,
y: position.y
}
image.onload = () => {
const scale = 1
this.image = image
this.width = image.width * scale
this.height = image.height * scale
}
}
draw() {
if (this.image) {
c.drawImage(
this.image,
this.position.x,
this.position.y,
this.width,
this.height
)
}
}
update({ velocity }) {
if (this.image) {
this.draw()
this.position.x += velocity.x
this.position.y += velocity.y
}
}
shoot(invaderProjectiles) {
// Ensure audio object is defined or remove this line if not necessary
if (typeof audio !== 'undefined' && audio.enemyShoot) {
audio.enemyShoot.play()
}
invaderProjectiles.push(
new InvaderProjectile({
position: {
x: this.position.x + this.width / 2,
y: this.position.y + this.height
},
velocity: {
x: 0,
y: 5
}
})
)
}
}
class Grid {
constructor() {
this.position = {
x: 0,
y: 0
}
this.velocity = {
x: 3,
y: 0
}
this.invaders = []
const columns = Math.floor(Math.random() * 10 + 5)
const rows = Math.floor(Math.random() * 5 + 2)
this.width = columns * 30
this.height = rows * 30
for (let x = 0; x < columns; x++) {
for (let y = 0; y < rows; y++) {
this.invaders.push(
new Invader({
position: {
x: x * 30,
y: y * 30
}
})
)
}
}
}
update() {
this.position.x += this.velocity.x
this.position.y += this.velocity.y
this.velocity.y = 0 // every fram reset the y velocity to 0 and then add 30 the height of one invader
if (this.position.x + this.width >= canvas.width || this.position.x <= 0) {
this.velocity.x = -this.velocity.x * 1.04
this.velocity.y = 30
}
}
}
let player = new Player()
let projectiles = []
let invaders = new Invader({ position: { x: 0, y: 0 } }) // Removed unused variable
let grids = []
let invaderProjectiles = []
let particles = []
let key = {
a: {
pressed: false
},
d: {
pressed: false
},
w: {
pressed: false
},
s: {
pressed: false
},
space: {
pressed: false
},
ArrowLeft: {
pressed: false
},
ArrowRight: {
pressed: false
},
ArrowUp: {
pressed: false
},
ArrowDown: {
pressed: false
}
}
function init() {
player = new Player()
projectiles = []
invaders = []
grids = []
invaderProjectiles = []
particles = []
key = {
a: {
pressed: false
},
d: {
pressed: false
},
w: {
pressed: false
},
s: {
pressed: false
},
space: {
pressed: false
},
ArrowLeft: {
pressed: false
},
ArrowRight: {
pressed: false
},
ArrowUp: {
pressed: false
},
ArrowDown: {
pressed: false
}
}
frames = 0
randomInterval = Math.floor(Math.random() * 500) + 500
game = {
isOver: false,
active: true
}
score = 0
document.querySelector('#finalScore').innerHTML = score
document.querySelector('#scoreEl').innerHTML = score
// create stars
for (let i = 0; i < 100; i++) {
particles.push(
new Particle({
position: {
x: Math.random() * canvas.width,
y: Math.random() * canvas.height
},
velocity: {
x: 0,
y: Math.random() * 0.1 + 0.2
},
radius: Math.random() * 1.5,
color: 'white'
})
)
}
}
let frames = 0
let randomInterval = Math.floor(Math.random() * 500) + 500
let game = {
isOver: false,
active: true
}
// create stars
for (let i = 0; i < 100; i++) {
particles.push(
new Particle({
position: {
x: Math.random() * canvas.width,
y: Math.random() * canvas.height
},
velocity: {
x: 0,
y: Math.random() * 0.1 + 0.2
},
radius: Math.random() * 1.5,
color: 'white'
})
)
}
function rectangularCollision({ rectangle1, rectangle2 }) {
if (!rectangle1 || !rectangle2) return false // Prevents errors
return (
rectangle1.position.y + rectangle1.height >= rectangle2.position.y &&
rectangle1.position.x + rectangle1.width >= rectangle2.position.x &&
rectangle1.position.x <= rectangle2.position.x + rectangle2.width &&
rectangle1.position.y <= rectangle2.position.y + rectangle2.height
)
}
function checkPlayerInvaderCollision() {
// Check for collision between player and invaders
grids.forEach((grid) => {
grid.invaders.forEach((invader) => {
if (game.isOver) return
if (invader.position && invader.width && invader.height) {
if (
rectangularCollision({
rectangle1: player,
rectangle2: invader
})
) {
setTimeout(() => {
player.opacity = 0
game.isOver = true
endGame()
// create explosion
createExplosion({
position: {
x: player.position.x + player.width / 2,
y: player.position.y + player.height / 2
},
color: 'white',
particleCount: 15
})
}, 0)
setTimeout(() => {
game.active = false
}, 2000)
}
}
})
})
}
function createExplosion({ position, color, particleCount }) {
audio.explode.play()
for (let i = 0; i < particleCount; i++) {
particles.push(
new Particle({
position: {
x: position.x,
y: position.y
},
velocity: {
x: (Math.random() - 0.5) * 1,
y: (Math.random() - 0.5) * 1
},
radius: Math.random() * 3,
color: color,
fades: true
})
)
}
}
function endGame() {
console.log('you lose')
audio.gameOver.play()
// Makes player disappear
setTimeout(() => {
player.opacity = 0
game.over = true
}, 0)
// stops game altogether
setTimeout(() => {
game.active = false
document.querySelector('#restartScreen').style.display = 'flex'
document.querySelector('#finalScore').innerHTML = score
}, 2000)
createExplosion({
position: {
x: player.position.x + player.width / 2,
y: player.position.y + player.height / 2
},
color: 'white',
particleCount: 15
})
}
function animation() {
if (!game.active) return
requestAnimationFrame(animation)
c.fillStyle = 'black'
c.fillRect(0, 0, canvas.width, canvas.height)
player.move()
particles.forEach((particle, particleIndex) => {
if (particle.position.y - particle.radius > canvas.height) {
particle.position.x = Math.random() * canvas.width
particle.position.y = -particle.radius
}
if (particle.opacity <= 0) {
setTimeout(() => {
particles.splice(particleIndex, 1)
}, 0)
} else {
particle.update()
}
})
particles.forEach((particle) => {
particle.update()
})
invaderProjectiles.forEach((invaderProjectile, index) => {
if (invaderProjectile.position.y > canvas.height) {
invaderProjectiles.splice(index, 1)
} else invaderProjectile.update()
// remove player if invaders touch it
checkPlayerInvaderCollision()
if (
rectangularCollision({
rectangle1: invaderProjectile,
rectangle2: player
})
) {
setTimeout(() => {
invaderProjectiles.splice(index, 1)
player.opacity = 0
game.isOver = true
endGame()
// create explosion
createExplosion({
position: {
x: player.position.x + player.width / 2,
y: player.position.y + player.height / 2
},
color: 'white',
particleCount: 15
})
}, 0)
setTimeout(() => {
game.active = false
}, 2000)
}
})
grids.forEach((grid, gridIndex) => {
grid.update()
// spawn projectiles
if (frames % 100 === 0 && grid.invaders.length > 0) {
grid.invaders[Math.floor(Math.random() * grid.invaders.length)].shoot(
invaderProjectiles
)
}
grid.invaders.forEach((invader) => {
invader.update({ velocity: grid.velocity })
})
// check for collision between projectiles and invaders
projectiles.forEach((projectile, index) => {
grid.invaders.forEach((invader, invaderIndex) => {
if (
// if our projectiles top position is less than the position of the invaders bottom position
// there is a collision so we want to remove the projectile and the invader
projectile.position.y - projectile.radius <=
invader.position.y + invader.height &&
projectile.position.x + projectile.radius >= invader.position.x &&
projectile.position.x - projectile.radius <=
invader.position.x + invader.width &&
projectile.position.y + projectile.radius >= invader.position.y
) {
setTimeout(() => {
const invaderFound = grid.invaders.find(
(invader2) => invader2 === invader
)
const projectileFound = projectiles.find(
(projectile2) => projectile2 === projectile
)
// Remove the invader and the projectile
if (invaderFound && projectileFound) {
score += 100
scoreEl.innerHTML = score
// create explosion
createExplosion({
position: {
x: invader.position.x + invader.width / 2,
y: invader.position.y + invader.height / 2
},
color: '#BAA0DE',
particleCount: 15
})
}
if (
grid.invaders.includes(invader) &&
projectiles.includes(projectile)
) {
grid.invaders.splice(invaderIndex, 1)
projectiles.splice(index, 1)
}
// update the width of the invaders grid to make sure we are not drawing the grid outside the canvas or bouncing before reaching the end of the window
if (grid.invaders.length > 0) {
const firstInvader = grid.invaders[0]
const lastInvader = grid.invaders[grid.invaders.length - 1]
grid.width =
lastInvader.position.x -
firstInvader.position.x +
lastInvader.width
grid.position.x = firstInvader.position.x
} else {
grids.splice(gridIndex, 1)
}
}, 0)
}
})
})
})
projectiles.forEach((projectile, index) => {
projectile.update()
if (
projectile.position.x + projectile.radius < 0 ||
projectile.position.x - projectile.radius > canvas.width ||
projectile.position.y + projectile.radius < 0 ||
projectile.position.y - projectile.radius > canvas.height
) {
setTimeout(() => {
projectiles.splice(index, 1)
}, 0)
}
})
if ((key.ArrowLeft.pressed || key.a.pressed) && player.position.x > 0) {
player.velocity.x = -player.speed
player.rotate = -0.15
} else if (
(key.ArrowRight.pressed || key.d.pressed) &&
player.position.x + player.width < canvas.width
) {
player.velocity.x = player.speed
player.rotate = 0.15
} else {
player.velocity.x = 0
player.rotate = 0
}
if ((key.ArrowUp.pressed || key.w.pressed) && player.position.y > 5) {
// we can set it to 0 but the tip of the spaceship will be cut off
player.velocity.y = -player.speed
} else if (
(key.ArrowDown.pressed || key.s.pressed) &&
player.position.y + player.height < canvas.height
) {
player.velocity.y = player.speed
} else {
player.velocity.y = 0
}
// spawn enemies
if (frames % randomInterval === 0) {
grids.push(new Grid())
randomInterval = Math.floor(Math.random() * 500) + 500
frames = 0
}
frames++
}
document.addEventListener(
'click',
() => {
const context = Howler.ctx
if (context.state === 'suspended') {
context.resume().then(() => {
Howler.volume(1)
audio.backgroundMusic.play()
})
}
},
{ once: true }
)
document.querySelector('#startButton').addEventListener('click', () => {
const context = Howler.ctx
if (context.state === 'suspended') {
context.resume().then(() => {
try {
audio.backgroundMusic.play()
} catch (error) {
console.error('Error playing background music:', error)
}
audio.start.play()
})
} else {
audio.backgroundMusic.play()
audio.start.play()
}
document.querySelector('#startScreen').style.display = 'none'
document.querySelector('#scoreContainer').style.display = 'block'
init()
animation()
})
document.querySelector('#restartButton').addEventListener('click', () => {
audio.select.play()
document.querySelector('#restartScreen').style.display = 'none'
init()
animation()
})
addEventListener('keydown', ({ key: keyPressed }) => {
if (game.isOver) return
switch (keyPressed) {
case 'a':
case 'ArrowLeft':
key.a.pressed = true
key.ArrowLeft.pressed = true
break
case 'd':
case 'ArrowRight':
key.d.pressed = true
key.ArrowRight.pressed = true
break
case 'w':
case 'ArrowUp':
key.w.pressed = true
key.ArrowUp.pressed = true
break
case 's':
case 'ArrowDown':
key.s.pressed = true
key.ArrowDown.pressed = true
break
case ' ':
audio.shoot.play()
projectiles.push(
new Projectiles(
{
x: player.position.x + player.width / 2,
y: player.position.y
},
{
x: 0,
y: -10
}
)
)
break
}
})
addEventListener('keyup', ({ key: keyPressed }) => {
if (game.isOver) return
switch (keyPressed) {
case 'a':
case 'ArrowLeft':
key.a.pressed = false
key.ArrowLeft.pressed = false
break
case 'd':
case 'ArrowRight':
key.d.pressed = false
key.ArrowRight.pressed = false
break
case 'w':
case 'ArrowUp':
key.w.pressed = false
key.ArrowUp.pressed = false
break
case 's':
case 'ArrowDown':
key.s.pressed = false
key.ArrowDown.pressed = false
break
}
})