Skip to content

Instantly share code, notes, and snippets.

@ichub
Created August 19, 2018 23:07
Show Gist options
  • Save ichub/8a36b66de1e9642fde266d1b8aa09d17 to your computer and use it in GitHub Desktop.
Save ichub/8a36b66de1e9642fde266d1b8aa09d17 to your computer and use it in GitHub Desktop.
<canvas id="myCanvas" width="800" height="600"></canvas>
<style>
#myCanvas {
border: 1px solid black;
}
</style>
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
let isRunning = true;
let score = 0;
const bird = {
x: 20,
y: 1,
vy: 0,
};
const gravity = 0.1;
const pipe = {
x: 200,
start: 100,
end: 200,
width: 20,
speed: 2
};
function resetPipe() {
pipe.start = Math.random() * 400 + 100;
pipe.end = Math.random() * 100 + 100;
score++;
pipe.x = 800;
pipe.speed += 1;
}
function update() {
bird.y += bird.vy;
bird.vy += gravity;
pipe.x -= pipe.speed;
if (pipe.x <= -pipe.width) {
resetPipe();
}
if (isBirdIntersectingWithPipe()) {
isRunning = false;
alert("you played! score was: " + score);
}
if (bird.y <= 0 || bird.y >= 600) {
isRunning = false;
alert("you played! score was: " + score);
}
}
function isBirdIntersectingWithPipe() {
let topIntersecti0n = isIntersecting(pipe.x, 0, pipe.width, pipe.start, bird.x, bird.y);
let bottomIntersection = isIntersecting(pipe.x, pipe.start + pipe.end, pipe.width, 600 - (pipe.start + pipe.end), bird.x, bird.y);
return topIntersecti0n || bottomIntersection;
}
function draw() {
ctx.clearRect(0, 0, 800, 600);
ctx.fillRect(bird.x, bird.y, 10, 10);
ctx.fillRect(pipe.x, 0, pipe.width, pipe.start);
ctx.fillRect(pipe.x, pipe.start + pipe.end, pipe.width, 600 - (pipe.start + pipe.end));
}
function isIntersecting(rx, ry, rw, rh, px, py) {
if (px >= rx && px <= rx + rw) {
if (py >= ry && py <= ry + rh) {
return true;
}
}
return false;
}
function frame() {
requestAnimationFrame(() => {
if (isRunning) {
update();
draw();
frame();
}
});
}
frame();
window.addEventListener("keydown", function (e) {
bird.vy = -5;
});
console.log(canvas);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment