Untitled

 avatar
unknown
plain_text
5 months ago
2.9 kB
3
Indexable
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flappy Bird Clone</title>
    <style>
        body { margin: 0; }
        canvas { background: #70c5ce; display: block; margin: auto; }
    </style>
</head>
<body>
    <canvas id="gameCanvas" width="400" height="600"></canvas>
    <script>
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');

        const bird = { x: 50, y: 150, width: 20, height: 20, gravity: 0.6, lift: -12, velocity: 0 };
        const pipes = [];
        let frame = 0;
        let score = 0;
        let gameOver = false;

        function addPipe() {
            const gap = 100;
            const height = Math.random() * (canvas.height - gap - 20) + 20;
            pipes.push({ x: canvas.width, height: height });
        }

        function drawBird() {
            ctx.fillStyle = 'yellow';
            ctx.fillRect(bird.x, bird.y, bird.width, bird.height);
        }

        function drawPipes() {
            ctx.fillStyle = 'green';
            pipes.forEach(pipe => {
                ctx.fillRect(pipe.x, 0, 40, pipe.height);
                ctx.fillRect(pipe.x, pipe.height + gap, 40, canvas.height - pipe.height - gap);
            });
        }

        function update() {
            if (gameOver) return;
            bird.velocity += bird.gravity;
            bird.y += bird.velocity;

            if (bird.y > canvas.height || bird.y < 0) {
                gameOver = true;
            }

            pipes.forEach((pipe, index) => {
                pipe.x -= 2;
                if (pipe.x + 40 < 0) {
                    pipes.splice(index, 1);
                    score++;
                }
                if (bird.x < pipe.x + 40 && bird.x + bird.width > pipe.x && (bird.y < pipe.height || bird.y + bird.height > pipe.height + gap)) {
                    gameOver = true;
                }
            });

            if (frame % 90 === 0) addPipe();
            frame++;
        }

        function drawScore() {
            ctx.fillStyle = 'white';
            ctx.font = '20px Arial';
            ctx.fillText(`Score: ${score}`, 10, 20);
        }

        function gameLoop() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            update();
            drawBird();
            drawPipes();
            drawScore();

            if (gameOver) {
                ctx.fillStyle = 'red';
                ctx.font = '40px Arial';
                ctx.fillText('Game Over!', 100, canvas.height / 2);
            } else {
                requestAnimationFrame(gameLoop);
            }
        }

        document.addEventListener('keydown', () => {
            bird.velocity = bird.lift;
        });

        gameLoop();
    </script>
</body>
</html>
Editor is loading...
Leave a Comment