flappyBird

flappyBird
继snakeGame之后,自己又写了一下flappyBird,还是很有意思的。

requestAnimationFrame() 浏览器提供的API,相比较定时器来循环间隔移动目标物体,有优化更合理,呈现更流畅的动画,当该标签页不可见,浏览器会暂停它,从而减少系统压力。

结构

structure

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flappy Bird | by pan sir</title>
</head>
<body>
<h2>Flappy Bird | by pan sir</h2>
<canvas id="canvas" width="288" height="512"></canvas>
<script src="flappybird.js"></script>
</body>
</html>

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
88
89
90
window.onload = function() {
var cvs = document.getElementById("canvas");
var ctx = cvs.getContext("2d");
var gap = 100;
var constant = 242 + gap;
var gravity = 1.3;
var score = 0;
//bird position
var bx = 10;
var by = 150;
//pipe
var pipe = [];
pipe[0] = {
x:cvs.width,
y:0
};
//on key down
document.addEventListener("keydown",moveUp);
function moveUp(){
by-=30;
}
//audio
var scoreAudio = new Audio();
scoreAudio.src = "sounds/score.mp3";
//load images
var bird = new Image();
var bg = new Image();
var fg = new Image();
var pipeNorth = new Image();
var pipeSouth = new Image();
bird.src = "images/fb-bird.png";
bg.src = "images/fb-bg.png";
fg.src = "images/fb-floor.png";
pipeNorth.src = "images/fb-pipe-north.png";
pipeSouth.src = "images/fb-pipe-south.png";
function draw() {
ctx.drawImage(bg, 0, 0);
for (var i = 0; i < pipe.length; i++) {
ctx.drawImage(pipeNorth,pipe[i].x , pipe[i].y);
ctx.drawImage(pipeSouth, pipe[i].x, pipe[i].y + constant);
pipe[i].x--;
// create new pipe
if(pipe[i].x == 125){
pipe.push({
x:cvs.width,
y:Math.floor(Math.random()*pipeNorth.height)-pipeNorth.height}
);
}
//detect collision
if (bx + bird.width >= pipe[i].x && bx <= pipe[i].x + pipeNorth.width &&
(by <= pipe[i].y + pipeNorth.height || by + bird.height >= pipe[i].y+constant)
|| by +bird.height >= cvs.height - fg.height) {
location.reload();
}
//score
if (pipe[i].x == 5){
score++;
scoreAudio.play();
}
}
ctx.drawImage(fg, 0, cvs.height-fg.height);
ctx.drawImage(bird, bx, by);
//记录分数
ctx.fillStyle = "black";
ctx.font = "18px Verdana";
ctx.fillText("score :"+ score,10,cvs.height-20);
by+=gravity;
requestAnimationFrame(draw);
}
draw();
}