<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>3D Speed Car Game</title>
    <style>
        body { margin: 0; overflow: hidden; background: #222; font-family: sans-serif; }
        
        #info {
            position: absolute; top: 10px; left: 10px; color: #fff;
            font-size: 18px; font-weight: bold; background: rgba(0,0,0,0.6); 
            padding: 8px 16px; border-radius: 8px; display: none; z-index: 10;
        }

        /* Overlay & Menu Styling */
        .overlay {
            position: absolute; top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0, 0, 0, 0.7); display: flex; flex-direction: column;
            justify-content: center; align-items: center; color: white; z-index: 20;
        }

        .title { font-size: 32px; font-weight: bold; margin-bottom: 20px; text-shadow: 2px 2px 4px #000; }
        .score-text { font-size: 22px; margin-bottom: 20px; color: #ffeb3b; }

        .game-btn {
            padding: 15px 40px; font-size: 22px; font-weight: bold; color: white;
            background: #28a745; border: none; border-radius: 30px; cursor: pointer;
            box-shadow: 0 4px 10px rgba(0,0,0,0.5); transition: 0.2s;
        }
        .game-btn:active { transform: scale(0.95); }

        #controls {
            position: absolute; bottom: 20px; width: 100%; display: none; 
            justify-content: space-around; z-index: 10;
        }
        .btn {
            width: 75px; height: 75px; background: rgba(255,255,255,0.3); border: 3px solid white;
            border-radius: 50%; color: white; font-size: 32px; display: flex;
            align-items: center; justify-content: center; user-select: none;
        }
    </style>
    <!-- Three.js Library -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
</head>
<body>

    <!-- Score Info -->
    <div id="info">
        Score: <span id="score">0</span> | Speed: <span id="speedDisplay">1</span>x
    </div>

    <!-- Start Screen -->
    <div id="startScreen" class="overlay">
        <div class="title">🏎️ 3D CAR RACER</div>
        <button class="game-btn" onclick="startGame()">START GAME</button>
    </div>

    <!-- Game Over Screen -->
    <div id="gameOverScreen" class="overlay" style="display: none;">
        <div class="title" style="color: #ff4d4d;">CRASHED! 💥</div>
        <div class="score-text">Final Score: <span id="finalScore">0</span></div>
        <button class="game-btn" style="background: #dc3545;" onclick="restartGame()">RESTART</button>
    </div>

    <!-- Touch Controls -->
    <div id="controls">
        <div class="btn" id="leftBtn">◄</div>
        <div class="btn" id="rightBtn">►</div>
    </div>

    <script>
        // 1. Scene & Camera Setup
        const scene = new THREE.Scene();
        scene.background = new THREE.Color(0x87CEEB);
        scene.fog = new THREE.Fog(0x87CEEB, 20, 80);

        const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 100);
        camera.position.set(0, 4, 9);
        camera.lookAt(0, 0, 0);

        const renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(renderer.domElement);

        // Lights
        const dirLight = new THREE.DirectionalLight(0xffffff, 1.2);
        dirLight.position.set(5, 20, 10);
        scene.add(dirLight);
        scene.add(new THREE.AmbientLight(0x606060));

        // 2. Road Creation
        const roadGroup = new THREE.Group();
        const roadGeo = new THREE.PlaneGeometry(10, 200);
        const roadMat = new THREE.MeshStandardMaterial({ color: 0x222222 });
        const road = new THREE.Mesh(roadGeo, roadMat);
        road.rotation.x = -Math.PI / 2;
        roadGroup.add(road);

        // Road Lines
        const lines = [];
        for (let i = -100; i < 100; i += 6) {
            const lineGeo = new THREE.PlaneGeometry(0.3, 3);
            const lineMat = new THREE.MeshBasicMaterial({ color: 0xffffff });
            const line = new THREE.Mesh(lineGeo, lineMat);
            line.rotation.x = -Math.PI / 2;
            line.position.set(0, 0.01, i);
            roadGroup.add(line);
            lines.push(line);
        }
        scene.add(roadGroup);

        // 3. Car Builder Function
        function createCar(color) {
            const car = new THREE.Group();
            
            // Body
            const bodyGeo = new THREE.BoxGeometry(1.4, 0.5, 2.6);
            const bodyMat = new THREE.MeshStandardMaterial({ color: color });
            const body = new THREE.Mesh(bodyGeo, bodyMat);
            body.position.y = 0.4;
            car.add(body);

            // Cabin
            const cabinGeo = new THREE.BoxGeometry(1, 0.4, 1.3);
            const cabinMat = new THREE.MeshStandardMaterial({ color: 0x111111 });
            const cabin = new THREE.Mesh(cabinGeo, cabinMat);
            cabin.position.set(0, 0.75, -0.2);
            car.add(cabin);

            // Wheels
            const wheelGeo = new THREE.CylinderGeometry(0.25, 0.25, 0.2, 16);
            const wheelMat = new THREE.MeshStandardMaterial({ color: 0x000000 });
            
            const positions = [
                [-0.75, 0.25, 0.8],
                [0.75, 0.25, 0.8],
                [-0.75, 0.25, -0.8],
                [0.75, 0.25, -0.8]
            ];

            positions.forEach(pos => {
                const wheel = new THREE.Mesh(wheelGeo, wheelMat);
                wheel.rotation.z = Math.PI / 2;
                wheel.position.set(...pos);
                car.add(wheel);
            });

            return car;
        }

        // Player Car
        const playerCar = createCar(0xff0000);
        playerCar.position.set(0, 0, 3);
        scene.add(playerCar);

        // Enemy Cars Variables
        let enemyCars = [];
        const colors = [0x0000ff, 0x00ff00, 0xffff00, 0xff00ff];

        function spawnEnemy() {
            const color = colors[Math.floor(Math.random() * colors.length)];
            const enemy = createCar(color);
            enemy.position.x = (Math.random() - 0.5) * 6.5;
            enemy.position.z = -50;
            scene.add(enemy);
            enemyCars.push(enemy);
        }

        // Controls
        let moveLeft = false, moveRight = false;
        document.addEventListener('keydown', (e) => {
            if (e.key === 'ArrowLeft') moveLeft = true;
            if (e.key === 'ArrowRight') moveRight = true;
        });
        document.addEventListener('keyup', (e) => {
            if (e.key === 'ArrowLeft') moveLeft = false;
            if (e.key === 'ArrowRight') moveRight = false;
        });

        // Touch Controls
        const leftBtn = document.getElementById('leftBtn');
        const rightBtn = document.getElementById('rightBtn');

        leftBtn.addEventListener('touchstart', (e) => { e.preventDefault(); moveLeft = true; });
        leftBtn.addEventListener('touchend', (e) => { e.preventDefault(); moveLeft = false; });
        rightBtn.addEventListener('touchstart', (e) => { e.preventDefault(); moveRight = true; });
        rightBtn.addEventListener('touchend', (e) => { e.preventDefault(); moveRight = false; });

        // Game State Variables
        let score = 0;
        let baseSpeed = 0.35;
        let currentSpeed = baseSpeed;
        let isGameRunning = false;

        // Start Game
        function startGame() {
            document.getElementById('startScreen').style.display = 'none';
            document.getElementById('info').style.display = 'block';
            document.getElementById('controls').style.display = 'flex';
            isGameRunning = true;
            animate();
        }

        // Restart Game
        function restartGame() {
            // Clear enemies
            enemyCars.forEach(car => scene.remove(car));
            enemyCars = [];

            // Reset variables
            score = 0;
            currentSpeed = baseSpeed;
            playerCar.position.x = 0;
            document.getElementById('score').innerText = score;
            document.getElementById('speedDisplay').innerText = "1.0";

            document.getElementById('gameOverScreen').style.display = 'none';
            isGameRunning = true;
            animate();
        }

        // Main Animation Loop
        function animate() {
            if (!isGameRunning) return;
            requestAnimationFrame(animate);

            // Speed multiplier
            currentSpeed = baseSpeed + (score * 0.003);
            document.getElementById('speedDisplay').innerText = (currentSpeed / baseSpeed).toFixed(1);

            // Steering Movement
            const turnSpeed = 0.12 + (currentSpeed * 0.1);
            if (moveLeft && playerCar.position.x > -3.5) playerCar.position.x -= turnSpeed;
            if (moveRight && playerCar.position.x < 3.5) playerCar.position.x += turnSpeed;

            // Road Effect
            lines.forEach(line => {
                line.position.z += currentSpeed;
                if (line.position.z > 20) line.position.z = -80;
            });

            // Spawn Enemy
            if (Math.random() < (0.015 + currentSpeed * 0.02)) spawnEnemy();

            // Move Enemies
            for (let i = 0; i < enemyCars.length; i++) {
                let enemy = enemyCars[i];
                enemy.position.z += currentSpeed;

                // Collision Detection
                if (Math.abs(enemy.position.z - playerCar.position.z) < 2.2 &&
                    Math.abs(enemy.position.x - playerCar.position.x) < 1.2) {
                    
                    isGameRunning = false;
                    document.getElementById('finalScore').innerText = score;
                    document.getElementById('gameOverScreen').style.display = 'flex';
                    return;
                }

                // Remove Passed Enemy
                if (enemy.position.z > 10) {
                    scene.remove(enemy);
                    enemyCars.splice(i, 1);
                    score += 10;
                    document.getElementById('score').innerText = score;
                }
            }

            renderer.render(scene, camera);
        }

        // Initial Render so scene is visible behind start screen
        renderer.render(scene, camera);
    </script>
</body>
</html>
