Make the code better: <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Epic 3D Snake Adventure</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background: radial-gradient(circle at center, #0f0c29, #302b63, #24243e);
            min-height: 100vh;
            overflow: hidden;
            display: flex;
            justify-content: center;
            align-items: center;
            color: white;
            touch-action: none;
            position: relative;
        }
        
        .game-container {
            position: relative;
            width: 100%;
            max-width: 800px;
            text-align: center;
            padding: 20px;
            z-index: 10;
        }
        
        .header {
            margin-bottom: 20px;
            text-shadow: 0 0 10px rgba(255, 255, 255, 0.6);
            position: relative;
        }
        
        .header h1 {
            font-size: 3.5rem;
            margin-bottom: 5px;
            background: linear-gradient(to right, #12c2e9, #c471ed, #f64f59);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            letter-spacing: 3px;
            text-transform: uppercase;
            font-weight: 900;
            position: relative;
            z-index: 2;
        }
        
        .header::after {
            content: "";
            position: absolute;
            top: -15px;
            left: 50%;
            transform: translateX(-50%);
            width: 200px;
            height: 200px;
            background: radial-gradient(circle, rgba(246, 79, 89, 0.4) 0%, transparent 70%);
            z-index: 1;
            animation: pulse 3s infinite;
        }
        
        .score-container {
            display: flex;
            justify-content: center;
            gap: 30px;
            margin-bottom: 10px;
            position: relative;
            z-index: 2;
        }
        
        .score-box {
            background: rgba(0, 0, 0, 0.3);
            padding: 12px 25px;
            border-radius: 15px;
            box-shadow: 0 5px 25px rgba(0, 0, 0, 0.5), 
                        0 0 15px rgba(18, 194, 233, 0.4);
            backdrop-filter: blur(6px);
            min-width: 130px;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            border: 2px solid rgba(255, 255, 255, 0.1);
            position: relative;
            overflow: hidden;
        }
        
        .score-box:hover {
            transform: scale(1.05);
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.6), 
                        0 0 20px rgba(18, 194, 233, 0.6);
        }
        
        .score-box::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.1), transparent);
            animation: shine 3s infinite;
        }
        
        .score-box h2 {
            color: #c471ed;
            font-size: 1.3rem;
            margin-bottom: 6px;
            letter-spacing: 1.2px;
        }
        
        .score-box p {
            color: #12c2e9;
            font-size: 2.2rem;
            font-weight: 800;
            text-shadow: 0 0 10px rgba(18, 194, 233, 0.7);
        }
        
        .game-board {
            position: relative;
            width: 100%;
            height: 65vh;
            max-height: 550px;
            border-radius: 18px;
            overflow: hidden;
            box-shadow: 0 15px 40px rgba(0, 0, 0, 0.7), 
                        0 0 25px rgba(246, 79, 89, 0.5);
            margin: 0 auto 20px;
            border: 3px solid rgba(255, 255, 255, 0.15);
            transform: perspective(1000px) rotateX(5deg);
            transition: transform 0.5s ease, box-shadow 0.5s ease;
        }
        
        .game-board:hover {
            transform: perspective(1000px) rotateX(5deg) scale(1.01);
            box-shadow: 0 20px 50px rgba(0, 0, 0, 0.8), 
                        0 0 35px rgba(246, 79, 89, 0.7);
        }
        
        #game3dContainer {
            width: 100%;
            height: 100%;
            border-radius: 18px;
            outline: none;
        }
        
        .controls {
            display: flex;
            justify-content: center;
            margin-top: 15px;
            gap: 20px;
        }
        
        .control-btn {
            background: rgba(255, 255, 255, 0.1);
            border: 2px solid rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            width: 65px;
            height: 65px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 30px;
            color: white;
            cursor: pointer;
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4),
                        0 0 10px rgba(18, 194, 233, 0.4);
            transition: all 0.2s ease;
            user-select: none;
            position: relative;
            overflow: hidden;
            z-index: 2;
        }
        
        .control-btn::before {
            content: "";
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transform: rotate(45deg);
            animation: shine 3s infinite;
        }
        
        .control-btn:active {
            transform: scale(0.9);
            background: rgba(255, 255, 255, 0.2);
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.4),
                        0 0 15px rgba(18, 194, 233, 0.6);
        }
        
        #pause {
            background: rgba(246, 79, 89, 0.25);
            border-color: rgba(246, 79, 89, 0.55);
            color: #f64f59;
            border-radius: 35px;
            width: 140px;
            font-size: 26px;
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4),
                        0 0 10px rgba(246, 79, 89, 0.4);
        }
        
        .instructions {
            margin-top: 18px;
            font-size: 1.1rem;
            line-height: 1.6;
            color: rgba(255, 255, 255, 0.9);
            max-width: 500px;
            margin-left: auto;
            margin-right: auto;
            background: rgba(0, 0, 0, 0.2);
            padding: 15px 25px;
            border-radius: 15px;
            border: 1px solid rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(5px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
            position: relative;
            z-index: 2;
        }
        
        .overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.9);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 20;
            color: #f64f59;
            font-weight: 700;
            text-align: center;
            padding: 20px;
            font-size: 2rem;
            border-radius: 18px;
            backdrop-filter: blur(10px);
        }
        
        .overlay.hidden {
            display: none;
        }
        
        .overlay h2 {
            font-size: 3.5rem;
            margin-bottom: 20px;
            text-shadow: 0 0 15px rgba(246, 79, 89, 0.8);
            animation: pulseText 2s infinite;
        }
        
        .overlay p {
            max-width: 80%;
            font-size: 1.4rem;
            margin-bottom: 20px;
            line-height: 1.6;
            color: #c471ed;
        }
        
        .overlay button {
            margin-top: 22px;
            background: linear-gradient(to right, #12c2e9, #c471ed, #f64f59);
            border: none;
            padding: 16px 48px;
            border-radius: 32px;
            color: white;
            font-size: 1.3rem;
            font-weight: 700;
            cursor: pointer;
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4),
                        0 0 15px rgba(200, 200, 255, 0.6);
            transition: all 0.3s ease;
            letter-spacing: 1px;
            position: relative;
            overflow: hidden;
            z-index: 2;
        }
        
        .overlay button::before {
            content: "";
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.3), transparent);
            transform: rotate(45deg);
            animation: shine 3s infinite;
        }
        
        .overlay button:hover {
            transform: scale(1.08);
            box-shadow: 0 8px 28px rgba(0, 0, 0, 0.6),
                        0 0 25px rgba(200, 200, 255, 0.8);
        }
        
        .swipe-hint {
            position: absolute;
            bottom: 20px;
            left: 0;
            width: 100%;
            text-align: center;
            font-size: 1.2rem;
            color: rgba(255, 255, 255, 0.8);
            animation: pulse 2s infinite;
            text-shadow: 0 0 5px rgba(18, 194, 233, 0.7);
            z-index: 2;
        }
        
        .particle {
            position: absolute;
            border-radius: 50%;
            background: currentColor;
            pointer-events: none;
            opacity: 0;
            animation: float 5s linear infinite;
            box-shadow: 0 0 10px currentColor;
        }
        
        .glow {
            position: absolute;
            border-radius: 50%;
            pointer-events: none;
            opacity: 0.5;
            animation: pulseGlow 3s infinite;
            z-index: 1;
        }
        
        @keyframes float {
            0% {
                transform: translateY(0) translateX(0) scale(0.5);
                opacity: 1;
            }
            100% {
                transform: translateY(-1000px) translateX(100px) scale(1.5);
                opacity: 0;
            }
        }
        
        @keyframes pulse {
            0% { opacity: 0.4; }
            50% { opacity: 1; }
            100% { opacity: 0.4; }
        }
        
        @keyframes pulseText {
            0% { text-shadow: 0 0 15px rgba(246, 79, 89, 0.8); }
            50% { text-shadow: 0 0 25px rgba(246, 79, 89, 1); }
            100% { text-shadow: 0 0 15px rgba(246, 79, 89, 0.8); }
        }
        
        @keyframes shine {
            0% { transform: translateX(-100%) rotate(45deg); }
            100% { transform: translateX(100%) rotate(45deg); }
        }
        
        @keyframes pulseGlow {
            0% { box-shadow: 0 0 10px rgba(18, 194, 233, 0.5); }
            50% { box-shadow: 0 0 30px rgba(18, 194, 233, 0.8); }
            100% { box-shadow: 0 0 10px rgba(18, 194, 233, 0.5); }
        }
        
        @media (max-width: 768px) {
            .header h1 {
                font-size: 2.8rem;
            }
            
            .score-box {
                padding: 10px 20px;
                min-width: 110px;
            }
            
            .score-box h2 {
                font-size: 1.1rem;
            }
            
            .score-box p {
                font-size: 1.8rem;
            }
            
            .control-btn {
                width: 60px;
                height: 60px;
                font-size: 26px;
            }
            
            #pause {
                width: 120px;
                font-size: 24px;
            }
            
            .overlay h2 {
                font-size: 2.8rem;
            }
            
            .overlay p {
                font-size: 1.2rem;
            }
            
            .instructions {
                font-size: 1rem;
                padding: 12px 20px;
            }
        }
        
        @media (max-width: 480px) {
            .header h1 {
                font-size: 2.2rem;
            }
            
            .score-box {
                min-width: 90px;
                padding: 8px 15px;
            }
            
            .score-box p {
                font-size: 1.6rem;
            }
            
            .control-btn {
                width: 55px;
                height: 55px;
                font-size: 24px;
            }
            
            #pause {
                width: 110px;
                font-size: 22px;
            }
            
            .overlay h2 {
                font-size: 2.2rem;
            }
            
            .overlay p {
                font-size: 1.1rem;
            }
            
            .instructions {
                font-size: 0.95rem;
                padding: 10px 15px;
            }
        }
    </style>
</head>
<body>
    <div class="game-container">
        <div class="header">
            <h1>3D SNAKE ADVENTURE</h1>
            <div class="score-container">
                <div class="score-box">
                    <h2>SCORE</h2>
                    <p id="score">0</p>
                </div>
                <div class="score-box">
                    <h2>APPLES</h2>
                    <p id="apples">0</p>
                </div>
            </div>
        </div>
        
        <div class="game-board">
            <div id="game3dContainer"></div>
            
            <div class="overlay" id="startOverlay">
                <h2>3D SNAKE ADVENTURE</h2>
                <p>Swipe to control the snake in this 3D world! Eat colorful apples to grow. Snake wraps around walls. 3-5 apples at a time.</p>
                <button id="startBtn">START GAME</button>
            </div>
            
            <div class="overlay hidden" id="gameOverOverlay">
                <h2>GAME OVER</h2>
                <p>Your final score: <span id="finalScore">0</span></p>
                <button id="restartBtn">PLAY AGAIN</button>
            </div>
            
            <div class="swipe-hint">SWIPE TO MOVE THE SNAKE</div>
        </div>
        
        <div class="controls">
            <button class="control-btn" id="pause">❚❚</button>
        </div>
        
        <div class="instructions">
            <p>Eat the colorful apples to grow! Snake wraps around walls. 3-5 apples at a time. Swipe or use arrow keys to move.</p>
        </div>
    </div>

    <script>
        // Game variables
        let scene, camera, renderer, snakeMeshes = [], appleMeshes = [];
        let snake = [], apples = [];
        let direction = 'right', nextDirection = 'right';
        let score = 0, applesEaten = 0;
        let gameSpeed = 8; // moves per second
        let gameRunning = false;
        let animationFrameId = null;
        let lastRenderTime = null;
        let gridWidth = 20, gridHeight = 15;
        const gridSize = 1;
        let particles = [];
        let touchStartX, touchStartY;
        let minApples = 3, maxApples = 5;
        
        // Initialize Three.js scene
        function initThreeScene() {
            // Create scene
            scene = new THREE.Scene();
            scene.background = new THREE.Color(0x0a0a1f);
            scene.fog = new THREE.Fog(0x0a0a1f, 15, 50);
            
            // Create camera
            camera = new THREE.PerspectiveCamera(
                75, 
                window.innerWidth / window.innerHeight,
                0.1,
                1000
            );
            camera.position.set(gridWidth/2, gridHeight * 1.5, gridHeight * 2);
            camera.lookAt(gridWidth/2, 0, gridHeight/2);
            
            // Create renderer
            renderer = new THREE.WebGLRenderer({ antialias: true });
            renderer.setSize(document.querySelector('.game-board').clientWidth, 
                            document.querySelector('.game-board').clientHeight);
            renderer.shadowMap.enabled = true;
            renderer.shadowMap.type = THREE.PCFSoftShadowMap;
            document.getElementById('game3dContainer').appendChild(renderer.domElement);
            
            // Add lighting
            const ambientLight = new THREE.AmbientLight(0xffffff, 0.4);
            scene.add(ambientLight);
            
            const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
            directionalLight.position.set(gridWidth/2, gridHeight * 2, gridHeight/2);
            directionalLight.castShadow = true;
            directionalLight.shadow.mapSize.width = 1024;
            directionalLight.shadow.mapSize.height = 1024;
            scene.add(directionalLight);
            
            // Create ground
            const groundGeometry = new THREE.PlaneGeometry(gridWidth * 1.2, gridHeight * 1.2);
            const groundMaterial = new THREE.MeshPhongMaterial({ 
                color: 0x1a1a2e,
                shininess: 30,
                side: THREE.DoubleSide,
                emissive: 0x121230,
                emissiveIntensity: 0.2
            });
            const ground = new THREE.Mesh(groundGeometry, groundMaterial);
            ground.rotation.x = -Math.PI / 2;
            ground.position.set(gridWidth/2, -0.5, gridHeight/2);
            ground.receiveShadow = true;
            scene.add(ground);
            
            // Create grid helper
            const gridHelper = new THREE.GridHelper(
                Math.max(gridWidth, gridHeight) * 1.2, 
                Math.max(gridWidth, gridHeight),
                0x444466,
                0x222244
            );
            gridHelper.position.set(gridWidth/2, 0.01, gridHeight/2);
            gridHelper.material.opacity = 0.3;
            gridHelper.material.transparent = true;
            scene.add(gridHelper);
            
            // Add star particles
            const starGeometry = new THREE.BufferGeometry();
            const starMaterial = new THREE.PointsMaterial({
                color: 0xffffff,
                size: 0.1,
                sizeAttenuation: false
            });
            
            const starVertices = [];
            for (let i = 0; i < 1000; i++) {
                const x = (Math.random() - 0.5) * 2000;
                const y = (Math.random() - 0.5) * 2000;
                const z = (Math.random() - 0.5) * 2000;
                starVertices.push(x, y, z);
            }
            
            starGeometry.setAttribute('position', new THREE.Float32BufferAttribute(starVertices, 3));
            const stars = new THREE.Points(starGeometry, starMaterial);
            scene.add(stars);
        }
        
        // Initialize game
        function initGame() {
            // Reset snake
            snake = [
                {x: Math.floor(gridWidth / 2), y: Math.floor(gridHeight / 2)},
                {x: Math.floor(gridWidth / 2) - 1, y: Math.floor(gridHeight / 2)},
                {x: Math.floor(gridWidth / 2) - 2, y: Math.floor(gridHeight / 2)}
            ];
            
            // Create snake meshes
            createSnakeMeshes();
            
            // Reset apples
            apples = [];
            spawnApples();
            
            // Reset game state
            direction = 'right';
            nextDirection = 'right';
            score = 0;
            applesEaten = 0;
            gameSpeed = 8;
            gameRunning = false;
            
            // Update UI
            document.getElementById('score').textContent = score;
            document.getElementById('apples').textContent = applesEaten;
            document.getElementById('startOverlay').classList.remove('hidden');
            document.getElementById('gameOverOverlay').classList.add('hidden');
            document.getElementById('pause').textContent = '❚❚';
        }
        
        // Create snake meshes
        function createSnakeMeshes() {
            // Clear existing snake
            snakeMeshes.forEach(segment => scene.remove(segment));
            snakeMeshes = [];
            
            // Create new snake segments
            snake.forEach((segment, index) => {
                const isHead = index === 0;
                const size = isHead ? 0.8 : 0.7 - (index * 0.01);
                const geometry = new THREE.SphereGeometry(size, 16, 16);
                
                // Create gradient color for snake
                let color;
                if (isHead) {
                    color = new THREE.Color(0x4caf50);
                } else {
                    const hue = 0.33 + 0.15 * (index / snake.length);
                    color = new THREE.Color().setHSL(hue, 0.7, 0.5);
                }
                
                const material = new THREE.MeshPhongMaterial({ 
                    color: color,
                    shininess: 50,
                    emissive: color,
                    emissiveIntensity: 0.1
                });
                
                const segmentMesh = new THREE.Mesh(geometry, material);
                segmentMesh.position.set(segment.x, 0.4, segment.y);
                segmentMesh.castShadow = true;
                segmentMesh.receiveShadow = true;
                snakeMeshes.push(segmentMesh);
                scene.add(segmentMesh);
            });
        }
        
        // Spawn apples
        function spawnApples() {
            // Clear existing apples
            appleMeshes.forEach(apple => scene.remove(apple));
            appleMeshes = [];
            
            // Spawn apples to maintain 3-5
            const currentCount = apples.length;
            const targetCount = Math.min(maxApples, Math.max(minApples, Math.floor(Math.random() * (maxApples - minApples + 1)) + minApples));
            const toSpawn = Math.max(0, targetCount - currentCount);
            
            for (let i = 0; i < toSpawn; i++) {
                const newApple = {
                    x: Math.floor(Math.random() * gridWidth),
                    y: Math.floor(Math.random() * gridHeight),
                    color: getRandomColor()
                };
                
                // Ensure apple doesn't spawn on snake
                const collisionWithSnake = snake.some(s => s.x === newApple.x && s.y === newApple.y);
                if (!collisionWithSnake) {
                    apples.push(newApple);
                }
            }
            
            // Create apple meshes
            createAppleMeshes();
        }
        
        // Create apple meshes
        function createAppleMeshes() {
            apples.forEach(apple => {
                const geometry = new THREE.SphereGeometry(0.4, 16, 16);
                const material = new THREE.MeshPhongMaterial({ 
                    color: apple.color,
                    shininess: 100,
                    emissive: apple.color,
                    emissiveIntensity: 0.2
                });
                const appleMesh = new THREE.Mesh(geometry, material);
                appleMesh.position.set(apple.x, 0.4, apple.y);
                appleMesh.castShadow = true;
                appleMesh.receiveShadow = true;
                appleMeshes.push(appleMesh);
                scene.add(appleMesh);
                
                // Add glow effect
                const glowGeometry = new THREE.SphereGeometry(0.5, 16, 16);
                const glowMaterial = new THREE.MeshBasicMaterial({
                    color: apple.color,
                    transparent: true,
                    opacity: 0.3,
                    side: THREE.BackSide
                });
                const glowMesh = new THREE.Mesh(glowGeometry, glowMaterial);
                glowMesh.position.set(apple.x, 0.4, apple.y);
                appleMeshes.push(glowMesh);
                scene.add(glowMesh);
            });
        }
        
        // Get random color
        function getRandomColor() {
            const colors = [
                '#FF5252', '#FF4081', '#E040FB', '#7C4DFF',
                '#536DFE', '#448AFF', '#40C4FF', '#18FFFF',
                '#64FFDA', '#69F0AE', '#B2FF59', '#EEFF41'
            ];
            return colors[Math.floor(Math.random() * colors.length)];
        }
        
        // Update game state
        function update() {
            // Apply next direction if valid (no 180 turns)
            if (nextDirection) {
                if (
                    (nextDirection === 'up' && direction !== 'down') ||
                    (nextDirection === 'down' && direction !== 'up') ||
                    (nextDirection === 'left' && direction !== 'right') ||
                    (nextDirection === 'right' && direction !== 'left')
                ) {
                    direction = nextDirection;
                }
            }
            
            // Compute new head position
            const head = {...snake[0]};
            switch (direction) {
                case 'up': head.y--; break;
                case 'down': head.y++; break;
                case 'left': head.x--; break;
                case 'right': head.x++; break;
            }
            
            // Wrap positions
            if (head.x < 0) head.x = gridWidth - 1;
            else if (head.x >= gridWidth) head.x = 0;
            if (head.y < 0) head.y = gridHeight - 1;
            else if (head.y >= gridHeight) head.y = 0;
            
            // Check collision with self
            for (let i = 0; i < snake.length; i++) {
                if (snake[i].x === head.x && snake[i].y === head.y) {
                    endGame();
                    return;
                }
            }
            
            snake.unshift(head);
            
            // Check if apple eaten
            let ateApple = false;
            for (let i = 0; i < apples.length; i++) {
                if (apples[i].x === head.x && apples[i].y === head.y) {
                    // Remove apple and create particles
                    apples.splice(i, 1);
                    createParticles(head.x, head.y, apples[i].color);
                    
                    // Update score
                    score += 10;
                    applesEaten++;
                    gameSpeed = Math.min(20, gameSpeed + 0.3);
                    
                    document.getElementById('score').textContent = score;
                    document.getElementById('apples').textContent = applesEaten;
                    
                    ateApple = true;
                    break;
                }
            }
            
            if (!ateApple) {
                snake.pop();
            } else {
                spawnApples();
                createSnakeMeshes();
            }
        }
        
        // Create particles when eating an apple
        function createParticles(x, y, color) {
            for (let i = 0; i < 30; i++) {
                const particle = document.createElement('div');
                particle.className = 'particle';
                particle.style.left = `${x * (100 / gridWidth)}%`;
                particle.style.top = `${y * (100 / gridHeight)}%`;
                particle.style.width = `${Math.random() * 15 + 5}px`;
                particle.style.height = particle.style.width;
                particle.style.color = color;
                particle.style.animationDuration = `${Math.random() * 1 + 0.5}s`;
                document.body.appendChild(particle);
                
                // Remove particle after animation
                setTimeout(() => {
                    particle.remove();
                }, 1000);
            }
        }
        
        // Render the scene
        function render() {
            // Update snake positions
            snakeMeshes.forEach((mesh, i) => {
                mesh.position.set(snake[i].x, 0.4, snake[i].y);
                
                // Add subtle animation to snake
                if (gameRunning) {
                    const time = Date.now() * 0.002;
                    mesh.rotation.y = Math.sin(time + i * 0.3) * 0.1;
                    mesh.rotation.x = Math.cos(time + i * 0.2) * 0.05;
                }
            });
            
            // Animate apples
            appleMeshes.forEach(apple => {
                if (apple.geometry.parameters.radius === 0.4) {
                    apple.rotation.y += 0.02;
                    apple.position.y = 0.4 + Math.sin(Date.now() * 0.002) * 0.1;
                }
            });
            
            // Render the scene
            renderer.render(scene, camera);
        }
        
        // Game loop
        function gameLoop(timestamp) {
            if (!gameRunning) return;
            
            if (!lastRenderTime) lastRenderTime = timestamp;
            
            const secondsSinceLastRender = (timestamp - lastRenderTime) / 1000;
            const interval = 1 / gameSpeed;
            
            if (secondsSinceLastRender >= interval) {
                lastRenderTime = timestamp;
                update();
            }
            
            render();
            animationFrameId = requestAnimationFrame(gameLoop);
        }
        
        // Start game
        function startGame() {
            gameRunning = true;
            lastRenderTime = null;
            document.getElementById('startOverlay').classList.add('hidden');
            animationFrameId = requestAnimationFrame(gameLoop);
        }
        
        // End game
        function endGame() {
            gameRunning = false;
            cancelAnimationFrame(animationFrameId);
            document.getElementById('finalScore').textContent = score;
            document.getElementById('gameOverOverlay').classList.remove('hidden');
        }
        
        // Toggle pause
        function togglePause() {
            if (!gameRunning) return;
            
            if (animationFrameId) {
                cancelAnimationFrame(animationFrameId);
                animationFrameId = null;
                document.getElementById('pause').textContent = '▶';
            } else {
                animationFrameId = requestAnimationFrame(gameLoop);
                document.getElementById('pause').textContent = '❚❚';
            }
        }
        
        // Handle swipe gestures
        function handleTouchStart(e) {
            touchStartX = e.touches[0].clientX;
            touchStartY = e.touches[0].clientY;
        }
        
        function handleTouchMove(e) {
            if (!touchStartX || !touchStartY || !gameRunning) return;
            
            const touchEndX = e.touches[0].clientX;
            const touchEndY = e.touches[0].clientY;
            
            const diffX = touchStartX - touchEndX;
            const diffY = touchStartY - touchEndY;
            
            // Determine swipe direction
            if (Math.abs(diffX) > Math.abs(diffY)) {
                // Horizontal swipe
                if (diffX > 0) {
                    // Left swipe
                    nextDirection = 'left';
                } else {
                    // Right swipe
                    nextDirection = 'right';
                }
            } else {
                // Vertical swipe
                if (diffY > 0) {
                    // Up swipe
                    nextDirection = 'up';
                } else {
                    // Down swipe
                    nextDirection = 'down';
                }
            }
            
            // Reset touch positions
            touchStartX = null;
            touchStartY = null;
        }
        
        // Initialize everything
        function init() {
            initThreeScene();
            initGame();
            
            // Add event listeners
            document.getElementById('startBtn').addEventListener('click', startGame);
            document.getElementById('restartBtn').addEventListener('click', () => {
                initGame();
                startGame();
            });
            document.getElementById('pause').addEventListener('click', togglePause);
            
            // Keyboard controls
            document.addEventListener('keydown', (e) => {
                if (!gameRunning) return;
                
                switch (e.key) {
                    case 'ArrowUp': nextDirection = 'up'; break;
                    case 'ArrowDown': nextDirection = 'down'; break;
                    case 'ArrowLeft': nextDirection = 'left'; break;
                    case 'ArrowRight': nextDirection = 'right'; break;
                    case ' ': togglePause(); break;
                }
            });
            
            // Touch controls
            const gameBoard = document.querySelector('.game-board');
            gameBoard.addEventListener('touchstart', handleTouchStart, { passive: false });
            gameBoard.addEventListener('touchmove', handleTouchMove, { passive: false });
            
            // Create background particles
            createBackgroundParticles();
        }
        
        // Create background particles
        function createBackgroundParticles() {
            for (let i = 0; i < 80; i++) {
                const particle = document.createElement('div');
                particle.className = 'particle';
                particle.style.left = `${Math.random() * 100}%`;
                particle.style.top = `${Math.random() * 100}%`;
                const size = Math.random() * 10 + 3;
                particle.style.width = `${size}px`;
                particle.style.height = `${size}px`;
                particle.style.color = getRandomColor();
                particle.style.animationDuration = `${Math.random() * 10 + 5}s`;
                particle.style.animationDelay = `${Math.random() * 5}s`;
                document.body.appendChild(particle);
            }
            
            // Add glow effects
            for (let i = 0; i < 5; i++) {
                const glow = document.createElement('div');
                glow.className = 'glow';
                glow.style.left = `${Math.random() * 100}%`;
                glow.style.top = `${Math.random() * 100}%`;
                const size = Math.random() * 300 + 100;
                glow.style.width = `${size}px`;
                glow.style.height = `${size}px`;
                glow.style.background = `radial-gradient(circle, ${getRandomColor()} 0%, transparent 70%)`;
                document.body.appendChild(glow);
            }
        }
        
        // Start the game when page loads
        window.addEventListener('load', init);
    </script>
</body>
</html>