forked from kailielexx/Space-Shooter-Game
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
46 lines (40 loc) · 1.56 KB
/
game.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
document.addEventListener('DOMContentLoaded', () => {
const gameContainer = document.getElementById('gameContainer');
let ship = createShip();
function createShip() {
let ship = document.createElement('div');
ship.classList.add('ship');
gameContainer.appendChild(ship);
ship.style.left = (gameContainer.offsetWidth / 2) - 25 + 'px'; // Center the ship
return ship;
}
function moveShip(event) {
if (event.key === 'ArrowLeft' && ship.offsetLeft > 0) {
ship.style.left = ship.offsetLeft - 10 + 'px';
} else if (event.key === 'ArrowRight' && ship.offsetLeft < (gameContainer.offsetWidth - 50)) {
ship.style.left = ship.offsetLeft + 10 + 'px';
}
}
function shoot() {
let bullet = document.createElement('div');
bullet.classList.add('bullet');
gameContainer.appendChild(bullet);
bullet.style.left = ship.offsetLeft + 22.5 + 'px'; // Center bullet on ship
bullet.style.bottom = '70px'; // Starting position
let bulletInterval = setInterval(() => {
if (bullet.offsetTop < 0) {
clearInterval(bulletInterval);
gameContainer.removeChild(bullet);
} else {
bullet.style.bottom = bullet.offsetTop + 10 + 'px';
}
}, 100);
}
document.addEventListener('keydown', (event) => {
if (event.key === ' ') {
shoot();
} else {
moveShip(event);
}
});
});