-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
83 lines (70 loc) · 2.44 KB
/
Copy pathmain.js
File metadata and controls
83 lines (70 loc) · 2.44 KB
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
document.addEventListener('DOMContentLoaded',()=>{
const bird =document.querySelector('.bird')
const gameDisplay = document.querySelector('.game-container')
const ground = document.querySelector('.ground')
let birdLeft= 220
let birdBottom = 100
let gravity =2
let isGameOver =false
let gap =430
function startGame(){
birdBottom -=gravity
bird.style.left=birdLeft + 'px'
bird.style.bottom = birdBottom + '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'
}
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(){
if(!isGameOver){
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('GameOvre')
isGameOver=true
document.removeEventListener('keyup',control)
}
})