!DOCTYPE html
!DOCTYPE html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flappy Bird (Pure Code Version)</title>
<style>
body {
margin: 0;
background-color: #70c5ce;
overflow: hidden;
}
canvas {
display: block;
margin: 0 auto;
background: #70c5ce;
}
</style>
</head>
<body>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Game variables
let frames = 0;
const gravity = 0.5;
const jump = -8;
let gameOver = false;
// Bird
const bird = {
x: 100,
y: 200,
radius: 15,
velocity: 0,
color: "yellow",
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.stroke();
},
update() {
this.velocity += gravity;
this.y += this.velocity;
flap() {
this.velocity = jump;
}
};
// Pipes
const pipes = [];
const pipeWidth = 50;
const pipeGap = 120;
const pipeSpeed = 2;
pipes.push({
x: canvas.width,
topHeight: pipeTopHeight,
bottomY: pipeBottomY
});
}
// Draw pipes
function drawPipes() {
ctx.fillStyle = "green";
pipes.forEach(pipe => {
// Top pipe
ctx.fillRect(pipe.x, 0, pipeWidth, pipe.topHeight);
// Bottom pipe
ctx.fillRect(pipe.x, pipe.bottomY, pipeWidth, canvas.height - pipe.bottomY);
});
}
// Update pipes
function updatePipes() {
pipes.forEach(pipe => {
pipe.x -= pipeSpeed;
// Collision detection
if (
bird.x + bird.radius > pipe.x &&
bird.x - bird.radius < pipe.x + pipeWidth &&
(bird.y - bird.radius < pipe.topHeight || bird.y + bird.radius >
pipe.bottomY)
) {
gameOver = true;
}
});
// Control
document.addEventListener('keydown', function(e) {
if (e.code === "Space" && !gameOver) {
bird.flap();
}
if (gameOver && e.code === "Space") {
resetGame();
}
});
// Reset Game
function resetGame() {
bird.y = 200;
bird.velocity = 0;
pipes.length = 0;
frames = 0;
gameOver = false;
}
// Main loop
function loop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawGround();
bird.draw();
bird.update();
if (frames % 90 === 0) {
createPipe();
}
drawPipes();
updatePipes();
if (gameOver) {
ctx.fillStyle = "black";
ctx.font = "30px Arial";
ctx.fillText("Game Over", canvas.width/2 - 80, canvas.height/2);
ctx.font = "20px Arial";
ctx.fillText("Press SPACE to restart", canvas.width/2 - 110, canvas.height/2 +
40);
} else {
requestAnimationFrame(loop);
}
frames++;
}
loop();
</script>
</body>
</html>