were working with this script ok

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Advanced Adventure Game</title>
    <style>
        body, html {
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #222;
            color: #fff;
            font-family: Arial, sans-serif;
            overflow: hidden;
        }
 
        #game-container {
            position: relative;
            width: 800px;
            height: 400px;
            background-color: #333;
            overflow: hidden;
            border: 2px solid #444;
        }


 
        #game-world {
            position: absolute;
            width: 2400px;
            height: 100%;
            transition: transform 0.1s linear;
        }
 
        #player {
            position: absolute;
            bottom: 0;
            left: 50px;
            width: 30px;
            height: 30px;
            background-color: #4CAF50;
            animation: idle 1s infinite alternate;
        }
 
        @keyframes idle {
            from { transform: translateY(0); }
            to { transform: translateY(2px); }
        }
 
@keyframes charging-prep {
    0%, 100% { box-shadow: 0 0 5px rgba(255, 0, 0, 0.6); }
    50% { box-shadow: 0 0 15px rgba(255, 0, 0, 1); }
}
 
@keyframes boss-shake {
    0%, 100% { transform: translate(0, 0); }
    25% { transform: translate(-5px, 0); }
    50% { transform: translate(5px, 0); }
    75% { transform: translate(-5px, 0); }
}
 
 
@keyframes charge-trail {
    0% { opacity: 0.8; transform: scale(1); }
    100% { opacity: 0; transform: scale(2); }
}
 
@keyframes boss-shield-glow {
    0%, 100% { box-shadow: 0 0 10px red; }
    50% { box-shadow: 0 0 20px red; }
}
 
        .character, .boss-door, .power-up, .enemy, .obstacle, .bullet, .burst, .boss, #friend, .coin, .flying-enemy, .charging-enemy, .stealth-enemy, .split-enemy, .sniper-enemy, .reflective-enemy, .explosive-enemy, .teleporter-enemy, .mourning-enemy, .velocity-enemy, .sticky-enemy, .reflective-enemy {
            position: absolute;
        }
 
        .character, .king, .stealth-enemy, .split-enemy, .sniper-enemy, .reflective-enemy, .explosive-enemy,
        .teleporter-enemy, .mourning-enemy, .velocity-enemy, .sticky-enemy, .reflective-enemy {
            border-radius: 50%;
        }

.energy-blast {
    position: absolute;
    width: 200px; /* Diameter of the burst */
    height: 200px; /* Diameter of the burst */
    border-radius: 50%; /* Make it circular */
    border: 2px solid rgba(0, 255, 255, 0.8); /* Color and transparency */
    opacity: 0.5; /* Semi-transparent */
    animation: pulse 0.5s ease-out; /* Animation for the burst */
}

@keyframes pulse {
    0% {
        transform: scale(1);
        opacity: 0.5;
    }
    100% {
        transform: scale(2); /* Expand the burst for the visual effect */
        opacity: 0; /* Fade out */
    }
}
 
.charging-prep {
    animation: charging-prep 1s infinite alternate;
}

.outlined {
    border: 3px solid green; /* Change as necessary */
    box-shadow: 0 0 10px green; /* Add glow effect */
}
 
.boss-shielded {
    animation: boss-shield-glow 0.8s infinite alternate;
    border: 3px solid red;
}
 
.charging-active {
    box-shadow: 0 0 15px red, 0 0 30px red;
    border: 2px solid red;
}
 
.charge-trail {
    position: absolute;
    width: 35px;
    height: 35px;
    background-color: rgba(255, 50, 50, 0.5);
    border-radius: 50%;
    opacity: 1;
    animation: charge-trail 0.4s ease-out;
}
 
.bullet-trail {
    position: absolute;
    width: 8px;
    height: 4px;
    background-color: rgba(255, 215, 0, 0.5);
    opacity: 1;
    transition: opacity 0.3s ease-out;
}
 
 
        .coin {
            width: 15px;
            height: 15px;
            background-color: #FFD700;
            border-radius: 50%;
            animation: spin 2s linear infinite;
        }
 
        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
 
        .flying-enemy {
            width: 30px;
            height: 30px;
            background-color: #0099FF;
            border-radius: 50%;
            opacity: 0.9;
        }
 
        .charging-enemy {
            width: 40px;
            height: 40px;
            background-color: #FF5500;
            animation: charge 1s linear infinite alternate;
            border-radius: 50%;
        }
 
        .enemy {
            width: 25px;
            height: 25px;
            background-color: #FF5733;
        }
 
        .obstacle {
            width: 30px;
            height: 30px;
            background-color: #f44336;
        }
 
        .power-up {
            width: 20px;
            height: 20px;
        }
 
        .bullet {
            width: 10px;
            height: 5px;
            background-color: #FFD700;
        }
 
        .burst {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background-color: rgba(255, 69, 0, 0.7);
            animation: burst 0.5s ease-out;
        }
 
        @keyframes burst {
            from { transform: scale(0.5); opacity: 1; }
            to { transform: scale(1.5); opacity: 0; }
        }
 
        .boss-door {
            width: 30px;
            height: 60px;
            background-color: #FFFF00;
        }
 
        .burst {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background-color: rgba(255, 69, 0, 0.7);
            animation: burst 0.5s ease-out;
        }   
 
        .boss {
            width: 60px;
            height: 60px;
            background-color: #FF4500;
        }


.reflective-enemy {
    width: 25px;
    height: 25px;
    background-color: #FF5733;
    border: 3px solid transparent; /* Initial border */
    box-shadow: 0 0 10px green; /* Glow effect */
}

        .mourning-enemy {
            width: 25px;
            height: 25px;
            background-color: #FF3333;
        }

        .sniper-enemy {
            width: 25px;
            height: 25px;
            background-color: #FF3333;
        }


 
        #score, #lives, #level, #timer {
            position: absolute;
            top: 10px;
            font-size: 16px;
        }
 
 
 
        #score { left: 10px; }
        #lives { right: 10px; }
        #level { left: 150px; }
        #timer { left: 250px; }
 
        #instructions, #cutscene, #level-intro, #boss-fight, #boss-hallway, #game-over, #interact-message {
            position: absolute;
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: rgba(0, 0, 0, 0.8);
            color: #fff;
            flex-direction: column;
            font-size: 18px;
            z-index: 10;
        }
 
        #instructions button, #cutscene button, #level-intro button, #boss-fight button, #game-over button, #boss-hallway button {
            margin-top: 10px;
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
            background-color: #555;
            color: #fff;
        }
 
        #cutscene, #level-intro, #boss-fight, #boss-hallway, #game-over, #interact-message {
            display: none;
        }
 
        #intro {
            position: absolute;
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: space-around;
            align-items: center;
            background-color: rgba(0, 0, 0, 0.8);
            color: #fff;
            flex-direction: row;
            font-size: 18px;
            z-index: 11;
        }
 
        #boss-health-bar {
            position: absolute;
            top: 10px;
            left: 50%;
            transform: translateX(-50%);
            width: 150px;
            height: 20px;
            background-color: #666;
            border: 1px solid #333;
            display: none;
        }
 
        #boss-health {
            height: 100%;
            width: 100%;
            background-color: #FF0000;
        }
 
        #friend {
            width: 30px;
            height: 30px;
            background-color: #00FF00;
            display: none;
        }
 
        #power-up-message {
            position: absolute;
            top: 50px;
            left: 50%;
            transform: translateX(-50%);
            font-size: 24px;
            z-index: 12;
            display: none;
        }
 
        /* New CSS for cool features */
        @keyframes flash {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
 
        .flashing {
            animation: flash 0.5s infinite;
        }
 
        .glow {
            box-shadow: 0 0 10px rgba(255,255,255,0.5);
        }
    </style>
</head>
<body>
    <div id="game-container">
        <div id="game-world">
            <div id="player"></div>
        </div>
        <div id="score">Score: 0</div>
        <div id="lives">Lives: 3</div>
        <div id="level">Level: 1</div>
        <div id="timer">Timer: 0</div>
        <div id="instructions">
            <p>Press Arrow Up to Jump</p>
            <p>Use Arrow Left/Right to Move</p>
            <p>Press Space to Shoot</p>
            <p>Press Z for Power-Up</p>
            <p>Press E to interact</p>
            <button onclick="startGame()">Start Game</button>
            <button onclick="togglePause()">Pause/Resume</button>
        </div>
        <div id="cutscene">
            <p>Get ready for the next level!</p>
            <button onclick="continueGame()">Continue</button>
        </div>
        <div id="level-intro">
            <p id="level-text">Level 1: Get Ready for Adventure!</p>
            <button onclick="startLevel()">Start Level</button>
        </div>
        <div id="boss-fight">
            <p>Defeat the Boss!</p>
        </div>
        <div id="game-over">
            <p>Game Over!</p>
            <button onclick="restartGame()">Restart</button>
        </div>
        <div id="boss-hallway">
            <p>You have entered the boss hallway! Prepare yourself!</p>
            <button onclick="startBossFight()">Proceed</button>
        </div>
        <div id="boss-health-bar">
            <div id="boss-health"></div>
        </div>
        <div id="power-up-message"></div>
        <div id="interact-message"></div>
        <div id="friend"></div>
    </div>
 
    <script>
            const gameContainer = document.getElementById('game-container');
            const gameWorld = document.getElementById('game-world');
            const player = document.getElementById('player');
            const scoreDisplay = document.getElementById('score');
            const livesDisplay = document.getElementById('lives');
            const levelDisplay = document.getElementById('level');
            const timerDisplay = document.getElementById('timer');
            const instructions = document.getElementById('instructions');
            const cutscene = document.getElementById('cutscene');
            const levelIntro = document.getElementById('level-intro');
            const levelText = document.getElementById('level-text');
            const bossFightScreen = document.getElementById('boss-fight');
            const gameOverScreen = document.getElementById('game-over');
            const intro = document.getElementById('intro');
            const dialoguePara = document.querySelector('#dialogue p');
            const bossHallway = document.getElementById('boss-hallway');
            const bossHealthBar = document.getElementById('boss-health-bar');
            const bossHealthDisplay = document.getElementById('boss-health');
            const powerUpMessage = document.getElementById('power-up-message');
            const interactMessage = document.getElementById('interact-message');
            const friend = document.getElementById('friend');

            let playerPositionX = 50;
            let playerPositionY = 0;
            let playerVelocityX = 0;
            let playerVelocityY = 0;
            let removedEnemies = [];
            let playerMaxSpeed = 5;
            const playerJumpStrength = 12;
            let jumpCount = 0;
            const maxJumps = 2;
            let isDoubleJumpEnabled = false;
            let isJumping = false;
            let isPaused = false;
            let canShoot = true;
            let waveCooldown = false; // Track if a wave is on cooldown
            let bossAttacking = false;
            let bossAttackPhase = 0;
            let gameInterval;
            let obstacles = [];
            let enemies = [];
            let bullets = [];
            let powerUps = [];
            let isTeleporting = false; // Track whether teleport is available
            let platforms = [];
            let bossDoors = [];
            let coins = [];
            let score = 0;
            let lives = 3;
            let level = localStorage.getItem('playerLevel') ? parseInt(localStorage.getItem('playerLevel')) : 1;
            const gravity = 0.5;
            const maxLevels = 5;
            let movingLeft = false, movingRight = false;
            let currentDirection = 1;
            let currentPowerUp = null;
            let powerUpTimer = 0;
            let gameScrollPosition = 0;
            const bossScoreThreshold = 10;
            const dialogues = [
                "Player: Hey friend! What a nice day for an adventure!",
                "Friend: Indeed! Maybe we should explore the caves.",
                "Player: What's that over there? Is it the King?",
                "King: Haha, I've found you! You're coming with me!",
                "Friend: Player, help me!"
            ];
            let dialogueIndex = 0;
            let boss = null;
            let bossHealth = 100;
            let bossShielded = true;
            let bossPowerObtained = false;
            let bossFightActive = false;
 
const allPowerUpTypes = [
    "super-speed", "invincibility", "teleportation", "time-freeze", 
    "reflective-shield", "double-shot", "extra-life", 
    "score-boost", "mega-jump", "energy-blast", "light-speed", 
    "blazing-trail", "sonic-wave", "armor", "telekinetic", 
    "camouflage", "dimension-shift", "energy-drain", "mind-control", 
    "hologram"
];
 
            window.addEventListener('keydown', handleKeydown);
            window.addEventListener('keyup', handleKeyup);
 
function handleKeydown(e) {
    switch (e.key) {
        case 'ArrowLeft':
            movingLeft = true;
            currentDirection = -1;
            break;
        case 'ArrowRight':
            movingRight = true;
            currentDirection = 1;
            break;
        case 'ArrowUp':
            handleJump();
            break;
        case ' ': // Space bar for shooting
            if (canShoot) {
                shootBullet(currentDirection);
                canShoot = false;
                setTimeout(() => canShoot = true, 300);
            }
            break;
        case 'z':
        case 'Z': // Power-Up activation
            if (currentPowerUp) { // Check if there is a power-up to use
                usePowerUp();
            } else if (bossPowerObtained) { // Charge if the boss power is obtained and no power-up is active
                isCharging = true;
                chargeTime = 0;
            }
            break;
        case 'e':
        case 'E':
            interact(); // Trigger the interact function when 'E' is pressed
            break;
    }
}
 
function handleKeyup(e) {
    switch (e.key) {
        case 'ArrowLeft':
            movingLeft = false;
            break;
        case 'ArrowRight':
            movingRight = false;
            break;
        case 'z':
        case 'Z':
            if (bossPowerObtained && isCharging) {
                isCharging = false;
                shootLaserBlast(chargeTime);
            }
            break;
    }
}
 
 
            function handleJump() {
                if (playerPositionY <= 0 || (isDoubleJumpEnabled && jumpCount < maxJumps)) {
                    playerVelocityY = playerJumpStrength;
                    jumpCount++;
                    isJumping = true;
                }
            }
 
            function nextDialogue() {
                if (dialogueIndex < dialogues.length - 1) {
                    dialogueIndex++;
                    dialoguePara.textContent = dialogues[dialogueIndex];
                } else {
                    intro.style.display = 'none';
                    startGame();
                }
            }
 
            function shootBullet(direction) {
                const bullet = createBullet(direction);
                bullets.push({ element: bullet, direction });
                gameWorld.appendChild(bullet);
 
                if (currentPowerUp === 'double-shot') {
                    const altBullet = createBullet(direction + 1);
                    bullets.push({ element: altBullet, direction });
                    gameWorld.appendChild(altBullet);
                }
 
                if (currentPowerUp === 'speed-bullet') {
                    const sideBullet1 = createBullet(direction + 6);
                    const sideBullet2 = createBullet(direction - 6);
                    bullets.push({ element: sideBullet1, direction });
                    bullets.push({ element: sideBullet2, direction });
                    gameWorld.appendChild(sideBullet1);
                    gameWorld.appendChild(sideBullet2);
                }
            }
 
            function createBurst(x, y) {
                const burst = document.createElement('div');
                burst.classList.add('burst');
                burst.style.left = x + 'px';
                burst.style.bottom = y + 'px';
                gameWorld.appendChild(burst);
                setTimeout(() => burst.remove(), 500);
            }
 
function moveCamera() {
    gameScrollPosition = Math.max(0, playerPositionX - (gameContainer.offsetWidth / 2));
    gameWorld.style.transform = `translateX(${-gameScrollPosition}px)`;
}
 
let summonCooldown = 0;
 
function summonAllies() {
    for (let i = 0; i < 3; i++) {
        let ally = createElement('ally', [], parseInt(player.style.left) + (i * 30));
        ally.style.bottom = player.style.bottom;
        gameWorld.appendChild(ally);
 
        let destroyCount = 0;
        let moveInterval = setInterval(() => {
            ally.style.left = (parseInt(ally.style.left) + 5) + 'px';
 
            enemies.forEach((enemy, index) => {
                if (checkCollision(ally, enemy) && destroyCount < 3) {
                    enemy.remove();
                    enemies.splice(index, 1);
                    destroyCount++;
                }
            });
 
            if (destroyCount >= 3) {
                ally.remove();
                clearInterval(moveInterval);
            }
        }, 50);
 
        setTimeout(() => {
            ally.remove();
            clearInterval(moveInterval);
        }, 5000);
    }
}
 
 
 
function createBulletTrail(x, y) {
    const trail = document.createElement('div');
    trail.classList.add('bullet-trail');
    trail.style.left = x + 'px';
    trail.style.bottom = y + 'px';
    gameWorld.appendChild(trail);
 
    setTimeout(() => {
        trail.style.opacity = '0';
        setTimeout(() => trail.remove(), 300);
    }, 50);
}
 
function moveBullets() {
    bullets.forEach((bulletObj, index) => {
        const bullet = bulletObj.element;
        const newX = parseInt(bullet.style.left) + (bulletObj.direction * 5);
        bullet.style.left = newX + 'px';

        // Add trail effect
        createBulletTrail(newX, parseInt(bullet.style.bottom));

        // Check if bullet is out of bounds and remove it
        if (newX > gameScrollPosition + gameContainer.offsetWidth || newX < 0) {
            bullet.remove();
            bullets.splice(index, 1);
        } else {
            // Check for collisions with enemy
            enemies.forEach((enemy, enemyIndex) => {
                if (checkCollision(bullet, enemy)) {
                    if (enemy.classList.contains('reflective-enemy')) {
                        // If the bullet hits a reflective enemy, handle accordingly
                        handleBulletCollisionWithReflectiveEnemy(enemy, bullet);
                    } else {
                        // Handle normal enemy hit
                        handleEnemyHit(enemy, enemyIndex);
                    }
                    createBurst(parseInt(bullet.style.left), parseInt(bullet.style.bottom)); // Impact effect
                    bullet.remove(); // Remove the bullet after impact
                    bullets.splice(index, 1); // Remove from bullets array
                }
            });
            // Check for boss hit
            checkBossHit();
        }
    });
}
 
 
            function handleEnemyHit(enemy, enemyIndex) {
                if (enemy.classList.contains('explosive-enemy')) {
                    handleExplosiveEnemyHit(enemy, enemyIndex);
                } else if (enemy.classList.contains('split-enemy') && !enemy.classList.contains('split')) {
                    handleSplitterEnemyHit(enemy, enemyIndex);
                } else {
                    enemy.remove();
                    enemies.splice(enemyIndex, 1);
                    score += 10;
                    updateDisplay();
                }
            }
 
            function startGame() {
                gameOverScreen.style.display = 'none';
                instructions.style.display = 'none';
                resetGame();
                levelIntro.style.display = 'flex';
            }
 
            function startLevel() {
                levelIntro.style.display = 'none';
                gameInterval = setInterval(gameLoop, 1000 / 60);
            }
 
            function resetGame() {
                lives = 3;
                playerPositionX = 50;
                playerPositionY = 0;
                playerVelocityX = 0;
                playerVelocityY = 0;
                isJumping = false;
                jumpCount = 0;
                isDoubleJumpEnabled = false;
                gameScrollPosition = 0;
                clearAllElements();
                switchLevelBackground();
                level = parseInt(localStorage.getItem('playerLevel') || 1);
                updateDisplay();
            }
 
            function updateDisplay() {
                scoreDisplay.textContent = `Score: ${score}`;
                livesDisplay.textContent = `Lives: ${lives}`;
                levelDisplay.textContent = `Level: ${level}`;
                timerDisplay.textContent = `Timer: ${powerUpTimer}`;
            }
 
            function updatePlayerPosition() {
                if (movingLeft) {
                    playerVelocityX = -playerMaxSpeed;
                } else if (movingRight) {
                    playerVelocityX = playerMaxSpeed;
                } else {
                    playerVelocityX = 0;
                }
 
                playerPositionX += playerVelocityX;
                playerPositionX = Math.max(0, Math.min(gameWorld.offsetWidth - player.offsetWidth, playerPositionX));
                player.style.left = playerPositionX + 'px';
 
                let onPlatform = false;
                platforms.forEach(platform => {
                    if (checkCollision(player, platform) && playerVelocityY < 0) {
                        playerPositionY = parseInt(platform.style.bottom) + platform.offsetHeight;
                        playerVelocityY = 0;
                        isJumping = false;
                        jumpCount = 0;
                        onPlatform = true;
                    }
                });
 
                if (!onPlatform || isJumping || playerPositionY > 0) {
                    playerVelocityY -= gravity;
                    playerPositionY += playerVelocityY;
                    if (playerPositionY <= 0) {
                        playerPositionY = 0;
                        isJumping = false;
                        jumpCount = 0;
                    }
                }
 
                player.style.bottom = playerPositionY + 'px';
                moveCamera();
            }
 
function spawnEntities() {
    if (!isPaused && !bossFightActive) {
        if (Math.random() < 0.003) spawnObstacle();
        
        // Spawn enemies based on the current level
        if (level === 1) {
            if (Math.random() < 0.005) spawnEnemy();
            if (Math.random() < 0.003) spawnFlyingEnemy(); // Flying enemy option for Level 1
            if (Math.random() < 0.003) spawnObstacle();
        } else if (level === 2) {
            if (Math.random() < 0.005) spawnEnemy();
            if (Math.random() < 0.002) spawnObstacle();
            if (Math.random() < 0.003) spawnChargingEnemy(); // Charging enemy option for Level 2
            if (Math.random() < 0.001) spawnSniperEnemy(); // Sniper enemy option for Level 2
            // Add more enemies specific to Level 2 as needed
        } else if (level === 3) {
            if (Math.random() < 0.005) spawnEnemy();
            if (Math.random() < 0.002) spawnObstacle();
            if (Math.random() < 0.003) spawnFlyingEnemy(); // Charging enemy option for Level 2
            if (Math.random() < 0.001) spawnReflectiveEnemy(); // Sniper enemy option for Level 2
            // Add more enemies specific to Level 2 as needed
        }

        if (Math.random() < 0.002 && !currentPowerUp) spawnPowerUp();
        if (Math.random() < 0.001) spawnPlatform();
        if (Math.random() < 0.003) spawnCoin();
        if (Math.random() < 0.001) spawnSplitterEnemy();

        // Spawn the boss door if conditions are met
        if (bossDoors.length === 0 && score >= level * bossScoreThreshold && enemies.length === 0) {
            spawnBossDoor();
        }
    }
}
 
            function moveElements() {
                moveArray(obstacles, 2, 15);
                moveArray(enemies, 1, 30);
                moveArray(coins, 2, 0);
                moveArray(powerUps, 2, 0, true);
                moveArray(platforms, 1, 0);
                moveFlyingEnemies();
                moveSniperEnemies();
                moveReflectiveEnemies();
                moveChargingEnemies();
                moveStealthEnemies();
                moveBullets();
                moveNewEnemies();
            }
 
            function spawnObstacle() {
                const obstacle = createElement('obstacle', obstacles, gameScrollPosition + gameContainer.offsetWidth);
                obstacle.style.bottom = '0px';
            }
 
            function spawnEnemy() {
                const baseEnemy = createElement('enemy', enemies, gameScrollPosition + gameContainer.offsetWidth);
                baseEnemy.style.bottom = '0px';
 
                const chance = Math.random();
                if (chance < 0.3) {
                    spawnTeleporterEnemy();
                } else if (chance < 0.7) {
                    spawnVelocityEnemy();
                } else if (chance < 0.9) {
                    spawnStickyEnemy();
                } else {
                    spawnReflectiveEnemy();
                }
            }
 
            function spawnPowerUp() {
                const powerUpTypes = allPowerUpTypes;
                const type = powerUpTypes[Math.floor(Math.random() * powerUpTypes.length)];
                const powerUp = createElement('power-up', powerUps, gameScrollPosition + gameContainer.offsetWidth);
                powerUp.setAttribute('data-type', type);
                powerUp.style.backgroundColor = getPowerUpColor(type);
                powerUp.style.bottom = Math.floor(Math.random() * 100) + 'px';
            }
 
            function spawnCoin() {
                const coin = createElement('coin', coins, gameScrollPosition + gameContainer.offsetWidth);
                coin.style.bottom = Math.floor(Math.random() * 50 + 50) + 'px';
            }
 
function getPowerUpColor(type) {
    switch (type) {
        case 'super-speed': return 'lime';
        case 'invincibility': return 'gold';
        case 'teleportation': return 'violet';
        case 'time-freeze': return 'cyan';
        case 'reflective-shield': return 'aqua';
        case 'double-shot': return 'red';
        case 'extra-life': return 'lightgreen';
        case 'score-boost': return 'coral';
        case 'mega-jump': return 'fuchsia';
        case 'energy-blast': return 'limegreen'; // Specify colors for valid powers
        case 'light-speed': return 'white'; // Define colors for light-speed
        case 'blazing-trail': return 'gold'; // Specify for blazing-trail
        case 'sonic-wave': return 'blueviolet'; // Specify for sonic-wave
        case 'armor': return 'lightgrey'; // Define color for armor
        case 'telekinetic': return 'silver'; // Define color for telekinetic
        case 'camouflage': return 'darkgreen'; // Define color for camouflage
        case 'dimension-shift': return 'black'; // Define color for dimension-shift
        case 'energy-drain': return 'red'; // Define color for energy-drain
        case 'mind-control': return 'purple'; // Define color for mind-control
        case 'hologram': return 'pink'; // Define color for hologram
        default: return 'white'; // Fallback for any unknown type
    }
}
 
            function spawnPlatform() {
                const platform = createElement('platform', platforms, gameScrollPosition + gameContainer.offsetWidth);
                platform.style.bottom = Math.floor(Math.random() * 200 + 100) + 'px';
            }
 
            function spawnBossDoor() {
                const bossDoor = createElement('boss-door', bossDoors, gameScrollPosition + gameContainer.offsetWidth + 200);
                bossDoor.style.bottom = '0px';
            }
 
            function createElement(className, array, leftPosition, type = '') {
                const element = document.createElement('div');
                element.classList.add(className);
                if (type) element.setAttribute('data-type', type);
                element.style.left = leftPosition + 'px';
                gameWorld.appendChild(element);
                array.push(element);
                return element;
            }
 
function moveArray(array, speed, scoreValue, isPowerUp = false) {
    array.forEach((el, index) => {
        el.style.left = (parseInt(el.style.left) - speed) + 'px';
        if (parseInt(el.style.left) < gameScrollPosition - el.offsetWidth) {
            removeElement(el, array, index, 0);
        } else if (checkCollision(player, el)) {
            handleCollision(el, array, index, scoreValue, isPowerUp);
        }
    });
}
 
            function removeElement(el, array, index, scoreValue) {
                el.remove();
                array.splice(index, 1);
                if (scoreValue) {
                    score += scoreValue;
                    updateDisplay();
                }
            }
 
            function handleCollision(el, array, index, scoreValue, isPowerUp = false) {
                if (el.classList.contains('coin')) {
                    score += 5;
                    updateDisplay();
                } else if (isPowerUp) {
                    applyPowerUp(el);
                } else if (el.classList.contains('boss-door') && score >= level * bossScoreThreshold) {
                    interactMessage.textContent = "Press 'E' to enter boss door.";
                    interactMessage.style.display = checkCollision(player, el) ? 'block' : 'none';
                    if (checkCollision(player, el) && playerPositionX >= parseInt(el.style.left)) {
                        openBossHallway();
                    }
                } else if (el.classList.contains('enemy') || el.classList.contains('obstacle')) {
                    reduceLives();
                }
                removeElement(el, array, index, scoreValue);
            }
 
            function applyPowerUp(el) {
                if (currentPowerUp || currentPowerUp === 'boss-power-up') return;
 
                const type = el.getAttribute('data-type');
                if (type === 'boss-power-up') {
                    grantBossPowerUp();
                } else {
                    currentPowerUp = type;
                    let duration = 10;
                    activatePowerUp(type);
                    powerUpTimer = duration;
 
                    const powerUpInterval = setInterval(() => {
                        powerUpTimer--;
                        if (powerUpTimer <= 0) {
                            clearInterval(powerUpInterval);
                            resetPowerUp();
                        }
                        updateDisplay();
                    }, 1000);
                }
 
                displayPowerUpMessage(type);
            }

function activatePowerUp(type) {
    switch (type) {
        case 'super-speed':
            player.style.backgroundColor = 'lime';
            playerMaxSpeed = 8; // Increase speed
            break;
        case 'invincibility':
            player.style.backgroundColor = 'gold';
            PlayerInvincibility(); // Implement this function for invincibility
            break;
        case 'teleportation':
            teleportPlayer(); // Implement this function for teleportation
            break;
        case 'time-freeze':
            activateTimeFreeze(); // Call the function for time freeze
            break;
        case 'reflective-shield':
            activateReflectiveShield(); // Implement the reflective shield functionality
            break;
        case 'double-shot':
            enableDoubleShot(); // Implement functionality for double shot
            break;
        case 'extra-life':
            gainExtraLife(); // Implement functionality for gaining an extra life
            break;
        case 'score-boost':
            boostScore(); // Implement functionality for score boost
            break;
        case 'mega-jump':
            activateMegaJump(); // Implement functionality for mega jump
            break;
        case 'energy-blast':
            activateEnergyBlast(); // Implement functionality for energy blast
            break;
        case 'light-speed':
            player.style.backgroundColor = 'lime';
            playerMaxSpeed = 17; // Increase speed
            break;
        case 'blazing-trail':
            activateBlazingTrail(); // Implement functionality for blazing trail
            break;
        case 'sonic-wave':
            activateSonicWave(); // Implement functionality for sonic wave
            break;
        case 'armor':
            activateArmor(); // Implement functionality for armor
            break;
        case 'telekinetic':
            activateTelekinetic(); // Implement functionality for telekinetic
            break;
        case 'camouflage':
            activateCamouflage(); // Implement functionality for camouflage
            break;
        case 'dimension-shift':
            activateDimensionShift(); // Implement functionality for dimension shift
            break;
        case 'energy-drain':
            activateEnergyDrain(); // Implement functionality for energy drain
            break;
        case 'mind-control':
            activateMindControl(); // Implement functionality for mind control
            break;
        case 'hologram':
            activateHologram(); // Implement functionality for hologram
            break;
        default:
            // Consider logging or managing invalid power-up requests
            console.log(`Unknown power-up type: ${type}`);
            break;
    }
}

function handlePlayerEnemyCollision() {
    enemies.forEach((enemy, index) => {
        // Check collision with the player
        if (checkCollision(player, enemy)) {
            if (enemy.classList.contains('frozen')) {
                // If frozen, destroy the enemy
                enemy.remove(); // Remove frozen enemy
                enemies.splice(index, 1); // Remove from the enemies array
                updateDisplay(); // Update any relevant game display elements if needed
            } else {
                // Normal behavior for non-frozen enemies
                reduceLives(); // This would reduce lives for non-frozen collisions
            }
        }
    });
}
 
function activateTimeFreeze() {
    if (timeFrozen) return; // If already frozen, do nothing

    timeFrozen = true; // Set state to frozen

    // Stop movement of all enemies and bullets
    enemies.forEach(enemy => enemy.style.left = enemy.style.left); // No movement
    bullets.forEach(bulletObj => bulletObj.element.style.left = bulletObj.element.style.left); // No movement

    // Countdown timer for the freeze duration
    var countdownDuration = 10; // 10 seconds
    var remainingTime = countdownDuration;

    // Display the message with countdown
    powerUpMessage.textContent = `Time Freeze Activated! ${remainingTime} seconds remaining.`;
    powerUpMessage.style.display = 'block';

    // Set up the countdown interval
    var countdownInterval = setInterval(() => {
        remainingTime--;
        powerUpMessage.textContent = `Time Freeze Activated! ${remainingTime} seconds remaining.`;

        if (remainingTime <= 0) {
            clearInterval(countdownInterval); // Stop the countdown
            timeFrozen = false; // Unfreeze time
            powerUpMessage.style.display = 'none'; // Hide the message

            // Restore movement for all enemies and bullets
            enemies.forEach(enemy => {
                // You may want to restore movement properties if needed
            });
        }
    }, 1000); // Countdown every second

    // Allow player movement during freeze
    window.addEventListener('keydown', allowPlayerMovement);
    
    // Optional: Stop allowing player movement after 10 seconds
    setTimeout(() => {
        window.removeEventListener('keydown', allowPlayerMovement);
    }, countdownDuration * 1000); // After the duration of the freeze
}

function allowPlayerMovement(e) {
    switch (e.key) {
        case 'ArrowLeft':
            playerPositionX -= playerMaxSpeed; // Move left
            player.style.left = playerPositionX + 'px';
            break;
        case 'ArrowRight':
            playerPositionX += playerMaxSpeed; // Move right
            player.style.left = playerPositionX + 'px';
            break;
        case ' ': // Space to shoot
            shootBullet(currentDirection); // Allow shooting during freeze
            break;
    }
}
 
function resetPowerUp() {
    currentPowerUp = null; // Also can now be re-assigned
    player.style.backgroundColor = '#4CAF50';
    playerMaxSpeed = 5;
    player.style.opacity = '1';
    isDoubleJumpEnabled = false;
    clearTimeout(timeSlowTimeout);
    resetGravity();
}
 
            function displayPowerUpMessage(type) {
                powerUpMessage.textContent = `You obtained ${type.replace(/-/g, ' ')}!`;
                powerUpMessage.style.display = 'block';
                setTimeout(() => powerUpMessage.style.display = 'none', 2000);
            }
 
            function grantBossPowerUp() {
                bossPowerObtained = true;
                powerUpMessage.textContent = "Boss Power-Up Obtained!";
                powerUpMessage.style.display = 'block';
                setTimeout(() => powerUpMessage.style.display = 'none', 2000);
            }

function PlayerInvincibility() {
    // Check for collision with enemies
    enemies.forEach((enemy) => {
        if (checkCollision(player, enemy)) {
            if (!isInvincible) { // Only reduce lives if not invincible
                if (lives > 0) {
                    lives--; // Deduct a life when colliding with an enemy
                    updateDisplay(); // Update the displayed lives
                }
            }
        }
    });

    // Immediately reset lives to 3 if they drop below that
    if (lives < 3) {
        lives = 3; // Reset lives to 3 instantly
        updateDisplay(); // Update display to show 3 lives
    }
}
 
            function usePowerUp() {
                if (!currentPowerUp) return;
                switch (currentPowerUp) {
                    case 'ice':
                        shootIce();
                        break;
                    case 'sonic-wave':
                        activateSonicWave();
                        break;
                    case 'fire':
                        shootFire();
                        break;
                    case 'teleportation':
                        teleportPlayer();
                        break;
                    case 'levitate':
                        useLevitate();
                        break;
                    case 'hypno':
                        shootHypno();
                        break;
                    case 'double-shot':
                        shootDouble();
                        break;
                    default:
                        break;
                }
            }
 
function shootIce() {
    const iceBullet = createBullet(currentDirection); // Create the ice bullet
    iceBullet.style.backgroundColor = 'blue'; // Set bullet color to blue
    gameWorld.appendChild(iceBullet);

    const iceBulletObj = { element: iceBullet, direction: currentDirection };
    
    animateBullet(iceBulletObj, 5, (target) => {
        // Check for collision with enemies
        if (target.classList.contains('enemy')) {
            target.classList.add('frozen'); // Mark the enemy as frozen
            target.style.backgroundColor = '#00f'; // Change color to blue
            target.style.opacity = '0.5'; // Reduce visibility
            target.dataset.isFrozen = 'true'; // Mark enemy as frozen

            // Set a timer to unfreeze
            setTimeout(() => {
                if (target.dataset.isFrozen === 'true') {
                    target.classList.remove('frozen'); // Remove frozen status
                    target.style.backgroundColor = ''; // Reset color
                    target.style.opacity = '1'; // Reset visibility
                    delete target.dataset.isFrozen; // Clear the frozen marker
                }
            }, 5000); // 5 seconds to unfreeze
        }
    });
}
 
            function shootFire() {
                const fireBullet = createBullet(currentDirection);
                fireBullet.style.backgroundColor = 'red';
                gameWorld.appendChild(fireBullet);
 
                const fireBulletObj = { element: fireBullet, direction: currentDirection };
                animateBullet(fireBulletObj, 5, (target) => {
                    if (target.classList.contains('obstacle')) {
                        target.style.transition = 'opacity 0.5s';
                        target.style.opacity = '0';
                        setTimeout(() => target.remove(), 500);
                    }
                });
            }
 
            function useLevitate() {
                player.style.transform = 'translateY(-20px)';
                const levitateUp = setTimeout(() => {
                    player.style.transform = 'translateY(0)';
                    clearTimeout(levitateUp);
                }, 1000);
            }
 
            function enableDoubleShot() {
            }
 
            function createBullet(direction = 1) {
                const bullet = document.createElement('div');
                bullet.classList.add('bullet');
                bullet.style.backgroundColor = '#FFD700';
                bullet.style.left = (playerPositionX + player.offsetWidth / 2 - 5) + 'px';
                bullet.style.bottom = (playerPositionY + player.offsetHeight / 2) + 'px';
                return bullet;
            }
 
            function shootHypno() {
                const hypnoBullet = createBullet(currentDirection);
                hypnoBullet.style.backgroundColor = 'pink';
                gameWorld.appendChild(hypnoBullet);
 
                const hypnoBulletObj = { element: hypnoBullet, direction: currentDirection };
                animateBullet(hypnoBulletObj, 5, (target) => {
                    if (target.classList.contains('enemy') && !target.classList.contains('hypnotized')) {
                        target.classList.add('hypnotized');
                        target.style.backgroundColor = 'pink';
                        hypnotizeEnemy(target);
                    }
                });
            }
 
            function shootDouble() {
                const bullet1 = createBullet(currentDirection);
                const bullet2 = createBullet(currentDirection);
                bullets.push({ element: bullet1, direction: currentDirection });
                bullets.push({ element: bullet2, direction: currentDirection });
                gameWorld.appendChild(bullet1);
                gameWorld.appendChild(bullet2);
            }
 
            function hypnotizeEnemy(enemy) {
                let destroyCount = 0;
                const moveInterval = setInterval(() => {
                    let nearestEnemy = findNearestEnemyTo(enemy);
                    if (!nearestEnemy) {
                        enemy.remove();
                        clearInterval(moveInterval);
                        return;
                    }
 
                    let ex = parseInt(enemy.style.left);
                    let ey = parseInt(enemy.style.bottom);
                    let nex = parseInt(nearestEnemy.style.left);
                    let ney = parseInt(nearestEnemy.style.bottom);
 
                    let dx = nex - ex;
                    let dy = ney - ey;
                    let distance = Math.sqrt(dx * dx + dy * dy);
 
                    if (distance < 5) {
                        destroyCount++;
                        createBurst(nex, ney);
                        nearestEnemy.remove();
                        enemies = enemies.filter(e => e !== nearestEnemy);
 
                        if (destroyCount >= 3) {
                            enemy.remove();
                            clearInterval(moveInterval);
                        }
                    } else {
                        let angle = Math.atan2(dy, dx);
                        enemy.style.left = (ex + Math.cos(angle) * 2) + 'px';
                        enemy.style.bottom = (ey + Math.sin(angle) * 2) + 'px';
                    }
                }, 1000 / 60);
            }
 
            function findNearestEnemyTo(sourceEnemy) {
                let minDistance = Infinity;
                let closestEnemy = null;
 
                enemies.forEach(enemy => {
                    if (enemy !== sourceEnemy) {
                        let distance = calculateDistance(sourceEnemy, enemy);
                        if (distance < minDistance) {
                            minDistance = distance;
                            closestEnemy = enemy;
                        }
                    }
                });
 
                return closestEnemy;
            }
 
            function calculateDistance(el1, el2) {
                let el1Rect = el1.getBoundingClientRect();
                let el2Rect = el2.getBoundingClientRect();
                let dx = (el1Rect.left + el1Rect.width / 2) - (el2Rect.left + el2Rect.width / 2);
                let dy = (el1Rect.top + el1Rect.height / 2) - (el2Rect.top + el2Rect.height / 2);
                return Math.sqrt(dx * dx + dy * dy);
            }
 
            function enableDoubleJump(enable = true) {
                isDoubleJumpEnabled = enable;
            }
 
function teleportPlayer() {
    if (isTeleporting) return; // Prevent multiple teleports in quick succession

    // Set cooldown
    isTeleporting = true; // Set to true to indicate teleport in progress

    // Calculate teleportation distance
    const teleportDistance = 5; // Set teleport distance in pixels (adjust this as necessary)

    // Determine player current direction
    let teleportOffset = teleportDistance * currentDirection; // Use currentDirection to allow for left (-1) and right (1) teleporting

    // Update player position
    playerPositionX += teleportOffset; // Move the player in the direction they are facing
    playerPositionX = Math.max(0, Math.min(gameWorld.offsetWidth - player.offsetWidth, playerPositionX)); // Ensure player stays in bounds
    player.style.left = playerPositionX + 'px'; // Update player's position on screen

    // Set a timeout for the cooldown
    setTimeout(() => {
        isTeleporting = false; // Reset teleport ability after cooldown
    }, 1000); // 1000 milliseconds = 1 second cooldown
}
 
            function toggleGravity() {
                const originalGravity = gravity;
                gravity = -gravity;
                setTimeout(() => {
                    gravity = originalGravity;
                }, 5000);
            }
 
function resetGravity() {
    gravity = Math.abs(gravity); // Needs to ensure gravity is declared with let or var
}
 
            function freezeEnemies() {
                enemies.forEach(enemy => {
                    enemy.style.transition = 'opacity 1s';
                    enemy.style.opacity = '0.2';
                    enemy.classList.add('frozen-enemy');
                });
                setTimeout(() => {
                    enemies.forEach(enemy => {
                        enemy.style.opacity = '1';
                        enemy.classList.remove('frozen-enemy');
                    });
                }, 5000);
            }
 
            function createClone() {
                const clone = createElement('player', [], playerPositionX + 50);
                clone.style.bottom = playerPositionY + 'px';
                clone.style.backgroundColor = '#00F';
                clone.style.border = '2px dashed #FFF';
                gameWorld.appendChild(clone);
                setTimeout(() => clone.remove(), 5000);
            }
 
            function triggerShockwave() {
                const shockwaveRadius = 100;
                enemies.forEach(enemy => {
                    const dist = calculateDistance(player, enemy);
                    if (dist < shockwaveRadius) {
                        createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
                        enemy.remove();
                    }
                });
            }
 
            function absorbEnergy() {
                score += 50;
                updateDisplay();
            }
 
            function shrinkPlayer() {
                player.style.transform = 'scale(0.5)';
                setTimeout(() => player.style.transform = 'scale(1)', 5000);
            }
 
            function growPlayer() {
                player.style.transform = 'scale(1.5)';
                setTimeout(() => player.style.transform = 'scale(1)', 5000);
            }
 
            function healPlayer() {
                if (lives < 5) {
                    lives++;
                    updateDisplay();
                }
            }
 
            function activateShield() {
                player.style.border = '3px solid purple';
                player.style.opacity = '0.6';
                lives = Math.min(lives + 1, 5);
                updateDisplay();
            }
 
            function gainExtraLife() {
                lives = Math.min(lives + 1, 5);
                updateDisplay();
            }
 
            function boostScore() {
                score += 100;
                updateDisplay();
            }
 
let consecutiveJumps = 0; // Initialize a variable to track consecutive jumps
const maxJumpCount = 3; // Maximum number of normal jumps before triggering a mega jump
const megaJumpMultiplier = 1.5; // Multiplier for the mega jump

function activateMegaJump() {
    if (consecutiveJumps < maxJumpCount) {
        // Perform a normal jump if within the max jump limit
        playerVelocityY = playerJumpStrength; // Regular jump value
        consecutiveJumps++; // Increment consecutive jumps
    } else {
        // Trigger a mega jump if max jump limit has been reached
        playerVelocityY = playerJumpStrength * megaJumpMultiplier; // Apply mega jump
        consecutiveJumps = 0; // Reset consecutive jumps to 0 after a mega jump
    }
    isJumping = true; // Set the jumping status to true
}

// Call this function whenever the player lands to reset the consecutive jumps count
function checkLanding() {
    if (playerPositionY <= 0) { // Assuming ground level is at y = 0
        consecutiveJumps = 0; // Reset consecutive jumps when landing
    }
}
 
            function activateReflectiveShield() {
                player.style.border = '3px dashed cyan';
                const reflectInterval = setInterval(() => {
                    bullets.forEach((bullet, index) => {
                        if (checkCollision(player, bullet.element)) {
                            bullet.direction *= -1;
                        }
                    });
                }, 1000 / 60);
 
                setTimeout(() => {
                    player.style.border = '';
                    clearInterval(reflectInterval);
                }, 5000);
            }
 
            function activateRegeneration() {
                const regenerationInterval = setInterval(() => {
                    if (lives < 5) lives++;
                    updateDisplay();
                    if (!currentPowerUp || currentPowerUp !== 'regeneration') {
                        clearInterval(regenerationInterval);
                    }
                }, 2000);
            }
 
            function activateMagnet() {
                const magnetInterval = setInterval(() => {
                    coins.forEach(coin => {
                        const coinX = parseInt(coin.style.left);
                        const coinY = parseInt(coin.style.bottom);
                        const dx = playerPositionX - coinX;
                        const dy = playerPositionY - coinY;
                        if (Math.sqrt(dx * dx + dy * dy) < 100) {
                            coin.style.left = (coinX + dx * 0.1) + 'px';
                            coin.style.bottom = (coinY + dy * 0.1) + 'px';
                        }
                    });
 
                    if (!currentPowerUp || currentPowerUp !== 'magnet') {
                        clearInterval(magnetInterval);
                    }
                }, 1000/ 60);
            }
 
            let timeSlowTimeout;
 
            function slowDownTime() {
                const originalTiming = 1000 / 60;
                clearInterval(gameInterval);
                gameInterval = setInterval(gameLoop, originalTiming * 2);
                timeSlowTimeout = setTimeout(() => {
                    clearInterval(gameInterval);
                    gameInterval = setInterval(gameLoop, originalTiming);
                }, 5000);
            }
 
function activateEnergyBlast() {
    const blastRadius = 100; // Define the radius of the blast
    const burst = document.createElement('div'); // Create a burst element
    burst.classList.add('energy-blast'); // Assign a class for styles
    burst.style.left = (playerPositionX - blastRadius) + 'px'; // Position the burst to the player's location
    burst.style.bottom = (playerPositionY - blastRadius) + 'px'; // Center the burst around the player
    gameWorld.appendChild(burst); // Add the burst to the game world

    // Set a timeout to remove the burst effect after a duration
    setTimeout(() => {
        burst.remove(); // Remove the burst after showing it
    }, 500); // Keep the burst visible for half a second

    // Identify and destroy nearby enemies
    let enemiesToRemove = enemies.filter(enemy => calculateDistance(player, enemy) < blastRadius);
    enemiesToRemove.forEach(enemy => {
        createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom)); // Create an explosion effect at enemy's location
        enemy.remove(); // Remove the enemy from the game
        enemies = enemies.filter(e => e !== enemy); // Ensure the enemy is removed from the enemies array
    });

    updateDisplay(); // Update the display to reflect any changes (like score)
}
 
function activateBlazingTrail() {
    let trailInterval = setInterval(() => {
        const trail = document.createElement('div');
        trail.className = 'bullet'; // Using the same class for stylistic purposes
        trail.style.left = (playerPositionX + player.offsetWidth / 2) + 'px'; // Position trail based on player's location
        trail.style.bottom = (playerPositionY + player.offsetHeight / 2) + 'px'; // Center the trail on the player
        trail.style.backgroundColor = 'orange'; // Trail color
        gameWorld.appendChild(trail); // Add the trail to the game

        // Check collision with enemies
        enemies.forEach((enemy, enemyIndex) => {
            if (checkCollision(trail, enemy)) {
                // Create burst effect for visual feedback
                const burst = document.createElement('div');
                burst.className = 'burst'; // The CSS class for the burst effect
                burst.style.left = enemy.style.left; // Position it at the enemy's position
                burst.style.bottom = enemy.style.bottom; // Position it at the enemy's position
                gameWorld.appendChild(burst);
                
                // Clean up burst after a short duration
                setTimeout(() => burst.remove(), 500); // Remove burst after 0.5 seconds
                
                // Remove enemy
                enemy.remove(); // Remove the enemy from game
                enemies.splice(enemyIndex, 1); // Remove from enemies array to prevent future collisions
            }
        });

        // Remove the trail after a short duration
        setTimeout(() => trail.remove(), 500); // Remove trail after 0.5 seconds
    }, 100); // The interval for creating the trails

    // Automatically clear the interval after a certain time, e.g., 5 seconds
    setTimeout(() => {
        clearInterval(trailInterval); // Clear the interval for the trail creation
    }, 5000);
}


 
function activateSonicWave() {
    if (waveCooldown) return; // Prevent activation if already on cooldown
    waveCooldown = true; // Set cooldown to prevent further activation

    const wave = document.createElement('div');
    wave.className = 'wave'; // Class for wave styling
    wave.style.left = (playerPositionX - 50) + 'px'; // Center the wave below the player
    wave.style.bottom = (playerPositionY - 50) + 'px'; // Position just below player
    wave.style.backgroundColor = 'cyan'; // Wave color
    wave.style.width = '100px'; // Width of the wave
    wave.style.height = '100px'; // Height of the wave
    wave.style.position = 'absolute'; // Ensure proper positioning
    gameWorld.appendChild(wave); // Add the wave to the game world

    let destroyedBlocks = 0; // Track how many blocks have been destroyed

    // Move the wave forward quickly
    let waveInterval = setInterval(() => {
        wave.style.left = (parseInt(wave.style.left) + 10) + 'px'; // Move wave to the right

        // Check for collision with obstacles
        obstacles.forEach((block, index) => {
            if (checkCollision(wave, block) && destroyedBlocks < 3) { // Destroy only until 3 blocks
                // Create burst effect
                const burst = document.createElement('div'); 
                burst.className = 'burst';
                burst.style.left = block.style.left; 
                burst.style.bottom = block.style.bottom; 
                gameWorld.appendChild(burst);
                
                setTimeout(() => burst.remove(), 500); // Remove burst after half a second
                
                block.remove(); // Remove the obstacle
                obstacles.splice(index, 1); // Remove from the array
                destroyedBlocks++; // Increment the destroyed block count
            }
        });

        // Cleanup if wave goes off screen
        if (parseInt(wave.style.left) > gameWorld.offsetWidth) {
            clearInterval(waveInterval); // Stop moving the wave if it goes off screen
            wave.remove(); // Remove the wave
            resetWave(); // Reset block destruction count
            return; // Exit the function
        }
    }, 50); // Adjust speed of the wave as needed

    // Automatically remove the wave after a brief time
    setTimeout(() => {
        clearInterval(waveInterval); // Ensure the interval is cleared after time is up
        wave.remove(); // Remove the wave
        resetWave(); // Reset properties after the effect finishes
    }, 2000); // Duration of the wave effect (2 seconds)
}

// Reset wave properties for future use
function resetWave() {
    destroyedBlocks = 0; // Reset the number of destroyed blocks for future waves
    waveCooldown = false; // Reset cooldown state
}
 
            function activateArmor() {
                player.style.border = '3px solid steelblue';
                lives = Math.min(lives + 3, 5);
                updateDisplay();
            }
 
function activateTelekinetic() {
    const forceInterval = setInterval(() => {
        enemies.forEach((enemy, index) => {
            const enemyX = parseInt(enemy.style.left) + enemy.offsetWidth / 2; // Get center position
            const enemyY = parseInt(enemy.style.bottom) + enemy.offsetHeight / 2; // Get center position
            const dx = playerPositionX - enemyX;
            const dy = playerPositionY - enemyY;

            // Check if the player is within a certain distance (e.g., 100 pixels)
            if (Math.sqrt(dx * dx + dy * dy) < 100) {
                // Move the enemy upwards slightly
                enemy.style.bottom = (enemyY + 2) + 'px'; // Adjust height as necessary for feel
            } else if (enemyY > 0) { // Only lower it if above 0
                // Bring the enemy back down to ground level smoothly
                enemy.style.bottom = (enemyY - 2) + 'px'; // Adjust to bring back down
                // Stop exactly at the ground level if necessary
                if (parseInt(enemy.style.bottom) < 0) {
                    enemy.style.bottom = '0px'; // Prevent going below 0
                }
            }
        });
    }, 1000 / 60); // Update at 60 FPS

    // Optional: Set a timeout for how long telekinesis lasts
    setTimeout(() => clearInterval(forceInterval), 5000); // Lasts for 5 seconds
}
 
            function activateCamouflage() {
                player.style.opacity = '0.2';
                setTimeout(() => player.style.opacity = '1', 5000);
            }
 
// Array to temporarily hold removed enemies

function activateDimensionShift() {
    // Change the background color to indicate the shift
    gameWorld.style.backgroundColor = 'black';

    // Hide and remove all enemies in the game world
    enemies.forEach((enemy, index) => {
        enemy.style.transition = 'opacity 1s'; // Set transition for fading effect
        enemy.style.opacity = '0'; // Start fading the enemy
        setTimeout(() => {
            enemy.remove(); // Remove from the DOM after fading
            enemies.splice(index, 1); // Remove from the enemies array
        }, 1000); // Match the timeout to the fade-out duration (1 second)
    });

    // Hide and remove all obstacles in the game world
    obstacles.forEach((obstacle, index) => {
        obstacle.style.transition = 'opacity 1s'; // Set transition for fading effect
        obstacle.style.opacity = '0'; // Start fading the obstacle
        setTimeout(() => {
            obstacle.remove(); // Remove from the DOM after fading
            obstacles.splice(index, 1); // Remove from the obstacles array
        }, 1000); // Match the timeout to the fade-out duration (1 second)
    });

    // Reset background color after a period
    setTimeout(() => {
        gameWorld.style.backgroundColor = ''; // Reset the background color after 5 seconds

        // Restore removed enemies
        removedEnemies.forEach(removedEnemy => {
            // Re-create the enemy in the game world
            const newEnemy = createElement(removedEnemy.className, enemies, gameScrollPosition + gameContainer.offsetWidth);
            newEnemy.style.bottom = '0px'; // Reset position
            gameWorld.appendChild(newEnemy); // Append back to game world
        });

        // Clear out the removedEnemies array for future use
        removedEnemies = [];

        // If you have obstacles that should be restored, handle that here as well
        // You may need to keep track of removed obstacles in a similar way if needed
    }, 5000); // Keep the black background for 5 seconds
}
 
            function activateEnergyDrain() {
                const drainInterval = setInterval(() => {
                    if (score > 0) {
                        score -= 1;
                        updateDisplay();
                    }
                }, 100);
 
                setTimeout(() => clearInterval(drainInterval), 5000);
            }
 
function activateMindControl() {
    // Loop through all enemies
    enemies.forEach(enemy => {
        const enemyX = parseInt(enemy.style.left) + (enemy.offsetWidth / 2); // Center the enemy
        const enemyY = parseInt(enemy.style.bottom) + (enemy.offsetHeight / 2); // Center the enemy
        const dx = playerPositionX - enemyX; // Calculate horizontal distance
        const dy = playerPositionY - enemyY; // Calculate vertical distance

        // Check if within the hypnotize range
        if (Math.sqrt(dx * dx + dy * dy) < 100) {
            if (!enemy.classList.contains('hypnotized')) {
                enemy.classList.add('hypnotized'); // Mark enemy as hypnotized
                enemy.style.backgroundColor = 'violet'; // Change color to indicate hypnotization
                
                // Use the hypnotizeEnemy function for this enemy
                hypnotizeEnemy(enemy);
            }
        }
    });
}
 
function activateHologram() {
    const hologram = document.createElement('div');
    hologram.className = 'hologram'; // Use a different class for the hologram
    hologram.style.left = (playerPositionX - 50) + 'px'; // Position based on player's current position
    hologram.style.bottom = playerPositionY + 'px'; // Center it vertically on the player
    hologram.style.backgroundColor = 'rgba(0, 0, 255, 0.5)'; // Blue color with some transparency
    hologram.style.borderRadius = '50%'; // Make it round like a player
    hologram.style.position = 'absolute';
    gameWorld.appendChild(hologram); // Add the hologram to the game world

    // Pulsate effect
    hologram.style.transition = 'transform 0.5s, opacity 0.5s'; // Transition for the effects
    let pulsingDirection = 1; // For pulsating effect
    let scale = 1;

    const pulseInterval = setInterval(() => {
        scale += 0.05 * pulsingDirection; // Scale up or down
        hologram.style.transform = `scale(${scale})`;
        
        // Reverse the pulsating direction
        if (scale >= 1.2 || scale <= 0.8) {
            pulsingDirection *= -1; // Change direction
        }
    }, 100);

    // Behavior to distract nearby enemies
    enemies.forEach(enemy => {
        const enemyX = parseInt(enemy.style.left) + (enemy.offsetWidth / 2); // Center X
        const enemyY = parseInt(enemy.style.bottom) + (enemy.offsetHeight / 2); // Center Y
        const dx = playerPositionX - enemyX;
        const dy = playerPositionY - enemyY;

        if (Math.sqrt(dx * dx + dy * dy) < 100) { // If nearby
            enemy.style.transition = 'left 0.5s';
            // Make enemies dash away from the hologram
            const newLeft = enemyX + (dx > 0 ? 50 : -50); // Push them away from the hologram
            enemy.style.left = `${newLeft}px`;
        }
    });

    // Set a timeout to remove hologram after 5 seconds
    setTimeout(() => {
        clearInterval(pulseInterval); // Clear the pulsating effect
        hologram.remove(); // Remove the hologram from the game world
    }, 5000);
}
 
            function animateBullet(bulletObj, speed, impactCallback = () => {}) {
                const bulletInterval = setInterval(() => {
                    const bullet = bulletObj.element;
                    bullet.style.left = (parseInt(bullet.style.left) + (bulletObj.direction * speed)) + 'px';
                    if (parseInt(bullet.style.left) > gameScrollPosition + gameContainer.offsetWidth || parseInt(bullet.style.left) < 0) {
                        bullet.remove();
                        clearInterval(bulletInterval);
                    } else {
                        [...obstacles, ...enemies].forEach(target => {
                            if (checkCollision(bullet, target)) {
                                impactCallback(target);
                                createBurst(parseInt(bullet.style.left), parseInt(bullet.style.bottom));
                                bullet.remove();
                                clearInterval(bulletInterval);
                            }
                        });
                    }
                }, 1000 / 60);
            }
 
function reduceLives() {
    if (player.style.border) {
        player.style.border = '';
        player.style.opacity = '1';
    } else {
        lives--;
        if (lives <= 0) {
            endGame(false); // Call endGame if lives are 0
        } else {
        }
    }
    updateDisplay();
}

function resetBoss() {
    if (boss) {
        bossHealth = 100; // Restore boss health
        updateBossHealth();
    }
}
 
            function checkCollision(rect1, rect2) {
                const rect1Bounds = rect1.getBoundingClientRect();
                const rect2Bounds = rect2.getBoundingClientRect();
                return !(rect1Bounds.top > rect2Bounds.bottom || rect1Bounds.bottom < rect2Bounds.top ||
                        rect1Bounds.left > rect2Bounds.right || rect1Bounds.right < rect2Bounds.left);
            }
 
            function togglePause() {
                if (isPaused) {
                    gameInterval = setInterval(gameLoop, 1000 / 60);
                    isPaused = false;
                } else {
                    clearInterval(gameInterval);
                    isPaused = true;
                }
            }
 
            function clearAllElements() {
                [obstacles, enemies, bullets.map(b => b.element), powerUps, platforms, bossDoors, coins]
                    .forEach(arr => {
                        arr.forEach(el => el.remove());
                        arr.length = 0;
                    });
            }
 
function interact() {
    if (checkCollision(player, friend)) {
        activateFriendDialogue();
    }
    bossDoors.forEach(door => {
        if (checkCollision(player, door)) {
            if (score >= level * bossScoreThreshold) {
                openBossHallway();
            } else {
                openBossHallway();
            }
        }
    });
}
 
            function openBossHallway() {
                bossHallway.style.display = 'flex';
                clearAllElements();
                clearInterval(gameInterval);
            }
 
function startBossFight() {
    bossHallway.style.display = 'none';
    triggerBossFight();
    gameInterval = setInterval(gameLoop, 1000 / 60); // Ensure the game loop is running for updates
}
 
            function incrementLevel() {
                level++;
                    playerMaxSpeed = 5; // Reset speed back to normal
                if (level > maxLevels) {
                    endGame(true);
                } else {
                    localStorage.setItem('playerLevel', level);
                    updateDisplay();
                    resetGame();
                    levelIntro.style.display = 'flex';
                    switchLevelBackground();
                    levelText.textContent = `Level ${level}: New Challenges Await!`;
                }
            }
 
            function switchLevelBackground() {
                const backgrounds = ['#333', '#1E90FF', '#228B22', '#E0FFFF', '#B22222'];
                gameContainer.style.backgroundColor = backgrounds[(level - 1) % backgrounds.length];
            }
 
            function continueGame() {
                levelIntro.style.display = 'none';
                gameInterval = setInterval(gameLoop, 1000 / 60);
            }
 
function gameLoop() {
    if (!isPaused) {
        updatePlayerPosition(); // Ensure this is called
        spawnEntities();        // You may want to stop spawning entities during the boss fight
        moveElements();         // This is optional, depending on your design
        handlePlayerEnemyCollision();
        checkScoreForLevelTransition(); // This can also be conditional
    }
}
 
function endGame(isWin = false) {
    clearInterval(gameInterval);
    if (!isWin) {
        // Reset boss health if the game is lost
        bossHealth = 100; // Reset to initial boss health
    }
    gameOverScreen.style.display = 'flex';
    gameOverScreen.innerHTML = `<p>${isWin ? 'Congratulations! You won!' : 'Game Over!'}</p>
    <button onclick="restartGame()">Restart</button>`;
}
 
            function restartGame() {
                gameOverScreen.style.display = 'none';
                resetGame();
                startLevel();
            }
 
            function triggerBossFight() {
                bossFightScreen.style.display = 'flex';
                setTimeout(() => {
                    bossFightScreen.style.display = 'none';
                    startBossLogic();
                }, 2000);
            }
 
            function startBossLogic() {
                bossFightActive = true;
                boss = createElement('boss', [], 600);
                boss.style.bottom = '100px';
                gameWorld.appendChild(boss);
                displayBossHealth();
 
                cycleBossAttacks(); // Start the attack pattern cycle
            }
 
 
 
function cycleBossAttacks() {
    if (bossHealth <= 0) return; // Exit if the boss is defeated

    bossAttacking = true;
    bossShielded = true;
    boss.classList.add('boss-shielded'); // Add shield effect to the boss

    // Check the current level and execute the appropriate attacks
    switch (level) {
        case 1:
            switch (bossAttackPhase) {
                case 0:
                    bossEnemyBarrage(); // Standard attack for Level 1
                    break;
                case 1:
                    bossTargetSlam(); // Slam attack for Level 1
                    break;
                case 2:
                    bossNewPower(); // A unique attack for Level 1
                    break;
                case 3:
                    bossExplosionRain(); // Explosive attack for Level 1
                    break;
            }
            break;

        case 2:
            switch (bossAttackPhase) {
                case 0:
                    bossPhaseTwoBarrage(); // Different barrage for Level 2
                    break;
                case 1:
                    bossPhaseTwoTargetSlam(); // Unique slam for Level 2
                    break;
                case 2:
                    bossPhaseTwoNewPower(); // New attack for Level 2
                    break;
                case 3:
                    bossPhaseTwoExplosionRain(); // Explosion attack for Level 2
                    break;
            }
            break;

        case 3:
            switch (bossAttackPhase) {
                case 0:
                    bossPhaseTwoBarrage(); // Different barrage for Level 2
                    break;
                case 1:
                    bossPhaseTwoTargetSlam(); // Unique slam for Level 2
                    break;
                case 2:
                    bossPhaseTwoNewPower(); // New attack for Level 2
                    break;
                case 3:
                    bossPhaseTwoExplosionRain(); // Explosion attack for Level 2
                    break;
            }
            break;
        
        // Additional cases can be added for more levels if needed
    }

    // Set a timeout to remove the shield effect after 5 seconds
    setTimeout(() => {
        bossShielded = false; // Allow boss damage
        boss.classList.remove('boss-shielded'); // Remove shield effect
        displayMessage("Boss shield is OFF! Attack now!"); // Inform players
    }, 5000); // Shield duration

    // Cycle the attack phase, adjust as per the number of phases defined
    bossAttackPhase = (bossAttackPhase + 1) % (level === 3 ? 4 : 4); // Assuming 4 phases for each level for demonstration
}

function bossPhaseTwoNewPower() {
    const originalPosition = { x: window.innerWidth / 2 - 50, y: 50 }; // Original position of the boss
    const boss = document.createElement('div'); // Create the boss element
    boss.style.position = 'absolute';
    boss.style.width = '100px'; // Width of the boss
    boss.style.height = '50px'; // Height of the boss
    boss.style.backgroundColor = 'blue'; // Color of the boss
    boss.style.left = `${originalPosition.x}px`; // Set original X position
    boss.style.top = `${originalPosition.y}px`; // Set Y position (height)
    document.body.appendChild(boss); // Add the boss to the document

    const moveDistance = 200; // Distance the boss will move left/right
    const moveDuration = 1000; // Duration of the left/right movement
    const moveInterval = 100; // Interval for the movement
    const direction = 1; // Start moving right

    // Function to make the boss move
    function moveBoss() {
        let startTime = null; // Track the start time of the animation
        const moveStep = (timestamp) => {
            if (!startTime) startTime = timestamp; // Initialize startTime on the first frame
            const elapsedTime = timestamp - startTime; // Calculate elapsed time

            // Interpolate movement based on elapsed time
            const progress = Math.min(elapsedTime / moveDuration, 1); 
            const offsetX = Math.sin(progress * Math.PI) * moveDistance * direction; // Move left/right
            
            // Update boss position
            boss.style.left = `${originalPosition.x + offsetX}px`;

            if (progress < 1) {
                requestAnimationFrame(moveStep); // Keep animating until complete
            } else {
                // Change direction and move back to original position
                direction *= -1; 
                setTimeout(() => {
                    moveBoss(); // Move again after a short delay
                }, 500); // Wait before moving in the opposite direction
            }
        };

        requestAnimationFrame(moveStep); // Start the animation
    }

    // Start the movement sequence
    moveBoss();

    // Function to teleport the boss back to its original position
    function teleportBoss() {
        boss.style.left = `${originalPosition.x}px`;
    }

    // After the boss goes through a set movement cycle (e.g., for 10 seconds)
    setTimeout(() => {
        teleportBoss(); // Teleport back to original position
    }, 10000); // Duration before teleporting (adjust as needed)
}



function bossPhaseTwoExplosionRain() {
    const blockWidth = 30; // Width of the falling blocks
    const blockHeight = 10; // Height of the falling blocks
    const blockSpeed = 5; // Speed of block movement
    const blocks = []; // Array to hold active blocks
    const spawnInterval = 500; // Time between block spawns (in milliseconds)
    const duration = 10000; // Duration of the attack (in milliseconds)

    // Function to create and spawn blocks
    function spawnBlock() {
        const block = document.createElement('div');
        block.classList.add('explosive-block'); // Add a class for styling
        block.style.width = `${blockWidth}px`;
        block.style.height = `${blockHeight}px`;
        block.style.position = 'absolute';
        block.style.backgroundColor = 'red';

        // Determine random left or right spawn position (off screen)
        const side = Math.random() < 0.5 ? -blockWidth : window.innerWidth; 
        block.style.left = side < 0 ? `${side}px` : `${side - blockWidth}px`;
        block.style.bottom = `${Math.random() * window.innerHeight}px`; // Random vertical position
        document.body.appendChild(block);

        // Move block across the screen
        const moveInterval = setInterval(() => {
            const currentLeft = parseInt(block.style.left);
            block.style.left = `${currentLeft + (side < 0 ? blockSpeed : -blockSpeed)}px`; // Move toward center

            // Check if the block is out of bounds
            if (currentLeft < -blockWidth || currentLeft > window.innerWidth) {
                clearInterval(moveInterval); // Stop moving if out of bounds
                block.remove(); // Remove block from DOM
            }

            // Check collision with player
            if (checkCollision(player, block)) {
                reduceLives(); // Reduce player's lives
                block.remove(); // Remove block on collision
                clearInterval(moveInterval); // Stop moving
            }
        }, 1000 / 60); // Move at 60 FPS
        blocks.push(block); // Add the block to the list of active blocks
    }

    // Start spawning blocks
    const spawnBlocksInterval = setInterval(spawnBlock, spawnInterval);

    // Stop spawning after the specified duration and clean up
    setTimeout(() => {
        clearInterval(spawnBlocksInterval);
        blocks.forEach(block => block.remove()); // Remove remaining blocks
        cycleBossAttacks(); // Move to next boss attack cycle
    }, duration);
}

function bossPhaseTwoTargetSlam() {
    let slamCount = 0; // To track the number of slams
    const maxSlams = 4; // Maximum number of slams
    const slamHeight = "0px"; // Slam to the ground level

    const slamInterval = setInterval(() => {
        // End slamming after reaching the maximum slam count
        if (slamCount >= maxSlams) {
            clearInterval(slamInterval);
            resetBossPosition(); // Reset boss position to center
            setTimeout(cycleBossAttacks, 10000); // Cooldown before next attack
            return; // Exit after the last slam
        }

        // Shake the screen
        shakeScreen();

        // Move boss directly above the player
        const playerX = parseInt(player.style.left) + (player.offsetWidth / 2);
        boss.style.left = `${playerX - (boss.offsetWidth / 2)}px`; // Center the boss over the player

        // Raise boss before slamming
        boss.style.bottom = "400px"; // Set slam height

        setTimeout(() => {
            // Animate the boss slamming down to ground level
            boss.style.transition = 'bottom 0.5s ease'; // Smooth transition
            boss.style.bottom = slamHeight; // Move boss down to the ground level

            setTimeout(() => {
                // After the slam, create a burst effect
                createBurst(playerX, 30); // Slam explosion effect

                // Check collision with player
                if (checkCollision(player, boss)) {
                    reduceLives(); // Damage the player if they collide with the boss
                }

                // Reset the boss's position after the slam (can add effects or logic here)
                boss.style.bottom = "100px"; // Raise back to normal position
            }, 500); // Delay until the slam down animation is completed

            slamCount++; // Increment slam count
        }, 1000); // Hold the slam position for 1 second

    }, 3000); // Slam every 3 seconds
}

// Function to shake the screen
function shakeScreen() {
    let shakeEffect = document.createElement('div');
    shakeEffect.style.position = "fixed";
    shakeEffect.style.top = "0";
    shakeEffect.style.left = "0";
    shakeEffect.style.width = "100%";
    shakeEffect.style.height = "100%";
    shakeEffect.style.backgroundColor = "rgba(255, 0, 0, 0.5)"; // Flashing effect
    shakeEffect.style.transition = 'transform 0.1s';
    document.body.appendChild(shakeEffect);

    // Shake effect
    setTimeout(() => {
        shakeEffect.style.transform = 'translateX(-5px)';
    }, 50);
    
    setTimeout(() => {
        shakeEffect.style.transform = 'translateX(5px)';
    }, 100);

    setTimeout(() => {
        shakeEffect.style.transform = 'translateX(0)';
    }, 150);

    setTimeout(() => {
        shakeEffect.remove(); // Clean up the shake effect
    }, 250); // Duration for the flash effect
}

// Function to reset the boss position to the center of the screen
function resetBossPosition() {
    boss.style.left = (gameContainer.offsetWidth / 2 - boss.offsetWidth / 2) + 'px'; // Center the boss
    boss.style.bottom = "100px"; // Reset position
}
 
 
function bossPhaseTwoNewPower() {
    let boss = document.getElementById('boss'); // Use the existing boss element
    let gameContainer = document.getElementById('game-container');
    let player = document.getElementById('player');
    
    let moveDirection = 1; // 1 for right, -1 for left
    let moveSpeed = 3; // Speed of the boss movement
    let bounceLimit = 5; // Number of bounces before stopping
    let bounceCount = 0; // Current count of bounces

    // Function to move the boss
    function moveBoss() {
        let currentBossPos = parseInt(boss.style.left); // Get current X position

        // Update boss position
        boss.style.left = `${currentBossPos + (moveDirection * moveSpeed)}px`;

        // Check for wall collisions
        if (currentBossPos <= 0 || currentBossPos + boss.offsetWidth >= gameContainer.offsetWidth) {
            moveDirection *= -1; // Change direction
            bounceCount++; // Increment bounce count
            
            // Check if we have exceeded the bounce count
            if (bounceCount >= bounceLimit) {
                // Teleport boss to center
                boss.style.left = `${(gameContainer.offsetWidth / 2) - (boss.offsetWidth / 2)}px`;
                
                // Call the next boss cycle after a short delay
                setTimeout(cycleBossAttacks, 2000); // Delay before transitioning
                return; // Exit the function after teleport
            }
        }

        // Check collision with the player
        if (checkCollision(boss, player)) {
            reduceLives(); // Damage the player if there is a collision
        }

        requestAnimationFrame(moveBoss); // Continue moving the boss
    }

    requestAnimationFrame(moveBoss); // Start the boss movement

    // Utility function to check collision between two elements
    function checkCollision(elem1, elem2) {
        let rect1 = elem1.getBoundingClientRect();
        let rect2 = elem2.getBoundingClientRect();
        
        return !(rect1.right < rect2.left || 
                 rect1.left > rect2.right || 
                 rect1.bottom < rect2.top || 
                 rect1.top > rect2.bottom);
    }

    // Utility function to reduce player lives
    function reduceLives() {
        lives--; // Assuming you have a lives variable defined globally
        if (lives <= 0) {
            endGame(false); // Call your end game function if lives reach zero
        }
    }

    // Example endGame function implementation
    function endGame(isWin) {
        console.log(isWin ? "You win!" : "Game Over!");
        // Implement the actual game over logic as necessary
    }
}

// Call this function when you need to start this boss phase
// bossPhaseTwoNewPower();

function bossPhaseTwoBarrage() {
    boss.style.animation = "boss-shake 1s infinite alternate"; // Boss shakes

    let spawnCount = 0;
    let spawnInterval = setInterval(() => {
        if (spawnCount >= 15) { // Stops after 10 spawns
            clearInterval(spawnInterval);
            boss.style.animation = ""; // Stop shaking
            setTimeout(cycleBossAttacks, 3000); // Cooldown before next attack
            return;
        }

        let enemy = createElement('enemy', enemies, Math.random() * gameContainer.offsetWidth);
        enemy.style.bottom = "400px"; // Start from top

        let fallSpeed = 12;
        let fallInterval = setInterval(() => {
            enemy.style.bottom = (parseInt(enemy.style.bottom) - fallSpeed) + "px";

            if (parseInt(enemy.style.bottom) <= 0) {
                enemy.style.bottom = "0px"; // Stop at ground level
                clearInterval(fallInterval);
            }

            // Check for collision with player
            if (checkCollision(player, enemy)) {
                reduceLives();
                enemy.remove();
                clearInterval(fallInterval);
            }
        }, 50);

        spawnCount++;
    }, 500); // Spawn every half second
}
 
function bossEnemyBarrage() {
    boss.style.animation = "boss-shake 1s infinite alternate"; // Boss shakes

    let spawnCount = 0;
    let spawnInterval = setInterval(() => {
        if (spawnCount >= 10) { // Stops after 10 spawns
            clearInterval(spawnInterval);
            boss.style.animation = ""; // Stop shaking
            setTimeout(cycleBossAttacks, 3000); // Cooldown before next attack
            return;
        }

        let enemy = createElement('enemy', enemies, Math.random() * gameContainer.offsetWidth);
        enemy.style.bottom = "400px"; // Start from top

        let fallSpeed = 8;
        let fallInterval = setInterval(() => {
            enemy.style.bottom = (parseInt(enemy.style.bottom) - fallSpeed) + "px";

            if (parseInt(enemy.style.bottom) <= 0) {
                enemy.style.bottom = "0px"; // Stop at ground level
                clearInterval(fallInterval);
            }

            // Check for collision with player
            if (checkCollision(player, enemy)) {
                reduceLives();
                enemy.remove();
                clearInterval(fallInterval);
            }
        }, 50);

        spawnCount++;
    }, 500); // Spawn every half second
}
 
 
 
function bossTargetSlam() {
    let slamCount = 0;
    boss.style.animation = "boss-shake 0.5s infinite alternate";

    let followInterval = setInterval(() => {
        if (slamCount >= 3) {
            clearInterval(followInterval);
            boss.style.animation = "";
            boss.style.bottom = "100px"; // Reset position after all slams
            setTimeout(cycleBossAttacks, 3000);
            return;
        }

        // Position the boss over the player first
        boss.style.left = player.style.left; 
        boss.style.bottom = "400px"; // Start at high position

        let warningLine = document.createElement('div');
        warningLine.classList.add('warning-line');
        warningLine.style.left = player.style.left;
        warningLine.style.bottom = "0px";
        warningLine.style.width = "30px";
        warningLine.style.height = "5px";
        warningLine.style.backgroundColor = "red";
        warningLine.style.position = "absolute";
        gameWorld.appendChild(warningLine);

        setTimeout(() => {
            warningLine.remove();

            // Slam down
            boss.style.bottom = "100px"; // Slam down position
            if (checkCollision(boss, player)) {
                reduceLives(); // Deal damage to the player
            }
            createBurst(parseInt(boss.style.left) + boss.offsetWidth / 2, 30); // Create burst effect

            // Check collision with player
            if (checkCollision(boss, player)) {
                reduceLives(); // Deal damage to the player
            }

            // Move the boss back up after the slam
            setTimeout(() => {
                boss.style.bottom = "0px"; // Move back up after slam
            }, 500);

        }, 1000); // Time until the slam occurs

        slamCount++;
    }, 2000); // Time interval between slams
}
 
 
function bossExplosionRain() {
    boss.style.animation = "boss-shake 1s infinite alternate";

    let dropCount = 0;
    let dropInterval = setInterval(() => {
        if (dropCount >= 10) {
            clearInterval(dropInterval);
            boss.style.animation = "";
            setTimeout(cycleBossAttacks, 3000); // Cooldown before next attack
            return;
        }

        // Randomize the X position based on the player's position
        let playerPositionX = parseInt(player.style.left);
        let explosionBlock = document.createElement('div'); // Corrected to use document.createElement
        explosionBlock.classList.add('explosive-block'); // Add a class if you want to style it later
        explosionBlock.style.position = "absolute"; // Important for positioning
        explosionBlock.style.left = (playerPositionX + Math.random() * 30 - 15) + "px"; // Randomize the horizontal position
        explosionBlock.style.bottom = "400px"; // Start high
        explosionBlock.style.width = "30px"; // Width of the falling block
        explosionBlock.style.height = "10px"; // Height of the falling block
        explosionBlock.style.backgroundColor = "red"; // Color of the falling block
        gameWorld.appendChild(explosionBlock);

        let fallSpeed = 5; // Speed of fall
        let fallInterval = setInterval(() => {
            explosionBlock.style.bottom = (parseInt(explosionBlock.style.bottom) - fallSpeed) + "px";

            if (parseInt(explosionBlock.style.bottom) <= 0) {
                createBurst(parseInt(explosionBlock.style.left), 0); // Create burst effect
                if (checkCollision(explosionBlock, player)) {
                    reduceLives(); // Reduce lives if hit
                }
                explosionBlock.remove(); // Remove block once it hits ground
                clearInterval(fallInterval);
            }
        }, 50); // Update every 50ms

        dropCount++;
    }, 1000); // Drop every second
}

function bossNewPower() {
    let shotsFired = 0;
    const maxShots = 15;
    const shotCooldown = 800; // 0.8 seconds between shots

    const shootInterval = setInterval(() => {
        if (shotsFired >= maxShots) {
            clearInterval(shootInterval);

            // Introduce a delay before invoking the next attack or phase
            setTimeout(() => {
                cycleBossAttacks(); // Call back the attack cycle function
            }, 2000); // 2 seconds for any cooling down or animation effect
            return; // Stop firing after maximum shots
        }

        // Calculate the boss's and player's positions
        const bossX = parseInt(boss.style.left) + boss.offsetWidth / 2; // Middle of the boss
        const bossY = parseInt(boss.style.bottom) + 30; // Just above the boss
        const playerX = parseInt(player.style.left) + player.offsetWidth / 2; // Middle of the player
        const playerY = parseInt(player.style.bottom); // Bottom of the player
        
        // Calculate the direction vector
        const dx = playerX - bossX;
        const dy = playerY - bossY;
        const distance = Math.sqrt(dx * dx + dy * dy);
        const velocity = 10; // Speed of the projectile

        // Create a projectile
        const projectile = document.createElement('div');
        projectile.classList.add('boss-projectile');
        projectile.style.width = '10px';
        projectile.style.height = '10px';
        projectile.style.backgroundColor = 'orange';
        projectile.style.position = 'absolute';
        projectile.style.left = `${bossX - 5}px`; // Center it
        projectile.style.bottom = `${bossY}px`; // Start just above the boss
        gameWorld.appendChild(projectile);

        let projectileInterval = setInterval(() => {
            // Move projectile towards the player
            const moveX = (dx / distance) * velocity; // Calculate x movement
            const moveY = (dy / distance) * velocity; // Calculate y movement
            projectile.style.left = (parseInt(projectile.style.left) + moveX) + 'px';
            projectile.style.bottom = (parseInt(projectile.style.bottom) + moveY) + 'px';

            // Check collision
            if (checkCollision(player, projectile)) {
                reduceLives(); // Reduce player lives on hit
                projectile.remove(); // Remove projectile on hit
                clearInterval(projectileInterval);
            }

            // Remove projectile if it goes off-screen
            if (parseInt(projectile.style.bottom) > gameContainer.offsetHeight || 
                parseInt(projectile.style.left) < 0 || 
                parseInt(projectile.style.left) > gameContainer.offsetWidth) {
                projectile.remove(); // Remove off-screen
                clearInterval(projectileInterval);
            }
        }, 50); // Update every 50ms

        shotsFired++;
    }, shotCooldown); // Fire every 0.8 seconds
}
 
 
 
 
            function displayBossHealth() {
                bossHealthBar.style.display = 'block';
                updateBossHealth();
            }
 
            function updateBossHealth() {
                bossHealthDisplay.style.width = `${bossHealth}%`;
            }
 
            function spawnBossEnemies() {
                if (bossShielded) {
                    for (let i = 0; i < 2; i++) {
                        const enemy = createElement('enemy', enemies, parseInt(boss.style.left) + (i * 50));
                        enemy.style.bottom = `${Math.random() * 250}px`;
                    }
                }
            }
 
            function spawnBossBullets() {
                const bullet = createBullet();
                bullet.style.left = parseInt(boss.style.left) + 'px';
                bullet.style.bottom = parseInt(boss.style.bottom) + 30 + 'px';
                bullet.style.backgroundColor = 'orange';
                gameWorld.appendChild(bullet);
                bullets.push({ element: bullet, direction: -1 });
            }
 
function checkBossHit() {
    if (!boss || bossShielded) return; // Stop damaging if boss is shielded

    bullets.forEach((bullet, bulletIndex) => {
        if (checkCollision(bullet.element, boss)) {
            bossHealth -= 2; // Decrement boss health
            updateBossHealth();
            bullet.element.remove();
            bullets.splice(bulletIndex, 1);
            
            // Check if the boss is defeated
            if (bossHealth <= 0) {
                displayMessage("Boss defeated!");
                onBossDefeated(); // Trigger boss defeat logic
            }
        }
    });
}
 
 
 
function onBossDefeated() {
    bossHealthBar.style.display = 'none';

    // An array of messages to be displayed based on the defeated boss level
    let messages = [];
    
    if (level === 1) {
        messages = [
            "Noooo! You may have won, but I'll see you in the next level!",
            "Until next time.",
            "Prepare yourself for what's to come!"
        ];
    } else if (level === 2) {
        messages = [
            "You think this is the end? I’ll return!",
            "With my new enemies, you will never win!",
            "Prepare for an even greater challenge in Level 3!",
            "You will need to be stronger to defeat me next time!"
        ];
    } else if (level === 3) {
        messages = [
            "How could this happen?!",
            "You’ve proven yourself worthy...",
            "But the fight isn’t over—brace yourself for more!"
        ];
    }

    // Function to display messages sequentially
    function displaySequentialMessages(messages, index) {
        if (index < messages.length) {
            displayMessage(messages[index]); // Display the current message
            
            // Set a timeout to display the next message
            setTimeout(() => {
                displaySequentialMessages(messages, index + 1); // Move to the next message
            }, 2000); // 2 seconds delay
        } else {
            // After the last message, set up the friend interaction and boss door
            setupFriendAndBossDoor();
        }
    }

    // Start displaying messages
    displaySequentialMessages(messages, 0);
}

function setupFriendAndBossDoor() {
    // Only increment if boss has been defeated for the first time
    let bossDefeated = localStorage.getItem('bossDefeated') === 'yes';

    if (!bossDefeated) {
        // Increment the level
        level += 1; // Increment level
        localStorage.setItem('playerLevel', level); // Save updated level in local storage
        localStorage.setItem('bossDefeated', 'yes'); // Mark boss as defeated
    } else {
        console.log("Boss has already been defeated, level will not increment.");
    }
    
    // Create a custom boss door
    const bossDoor = document.createElement('div'); // Create a new div for the boss door
    bossDoor.classList.add('boss-door'); // Add class for styling
    bossDoor.style.position = 'absolute'; // Positioning for the door
    bossDoor.style.left = '600px'; // Specify door's X position
    bossDoor.style.bottom = '0px'; // Specify door's Y position (ground level)
    bossDoor.style.width = '50px'; // Set width
    bossDoor.style.height = '100px'; // Set height
    bossDoor.style.backgroundColor = 'gold'; // Set background color (for visibility)
    bossDoor.style.border = '2px solid black'; // Optional: add a border
    bossDoor.style.boxShadow = '0 0 15px rgba(255, 215, 0, 1)'; // Glow effect

    // Append the boss door to the game world
    gameWorld.appendChild(bossDoor);

    // Display message to inform the player they can interact with the door
    displayMessage("You’ve defeated the boss! Click the door to proceed to Level " + level + "!");

    // Allow the player to click on the boss door to transition to the next level
    bossDoor.addEventListener('click', () => {
        displayMessage("Opening the door to Level " + level + "..."); // Confirm action

        // Clear all elements in the game world
        clearAllElements(); 
        resetGame(); // Reset game variables and state
        startLevel(); // Start the next level based on the current state
        console.log("Moved to Level " + level + "."); // Log to console for debugging
    });
}

function clearAllElements() {
    // Clear all elements in the game (elements grouped into arrays for easier management)
    [obstacles, enemies, bullets.map(b => b.element), powerUps, platforms, bossDoors, coins].forEach(arr => {
        arr.forEach(el => el.remove());
        arr.length = 0; // Clear the array
    });
}

function SendBackToDoor() {
    setTimeout(() => {
        player.style.left = "50px";
        player.style.bottom = "0px";

        setTimeout(() => {
            activateBossPower();
            level = 2; // Reset to Level 1
            resetGame();
            startLevel(); // Restart the game
        }, 2000);
    }, 3000);
}
 
 
            function activateFriendDialogue() {
                interactMessage.style.display = 'none';
                displayMessage("Thank you for saving me!");
                setTimeout(() => {
                    displayMessage("I got a secret power for you.");
                    setTimeout(() => {
                        grantBossPowerUp();
                        sendbacktodoor();
                        friend.style.display = 'none';
                    }, 3000);
                }, 2000);
            }
 
let isCharging = false;
let chargeTime = 0;
 
function shootLaserBlast(chargeTime) {
    let laser = document.createElement('div');
    laser.classList.add('laser');
    laser.style.left = player.style.left;
    laser.style.bottom = player.style.bottom;
    laser.style.width = `${chargeTime * 10}px`;
    laser.style.height = "10px";
    laser.style.backgroundColor = "cyan";
    gameWorld.appendChild(laser);
 
    setTimeout(() => {
        laser.remove();
        enemies.forEach(enemy => {
            if (checkCollision(laser, enemy)) {
                enemy.remove();
            }
        });
    }, 100);
}
 
 
            function displayMessage(message) {
                powerUpMessage.textContent = message;
                powerUpMessage.style.display = 'block';
                setTimeout(() => {
                    powerUpMessage.style.display = 'none';
                }, 2000);
            }
 
            function checkScoreForLevelTransition() {
                if (score >= level * 10000) {
                    incrementLevel();
                }
            }
 
            function spawnFlyingEnemy() {
                const flyingEnemy = createElement('flying-enemy', enemies, gameScrollPosition + gameContainer.offsetWidth);
                flyingEnemy.style.bottom = Math.random() * 150 + 50 + 'px';
            }
 
function moveFlyingEnemies() {
    enemies.forEach((enemy, index) => {
        if (enemy.classList.contains('flying-enemy')) {
            // Move the enemy up and down
            let enemyYPosition = parseInt(enemy.style.bottom) || 0; // Get current Y position or default to 0
            let direction = enemy.dataset.direction ? parseInt(enemy.dataset.direction) : 1; // Up or down direction

            // Update vertical position of the flying enemy
            enemyYPosition += direction * 1; // Move 1 pixel per frame 
            enemy.style.bottom = enemyYPosition + 'px';

            // Reverse direction if the flying enemy reaches a certain height
            if (enemyYPosition >= 150) { // Maximum height
                direction = -1; // Change to downward movement
            } else if (enemyYPosition <= 0) { // Minimum height (ground)
                direction = 1; // Change to upward movement
            }
            enemy.dataset.direction = direction; // Store the current direction for the next update

            // Move the enemy left
            enemy.style.left = (parseInt(enemy.style.left) - 2) + 'px';

            // Check shooting
            if (enemy.dataset.lastShotTime === undefined || Date.now() - enemy.dataset.lastShotTime > 10000) { // Every 10 seconds
                shootBulletAtPlayer(enemy); // Shoot at the player
                enemy.dataset.lastShotTime = Date.now(); // Update the last shot time
            }

            // Boundary checking and collision with the player
            if (parseInt(enemy.style.left) < 0) {
                removeElement(enemy, enemies, index, 30);
            } else if (checkCollision(player, enemy)) {
                reduceLives();
                removeElement(enemy, enemies, index, 0);
            }
        }
    });
}

// Function to shoot a bullet aimed at the player
function shootBulletAtPlayer(enemy) {
    const bullet = document.createElement('div');
    bullet.classList.add('bullet'); // Add your bullet class
    bullet.style.width = '10px';
    bullet.style.height = '5px';
    bullet.style.backgroundColor = 'orange'; // Bullet color
    bullet.style.position = 'absolute';
    
    // Position the bullet at the enemy's current position
    bullet.style.left = (parseInt(enemy.style.left) + 20) + 'px'; // Position it slightly in front of the enemy
    bullet.style.bottom = (parseInt(enemy.style.bottom) + 15) + 'px'; // Start just below the enemy
    gameWorld.appendChild(bullet); // Add bullet to the game world
    
    // Calculate angle towards the player
    const playerX = parseInt(player.style.left) + player.offsetWidth / 2; // Center of player
    const playerY = parseInt(player.style.bottom); // Bottom of player

    const dx = playerX - (parseInt(bullet.style.left) + bullet.offsetWidth / 2);
    const dy = playerY - (parseInt(bullet.style.bottom));
    const distance = Math.sqrt(dx * dx + dy * dy); 
    const velocity = 5; // Speed of the bullet

    // Bullet movement
    const moveBullet = setInterval(() => {
        const moveX = (dx / distance) * velocity; 
        const moveY = (dy / distance) * velocity;

        bullet.style.left = (parseInt(bullet.style.left) + moveX) + 'px';
        bullet.style.bottom = (parseInt(bullet.style.bottom) + moveY) + 'px';

        // Check if the bullet hits the player or goes off screen
        if (checkCollision(bullet, player)) {
            reduceLives(); // Damages the player
            bullet.remove(); // Remove bullet
            clearInterval(moveBullet); // Stop moving the bullet
        }

        if (parseInt(bullet.style.left) < 0 || parseInt(bullet.style.left) > gameWorld.offsetWidth || parseInt(bullet.style.bottom) < 0) {
            bullet.remove(); // Remove bullet if it goes off screen
            clearInterval(moveBullet); // Stop moving the bullet
        }
    }, 1000 / 60); // 60 FPS
}
 
            function spawnChargingEnemy() {
                const chargingEnemy = createElement('charging-enemy', enemies, gameScrollPosition + gameContainer.offsetWidth);
                chargingEnemy.style.bottom = '0px';
                chargingEnemy.setAttribute('data-charge', '0');
                chargingEnemy.classList.add('charging-prep'); // Fading in/out red glow effect
            }
 
 
            function createChargeTrail(x, y) {
                const trail = document.createElement('div');
                trail.classList.add('charge-trail');
                trail.style.left = x + 'px';
                trail.style.bottom = y + 'px';
                gameWorld.appendChild(trail);
 
                setTimeout(() => trail.remove(), 400); // Shorter effect for smoothness
            }
 
 
 
 
function moveChargingEnemies() {
    enemies.forEach((enemy, index) => {
        if (enemy.classList.contains('charging-enemy')) {
            let chargeTime = parseInt(enemy.getAttribute('data-charge'));
 
            if (chargeTime < 60) {
                // Charging phase (fading in/out glow)
                enemy.setAttribute('data-charge', chargeTime + 1);
            } else {
                // Fully Charged (Solid Red Outline + Charging Forward)
                enemy.classList.remove('charging-prep');
                enemy.classList.add('charging-active');
                enemy.style.left = (parseInt(enemy.style.left) - 6) + 'px';
 
                // Create a bright red trail
                createChargeTrail(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            }
 
            // Check collision with player
            if (checkCollision(player, enemy)) {
                createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom)); // Impact explosion
                reduceLives();
                removeElement(enemy, enemies, index, 0);
            }
 
            // Remove if out of bounds
            if (parseInt(enemy.style.left) < gameScrollPosition - enemy.offsetWidth) {
                removeElement(enemy, enemies, index, 30);
            }
        }
    });
}
 
 
 
            function spawnStealthEnemy() {
                const stealthEnemy = createElement('stealth-enemy', enemies, gameScrollPosition + gameContainer.offsetWidth);
                stealthEnemy.setAttribute('data-stealth', '0');
                stealthEnemy.style.backgroundColor = '#555';
                stealthEnemy.style.opacity = '1';
            }
 
            function moveStealthEnemies() {
                enemies.forEach(en => {
                    if (en.classList.contains('stealth-enemy')) {
                        const stealth = parseInt(en.getAttribute('data-stealth'));
                        if (stealth > 50) {
                            en.style.opacity = en.style.opacity == '0' ? '1' : '0';
                            en.setAttribute('data-stealth', '0');
                        } else {
                            en.setAttribute('data-stealth', stealth + 1);
                        }
                    }
                });
            }

function moveSniperEnemies() {
    enemies.forEach((enemy, index) => {
        if (enemy.classList.contains('sniper-enemy')) {
            const enemyX = parseInt(enemy.style.left) + enemy.offsetWidth / 2; // Center position
            const enemyY = parseInt(enemy.style.bottom) + enemy.offsetHeight; // Height

            // Shooting mechanism
            if (!enemy.dataset.lastShotTime || Date.now() - enemy.dataset.lastShotTime > 3000) { // Every 3 seconds
                shootAtPlayer(enemy);
                enemy.dataset.lastShotTime = Date.now(); // Update for next shot
            }

            // Check distance to player
            const distanceToPlayer = Math.sqrt(Math.pow(enemyX - (parseInt(player.style.left) + player.offsetWidth / 2), 2) + 
                Math.pow(enemyY - parseInt(player.style.bottom), 2));
            
            if (distanceToPlayer < 300) { // Within 300 pixels visibility range
                enemy.style.opacity = '1'; // Fully visible
            } else {
                enemy.style.opacity = '0.5'; // Reduced opacity
            }
        }
    });
}

// Function for the sniper to shoot at the player
function shootAtPlayer(enemy) {
    const bullet = document.createElement('div');
    bullet.classList.add('bullet'); // Add your class for the bullet
    bullet.style.width = '10px';
    bullet.style.height = '5px';
    bullet.style.backgroundColor = 'red'; // Bullet color
    bullet.style.position = 'absolute';
    
    // Position the bullet at the sniper's location
    bullet.style.left = (parseInt(enemy.style.left) + 20) + 'px'; // Set slight offset
    bullet.style.bottom = (parseInt(enemy.style.bottom) + 15) + 'px'; // Set above the sniper
    gameWorld.appendChild(bullet); // Add bullet to the game world

    // Calculate angle towards the player
    const playerX = parseInt(player.style.left) + player.offsetWidth / 2; // Center of player
    const playerY = parseInt(player.style.bottom); // Bottom of player

    const dx = playerX - (parseInt(bullet.style.left) + bullet.offsetWidth / 2);
    const dy = playerY - (parseInt(bullet.style.bottom));
    const distance = Math.sqrt(dx * dx + dy * dy); 
    const velocity = 5; // Speed of the bullet

    // Bullet movement logic
    const moveBullet = setInterval(() => {
        const moveX = (dx / distance) * velocity; // Calculate x movement direction
        const moveY = (dy / distance) * velocity; // Calculate y movement direction

        bullet.style.left = (parseInt(bullet.style.left) + moveX) + 'px';
        bullet.style.bottom = (parseInt(bullet.style.bottom) + moveY) + 'px';

        // Check for bullet collision with player
        if (checkCollision(bullet, player)) {
            reduceLives(); // Damage player
            bullet.remove(); // Remove bullet
            clearInterval(moveBullet); // Stop bullet movement
        }

        // Remove bullet if it goes off screen
        if (parseInt(bullet.style.left) < 0 || parseInt(bullet.style.left) > gameWorld.offsetWidth || parseInt(bullet.style.bottom) < 0) {
            bullet.remove(); // Remove bullet if it goes off screen
            clearInterval(moveBullet); // Stop bullet movement
        }
    }, 1000 / 60); // 60 FPS
}
 
            function spawnSplitterEnemy() {
                const splitter = createElement('split-enemy', enemies, gameScrollPosition + gameContainer.offsetWidth);
                splitter.style.bottom = '0px';
                splitter.classList.add('split');
            }
 
            function handleSplitterEnemyHit(enemy, enemyIndex) {
                if (!enemy.classList.contains('split')) {
                    for (let i = 0; i < 3; i++) {
                        const miniEnemy = createElement('split-enemy', enemies, parseInt(enemy.style.left) + i * 30);
                        miniEnemy.style.width = '15px';
                        miniEnemy.style.height = '15px';
                        miniEnemy.classList.remove('split');
                    }
                }
                removeElement(enemy, enemies, enemyIndex, 0);
            }
 
            function handleExplosiveEnemyHit(enemy, enemyIndex) {
                removeElement(enemy, enemies, enemyIndex, 0);
                enemies.forEach((otherEnemy, index) => {
                    if (calculateDistance(enemy, otherEnemy) < 50) {
                        removeElement(otherEnemy, enemies, index, 0);
                    }
                });
                createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
                reduceLives();
            }
 
            function spawnSniperEnemy() {
                const sniper = createElement('sniper-enemy', enemies, gameScrollPosition + gameContainer.offsetWidth);
                sniper.style.bottom = '200px';
                const sniperInterval = setInterval(() => {
                    if (Math.random() < 0.05 && calculateDistance(player, sniper) < 300) {
                        const bullet = createBullet();
                        bullet.style.left = parseInt(sniper.style.left) + 'px';
                        bullet.style.bottom = parseInt(sniper.style.bottom) + 'px';
                        bullet.style.backgroundColor = 'red';
                        gameWorld.appendChild(bullet);
                        bullets.push({ element: bullet, direction: -1 });
                    }
                }, 1000);
 
                sniper.setAttribute('data-interval', sniperInterval);
            }
 

// Function to spawn the reflective enemy at the bottom
function spawnReflectiveEnemy() {
    // Create the reflective enemy element
    var reflectiveEnemy = createElement('reflective-enemy', enemies, gameScrollPosition + gameContainer.offsetWidth);

    // Set initial attributes
    reflectiveEnemy.setAttribute('data-health', '10'); // Set initial health or reflection strength
    reflectiveEnemy.classList.add('outlined'); // Add CSS class for glowing outline
    reflectiveEnemy.dataset.reflectiveHits = 0; // Initialize reflection hits tracking

    // Position the reflective enemy at the bottom of the game world
    reflectiveEnemy.style.bottom = '0px'; // Set to 0 for the bottom position

    // Set up shooting capability
    reflectiveEnemy.dataset.lastShotTime = Date.now(); // Track when the last shot was fired

    // Append the reflective enemy to the game world
    gameWorld.appendChild(reflectiveEnemy);
}

// Function to handle shooting bullets at the player
function shootAtPlayer2(reflectiveEnemy) {
    const bullet = document.createElement('div');
    bullet.classList.add('enemy-bullet'); // Style class for the bullet
    bullet.style.width = '10px';
    bullet.style.height = '5px';
    bullet.style.backgroundColor = 'red'; // Enemy bullet color
    bullet.style.position = 'absolute';

    // Position the bullet at the enemy's location
    bullet.style.left = `${parseInt(reflectiveEnemy.style.left) + 20}px`; // Center the bullet
    bullet.style.bottom = `${parseInt(reflectiveEnemy.style.bottom) + 15}px`; // Above the enemy
    gameWorld.appendChild(bullet); // Add bullet to the game world

    // Calculate the player’s position
    const playerX = parseInt(player.style.left) + player.offsetWidth / 2; // Center of player
    const playerY = parseInt(player.style.bottom); // Bottom of player

    // Calculate direction towards the player
    const dx = playerX - (parseInt(bullet.style.left) + bullet.offsetWidth / 2);
    const dy = playerY - parseInt(bullet.style.bottom);
    const distance = Math.sqrt(dx * dx + dy * dy);
    const velocity = 5; // Speed of the bullet

    // Move the bullet towards the player
    const moveBulletInterval = setInterval(() => {
        const moveX = (dx / distance) * velocity; // Calculate x movement
        const moveY = (dy / distance) * velocity; // Calculate y movement

        bullet.style.left = (parseInt(bullet.style.left) + moveX) + 'px';
        bullet.style.bottom = (parseInt(bullet.style.bottom) + moveY) + 'px';

        // Check for collision with player
        if (checkCollision(player, bullet)) {
            reduceLives(); // Damage player
            bullet.remove(); // Remove bullet
            clearInterval(moveBulletInterval); // Stop movement
        }

        // Remove bullet if it goes off screen
        if (parseInt(bullet.style.left) < 0 || parseInt(bullet.style.left) > gameWorld.offsetWidth || parseInt(bullet.style.bottom) < 0) {
            bullet.remove(); // Remove bullet if it goes off screen
            clearInterval(moveBulletInterval); // Stop movement
        }
    }, 1000 / 60); // Move at 60 FPS
}

// Update reflective enemy behavior to shoot at player on hit
function handleBulletCollisionWithReflectiveEnemy(reflectiveEnemy, bullet) {
    // Check if the bullet collides with the reflective enemy
    if (checkCollision(reflectiveEnemy, bullet)) {
        bullet.remove(); // Remove bullet on collision
        reflectiveEnemy.dataset.reflectiveHits++; // Track the number of hits

        // Call the shoot function after a certain interval
        if (Date.now() - reflectiveEnemy.dataset.lastShotTime >= 2000) { // Cooldown for 2 seconds between shots
            shootAtPlayer2(reflectiveEnemy);
            reflectiveEnemy.dataset.lastShotTime = Date.now(); // Reset the shot time
        }
    }
}
 
            function spawnNewInteractiveEnemies() {
                const randomFeature = Math.random();
                if (randomFeature < 0.2) {
                    spawnTeleporterEnemy();
                } else if (randomFeature < 0.6) {
                    spawnVelocityEnemy();
                } else if (randomFeature < 0.8) {
                    spawnStickyEnemy();
                } else {
                    spawnReflectiveEnemy();
                }
            }
 
            function moveNewEnemies() {
                moveTeleporterEnemies();
                moveVelocityEnemies();
                moveStickyEnemies();
            }
 
            // New enemies with creative features
            function spawnTeleporterEnemy() {
                const teleporterEnemy = createElement('teleporter-enemy', enemies, gameScrollPosition + gameContainer.offsetWidth);
                teleporterEnemy.style.backgroundColor = '#8A2BE2'; 
                teleporterEnemy.style.bottom = '0px';
                teleporterEnemy.setAttribute('data-teleport', '0');
            }
 
            function moveTeleporterEnemies() {
                enemies.forEach(en => {
                    if (en.classList.contains('teleporter-enemy')) {
                        const teleport = parseInt(en.getAttribute('data-teleport'));
                        if (teleport > 100) {
                            en.style.left = Math.random() * (gameWorld.offsetWidth - en.offsetWidth) + 'px';
                            en.setAttribute('data-teleport', '0');
                        } else {
                            en.setAttribute('data-teleport', teleport + 1);
                        }
                    }
                });
            }

function moveReflectiveEnemies() {
    var enemiesToRemove = []; // Array to track enemies to be removed

    enemies.forEach(function(en, index) {
        if (en.classList.contains('reflective-enemy')) {
            // Move the reflective enemy to the left
            en.style.left = (parseInt(en.style.left) - 1) + 'px';

            // Check for collision with bullets
            bullets.forEach(function(bullet, bulletIndex) {
                // If the bullet collides with the reflective enemy
                if (checkCollision(en, bullet.element)) {
                    // Reflect the bullet's direction
                    bullet.direction *= -1; 

                    // Adjust bullet position slightly to avoid getting stuck
                    bullet.element.style.left = (parseInt(bullet.element.style.left) + (bullet.direction * 5)) + 'px';

                    // Increment the reflective hits count
                    en.dataset.reflectiveHits++;

                    // Optional: handle when you want to remove the enemy after a number of hits, if desired
                    if (parseInt(en.dataset.reflectiveHits) >= 10) {
                        enemiesToRemove.push(index); // Mark for removal
                    }

                    // Remove the bullet
                    bullet.element.remove();
                    bullets.splice(bulletIndex, 1); // Remove bullet from the bullets array
                }
            });

            // Check for collision with the player
            if (checkCollision(player, en)) {
                reduceLives(); // Reduce lives if player hits the reflective enemy
                enemiesToRemove.push(index); // Mark enemy for removal
            }

            // Remove if off-screen
            if (parseInt(en.style.left) < -en.offsetWidth) {
                enemiesToRemove.push(index); // Mark for removal
            }
        }
    });

    // Remove enemies marked for removal
    enemiesToRemove.reverse().forEach(function(index) {
        removeElement(enemies[index], enemies, index, 0);
    });
}
 
            function spawnVelocityEnemy() {
                const velocityEnemy = createElement('velocity-enemy', enemies, gameScrollPosition + gameContainer.offsetWidth);
                velocityEnemy.style.backgroundColor = '#FF4500'; 
                velocityEnemy.style.bottom = Math.random() * 150 + 'px';
                velocityEnemy.setAttribute('data-speed', '2');
            }
 
            function moveVelocityEnemies() {
                enemies.forEach(en => {
                    if (en.classList.contains('velocity-enemy')) {
                        const speed = parseInt(en.getAttribute('data-speed'));
                        en.style.left = (parseInt(en.style.left) - speed) + 'px';
                        en.style.bottom = (parseInt(en.style.bottom) + (Math.random() - 0.5) * 10) + 'px';
                        if (parseInt(en.style.left) < gameScrollPosition - en.offsetWidth) {
                            removeElement(en, enemies, 0, 30);
                        } else if (checkCollision(player, en)) {
                            reduceLives();
                            removeElement(en, enemies, 0, 0);
                        }
                    }
                });
            }
 
            function spawnStickyEnemy() {
                const stickyEnemy = createElement('sticky-enemy', enemies, gameScrollPosition + gameContainer.offsetWidth);
                stickyEnemy.style.backgroundColor = '#FFD700'; 
                stickyEnemy.style.bottom = '0px';
            }
 
            function moveStickyEnemies() {
                enemies.forEach(en => {
                    if (en.classList.contains('sticky-enemy')) {
                        en.style.left = (parseInt(en.style.left) - 1) + 'px';
                        if (checkCollision(player, en)) {
                            player.style.backgroundColor = '#FFD700';
                            setTimeout(() => player.style.backgroundColor = '#4CAF50', 2000);
                            removeElement(en, enemies, 0, 0);
                        }
                    }
                });
            }
 
 
    </script>
</body>
</html>