-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
79 lines (67 loc) · 2.36 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
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
document.addEventListener('DOMContentLoaded', function() {
const bird = document.getElementById('bird');
const gameArea = document.getElementById('gameArea');
let gravity = 0.6;
let velocity = 0;
let gameInProgress = false;
function startGame() {
gameInProgress = true;
document.addEventListener('keydown', jump);
animate();
createPipes();
}
function jump(event) {
if (event.key === ' ') {
velocity = -10; // Adjust jump strength as needed
}
}
function animate() {
if (gameInProgress) {
velocity += gravity;
bird.style.top = bird.offsetTop + velocity + 'px';
checkCollision();
requestAnimationFrame(animate);
}
}
function createPipes() {
setInterval(() => {
if (gameInProgress) {
let pipeHeight = Math.floor(Math.random() * 200) + 100; // Random height for pipes
let pipeTop = document.createElement('div');
let pipeBottom = document.createElement('div');
pipeTop.classList.add('pipe');
pipeBottom.classList.add('pipe');
pipeTop.style.height = pipeHeight + 'px';
pipeBottom.style.height = (gameArea.clientHeight - pipeHeight - 100) + 'px'; // 100px gap between pipes
gameArea.appendChild(pipeTop);
gameArea.appendChild(pipeBottom);
}
}, 2000); // Adjust pipe creation interval as needed
}
function checkCollision() {
let birdTop = bird.getBoundingClientRect().top;
let birdBottom = bird.getBoundingClientRect().bottom;
let birdLeft = bird.getBoundingClientRect().left;
let birdRight = bird.getBoundingClientRect().right;
let pipes = document.querySelectorAll('.pipe');
pipes.forEach(pipe => {
let pipeTop = pipe.getBoundingClientRect().top;
let pipeBottom = pipe.getBoundingClientRect().bottom;
let pipeLeft = pipe.getBoundingClientRect().left;
let pipeRight = pipe.getBoundingClientRect().right;
if (
birdTop <= pipeBottom &&
birdBottom >= pipeTop &&
birdRight >= pipeLeft &&
birdLeft <= pipeRight
) {
gameOver();
}
});
}
function gameOver() {
gameInProgress = false;
alert('Game Over! Refresh the page to play again.');
}
startGame();
});