Okay, here is a complete Flappy Bird clone implemented using HTML Canvas and JavaScript, all within a single code block.
You can copy this entire block, save it as an .html file (e.g., flappy.html), and then open that file in your web browser to play.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<title>Flappy Bird Clone</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
font-family: sans-serif;
}
canvas {
border: 1px solid #000;
display: block;
margin: auto;
background-color: #70c5ce; /* Sky blue background */
}
</style>
</head>
<body>
<canvas height="480" id="gameCanvas" width="320"></canvas>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Game Variables
let bird;
let pipes;
let score;
let frameCount;
let gameState; // 'start', 'playing', 'gameOver'
const gravity = 0.25;
const lift = -6;
const pipeSpeed = 2;
const pipeWidth = 50;
const pipeGap = 100; // Vertical gap between pipes
const pipeFrequency = 90; // Add new pipe every X frames
// Bird Class
class Bird {
constructor(x, y, radius, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.velocity = 0;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
update() {
this.velocity += gravity;
// Limit velocity to prevent extreme speeds
this.velocity = Math.min(8, Math.max(-8, this.velocity));
this.y += this.velocity;
// Prevent going above the top edge
if (this.y - this.radius < 0) {
this.y = this.radius;
this.velocity = 0;
}
}
flap() {
this.velocity = lift;
}
// Check collision with ground
hitsGround() {
return this.y + this.radius > canvas.height;
}
}
// Pipe Class (represents a pair of pipes)
class Pipe {
constructor() {
this.topHeight = Math.random() * (canvas.height - pipeGap - 100) + 50; // Min 50px height from top/bottom
this.bottomHeight = canvas.height - this.topHeight - pipeGap;
this.x = canvas.width;
this.width = pipeWidth;
this.color = '#008000'; // Green pipes
this.scored = false; // Has the bird passed this pipe?
}
draw() {
// Top pipe
ctx.fillStyle = this.color;
ctx.fillRect(this.x, 0, this.width, this.topHeight);
// Bottom pipe
ctx.fillRect(this.x, canvas.height - this.bottomHeight, this.width, this.bottomHeight);
}
update() {
this.x -= pipeSpeed;
}
// Check if pipe is offscreen
isOffscreen() {
return this.x + this.width < 0;
}
// Check collision with the bird
hits(bird) {
// Check horizontal overlap
if (bird.x + bird.radius > this.x && bird.x - bird.radius < this.x + this.width) {
// Check vertical overlap (collision)
if (bird.y - bird.radius < this.topHeight || bird.y + bird.radius > canvas.height - this.bottomHeight) {
return true;
}
}
return false;
}
}
// --- Game Functions ---
function setup() {
bird = new Bird(canvas.width / 4, canvas.height / 2, 15, '#FFD700'); // Yellow bird
pipes = [];
score = 0;
frameCount = 0;
gameState = 'start';
pipes.push(new Pipe()); // Start with one pipe immediately
draw(); // Draw initial state
}
function draw() {
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw Background (simple color)
ctx.fillStyle = '#70c5ce'; // Sky blue
ctx.fillRect(0, 0, canvas.width, canvas.height);
// --- Draw elements based on game state ---
if (gameState === 'start') {
// Draw Bird
bird.draw();
// Draw Start Message
ctx.fillStyle = '#000';
ctx.font = '20px Arial';
ctx.textAlign = 'center';
ctx.fillText('Click or Press Space to Start', canvas.width / 2, canvas.height / 2);
ctx.fillText(`High Score: ${localStorage.getItem('flappyHighScore') || 0}`, canvas.width / 2, canvas.height / 2 + 30);
} else if (gameState === 'playing') {
// Draw Pipes
pipes.forEach(pipe => pipe.draw());
// Draw Bird
bird.draw();
// Draw Score
ctx.fillStyle = '#FFF';
ctx.font = '30px Arial';
ctx.strokeStyle = '#000'; // Black stroke for visibility
ctx.lineWidth = 2;
ctx.textAlign = 'center';
ctx.strokeText(score.toString(), canvas.width / 2, 50);
ctx.fillText(score.toString(), canvas.width / 2, 50);
} else if (gameState === 'gameOver') {
// Draw Pipes (static final position)
pipes.forEach(pipe => pipe.draw());
// Draw Bird (static final position)
bird.draw();
// Draw Game Over Message & Score
ctx.fillStyle = 'rgba(0, 0, 0, 0.5)'; // Semi-transparent overlay
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#FFF';
ctx.font = '30px Arial';
ctx.textAlign = 'center';
ctx.fillText('Game Over!', canvas.width / 2, canvas.height / 2 - 40);
ctx.font = '24px Arial';
ctx.fillText(`Score: ${score}`, canvas.width / 2, canvas.height / 2);
ctx.fillText(`High Score: ${localStorage.getItem('flappyHighScore') || 0}`, canvas.width / 2, canvas.height / 2 + 40);
ctx.font = '18px Arial';
ctx.fillText('Click or Space to Restart', canvas.width / 2, canvas.height / 2 + 80);
}
}
function update() {
if (gameState !== 'playing') return;
// Update Bird
bird.update();
// Check for ground collision
if (bird.hitsGround()) {
gameOver();
return; // Stop further updates in this frame
}
// Update Pipes
for (let i = pipes.length - 1; i >= 0; i--) {
pipes[i].update();
// Check for collision with bird
if (pipes[i].hits(bird)) {
gameOver();
return; // Stop further updates
}
// Check if bird passed the pipe
if (!pipes[i].scored && pipes[i].x + pipes[i].width < bird.x - bird.radius) {
score++;
pipes[i].scored = true;
// Optional: Add sound effect here
// scoreSound.play();
}
// Remove pipes that are offscreen
if (pipes[i].isOffscreen()) {
pipes.splice(i, 1);
}
}
// Add new pipes periodically
frameCount++;
if (frameCount % pipeFrequency === 0) {
pipes.push(new Pipe());
}
}
function gameLoop() {
update();
draw();
requestAnimationFrame(gameLoop); // Keep the loop going
}
function handleInput() {
switch (gameState) {
case 'start':
gameState = 'playing';
bird.flap(); // Give initial flap
break;
case 'playing':
bird.flap();
// Optional: Add sound effect here
// flapSound.play();
break;
case 'gameOver':
// Reset the game
setup(); // This sets gameState back to 'start', draw() handles the rest
break;
}
}
function gameOver() {
if (gameState === 'gameOver') return; // Prevent multiple triggers
gameState = 'gameOver';
// Optional: Add sound effect here
// hitSound.play();
// Update High Score
const currentHighScore = parseInt(localStorage.getItem('flappyHighScore') || '0');
if (score > currentHighScore) {
localStorage.setItem('flappyHighScore', score.toString());
}
}
// --- Event Listeners ---
window.addEventListener('click', handleInput);
window.addEventListener('keydown', (e) => {
if (e.code === 'Space') {
handleInput();
}
});
// Add touch support for mobile
window.addEventListener('touchstart', handleInput);
// --- Start the Game ---
setup(); // Initialize game variables
// gameLoop() will be started by the first frame request in setup via draw()
// Start the main game loop
requestAnimationFrame(gameLoop);
// Optional: Add sounds (you'd need sound files)
/*
const flapSound = new Audio('sounds/flap.wav');
const scoreSound = new Audio('sounds/score.wav');
const hitSound = new Audio('sounds/hit.wav');
*/
</script>
</body>
</html>
**How it Works