-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
726 lines (676 loc) · 22.1 KB
/
app.js
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
import { topScoresTemplate, userLoginTemplate } from './displayElements.js';
import levels from './levels.js';
const maintenanceMode = false;
const API_URL = 'https://krivdat-api.herokuapp.com/asteroids';
// const API_URL = 'http://35.234.64.91/asteroids';
// const API_URL = 'http://localhost:3000/asteroids';
const space = document.querySelector('.space');
// get space width from css property
let str = window.getComputedStyle(space).width;
str = str.slice(0, str.length - 2);
const spaceWidth = Math.round(parseFloat(str, 10));
// create DOM elements
const weapon = document.createElement('div');
const startButton = document.createElement('button');
const missedDisplay = document.createElement('div');
const destroyedDisplay = document.createElement('div');
const levelDisplay = document.createElement('div');
const gameSummary = document.createElement('div');
const gameTitle = document.createElement('div');
const moveRightIcon = document.createElement('div');
const moveLeftIcon = document.createElement('div');
const fireControlIcon = document.createElement('div');
const asteroidsMoveInterval = 40; // general move delay in ms
const weaponParams = {
xPos: 180,
yPos: 600 - 10,
width: 40,
height: 40
};
const maxLevel = Object.keys(levels).length;
const levelStep = 15; // number of destroyed asteroids to increase level
let level = 1; // initial level
const asteroids = [];
const bullets = [];
let bulletsCountMax = 3;
const bulletParams = {
step: 3,
delay: 20,
width: 15,
height: 30
};
let missedCount = 0; // asteroids that passed bottom line
const allowMissedCount = 3; // max number of asteroids missed to end the game
let destroyedCount = 0;
const bottomLine = 10; // y-distance from bottom where asteroids disappear
const sndUrls = {
shoot: './snd/257232__javierzumer__retro-shot-blaster.wav',
blast: './snd/322502__liamg-sfx__explosion-15.wav',
missed: './snd/49693__ejfortin__energy-gloves.wav',
levelUp: './snd/412165__screamstudio__arcade-level.wav',
gameOver: './snd/365766__matrixxx__game-over-03.wav',
gameStart: './snd/196889__ionicsmusic__race-robot-start.wav'
};
let sounds = {};
let isGameOver = true;
let topScores = [];
for (let i = 0; i < 10; i++) {
topScores.push({ username: '-', score: 0 });
}
let isFirstStart = true;
let isWeaponMoving = false;
let moveAsteroidsTimer;
let genNewAsteroidsTimer;
let moveBulletsTimer;
let moveWeaponTimer;
let isLogged = false;
let loggedUser = JSON.parse(localStorage.getItem('asteroidsLoggedUser'));
if (loggedUser) {
isLogged = true;
console.log('Welcome back', loggedUser.username);
}
class DisplayElement {
constructor(cssClass, content = '') {
this.el = document.createElement('div');
this.content = content;
//const vis = this.el;
this.el.className = cssClass;
this.el.style.display = 'none'; // do not display panel when created
this.el.innerHTML = this.content;
space.appendChild(this.el);
}
setContent(content) {
this.content = content;
this.el.innerHTML = this.content;
}
display(onoff = 'on') {
//show or hide element
if (onoff === 'on') {
this.el.style.display = '';
} else if (onoff === 'off') {
this.el.style.display = 'none';
}
}
destroy() {
this.el.remove();
}
}
const topScoresPanel = new DisplayElement('top-scores', topScoresTemplate(topScores));
const userLoginPanel = new DisplayElement('user-login', userLoginTemplate());
const statusBarEl = new DisplayElement('status-bar');
function setStatus(msg) {
statusBarEl.setContent(msg);
}
class Asteroid {
constructor(xPos, yPos, width, height, step) {
this.yPos = yPos;
this.xPos = xPos;
this.width = width;
this.height = height;
this.step = step; // px to move with each interval aka speed
this.visual = document.createElement('div');
let vis = this.visual;
vis.style.transform = `translate(${this.xPos}px, ${this.yPos}px)`;
vis.className = 'asteroid';
space.appendChild(vis);
}
destroy() {
this.visual.remove();
}
}
class Explosion {
constructor(xPos, yPos) {
this.yPos = yPos;
this.xPos = xPos;
this.visual = document.createElement('div');
const vis = this.visual;
vis.style.transform = `translate(${this.xPos}px, ${this.yPos}px)`;
vis.className = 'explosion';
space.appendChild(vis);
}
destroy() {
this.visual.remove();
}
}
class Bullet {
constructor(xPos, yPos) {
this.xPos = xPos;
this.yPos = yPos;
this.visual = document.createElement('div');
const visual = this.visual;
visual.className = 'bullet';
visual.style.transform = `translate(${this.xPos}px, ${this.yPos}px)`;
space.appendChild(visual);
}
destroy() {
this.visual.remove();
}
}
function createWeapon() {
weapon.className = 'weapon';
weapon.style.transform = `translate(${weaponParams.xPos}px, ${weaponParams.yPos}px)`;
space.appendChild(weapon);
// console.log("created weapon");
}
function getRandBetween(min, max) {
// min and max included
return Math.floor(Math.random() * (max - min + 1) + min);
}
function createCounterDisplays() {
missedDisplay.className = 'counter missed';
missedDisplay.textContent = missedCount;
levelDisplay.className = 'level';
levelDisplay.textContent = 'LEVEL ' + level;
destroyedDisplay.className = 'counter destroyed';
destroyedDisplay.textContent = destroyedCount;
space.appendChild(missedDisplay);
space.appendChild(destroyedDisplay);
space.appendChild(levelDisplay);
}
function createGameSummary() {
gameSummary.className = 'game-summary';
space.appendChild(gameSummary);
}
function createGameTitle() {
let text = `
<h1>Shooting Asteroids</h1>`;
gameTitle.innerHTML = text;
gameTitle.className = 'game-title';
space.appendChild(gameTitle);
// console.log("created Game Title");
// console.log(gameTitle);
}
function createTouchControls() {
moveLeftIcon.className = 'move-control left';
moveRightIcon.className = 'move-control right';
fireControlIcon.className = 'fire-control';
moveLeftIcon.setAttribute('id', 'move-left');
moveRightIcon.setAttribute('id', 'move-right');
space.appendChild(moveLeftIcon);
space.appendChild(moveRightIcon);
space.appendChild(fireControlIcon);
// add event listeners
moveLeftIcon.addEventListener('touchstart', control);
moveLeftIcon.addEventListener('mousedown', control);
moveLeftIcon.addEventListener('touchend', controlStop);
moveLeftIcon.addEventListener('mouseup', controlStop);
moveRightIcon.addEventListener('touchstart', control);
moveRightIcon.addEventListener('mousedown', control);
moveRightIcon.addEventListener('touchend', controlStop);
moveRightIcon.addEventListener('mouseup', controlStop);
fireControlIcon.addEventListener('touchstart', fire);
}
function gameSummaryDisplay(onoff) {
if (onoff === 'on' || !onoff) {
//console.log("displaying game summary");
let text = `
Game Over!<br />
You have destroyed<br />
<strong>${destroyedCount}</strong><br />
asteroids and reached<br />
level ${level}`;
if (destroyedCount < 2) {
//console.log("less than two destroyed");
text = text.replace('asteroids', 'asteroid'); //if only one asteroid destroyed
}
if (destroyedCount === 0) {
//console.log("no asteroids destroyed");
text = `Game Over!<br />
You have destroyed<br />
<strong>nothing</strong>`;
}
gameSummary.innerHTML = text;
gameSummary.style.display = '';
} else if (onoff === 'off') {
gameSummary.style.display = 'none';
}
}
function gameTitleDisplay(onoff) {
if (onoff === 'on' || onoff === '') {
//console.log("displaying game title");
gameTitle.style.display = '';
// console.log("game title switched on");
} else {
gameTitle.style.display = 'none';
// console.log("game title switched off");
}
}
function updateCounterDisplays() {
missedDisplay.textContent = missedCount;
destroyedDisplay.textContent = destroyedCount;
levelDisplay.textContent = 'LEVEL ' + level;
}
function generateNewAsteroid() {
//create new asteroid on top
const width = levels[level].width;
const height = levels[level].height;
const xPos = getRandBetween(20, spaceWidth - 20 - width);
const yPos = 10 + height;
const step = getRandBetween(levels[level].stepMin, levels[level].stepMax);
const newAsteroid = new Asteroid(xPos, yPos, width, height, step);
asteroids.push(newAsteroid);
}
function generateNewBullet(xPos, yPos) {
if (bullets.length >= bulletsCountMax) {
// console.log("shot not fired - max number of bullets reached");
return false;
}
const newBullet = new Bullet(xPos, yPos);
bullets.push(newBullet);
// console.log(bullets);
}
function initAsteroids() {
generateNewAsteroid(); // generate first one only
}
function createUI() {
startButton.className = 'start-button';
startButton.innerHTML = `
<h2>PRESS ENTER OR CLICK HERE TO START</h2>
<p>controls: <br />← → to move weapon, spacebar to shoot</p>`;
space.appendChild(startButton);
startButton.style.display = 'none';
startButton.addEventListener('click', start);
document.addEventListener('keydown', control);
document.addEventListener('keyup', controlStop);
}
function moveAsteroids() {
asteroids.forEach((asteroid, index) => {
if (asteroid.yPos >= 600 - bottomLine) {
//asteroid missed bottom line
missedCount += 1;
sounds.missed.cloneNode().play();
updateCounterDisplays();
asteroid.destroy();
asteroids.splice(index, 1);
// console.log("missed asteroids: ", missedCount);
if (missedCount >= allowMissedCount) {
gameOver();
}
} else if (
asteroid.xPos + asteroid.width > weaponParams.xPos &&
asteroid.xPos < weaponParams.xPos + weaponParams.width &&
asteroid.yPos + asteroid.height > weaponParams.yPos &&
asteroid.yPos < weaponParams.yPos + weaponParams.height
) {
//asteroid crashed to weapon
// console.log("asteroid destroyed weapon");
sounds.blast.cloneNode().play();
missedCount += 1;
updateCounterDisplays();
gameOver();
} else {
//move asteroids
asteroid.yPos += asteroid.step;
asteroid.visual.style.transform = `translate(${asteroid.xPos}px, ${asteroid.yPos}px)`;
}
});
}
function moveBullets() {
bullets.forEach((bullet, i) => {
bullet.yPos -= bulletParams.step;
if (bullet.yPos <= 0 + bulletParams.height) {
//reached top of space
// console.log("bullet reached top of space");
bullet.destroy();
bullets.splice(i, 1);
if (bullets.length === 0) {
// if removed bullet was the last
// console.log("no more bullets to move");
clearInterval(moveBulletsTimer);
return;
}
} else {
bullet.visual.style.transform = `translate(${bullet.xPos}px, ${bullet.yPos}px)`;
//check if bullet hit any asteroid, if yes remove bullet and asteroid
asteroids.forEach((asteroid, j) => {
if (
bullet.xPos + bulletParams.width > asteroid.xPos &&
bullet.xPos < asteroid.xPos + asteroid.width &&
bullet.yPos - bulletParams.height < asteroid.yPos &&
bullet.yPos > asteroid.yPos - asteroid.height
) {
// console.log("bullet hit the asteroid");
sounds.blast.cloneNode().play();
destroyedCount++;
//check if we want to increase level
if (destroyedCount % levelStep === 0 && level < maxLevel) {
level++;
if (level === 6) {
bulletsCountMax = 5;
}
clearInterval(genNewAsteroidsTimer);
genNewAsteroidsTimer = setInterval(
generateNewAsteroid,
levels[level].genNewAsteroidInt
);
sounds.levelUp.cloneNode().play();
// console.log("increased level to ", level);
}
updateCounterDisplays();
const explosion = new Explosion(asteroid.xPos, asteroid.yPos);
setTimeout(() => explosion.destroy(), 250);
bullet.destroy();
asteroid.destroy();
bullets.splice(i, 1);
asteroids.splice(j, 1);
if (bullets.length === 0) {
//if removed bullet was the last exit function
// console.log("no more bullets to move");
clearInterval(moveBulletsTimer);
return;
}
}
});
}
});
}
function moveWeapon(direction) {
const step = {
left: -5,
right: 5
};
isWeaponMoving = true;
// console.log("moved");
moveWeaponTimer = setInterval(() => {
if (
(direction === 'left' && weaponParams.xPos <= 5) ||
(direction === 'right' && weaponParams.xPos >= spaceWidth - weaponParams.width - 5)
) {
isWeaponMoving = false;
clearInterval(moveWeaponTimer);
return;
}
weaponParams.xPos += step[direction];
weapon.style.transform = `translate(${weaponParams.xPos}px, ${weaponParams.yPos}px)`;
}, 20);
}
function control(e) {
e.preventDefault();
if (isGameOver) {
if (e.key === 'Enter') {
start();
return;
}
} else {
if ((e.key === 'ArrowLeft' || e.currentTarget.id === 'move-left') && !isWeaponMoving) {
// console.log("want to move left");
moveWeapon('left');
} else if ((e.key === 'ArrowRight' || e.currentTarget.id === 'move-right') && !isWeaponMoving) {
// console.log("want to move right");
moveWeapon('right');
}
if (e.key === ' ') {
fire();
}
//console.log({ isWeaponMoving });
}
// console.log(`key pressed: "${e.key}"`);
// console.log(e.currentTarget);
// console.log({ isGameOver });
}
function fire() {
if (bullets.length >= bulletsCountMax) {
// console.log("max number of bullets used");
return;
}
// console.log("shot fired");
sounds.shoot.cloneNode().play();
generateNewBullet(weaponParams.xPos + 20 - bulletParams.width / 2, weaponParams.yPos - 40);
if (bullets.length === 1) {
//if first bullet then start move timer
moveBulletsTimer = setInterval(moveBullets, bulletParams.delay);
}
}
function controlStop(e) {
if (e.key === ' ') {
return;
}
if (!isGameOver && isWeaponMoving) {
clearInterval(moveWeaponTimer);
isWeaponMoving = false;
// console.log("weapon stopped");
}
}
function initSounds() {
sounds = {
shoot: new Audio(sndUrls['shoot']),
blast: new Audio(sndUrls['blast']),
missed: new Audio(sndUrls['missed']),
levelUp: new Audio(sndUrls['levelUp']),
gameOver: new Audio(sndUrls['gameOver']),
gameStart: new Audio(sndUrls['gameStart'])
};
Object.keys(sounds).forEach((type) => {
sounds[type].load();
// console.log(`sound "${type}" loaded`);
});
}
function gameOver() {
isGameOver = true;
clearInterval(moveAsteroidsTimer);
clearInterval(genNewAsteroidsTimer);
clearInterval(moveBulletsTimer);
clearInterval(moveWeaponTimer);
isWeaponMoving = false;
setStatus('game over');
sounds.gameOver.play();
weapon.remove();
missedDisplay.remove();
destroyedDisplay.remove();
levelDisplay.remove();
moveLeftIcon.remove();
moveRightIcon.remove();
fireControlIcon.remove();
asteroids.forEach((asteroid) => {
asteroid.destroy(); //destroy all asteroid objects
});
asteroids.length = 0; //empty asteroids array, just in case
bullets.forEach((bullet) => {
bullet.destroy(); //destroy all bullets
});
bullets.length = 0; //empty bullets array, just in case
gameSummaryDisplay();
if (!maintenanceMode) {
console.log('starting update of top scores');
updateTopScores()
.then((result) => {
console.log('In gameOver function', { result });
console.log('topscores variable before topscores.setcontent call', topScores);
})
.then(() => {
missedCount = 0;
destroyedCount = 0;
topScoresPanel.setContent(topScoresTemplate(topScores));
topScoresPanel.display();
startButton.style.display = '';
})
.catch(() => {
console.error('Error during updating top scores');
});
} else {
console.log('In maintenance mode - skipping update of top scores.');
missedCount = 0;
destroyedCount = 0;
topScoresPanel.setContent(topScoresTemplate(topScores));
topScoresPanel.display();
startButton.style.display = '';
}
}
function start() {
if (!isGameOver) {
return; //already playing
}
setStatus(`Go, ${isLogged ? loggedUser.username : 'human'}, go!`);
startButton.style.display = 'none';
sounds.gameStart.play();
isGameOver = false;
level = 1;
createWeapon();
createCounterDisplays();
gameSummaryDisplay('off');
topScoresPanel.display('off');
if (isFirstStart) {
gameTitleDisplay('off');
isFirstStart = false;
}
createTouchControls();
initAsteroids();
moveAsteroidsTimer = setInterval(moveAsteroids, asteroidsMoveInterval);
genNewAsteroidsTimer = setInterval(generateNewAsteroid, levels[level].genNewAsteroidInt);
}
async function initGetTopScores() {
// get current top scores from remote db
topScoresPanel.setContent('wait, loading TOP 10 scores...');
topScoresPanel.display();
const resp = await fetch(API_URL + '/top-scores');
const data = await resp.json();
console.log(data);
if (data.topScores.length > 0) {
topScores = data.topScores;
}
console.log('current fetched topscores:', topScores);
topScoresPanel.setContent(topScoresTemplate(topScores));
console.log(startButton.style);
startButton.style.display = '';
}
async function updateTopScores() {
// get current top scores from remote db
const resp = await fetch(API_URL + '/top-scores');
const data = await resp.json();
console.log(data);
if (data.topScores.length > 0) {
topScores = data.topScores;
}
console.log('current fetched topscores:', topScores);
console.log(data.status);
if (data.status !== 'success') {
return false;
}
const minScore = topScores[topScores.length - 1].score;
console.log({ minScore });
if (topScores.length >= 10 && minScore > destroyedCount) {
console.log({ destroyedCount });
console.log('Score not high enough for top 10');
return true;
}
if (!isLogged) {
// user not logged in
console.log('user is not logged in, calling register function');
gameSummaryDisplay('off');
const loginSuccess = await registerNewUser();
if (!loginSuccess) {
console.log('could not register new user');
setStatus(`registering process failed:(`);
gameSummaryDisplay();
return false;
}
gameSummaryDisplay();
setStatus('wait, updating TOP 10 scores...');
const dbUpdateSuccess = await updateTopScoresDb();
if (dbUpdateSuccess === 'rejected') {
console.log('could not update remote topScore database');
setStatus(`could not update TOP 10 scores:(`);
return false;
}
console.log('remote user database updated successfully');
setStatus(`TOP 10 scores updated successfully`);
return true;
} else {
// if user is already logged in
setStatus('wait, updating TOP 10 scores...');
const dbUpdateSuccess = await updateTopScoresDb();
if (dbUpdateSuccess === 'rejected') {
console.log('could not update remote topScore database');
setStatus(`could not update TOP 10 scores:(`);
return false;
}
setStatus(`TOP 10 scores updated successfully`);
console.log('remote user database updated successfully');
return true;
}
}
async function updateTopScoresDb() {
const postResp = await fetch(API_URL + '/top-scores', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username: loggedUser.username,
secret: loggedUser.secret,
score: destroyedCount
})
});
const postData = await postResp.json();
if (postData.status !== 'success') {
console.error('cannot update top scores database', postData.message);
return 'rejected';
}
console.log('top scores updated successfully');
topScores = postData.topScores;
return 'done';
}
function registerNewUser() {
return new Promise((resolve) => {
gameSummaryDisplay('off');
document.removeEventListener('keydown', control);
document.removeEventListener('keyup', controlStop);
userLoginPanel.display();
const formEl = document.querySelector('#user-login');
const input = document.querySelector('#username');
const statusMsg = document.querySelector('#status-msg');
formEl.addEventListener('submit', async (e) => {
e.preventDefault();
console.log(input.value);
const response = await fetch(API_URL + '/users');
const users = await response.json();
console.log(users);
const isRegistered = users.filter((item) => item.username === input.value);
if (isRegistered.length > 0) {
let msg = 'User with this nickname is already registered! Try different one';
console.log(msg);
statusMsg.textContent = msg;
} else {
setStatus('moment please...');
const postResp = await fetch(API_URL + '/users', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: input.value })
});
const postData = await postResp.json();
console.log(postData);
if (postData.status !== 'success') {
console.log(postData.message);
statusMsg.textContent = 'something went wrong, try again...';
setStatus('');
} else {
console.log('user was successfully registered');
statusMsg.textContent = `Thank you ${postData.username}, you are now registered!`;
isLogged = true;
loggedUser = {
username: postData.username,
secret: postData.secret
};
setStatus(`Hi ${loggedUser.username}, you are now registered.`);
localStorage.setItem('asteroidsLoggedUser', JSON.stringify(loggedUser));
input.value = '';
document.addEventListener('keydown', control);
document.addEventListener('keyup', controlStop);
userLoginPanel.display('off');
gameSummaryDisplay('on');
resolve(loggedUser);
}
}
});
});
}
createUI();
initGetTopScores();
statusBarEl.display();
if (isLogged) {
setStatus(`Welcome back, <strong>${loggedUser.username}</strong>!`);
} else {
setStatus('Welcome, human!');
}
initSounds();
createGameSummary();
gameSummaryDisplay('off');
createGameTitle();