<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Pac-Siswa: Misi IPS</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&family=Nunito:wght@700&display=swap');

        body {
            background-color: #111;
            color: white;
            font-family: 'Nunito', sans-serif;
            overflow: hidden;
            touch-action: none;
            user-select: none;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }

        #game-wrapper {
            position: relative;
            width: 100%;
            max-width: 600px; /* Max width for mobile playability */
            aspect-ratio: 3/4;
            background: #000;
            box-shadow: 0 0 20px #22c55e;
            border-radius: 8px;
            overflow: hidden;
        }

        canvas {
            display: block;
            width: 100%;
            height: 100%;
        }

        /* UI Overlay */
        .ui-layer {
            position: absolute;
            top: 0; left: 0; width: 100%; height: 100%;
            pointer-events: none;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            z-index: 10;
        }

        /* HUD */
        #hud {
            display: flex;
            justify-content: space-between;
            padding: 20px;
            font-family: 'Press Start 2P', cursive;
            font-size: 16px;
            text-shadow: 2px 2px 0 #000;
            color: #fbbf24;
            background: rgba(0,0,0,0.6);
            border-bottom: 2px solid #333;
        }

        /* Mobile Controls */
        #mobile-controls {
            pointer-events: auto;
            display: none; /* Shown via JS on touch devices */
            padding: 20px;
            padding-bottom: 40px;
            justify-content: center;
            gap: 20px;
            opacity: 0.6;
        }

        .dpad-btn {
            width: 60px;
            height: 60px;
            background: rgba(255,255,255,0.2);
            border: 2px solid rgba(255,255,255,0.5);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            color: white;
        }
        
        .dpad-btn:active { background: rgba(255,255,255,0.5); }

        /* Quiz Modal */
        #quiz-modal {
            position: absolute;
            top: 50%; left: 50%;
            transform: translate(-50%, -50%) scale(0.9);
            width: 85%;
            background: #fff;
            color: #1f2937;
            border: 4px solid #3b82f6;
            border-radius: 16px;
            padding: 20px;
            pointer-events: auto;
            opacity: 0;
            transition: all 0.2s;
            display: none;
            z-index: 50;
            box-shadow: 0 10px 30px rgba(0,0,0,0.8);
        }

        #quiz-modal.show {
            opacity: 1;
            transform: translate(-50%, -50%) scale(1);
            display: block;
        }

        .quiz-title {
            font-size: 1.2rem;
            color: #3b82f6;
            font-weight: bold;
            text-transform: uppercase;
            margin-bottom: 10px;
            text-align: center;
        }

        .quiz-q {
            font-size: 1.1rem;
            font-weight: bold;
            margin-bottom: 20px;
            text-align: center;
        }

        .option-btn {
            width: 100%;
            padding: 12px;
            margin: 5px 0;
            border: 2px solid #e5e7eb;
            background: #f9fafb;
            border-radius: 8px;
            text-align: left;
            font-weight: bold;
            cursor: pointer;
            transition: 0.1s;
        }

        .option-btn:hover { background: #dbeafe; border-color: #3b82f6; }
        .option-btn.correct { background: #dcfce7; border-color: #22c55e; color: #166534; }
        .option-btn.wrong { background: #fee2e2; border-color: #ef4444; color: #991b1b; }

        /* Screens */
        .screen {
            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: 60;
            pointer-events: auto;
            text-align: center;
        }

        .btn-start {
            background: #fbbf24;
            color: black;
            border: 4px solid #b45309;
            padding: 15px 30px;
            font-family: 'Press Start 2P', cursive;
            font-size: 14px;
            cursor: pointer;
            margin-top: 20px;
        }
        
        .btn-start:active { transform: translateY(4px); }

        .btn-back {
            color: #888;
            text-decoration: none;
            font-size: 12px;
            margin-top: 15px;
            font-family: 'Nunito', sans-serif;
        }
        .btn-back:hover { color: #ccc; }

    </style>
</head>
<body>
<div id="game-wrapper">
    <canvas id="gameCanvas"></canvas>

    <div class="ui-layer">
        <div id="hud">
            <span>SCORE: <span id="score-el">0</span></span>
            <span style="color: #ef4444;">LIVES: <span id="lives-el">❤❤❤</span></span>
        </div>

        <div style="flex-grow: 1;"></div>

        <!-- D-Pad for Mobile -->
        <div id="mobile-controls">
            <div class="dpad-btn" onclick="handleInput('left')">◀</div>
            <div class="dpad-btn" onclick="handleInput('up')">▲</div>
            <div class="dpad-btn" onclick="handleInput('down')">▼</div>
            <div class="dpad-btn" onclick="handleInput('right')">▶</div>
        </div>
    </div>

    <!-- Quiz Modal -->
    <div id="quiz-modal">
        <div class="quiz-title">PERTANYAAN IPS</div>
        <div id="q-text" class="quiz-q">...</div>
        <div id="options-container"></div>
    </div>

    <!-- Start Screen -->
    <div id="start-screen" class="screen">
        <h1 class="text-4xl text-yellow-400 mb-4" style="font-family: 'Press Start 2P'; line-height: 1.5;">PAC-SISWA<br>MISI IPS</h1>
        <div class="bg-gray-800 p-4 rounded-lg text-sm text-gray-300 max-w-xs border border-gray-600">
            <p class="mb-2 font-bold text-yellow-400">ATURAN MAIN:</p>
            <ul class="text-left space-y-2">
                <li>🔵 Jawab Benar = Hantu Lemah</li>
                <li>❌ Jawab Salah = <span class="text-red-400 font-bold">GAME OVER</span></li>
                <li>👻 Hantu = Kurang Nyawa (Maks 3)</li>
            </ul>
        </div>
        <button class="btn-start" onclick="initGame()">MULAI MAIN</button>
        <a href="index.php?game_id=9&spawn=entrance" class="btn-back">← Kembali ke Lobby</a>
    </div>

    <!-- Game Over Screen -->
    <div id="end-screen" class="screen" style="display: none;">
        <h1 id="end-title" class="text-4xl text-white mb-4" style="font-family: 'Press Start 2P'">GAME OVER</h1>
        <p id="end-reason" class="text-red-400 font-bold mb-4 text-sm"></p>
        <p class="text-xl text-yellow-400 mb-8">Score: <span id="final-score">0</span></p>
        <button class="btn-start" onclick="location.reload()">COBA LAGI</button>
        <a href="index.php?game_id=9&spawn=entrance" class="btn-back">← Kembali ke Lobby</a>
    </div>
</div>

<script>
    const canvas = document.getElementById('gameCanvas');
    const ctx = canvas.getContext('2d');

    // --- MAP DATA ---
    const rawMap = [
        [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
        [1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1],
        [1,0,1,1,1,0,1,1,1,1,1,1,1,0,1,1,1,0,1],
        [1,3,1,1,1,0,1,1,1,1,1,1,1,0,1,1,1,3,1],
        [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
        [1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1],
        [1,0,0,0,0,0,1,0,0,2,0,0,1,0,0,0,0,0,1],
        [1,1,1,1,1,0,1,1,1,2,1,1,1,0,1,1,1,1,1],
        [2,2,2,2,1,0,1,2,2,8,2,2,1,0,1,2,2,2,2],
        [1,1,1,1,1,0,1,2,8,8,8,2,1,0,1,1,1,1,1],
        [2,2,2,2,2,0,2,2,1,1,1,2,2,0,2,2,2,2,2],
        [1,1,1,1,1,0,1,2,2,2,2,2,1,0,1,1,1,1,1],
        [1,0,0,0,0,0,1,0,1,1,1,0,1,0,0,0,0,0,1],
        [1,0,1,1,1,0,0,0,0,9,0,0,0,0,1,1,1,0,1],
        [1,3,0,0,1,0,1,1,1,1,1,1,1,0,1,0,0,3,1],
        [1,1,1,0,1,0,0,0,0,1,0,0,0,0,1,0,1,1,1],
        [1,0,0,0,0,0,1,1,0,3,0,1,1,0,0,0,0,0,1],
        [1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1],
        [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
        [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
    ];

    // --- CONFIGURATION ---
    const TILE_SIZE = 30; 
    let ROWS = rawMap.length;
    let COLS = rawMap[0].length;

    // Questions IPS Kelas 6 (Sequential)
    let questions = [
        { q: "1. Negara anggota ASEAN yang tidak pernah dijajah adalah...", opts: ["Thailand", "Malaysia", "Vietnam", "Filipina"], a: 0 },
        { q: "2. Ibu kota negara Filipina adalah...", opts: ["Manila", "Bangkok", "Hanoi", "Kuala Lumpur"], a: 0 },
        { q: "3. Mata uang negara Malaysia adalah...", opts: ["Ringgit", "Baht", "Peso", "Dollar"], a: 0 },
        { q: "4. Proklamasi Kemerdekaan Indonesia dibacakan oleh...", opts: ["Soekarno-Hatta", "Soeharto", "B.J. Habibie", "Sudirman"], a: 0 },
        { q: "5. Landasan idiil koperasi Indonesia adalah...", opts: ["Pancasila", "UUD 1945", "GBHN", "Keppres"], a: 0 }
    ];

    // Fetch Questions from DB
    async function fetchQuestions() {
        const urlParams = new URLSearchParams(window.location.search);
        const gameId = urlParams.get('game_id') || 9;
        try {
            const res = await fetch(`questions.php?game_id=${gameId}`);
            if (res.ok) {
                const data = await res.json();
                if (data && Object.keys(data).length > 0) {
                    const newQuestions = [];
                    Object.keys(data).forEach((lvl, idx) => {
                        const q = data[lvl];
                        newQuestions.push({
                            q: `${idx + 1}. ${q.q}`, // Add number prefix as in original
                            opts: q.options,
                            a: q.correct
                        });
                    });
                    
                    if (newQuestions.length > 0) {
                        while (newQuestions.length < 5) {
                            newQuestions.push(newQuestions[newQuestions.length % newQuestions.length]);
                        }
                        questions = newQuestions;
                        console.log("Questions loaded from DB:", questions);
                    }
                }
            }
        } catch (e) {
            console.error("Failed to fetch questions:", e);
        }
    }

    // Init Data
    fetchQuestions();

    // --- GAME VARIABLES ---
    let map = [];
    let scale = 1;
    let offsetX = 0, offsetY = 0;
    let gameState = 'MENU';
    let score = 0;
    let lives = 3;
    let dotsRemaining = 0;
    let currentQuestionIdx = 0; // Track current question
    
    // Entities
    // Pacman Speed 1.5 (Santai)
    let pacman = { x: 1, y: 1, dir: {x:0, y:0}, nextDir: {x:0, y:0}, mouth: 0.2, mouthOpen: true, speed: 1.5, gridX: 1, gridY: 1 };
    let ghosts = [];
    const GHOST_COLORS = ['red', 'pink', 'cyan', 'orange'];
    let scaredMode = false;
    let scaredTimer = 0;

    // --- SETUP ---
    
    function resizeCanvas() {
        const container = document.getElementById('game-wrapper');
        canvas.width = container.clientWidth;
        canvas.height = container.clientHeight;
        
        const mapW = COLS * TILE_SIZE;
        const mapH = ROWS * TILE_SIZE;
        scale = Math.min(canvas.width / mapW, canvas.height / mapH);
        
        offsetX = (canvas.width - mapW * scale) / 2;
        offsetY = (canvas.height - mapH * scale) / 2;
        
        if ('ontouchstart' in window || navigator.maxTouchPoints) {
            document.getElementById('mobile-controls').style.display = 'flex';
        }
    }
    window.addEventListener('resize', resizeCanvas);

    function initGame() {
        resizeCanvas();
        document.getElementById('start-screen').style.display = 'none';
        document.getElementById('end-screen').style.display = 'none';
        
        map = JSON.parse(JSON.stringify(rawMap));
        ghosts = [];
        dotsRemaining = 0;
        score = 0;
        lives = 3;
        scaredMode = false;
        currentQuestionIdx = 0; // Reset question order
        
        for(let r=0; r<ROWS; r++) {
            for(let c=0; c<COLS; c++) {
                const type = map[r][c];
                if(type === 0) dotsRemaining++;
                if(type === 9) { 
                    pacman.gridX = c; pacman.gridY = r;
                    pacman.x = c * TILE_SIZE; pacman.y = r * TILE_SIZE;
                    pacman.dir = {x:0, y:0};
                    pacman.nextDir = {x:0, y:0};
                    map[r][c] = 2; 
                }
                if(type === 8) { 
                    ghosts.push({
                        gridX: c, gridY: r,
                        x: c * TILE_SIZE, y: r * TILE_SIZE,
                        color: GHOST_COLORS[ghosts.length % 4],
                        dir: {x:0, y:-1}, 
                        speed: 1.0, // Hantu Pelan
                        state: 'scatter'
                    });
                    map[r][c] = 2; 
                }
            }
        }
        
        gameState = 'PLAY';
        updateHUD();
        gameLoop();
    }

    // --- LOGIC ---

    function handleInput(dir) {
        let dx=0, dy=0;
        if (dir === 'up') dy = -1;
        if (dir === 'down') dy = 1;
        if (dir === 'left') dx = -1;
        if (dir === 'right') dx = 1;
        pacman.nextDir = {x: dx, y: dy};
    }

    document.addEventListener('keydown', e => {
        if(e.key === 'ArrowUp') handleInput('up');
        if(e.key === 'ArrowDown') handleInput('down');
        if(e.key === 'ArrowLeft') handleInput('left');
        if(e.key === 'ArrowRight') handleInput('right');
    });

    function canMove(gx, gy) {
        if(gy < 0 || gy >= ROWS || gx < 0 || gx >= COLS) return false;
        return map[gy][gx] !== 1;
    }

    function update() {
        if(gameState !== 'PLAY') return;

        if(scaredMode) {
            scaredTimer--;
            if(scaredTimer <= 0) scaredMode = false;
        }

        // --- PACMAN MOVEMENT ---
        const centerX = pacman.gridX * TILE_SIZE;
        const centerY = pacman.gridY * TILE_SIZE;
        const dist = Math.sqrt(Math.pow(pacman.x - centerX, 2) + Math.pow(pacman.y - centerY, 2));

        if (dist <= pacman.speed) {
            pacman.x = centerX;
            pacman.y = centerY;

            if (pacman.nextDir.x !== 0 || pacman.nextDir.y !== 0) {
                if (canMove(pacman.gridX + pacman.nextDir.x, pacman.gridY + pacman.nextDir.y)) {
                    pacman.dir = {...pacman.nextDir};
                }
            }

            if (!canMove(pacman.gridX + pacman.dir.x, pacman.gridY + pacman.dir.y)) {
                pacman.dir = {x:0, y:0}; 
            }

            pacman.gridX += pacman.dir.x;
            pacman.gridY += pacman.dir.y;
        }

        pacman.x += pacman.dir.x * pacman.speed;
        pacman.y += pacman.dir.y * pacman.speed;

        pacman.mouthOpen = Math.floor(Date.now() / 100) % 2 === 0;

        // --- COLLISIONS (Items) ---
        const tileType = map[pacman.gridY][pacman.gridX];
        if (tileType === 0) { // Dot
            map[pacman.gridY][pacman.gridX] = 2; 
            score += 10;
            dotsRemaining--;
            if(dotsRemaining <= 0) endGame(true, "Semua titik habis!");
            updateHUD();
        } else if (tileType === 3) { // Question
            map[pacman.gridY][pacman.gridX] = 2; 
            triggerQuiz();
        }

        // --- GHOST AI ---
        ghosts.forEach(g => {
            const gCenterX = g.gridX * TILE_SIZE;
            const gCenterY = g.gridY * TILE_SIZE;
            const gDist = Math.sqrt(Math.pow(g.x - gCenterX, 2) + Math.pow(g.y - gCenterY, 2));

            if (gDist <= g.speed) {
                g.x = gCenterX;
                g.y = gCenterY;

                const dirs = [{x:0,y:-1}, {x:0,y:1}, {x:-1,y:0}, {x:1,y:0}];
                let validDirs = dirs.filter(d => 
                    canMove(g.gridX + d.x, g.gridY + d.y) && 
                    !(d.x === -g.dir.x && d.y === -g.dir.y) 
                );
                
                if(validDirs.length === 0) validDirs = dirs.filter(d => canMove(g.gridX + d.x, g.gridY + d.y)); 

                const chosen = validDirs[Math.floor(Math.random() * validDirs.length)];
                g.dir = chosen;
                g.gridX += g.dir.x;
                g.gridY += g.dir.y;
            }

            const currentSpeed = scaredMode ? 0.6 : g.speed; 
            g.x += g.dir.x * currentSpeed;
            g.y += g.dir.y * currentSpeed;

            const dHit = Math.hypot(pacman.x - g.x, pacman.y - g.y);
            if (dHit < TILE_SIZE / 1.5) {
                if (scaredMode) {
                    g.x = 9 * TILE_SIZE; 
                    g.y = 9 * TILE_SIZE;
                    g.gridX = 9; g.gridY = 9;
                    score += 200;
                    updateHUD();
                } else {
                    handleDeath();
                }
            }
        });
    }

    function handleDeath() {
        lives--;
        updateHUD();
        if (lives <= 0) {
            endGame(false, "Kehabisan Nyawa!");
        } else {
            // Reset positions
            pacman.x = 9 * TILE_SIZE; pacman.y = 13 * TILE_SIZE;
            pacman.gridX = 9; pacman.gridY = 13;
            pacman.dir = {x:0, y:0};
            pacman.nextDir = {x:0, y:0};
            
            ghosts.forEach((g, i) => {
                g.gridX = 9 + (i%2==0?1:-1); g.gridY = 9;
                g.x = g.gridX * TILE_SIZE; g.y = g.gridY * TILE_SIZE;
            });
        }
    }

    function triggerQuiz() {
        gameState = 'QUIZ';
        // USE SEQUENTIAL QUESTION
        if (currentQuestionIdx >= questions.length) currentQuestionIdx = 0; // Reset loop if needed, but dots limit it
        const qData = questions[currentQuestionIdx];
        
        const modal = document.getElementById('quiz-modal');
        document.getElementById('q-text').innerText = qData.q;
        const optsDiv = document.getElementById('options-container');
        optsDiv.innerHTML = '';

        qData.opts.forEach((opt, idx) => {
            const btn = document.createElement('div');
            btn.className = 'option-btn';
            btn.innerText = opt;
            btn.onclick = () => handleAnswer(idx === qData.a, btn);
            optsDiv.appendChild(btn);
        });

        modal.classList.add('show');
    }

    function handleAnswer(isCorrect, btn) {
        if (isCorrect) {
            btn.classList.add('correct');
            setTimeout(() => {
                document.getElementById('quiz-modal').classList.remove('show');
                scaredMode = true;
                scaredTimer = 600; 
                score += 100;
                currentQuestionIdx++; // Next question
                updateHUD();
                gameState = 'PLAY';
            }, 1000);
        } else {
            btn.classList.add('wrong');
            // WRONG ANSWER = GAME OVER
            setTimeout(() => {
                document.getElementById('quiz-modal').classList.remove('show');
                endGame(false, "Salah Jawab! (Kuis Gagal)");
            }, 1000);
        }
    }

    function draw() {
        ctx.fillStyle = 'black';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        ctx.save();
        ctx.translate(offsetX, offsetY);
        ctx.scale(scale, scale);

        for(let r=0; r<ROWS; r++) {
            for(let c=0; c<COLS; c++) {
                const tile = map[r][c];
                const x = c * TILE_SIZE;
                const y = r * TILE_SIZE;

                if (tile === 1) { 
                    ctx.fillStyle = '#1e3a8a';
                    ctx.fillRect(x, y, TILE_SIZE, TILE_SIZE);
                    ctx.fillStyle = 'black'; 
                    ctx.fillRect(x+4, y+4, TILE_SIZE-8, TILE_SIZE-8);
                    ctx.strokeStyle = '#3b82f6';
                    ctx.lineWidth = 2;
                    ctx.strokeRect(x+4, y+4, TILE_SIZE-8, TILE_SIZE-8);
                } else if (tile === 0) { 
                    ctx.fillStyle = '#fbbf24';
                    ctx.beginPath();
                    ctx.arc(x + TILE_SIZE/2, y + TILE_SIZE/2, 3, 0, Math.PI*2);
                    ctx.fill();
                } else if (tile === 3) { 
                    ctx.fillStyle = '#ef4444';
                    ctx.fillRect(x+5, y+5, TILE_SIZE-10, TILE_SIZE-10);
                    ctx.fillStyle = 'white';
                    ctx.font = 'bold 16px sans-serif';
                    ctx.textAlign = 'center';
                    ctx.fillText('?', x + TILE_SIZE/2, y + TILE_SIZE/2 + 6);
                }
            }
        }

        ctx.fillStyle = '#fbbf24';
        ctx.beginPath();
        const pSize = TILE_SIZE / 2 - 2;
        let angle = 0;
        if(pacman.dir.x === 1) angle = 0;
        if(pacman.dir.y === 1) angle = Math.PI/2;
        if(pacman.dir.x === -1) angle = Math.PI;
        if(pacman.dir.y === -1) angle = -Math.PI/2;
        
        const mouthAngle = pacman.mouthOpen ? 0.2 * Math.PI : 0;
        
        ctx.translate(pacman.x + TILE_SIZE/2, pacman.y + TILE_SIZE/2);
        ctx.rotate(angle);
        ctx.arc(0, 0, pSize, mouthAngle, 2 * Math.PI - mouthAngle);
        ctx.lineTo(0,0);
        ctx.fill();
        ctx.rotate(-angle);
        ctx.translate(-(pacman.x + TILE_SIZE/2), -(pacman.y + TILE_SIZE/2));

        ghosts.forEach(g => {
            ctx.fillStyle = scaredMode ? '#3b82f6' : g.color;
            const gx = g.x + 4;
            const gy = g.y + 4;
            const gw = TILE_SIZE - 8;
            const gh = TILE_SIZE - 8;
            
            ctx.beginPath();
            ctx.arc(gx + gw/2, gy + gh/2 - 2, gw/2, Math.PI, 0);
            ctx.lineTo(gx + gw, gy + gh);
            ctx.lineTo(gx, gy + gh);
            ctx.fill();
            
            ctx.fillStyle = 'white';
            ctx.beginPath();
            ctx.arc(gx + gw/3, gy + gh/3, 4, 0, Math.PI*2);
            ctx.arc(gx + gw*2/3, gy + gh/3, 4, 0, Math.PI*2);
            ctx.fill();
            ctx.fillStyle = 'black';
            ctx.beginPath();
            ctx.arc(gx + gw/3 + (g.dir.x*1), gy + gh/3 + (g.dir.y*1), 2, 0, Math.PI*2);
            ctx.arc(gx + gw*2/3 + (g.dir.x*1), gy + gh/3 + (g.dir.y*1), 2, 0, Math.PI*2);
            ctx.fill();
        });

        ctx.restore();
    }

    function updateHUD() {
        document.getElementById('score-el').innerText = score;
        document.getElementById('lives-el').innerText = "❤".repeat(Math.max(0, lives));
    }

    function endGame(win, reason="") {
        gameState = 'END';
        const screen = document.getElementById('end-screen');
        screen.style.display = 'flex';
        document.getElementById('final-score').innerText = score;
        document.getElementById('end-reason').innerText = reason;
        const title = document.getElementById('end-title');
        if(win) {
            title.innerText = "YOU WIN!";
            title.style.color = "#4ade80";
        } else {
            title.innerText = "GAME OVER";
            title.style.color = "#ef4444";
        }
    }

    function gameLoop() {
        update();
        draw();
        requestAnimationFrame(gameLoop);
    }

</script>
</body>
</html>


