forked from kubowania/flappy-bird
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
87 lines (73 loc) · 2.62 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
document.addEventListener('DOMContentLoaded' , () => {
const bird = document.querySelector('.bird')
const gameDisplay = document.querySelector('.game-container')
const ground = document.querySelector('.ground-moving')
let birdLeft = 220
let birdBottom = 100
let gravity = 3
let isGameOver = false
let gap = 430
function startGame() {
birdBottom -= gravity
bird.style.bottom = birdBottom + 'px'
bird.style.left = birdLeft + 'px'
}
let gameTimerId = setInterval(startGame, 20)
function control(e) {
if (e.keyCode === 32) {
jump()
}
}
function jump() {
if (birdBottom < 500) birdBottom += 50
bird.style.bottom = birdBottom + 'px'
console.log(birdBottom)
}
document.addEventListener('keyup', control)
function generateObstacle() {
let obstacleLeft = 500
let randomHeight = Math.random() * 60
let obstacleBottom = randomHeight
const obstacle = document.createElement('div')
const topObstacle = document.createElement('div')
if (!isGameOver) {
obstacle.classList.add('obstacle')
topObstacle.classList.add('topObstacle')
}
gameDisplay.appendChild(obstacle)
gameDisplay.appendChild(topObstacle)
obstacle.style.left = obstacleLeft + 'px'
topObstacle.style.left = obstacleLeft + 'px'
obstacle.style.bottom = obstacleBottom + 'px'
topObstacle.style.bottom = obstacleBottom + gap + 'px'
function moveObstacle() {
obstacleLeft -=2
obstacle.style.left = obstacleLeft + 'px'
topObstacle.style.left = obstacleLeft + 'px'
if (obstacleLeft === -60) {
clearInterval(timerId)
gameDisplay.removeChild(obstacle)
gameDisplay.removeChild(topObstacle)
}
if (
obstacleLeft > 200 && obstacleLeft < 280 && birdLeft === 220 &&
(birdBottom < obstacleBottom + 153 || birdBottom > obstacleBottom + gap -200)||
birdBottom === 0
) {
gameOver()
clearInterval(timerId)
}
}
let timerId = setInterval(moveObstacle, 20)
if (!isGameOver) setTimeout(generateObstacle, 3000)
}
generateObstacle()
function gameOver() {
clearInterval(gameTimerId)
console.log('game over')
isGameOver = true
document.removeEventListener('keyup', control)
ground.classList.add('ground')
ground.classList.remove('ground-moving')
}
})