-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflappy2.html
More file actions
96 lines (94 loc) · 2.46 KB
/
flappy2.html
File metadata and controls
96 lines (94 loc) · 2.46 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
<canvas id="my-canvas" width="500" height="500"></canvas>
<script>
let mycanvas = document.getElementById('my-canvas')
let ctx = mycanvas.getContext('2d')
console.log(mycanvas)
let bird = {
x: 20,
y: 0,
vx: 0,
vy: 1,
}
let pipe = {
width: 20,
holeStart: 100,
holeEnd: 200,
x: 500
}
let gravity = 0.25
let haveYouLost = false;
let score = 0
function isColliding(px, py, rx, ry, rw, rh) {
if (px < rx) {
return false
}
if (py < ry) {
return false
}
if (px > rx + rw) {
return false
}
if (py > ry + rh) {
return false
}
return true
}
function isBirdCollidingWithPipe() {
if (isColliding(bird.x, bird.y, pipe.x, 0, pipe.width, pipe.holeStart)) {
return true
}
if (isColliding(bird.x, bird.y, pipe.x, pipe.holeEnd, pipe.width, 500 - pipe.holeEnd)) {
return true
}
return false
}
function draw() {
ctx.fillRect(bird.x, bird.y, 15, 15)
ctx.fillRect(pipe.x, 0, pipe.width, pipe.holeStart)
ctx.fillRect(pipe.x, pipe.holeEnd, pipe.width, 500 - pipe.holeEnd)
}
function clear() {
ctx.clearRect(0, 0, 500, 500)
}
function update() {
bird.x += bird.vx
bird.y += bird.vy
bird.vy += gravity
pipe.x -= 6
if (isBirdCollidingWithPipe()) {
haveYouLost = true;
alert("your score was " + score)
}
if (bird.y < 0 || bird.y > 500) {
haveYouLost = true;
alert("your score was " + score)
}
if (pipe.x < -pipe.width) {
pipe.x = 500
score++
let newHoleStart = Math.random() * 300;
let newHoleEnd = newHoleStart + Math.random() * 50 + 50;
pipe.holeEnd = newHoleEnd;
pipe.holeStart = newHoleStart;
}
}
function frame() {
if (haveYouLost) {
return;
}
update()
clear()
draw()
}
setInterval(frame, 1000 / 60)
function onKeyPress(e) {
bird.vy = -5
}
document.addEventListener('keydown', onKeyPress)
</script>
<style>
/* don't have to have this */
canvas {
border: 1px solid green;
}
</style>