Skip to content
The Chat Archive
gemini-2.5-pro· Google LMArena Human Preference 140K

Crie html do jogo Flappy Bird 3d

  1. User

    Crie html do jogo Flappy Bird 3d

  2. Assistant

    Claro! Criar um jogo 3D completo em um único arquivo HTML envolve o uso de HTML para a estrutura, CSS para o estilo e JavaScript com uma biblioteca 3D como a Three.js para a lógica e a renderização.

    A Three.js simplifica o trabalho com WebGL, permitindo criar cenas 3D complexas no navegador.

    Aqui está um código completo e funcional de um Flappy Bird 3D. Basta copiar tudo, colar em um arquivo com a extensão .html (por exemplo, flappy3d.html) e abrir em seu navegador.

    O que este código faz:

    • Cena 3D: Cria um cenário com um "pássaro" (uma esfera amarela) e canos (cubos verdes).
    • Movimento: O pássaro cai com a gravidade e "pula" quando você clica com o mouse ou pressiona a barra de espaço.
    • Obstáculos: Canos são gerados aleatoriamente e se movem em direção ao jogador.
    • Colisão: O jogo detecta colisões com os canos e com o "chão".
    • Pontuação: A pontuação aumenta a cada cano ultrapassado.
    • Tela de Game Over: Exibe a pontuação final e um botão para reiniciar.

    Código Completo (flappy3d.html)

    <!DOCTYPE html>
    <html lang="pt-br">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Flappy Bird 3D</title>
        <style>
            body {
                margin: 0;
                overflow: hidden;
                font-family: 'Arial', sans-serif;
                background-color: #70c5ce;
            }
            canvas {
                display: block;
            }
            #ui-container {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                pointer-events: none; /* Permite cliques através do container */
                color: white;
                text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
            }
            #score {
                position: absolute;
                top: 20px;
                left: 50%;
                transform: translateX(-50%);
                font-size: 4em;
                font-weight: bold;
            }
            #game-over-screen, #start-screen {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.5);
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                pointer-events: auto; /* Habilita cliques na tela de game over */
            }
            #game-over-screen h1, #start-screen h1 {
                font-size: 3em;
                margin: 0;
            }
            #game-over-screen p, #start-screen p {
                font-size: 1.5em;
            }
            #restart-button {
                padding: 15px 30px;
                font-size: 1.2em;
                cursor: pointer;
                border: 2px solid white;
                background-color: #ff8c00;
                color: white;
                border-radius: 10px;
                margin-top: 20px;
            }
            #restart-button:hover {
                background-color: #e07b00;
            }
            .hidden {
                display: none !important;
            }
        </style>
    </head>
    <body>
        <!-- Elementos da Interface do Usuário (UI) -->
        <div id="ui-container">
            <div id="score">0</div>
            
            <div id="start-screen">
                <h1>Flappy Bird 3D</h1>
                <p>Clique ou pressione Espaço para começar</p>
            </div>
    
            <div id="game-over-screen" class="hidden">
                <h1>Fim de Jogo</h1>
                <p>Sua pontuação: <span id="final-score">0</span></p>
                <button id="restart-button">Reiniciar</button>
            </div>
        </div>
    
        <!-- Importa a biblioteca Three.js -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
    
        <script>
            // --- CONFIGURAÇÕES GLOBAIS ---
            let scene, camera, renderer, bird, pipes = [];
            let birdVelocity = 0;
            const gravity = -0.015;
            const flapStrength = 0.4;
            const pipeSpeed = 0.1;
            
            let gameState = 'start'; // 'start', 'playing', 'gameOver'
            let score = 0;
            let lastPipeSpawnX = 20;
    
            // --- ELEMENTOS DA UI ---
            const scoreElement = document.getElementById('score');
            const startScreen = document.getElementById('start-screen');
            const gameOverScreen = document.getElementById('game-over-screen');
            const finalScoreElement = document.getElementById('final-score');
            const restartButton = document.getElementById('restart-button');
    
            // --- FUNÇÃO DE INICIALIZAÇÃO ---
            function init() {
                // 1. Cena
                scene = new THREE.Scene();
                scene.background = new THREE.Color(0x70c5ce);
    
                // 2. Câmera
                camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
                camera.position.set(0, 0, 15);
                camera.lookAt(0, 0, 0);
    
                // 3. Renderizador
                renderer = new THREE.WebGLRenderer({ antialias: true });
                renderer.setSize(window.innerWidth, window.innerHeight);
                document.body.appendChild(renderer.domElement);
                
                // 4. Luzes
                const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
                scene.add(ambientLight);
                const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
                directionalLight.position.set(5, 10, 7);
                scene.add(directionalLight);
    
                // 5. Objetos do Jogo
                createBird();
                createGround();
    
                // 6. Event Listeners
                window.addEventListener('resize', onWindowResize, false);
                document.addEventListener('keydown', onKeyPress, false);
                document.addEventListener('mousedown', onMouseDown, false);
                restartButton.addEventListener('click', resetGame);
    
                animate();
            }
    
            // --- CRIAÇÃO DE OBJETOS ---
            function createBird() {
                const birdGeometry = new THREE.SphereGeometry(0.5, 32, 16);
                const birdMaterial = new THREE.MeshStandardMaterial({ color: 0xffff00 });
                bird = new THREE.Mesh(birdGeometry, birdMaterial);
                bird.position.x = -5; // Posição fixa no eixo X
                scene.add(bird);
            }
    
            function createGround() {
                const groundGeometry = new THREE.BoxGeometry(100, 2, 10);
                const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x964B00 }); // Marrom
                const ground = new THREE.Mesh(groundGeometry, groundMaterial);
                ground.position.y = -10; // Nível do chão
                scene.add(ground);
            }
    
            function createPipePair(xPosition) {
                const pipeWidth = 2;
                const pipeHeight = 15;
                const pipeGap = 4;
    
                const pipeGroup = new THREE.Group();
                pipeGroup.userData = { scored: false }; // Propriedade para controlar pontuação
    
                const pipeMaterial = new THREE.MeshStandardMaterial({ color: 0x00ff00 }); // Verde
    
                // Cano de cima
                const topPipeGeometry = new THREE.BoxGeometry(pipeWidth, pipeHeight, pipeWidth);
                const topPipe = new THREE.Mesh(topPipeGeometry, pipeMaterial);
                
                // Cano de baixo
                const bottomPipeGeometry = new THREE.BoxGeometry(pipeWidth, pipeHeight, pipeWidth);
                const bottomPipe = new THREE.Mesh(bottomPipeGeometry, pipeMaterial);
    
                const gapCenter = (Math.random() - 0.5) * 8; // Variação vertical do buraco
    
                topPipe.position.y = gapCenter + pipeGap / 2 + pipeHeight / 2;
                bottomPipe.position.y = gapCenter - pipeGap / 2 - pipeHeight / 2;
                
                pipeGroup.add(topPipe);
                pipeGroup.add(bottomPipe);
    
                pipeGroup.position.x = xPosition;
                
                pipes.push(pipeGroup);
                scene.add(pipeGroup);
            }
    
            // --- LÓGICA DO JOGO (LOOP) ---
            function animate() {
                requestAnimationFrame(animate);
                
                if (gameState !== 'playing') {
                    renderer.render(scene, camera);
                    return;
                }
    
                // Atualizar física do pássaro
                birdVelocity += gravity;
                bird.position.y += birdVelocity;
                
                // Adiciona uma leve rotação para dar efeito de queda/subida
                bird.rotation.z = Math.min(Math.max(birdVelocity * 2, -Math.PI / 4), Math.PI / 4);
    
                // Gerar e mover canos
                updatePipes();
                
                // Checar por colisões
                checkCollisions();
                
                renderer.render(scene, camera);
            }
            
            function updatePipes() {
                let lastPipeX = 0;
                
                for (let i = pipes.length - 1; i >= 0; i--) {
                    const pipeGroup = pipes[i];
                    pipeGroup.position.x -= pipeSpeed;
                    
                    // Marcar ponto
                    if (!pipeGroup.userData.scored && pipeGroup.position.x < bird.position.x) {
                        score++;
                        scoreElement.innerText = score;
                        pipeGroup.userData.scored = true;
                    }
    
                    // Remover canos que saíram da tela
                    if (pipeGroup.position.x < -20) {
                        scene.remove(pipeGroup);
                        pipes.splice(i, 1);
                    }
                    
                    if(i === pipes.length - 1) {
                        lastPipeX = pipeGroup.position.x;
                    }
                }
    
                // Gerar novo cano quando o último atingir certa distância
                if (pipes.length === 0 || lastPipeX < 5) {
                    createPipePair(lastPipeSpawnX);
                }
            }
            
            function checkCollisions() {
                // Colisão com o chão
                if (bird.position.y - 0.5 <= -9) { // 0.5 é o raio do pássaro
                    gameOver();
                    return;
                }
    
                // Colisão com os canos
                const birdBox = new THREE.Box3().setFromObject(bird);
    
                for (const pipeGroup of pipes) {
                    const topPipe = pipeGroup.children[0];
                    const bottomPipe = pipeGroup.children[1];
                    
                    const topPipeBox = new THREE.Box3().setFromObject(topPipe);
                    const bottomPipeBox = new THREE.Box3().setFromObject(bottomPipe);
    
                    if (birdBox.intersectsBox(topPipeBox) || birdBox.intersectsBox(bottomPipeBox)) {
                        gameOver();
                        return;
                    }
                }
            }
    
            // --- FUNÇÕES DE CONTROLE DE ESTADO ---
            function flap() {
                 if (gameState === 'playing') {
                    birdVelocity = flapStrength;
                } else if (gameState === 'start') {
                    gameState = 'playing';
                    startScreen.classList.add('hidden');
                    scoreElement.classList.remove('hidden');
                    birdVelocity = flapStrength;
                }
            }
    
            function gameOver() {
                gameState = 'gameOver';
                gameOverScreen.classList.remove('hidden');
                scoreElement.classList.add('hidden');
                finalScoreElement.innerText = score;
            }
    
            function resetGame() {
                // Resetar estado
                gameState = 'start';
                score = 0;
                scoreElement.innerText = 0;
                
                // Esconder UI
                gameOverScreen.classList.add('hidden');
                startScreen.classList.remove('hidden');
    
                // Resetar pássaro
                bird.position.y = 0;
                bird.rotation.z = 0;
                birdVelocity = 0;
    
                // Remover todos os canos da cena e do array
                for (let i = pipes.length - 1; i >= 0; i--) {
                    scene.remove(pipes[i]);
                }
                pipes = [];
            }
    
            // --- EVENT HANDLERS ---
            function onWindowResize() {
                camera.aspect = window.innerWidth / window.innerHeight;
                camera.updateProjectionMatrix();
                renderer.setSize(window.innerWidth, window.innerHeight);
            }
    
            function onKeyPress(event) {
                if (event.code === 'Space') {
                    flap();
                }
            }
    
    
            function onMouseDown() {
                flap();
            }
    
            // --- INICIAR O JOGO ---
            init();
        </script>
    </body>
    </html>
    

    Como Jogar

    1. Salvar: Copie o código acima e salve-o em um arquivo chamado flappy3d.html.
    2. Abrir: Abra este arquivo em um navegador de internet moderno (como Chrome, Firefox, Edge, etc.).
    3. Jogar:
      • Clique com o mouse ou pressione a Barra de Espaço para começar o jogo.
      • Continue clicando ou pressionando a barra de espaço para fazer o "pássaro" pular e desviar dos canos.
      • Tente fazer a maior pontuação possível

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.