forked from CodeExplainedRepo/FlappyBird-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflappyBird.js
More file actions
142 lines (78 loc) · 2.48 KB
/
flappyBird.js
File metadata and controls
142 lines (78 loc) · 2.48 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
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
var cvs = document.getElementById("canvas");
var ctx = cvs.getContext("2d");
// load images
var superwoman = new Image();
var bg = new Image();
var fg = new Image();
var pipeNorth = new Image();
var tree = new Image();
superwoman.src = "images/superwoman.png";
bg.src = "images/bg.png";
fg.src = "images/fg.png";
pipeNorth.src = "images/pipeWithSmoke.png";
tree.src = "images/tree.png";
// some variables
var gap = 85;
var constant;
var bX = 10;
var bY = 150;
var gravity = 1.5;
var score = 0;
// audio files
var fly = new Audio();
var scor = new Audio();
fly.src = "sounds/fly.mp3";
scor.src = "sounds/score.mp3";
// on key down
document.addEventListener("keydown",moveUp);
function moveUp(){
bY -= 25;
fly.play();
}
// pipe coordinates
var pipe = [];
pipe[0] = {
x : cvs.width,
y : 0
};
var Y=250; // randomize north pipe height
// draw images
function draw(){
ctx.drawImage(bg,0,0);
for(var i = 0; i < pipe.length; i++){
constant = pipeNorth.height+gap;
ctx.drawImage(pipeNorth,pipe[i].x,pipe[i].y);
ctx.drawImage(tree,pipe[i].x,pipe[i].y+constant);
pipe[i].x--;
if( pipe[i].x == 125 ){
randNorthPipePosY(i);
pipe.push({
x : cvs.width,
y : Y
});
}
// detect collision
if( bX + superwoman.width >= pipe[i].x && bX <= pipe[i].x + pipeNorth.width && (bY <= pipe[i].y + pipeNorth.height || bY+superwoman.height >= pipe[i].y+constant) || bY + superwoman.height >= cvs.height - fg.height){
location.reload(); // reload the page
}
if(pipe[i].x == 5){
score++;
scor.play();
}
}
ctx.drawImage(fg,0,cvs.height - fg.height);
ctx.drawImage(superwoman,bX,bY);
bY += gravity;
ctx.fillStyle = "#000";
ctx.font = "20px Verdana";
ctx.fillText("Score : "+score,10,cvs.height-20);
requestAnimationFrame(draw);
}
//randomize the next north pipe height
function randNorthPipePosY(i){
Y=250;
while(Y>(pipe[i].y+55) || Y<(pipe[i].y-75)) //make sure the next pipe is not too high or too low, player can fly through
Y=Math.floor(Math.random()*pipeNorth.height)-pipeNorth.height;
return Y;
}
draw();