-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathasteroids.html
672 lines (588 loc) · 24.5 KB
/
asteroids.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Asteroids</title>
<style></style>
</head>
<body>
<canvas id="gameCanvas" width="760" height="570"></canvas>
<script>
const FPS = 30; // frames per second
const FRICTION = 0.7; // friction coefficient of space (0 = no friction, 1 = lots of friction)
const GAME_LIVES = 3; // starting number of lives
const LASER_DIST = 0.6; // max distance laser can travel as fraction of screen width
const LASER_EXPLODE_DUR = 0.1; // duration of the lasers' explosion in seconds
const LASER_MAX = 10; // maximum number of lasers on screen at once
const LASER_SPD = 500; // speed of lasers in pixels per second
const ROID_JAG = 0.4; // jaggedness of the asteroids (0 = none, 1 = lots)
const ROID_PTS_LGE = 20; // points scored for a large asteroid
const ROID_PTS_MED = 50; // points scored for a medium asteroid
const ROID_PTS_SML = 100; // points scored for a small asteroid
const ROID_NUM = 3; // starting number of asteroids
const ROID_SIZE = 100; // starting size of asteroids in pixels
const ROID_SPD = 50; // max starting speed of asteroids in pixels per second
const ROID_VERT = 10; // average number of vertices on each asteroid
const SAVE_KEY_SCORE = "highscore"; // save key for local storage of high score
const SHIP_BLINK_DUR = 0.1; // duration in seconds of a single blink during ship's invisibility
const SHIP_EXPLODE_DUR = 0.3; // duration of the ship's explosion in seconds
const SHIP_INV_DUR = 3; // duration of the ship's invisibility in seconds
const SHIP_SIZE = 30; // ship height in pixels
const SHIP_THRUST = 5; // acceleration of the ship in pixels per second per second
const SHIP_TURN_SPD = 360; // turn speed in degrees per second
const SHOW_BOUNDING = false; // show or hide collision bounding
const SHOW_CENTRE_DOT = false; // show or hide ship's centre dot
const MUSIC_ON = true;
const SOUND_ON = true;
const TEXT_FADE_TIME = 2.5; // text fade time in seconds
const TEXT_SIZE = 40; // text font height in pixels
/** @type {HTMLCanvasElement} */
var canv = document.getElementById("gameCanvas");
var ctx = canv.getContext("2d");
// set up sound effects
var fxExplode = new Sound("sounds/explode.m4a");
var fxHit = new Sound("sounds/hit.m4a", 5);
var fxLaser = new Sound("sounds/laser.m4a", 5, 0.5);
var fxThrust = new Sound("sounds/thrust.m4a");
// set up the music
var music = new Music("sounds/music-low.m4a", "sounds/music-high.m4a");
var roidsLeft, roidsTotal;
// set up the game parameters
var level, lives, roids, score, scoreHigh, ship, text, textAlpha;
newGame();
// set up event handlers
document.addEventListener("keydown", keyDown);
document.addEventListener("keyup", keyUp);
// set up the game loop
setInterval(update, 1000 / FPS);
function createAsteroidBelt() {
roids = [];
roidsTotal = (ROID_NUM + level) * 7;
roidsLeft = roidsTotal;
var x, y;
for (var i = 0; i < ROID_NUM + level; i++) {
// random asteroid location (not touching spaceship)
do {
x = Math.floor(Math.random() * canv.width);
y = Math.floor(Math.random() * canv.height);
} while (distBetweenPoints(ship.x, ship.y, x, y) < ROID_SIZE * 2 + ship.r);
roids.push(newAsteroid(x, y, Math.ceil(ROID_SIZE / 2)));
}
}
function destroyAsteroid(index) {
var x = roids[index].x;
var y = roids[index].y;
var r = roids[index].r;
// split the asteroid in two if necessary
if (r == Math.ceil(ROID_SIZE / 2)) { // large asteroid
roids.push(newAsteroid(x, y, Math.ceil(ROID_SIZE / 4)));
roids.push(newAsteroid(x, y, Math.ceil(ROID_SIZE / 4)));
score += ROID_PTS_LGE;
} else if (r == Math.ceil(ROID_SIZE / 4)) { // medium asteroid
roids.push(newAsteroid(x, y, Math.ceil(ROID_SIZE / 8)));
roids.push(newAsteroid(x, y, Math.ceil(ROID_SIZE / 8)));
score += ROID_PTS_MED;
} else {
score += ROID_PTS_SML;
}
// check high score
if (score > scoreHigh) {
scoreHigh = score;
localStorage.setItem(SAVE_KEY_SCORE, scoreHigh);
}
// destroy the asteroid
roids.splice(index, 1);
fxHit.play();
// calculate the ratio of remaining asteroids to determine music tempo
roidsLeft--;
music.setAsteroidRatio(roidsLeft / roidsTotal);
// new level when no more asteroids
if (roids.length == 0) {
level++;
newLevel();
}
}
function distBetweenPoints(x1, y1, x2, y2) {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
function drawShip(x, y, a, colour = "white") {
ctx.strokeStyle = colour;
ctx.lineWidth = SHIP_SIZE / 20;
ctx.beginPath();
ctx.moveTo( // nose of the ship
x + 4 / 3 * ship.r * Math.cos(a),
y - 4 / 3 * ship.r * Math.sin(a)
);
ctx.lineTo( // rear left
x - ship.r * (2 / 3 * Math.cos(a) + Math.sin(a)),
y + ship.r * (2 / 3 * Math.sin(a) - Math.cos(a))
);
ctx.lineTo( // rear right
x - ship.r * (2 / 3 * Math.cos(a) - Math.sin(a)),
y + ship.r * (2 / 3 * Math.sin(a) + Math.cos(a))
);
ctx.closePath();
ctx.stroke();
}
function explodeShip() {
ship.explodeTime = Math.ceil(SHIP_EXPLODE_DUR * FPS);
fxExplode.play();
}
function gameOver() {
ship.dead = true;
text = "Game Over";
textAlpha = 1.0;
}
function keyDown(/** @type {KeyboardEvent} */ ev) {
if (ship.dead) {
return;
}
switch(ev.keyCode) {
case 32: // space bar (shoot laser)
shootLaser();
break;
case 37: // left arrow (rotate ship left)
ship.rot = SHIP_TURN_SPD / 180 * Math.PI / FPS;
break;
case 38: // up arrow (thrust the ship forward)
ship.thrusting = true;
break;
case 39: // right arrow (rotate ship right)
ship.rot = -SHIP_TURN_SPD / 180 * Math.PI / FPS;
break;
}
}
function keyUp(/** @type {KeyboardEvent} */ ev) {
if (ship.dead) {
return;
}
switch(ev.keyCode) {
case 32: // space bar (allow shooting again)
ship.canShoot = true;
break;
case 37: // left arrow (stop rotating left)
ship.rot = 0;
break;
case 38: // up arrow (stop thrusting)
ship.thrusting = false;
break;
case 39: // right arrow (stop rotating right)
ship.rot = 0;
break;
}
}
function newAsteroid(x, y, r) {
var lvlMult = 1 + 0.1 * level;
var roid = {
x: x,
y: y,
xv: Math.random() * ROID_SPD * lvlMult / FPS * (Math.random() < 0.5 ? 1 : -1),
yv: Math.random() * ROID_SPD * lvlMult / FPS * (Math.random() < 0.5 ? 1 : -1),
a: Math.random() * Math.PI * 2, // in radians
r: r,
offs: [],
vert: Math.floor(Math.random() * (ROID_VERT + 1) + ROID_VERT / 2)
};
// populate the offsets array
for (var i = 0; i < roid.vert; i++) {
roid.offs.push(Math.random() * ROID_JAG * 2 + 1 - ROID_JAG);
}
return roid;
}
function newGame() {
level = 0;
lives = GAME_LIVES;
score = 0;
ship = newShip();
// get the high score from local storage
var scoreStr = localStorage.getItem(SAVE_KEY_SCORE);
if (scoreStr == null) {
scoreHigh = 0;
} else {
scoreHigh = parseInt(scoreStr);
}
newLevel();
}
function newLevel() {
music.setAsteroidRatio(1);
text = "Level " + (level + 1);
textAlpha = 1.0;
createAsteroidBelt();
}
function newShip() {
return {
x: canv.width / 2,
y: canv.height / 2,
a: 90 / 180 * Math.PI, // convert to radians
r: SHIP_SIZE / 2,
blinkNum: Math.ceil(SHIP_INV_DUR / SHIP_BLINK_DUR),
blinkTime: Math.ceil(SHIP_BLINK_DUR * FPS),
canShoot: true,
dead: false,
explodeTime: 0,
lasers: [],
rot: 0,
thrusting: false,
thrust: {
x: 0,
y: 0
}
}
}
function shootLaser() {
// create the laser object
if (ship.canShoot && ship.lasers.length < LASER_MAX) {
ship.lasers.push({ // from the nose of the ship
x: ship.x + 4 / 3 * ship.r * Math.cos(ship.a),
y: ship.y - 4 / 3 * ship.r * Math.sin(ship.a),
xv: LASER_SPD * Math.cos(ship.a) / FPS,
yv: -LASER_SPD * Math.sin(ship.a) / FPS,
dist: 0,
explodeTime: 0
});
fxLaser.play();
}
// prevent further shooting
ship.canShoot = false;
}
function Music(srcLow, srcHigh) {
this.soundLow = new Audio(srcLow);
this.soundHigh = new Audio(srcHigh);
this.low = true;
this.tempo = 1.0; // seconds per beat
this.beatTime = 0; // frames left until next beat
this.play = function() {
if (MUSIC_ON) {
if (this.low) {
this.soundLow.play();
} else {
this.soundHigh.play();
}
this.low = !this.low;
}
}
this.setAsteroidRatio = function(ratio) {
this.tempo = 1.0 - 0.75 * (1.0 - ratio);
}
this.tick = function() {
if (this.beatTime == 0) {
this.play();
this.beatTime = Math.ceil(this.tempo * FPS);
} else {
this.beatTime--;
}
}
}
function Sound(src, maxStreams = 1, vol = 1.0) {
this.streamNum = 0;
this.streams = [];
for (var i = 0; i < maxStreams; i++) {
this.streams.push(new Audio(src));
this.streams[i].volume = vol;
}
this.play = function() {
if (SOUND_ON) {
this.streamNum = (this.streamNum + 1) % maxStreams;
this.streams[this.streamNum].play();
}
}
this.stop = function() {
this.streams[this.streamNum].pause();
this.streams[this.streamNum].currentTime = 0;
}
}
function update() {
var blinkOn = ship.blinkNum % 2 == 0;
var exploding = ship.explodeTime > 0;
// tick the music
music.tick();
// draw space
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canv.width, canv.height);
// draw the asteroids
var a, r, x, y, offs, vert;
for (var i = 0; i < roids.length; i++) {
ctx.strokeStyle = "slategrey";
ctx.lineWidth = SHIP_SIZE / 20;
// get the asteroid properties
a = roids[i].a;
r = roids[i].r;
x = roids[i].x;
y = roids[i].y;
offs = roids[i].offs;
vert = roids[i].vert;
// draw the path
ctx.beginPath();
ctx.moveTo(
x + r * offs[0] * Math.cos(a),
y + r * offs[0] * Math.sin(a)
);
// draw the polygon
for (var j = 1; j < vert; j++) {
ctx.lineTo(
x + r * offs[j] * Math.cos(a + j * Math.PI * 2 / vert),
y + r * offs[j] * Math.sin(a + j * Math.PI * 2 / vert)
);
}
ctx.closePath();
ctx.stroke();
// show asteroid's collision circle
if (SHOW_BOUNDING) {
ctx.strokeStyle = "lime";
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI * 2, false);
ctx.stroke();
}
}
// thrust the ship
if (ship.thrusting && !ship.dead) {
ship.thrust.x += SHIP_THRUST * Math.cos(ship.a) / FPS;
ship.thrust.y -= SHIP_THRUST * Math.sin(ship.a) / FPS;
fxThrust.play();
// draw the thruster
if (!exploding && blinkOn) {
ctx.fillStyle = "red";
ctx.strokeStyle = "yellow";
ctx.lineWidth = SHIP_SIZE / 10;
ctx.beginPath();
ctx.moveTo( // rear left
ship.x - ship.r * (2 / 3 * Math.cos(ship.a) + 0.5 * Math.sin(ship.a)),
ship.y + ship.r * (2 / 3 * Math.sin(ship.a) - 0.5 * Math.cos(ship.a))
);
ctx.lineTo( // rear centre (behind the ship)
ship.x - ship.r * 5 / 3 * Math.cos(ship.a),
ship.y + ship.r * 5 / 3 * Math.sin(ship.a)
);
ctx.lineTo( // rear right
ship.x - ship.r * (2 / 3 * Math.cos(ship.a) - 0.5 * Math.sin(ship.a)),
ship.y + ship.r * (2 / 3 * Math.sin(ship.a) + 0.5 * Math.cos(ship.a))
);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
} else {
// apply friction (slow the ship down when not thrusting)
ship.thrust.x -= FRICTION * ship.thrust.x / FPS;
ship.thrust.y -= FRICTION * ship.thrust.y / FPS;
fxThrust.stop();
}
// draw the triangular ship
if (!exploding) {
if (blinkOn && !ship.dead) {
drawShip(ship.x, ship.y, ship.a);
}
// handle blinking
if (ship.blinkNum > 0) {
// reduce the blink time
ship.blinkTime--;
// reduce the blink num
if (ship.blinkTime == 0) {
ship.blinkTime = Math.ceil(SHIP_BLINK_DUR * FPS);
ship.blinkNum--;
}
}
} else {
// draw the explosion (concentric circles of different colours)
ctx.fillStyle = "darkred";
ctx.beginPath();
ctx.arc(ship.x, ship.y, ship.r * 1.7, 0, Math.PI * 2, false);
ctx.fill();
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(ship.x, ship.y, ship.r * 1.4, 0, Math.PI * 2, false);
ctx.fill();
ctx.fillStyle = "orange";
ctx.beginPath();
ctx.arc(ship.x, ship.y, ship.r * 1.1, 0, Math.PI * 2, false);
ctx.fill();
ctx.fillStyle = "yellow";
ctx.beginPath();
ctx.arc(ship.x, ship.y, ship.r * 0.8, 0, Math.PI * 2, false);
ctx.fill();
ctx.fillStyle = "white";
ctx.beginPath();
ctx.arc(ship.x, ship.y, ship.r * 0.5, 0, Math.PI * 2, false);
ctx.fill();
}
// show ship's collision circle
if (SHOW_BOUNDING) {
ctx.strokeStyle = "lime";
ctx.beginPath();
ctx.arc(ship.x, ship.y, ship.r, 0, Math.PI * 2, false);
ctx.stroke();
}
// show ship's centre dot
if (SHOW_CENTRE_DOT) {
ctx.fillStyle = "red";
ctx.fillRect(ship.x - 1, ship.y - 1, 2, 2);
}
// draw the lasers
for (var i = 0; i < ship.lasers.length; i++) {
if (ship.lasers[i].explodeTime == 0) {
ctx.fillStyle = "salmon";
ctx.beginPath();
ctx.arc(ship.lasers[i].x, ship.lasers[i].y, SHIP_SIZE / 15, 0, Math.PI * 2, false);
ctx.fill();
} else {
// draw the eplosion
ctx.fillStyle = "orangered";
ctx.beginPath();
ctx.arc(ship.lasers[i].x, ship.lasers[i].y, ship.r * 0.75, 0, Math.PI * 2, false);
ctx.fill();
ctx.fillStyle = "salmon";
ctx.beginPath();
ctx.arc(ship.lasers[i].x, ship.lasers[i].y, ship.r * 0.5, 0, Math.PI * 2, false);
ctx.fill();
ctx.fillStyle = "pink";
ctx.beginPath();
ctx.arc(ship.lasers[i].x, ship.lasers[i].y, ship.r * 0.25, 0, Math.PI * 2, false);
ctx.fill();
}
}
// draw the game text
if (textAlpha >= 0) {
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "rgba(255, 255, 255, " + textAlpha + ")";
ctx.font = "small-caps " + TEXT_SIZE + "px dejavu sans mono";
ctx.fillText(text, canv.width / 2, canv.height * 0.75);
textAlpha -= (1.0 / TEXT_FADE_TIME / FPS);
} else if (ship.dead) {
// after "game over" fades, start a new game
newGame();
}
// draw the lives
var lifeColour;
for (var i = 0; i < lives; i++) {
lifeColour = exploding && i == lives - 1 ? "red" : "white";
drawShip(SHIP_SIZE + i * SHIP_SIZE * 1.2, SHIP_SIZE, 0.5 * Math.PI, lifeColour);
}
// draw the score
ctx.textAlign = "right";
ctx.textBaseline = "middle";
ctx.fillStyle = "white";
ctx.font = TEXT_SIZE + "px dejavu sans mono";
ctx.fillText(score, canv.width - SHIP_SIZE / 2, SHIP_SIZE);
// draw the high score
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "white";
ctx.font = (TEXT_SIZE * 0.75) + "px dejavu sans mono";
ctx.fillText("BEST " + scoreHigh, canv.width / 2, SHIP_SIZE);
// detect laser hits on asteroids
var ax, ay, ar, lx, ly;
for (var i = roids.length - 1; i >= 0; i--) {
// grab the asteroid properties
ax = roids[i].x;
ay = roids[i].y;
ar = roids[i].r;
// loop over the lasers
for (var j = ship.lasers.length - 1; j >= 0; j--) {
// grab the laser properties
lx = ship.lasers[j].x;
ly = ship.lasers[j].y;
// detect hits
if (ship.lasers[j].explodeTime == 0 && distBetweenPoints(ax, ay, lx, ly) < ar) {
// destroy the asteroid and activate the laser explosion
destroyAsteroid(i);
ship.lasers[j].explodeTime = Math.ceil(LASER_EXPLODE_DUR * FPS);
break;
}
}
}
// check for asteroid collisions (when not exploding)
if (!exploding) {
// only check when not blinking
if (ship.blinkNum == 0 && !ship.dead) {
for (var i = 0; i < roids.length; i++) {
if (distBetweenPoints(ship.x, ship.y, roids[i].x, roids[i].y) < ship.r + roids[i].r) {
explodeShip();
destroyAsteroid(i);
break;
}
}
}
// rotate the ship
ship.a += ship.rot;
// move the ship
ship.x += ship.thrust.x;
ship.y += ship.thrust.y;
} else {
// reduce the explode time
ship.explodeTime--;
// reset the ship after the explosion has finished
if (ship.explodeTime == 0) {
lives--;
if (lives == 0) {
gameOver();
} else {
ship = newShip();
}
}
}
// handle edge of screen
if (ship.x < 0 - ship.r) {
ship.x = canv.width + ship.r;
} else if (ship.x > canv.width + ship.r) {
ship.x = 0 - ship.r;
}
if (ship.y < 0 - ship.r) {
ship.y = canv.height + ship.r;
} else if (ship.y > canv.height + ship.r) {
ship.y = 0 - ship.r;
}
// move the lasers
for (var i = ship.lasers.length - 1; i >= 0; i--) {
// check distance travelled
if (ship.lasers[i].dist > LASER_DIST * canv.width) {
ship.lasers.splice(i, 1);
continue;
}
// handle the explosion
if (ship.lasers[i].explodeTime > 0) {
ship.lasers[i].explodeTime--;
// destroy the laser after the duration is up
if (ship.lasers[i].explodeTime == 0) {
ship.lasers.splice(i, 1);
continue;
}
} else {
// move the laser
ship.lasers[i].x += ship.lasers[i].xv;
ship.lasers[i].y += ship.lasers[i].yv;
// calculate the distance travelled
ship.lasers[i].dist += Math.sqrt(Math.pow(ship.lasers[i].xv, 2) + Math.pow(ship.lasers[i].yv, 2));
}
// handle edge of screen
if (ship.lasers[i].x < 0) {
ship.lasers[i].x = canv.width;
} else if (ship.lasers[i].x > canv.width) {
ship.lasers[i].x = 0;
}
if (ship.lasers[i].y < 0) {
ship.lasers[i].y = canv.height;
} else if (ship.lasers[i].y > canv.height) {
ship.lasers[i].y = 0;
}
}
// move the asteroids
for (var i = 0; i < roids.length; i++) {
roids[i].x += roids[i].xv;
roids[i].y += roids[i].yv;
// handle asteroid edge of screen
if (roids[i].x < 0 - roids[i].r) {
roids[i].x = canv.width + roids[i].r;
} else if (roids[i].x > canv.width + roids[i].r) {
roids[i].x = 0 - roids[i].r
}
if (roids[i].y < 0 - roids[i].r) {
roids[i].y = canv.height + roids[i].r;
} else if (roids[i].y > canv.height + roids[i].r) {
roids[i].y = 0 - roids[i].r
}
}
}
</script>
</body>
</html>