const canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
let bottom = canvas.height,
dx = 2,
randomHeight,
jumps = 0;
const hero = new Image();
hero.src = "img/man.png";
let heroHeight = 75,
heroWidth = 100,
heroX = 40,
heroY = bottom - heroHeight;
const pipe = new Image();
pipe.src = "img/pipe.png";
let startPipePos = canvas.width,
pipeHeight = Math.floor(Math.random() * 90),
pipeY = bottom - pipeHeight;
let pipes = [{x: startPipePos, height: pipeHeight, pipeY: bottom - pipeHeight}];
pipe.onload = () => {
game();
}
function game() {
action();
render();
requestAnimationFrame(game);
}
function action() {
for(let i = 0, len = pipes.length; i < len; i++) {
pipes[i].x -= dx;
if(pipes[i].x == 600) {
randomHeight = Math.floor(Math.random() * 90);
pipes.push({x: startPipePos, height: randomHeight, pipeY: bottom - randomHeight});
}
if(heroY < bottom - heroHeight) {
heroY += .7;
}
// if(pipes[i].x < -30) {
// pipes.splice(i, 1);
// }
if(heroY >= bottom - heroHeight) jumps = 0;
}
}
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(hero, heroX, heroY, heroWidth, heroHeight);
for(let i = 0, len = pipes.length; i < len; i++) {
ctx.drawImage(pipe, pipes[i].x, pipes[i].pipeY, 30, pipes[i].height);
}
}
document.onkeypress = (e) => {
if(e.keyCode != 32 || jumps >= 2) return;
heroY -= 90;
jumps++;
}