Published
Edited
Jun 2, 2021
Insert cell
# Flappy Bird game
Insert cell
canvas = htl.html`<canvas id="canvas" width="288" height="512"></canvas>`
Insert cell
{
canvas

var cvs = document.getElementById("canvas");

var ctx = cvs.getContext("2d");



// some variables

var gap = 85;

var constant;

var bX = 10;

var bY = 150;

var gravity = 1.5;

var score = 0;

// on key down

document.addEventListener("keydown",moveUp);

function moveUp(){

bY -= 25;

}

// pipe coordinates

var pipe = [];

pipe[0] = {

x : cvs.width,

y : 0

};

// 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(pipeSouth,pipe[i].x,pipe[i].y+constant);


pipe[i].x--;


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(); // reload the page
gap = 85;
bX = 10;
bY = 150;
gravity = 1.5;
score = 0;

}


if(pipe[i].x == 5){

score++;

}



}

ctx.drawImage(fg,0,cvs.height - fg.height);


ctx.drawImage(bird,bX,bY);


bY += gravity;


ctx.fillStyle = "#000";

ctx.font = "20px Verdana";

ctx.fillText("Score : "+score,10,cvs.height-20);


requestAnimationFrame(draw);


}

draw();
}
Insert cell
bg = FileAttachment("bg.png").image();
Insert cell
bird = FileAttachment("bird.png").image();
Insert cell
fg = FileAttachment("fg.png").image()
Insert cell
pipeNorth = FileAttachment("pipeNorth.png").image()
Insert cell
pipeSouth = FileAttachment("pipeSouth.png").image()
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more