<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>恶魔轮盘赌 - 完美修复版 | 动画全开</title>
    <style>
        * {
            user-select: none;
            box-sizing: border-box;
        }

        body {
            margin: 0;
            min-height: 100vh;
            background: radial-gradient(circle at 20% 30%, #1a0b0b, #050101);
            display: flex;
            justify-content: center;
            align-items: center;
            font-family: 'Courier New', 'Press Start 2P', 'Segoe UI', monospace;
            padding: 20px;
            transition: transform 0.05s linear;
        }

        body.shake-effect {
            animation: screenShake 0.15s ease-in-out 0s 2;
        }

        @keyframes screenShake {
            0% { transform: translate(1px, 1px); }
            25% { transform: translate(-1px, -2px); }
            50% { transform: translate(-2px, 1px); }
            75% { transform: translate(1px, -1px); }
            100% { transform: translate(0,0); }
        }

        .game-container {
            max-width: 1300px;
            width: 100%;
            background: rgba(0, 0, 0, 0.65);
            backdrop-filter: blur(3px);
            border-radius: 4rem 2rem 4rem 2rem;
            box-shadow: 0 25px 40px rgba(0, 0, 0, 0.6), inset 0 1px 2px rgba(255, 255, 255, 0.1);
            border: 2px solid #7a2e2e;
            padding: 20px 25px 35px;
            transition: all 0.2s;
            position: relative;
            overflow: hidden;
        }

        .gun-transfer {
            position: fixed;
            font-size: 3.5rem;
            filter: drop-shadow(0 0 8px orange);
            z-index: 1000;
            pointer-events: none;
            transition: all 0.4s cubic-bezier(0.2, 1.2, 0.8, 1);
            opacity: 0;
        }

        .characters {
            display: flex;
            justify-content: space-between;
            gap: 20px;
            flex-wrap: wrap;
            margin-bottom: 30px;
        }

        .character-card {
            flex: 1;
            background: #1f1212e6;
            border-radius: 2rem;
            padding: 20px 15px;
            text-align: center;
            box-shadow: 0 10px 20px rgba(0,0,0,0.5), inset 0 0 20px rgba(220, 60, 60, 0.2);
            border-bottom: 4px solid #aa2e2e;
            transition: transform 0.2s, box-shadow 0.2s;
            position: relative;
        }

        .character-card.active-turn {
            transform: scale(1.02);
            box-shadow: 0 0 0 2px #ff5e5e, 0 0 15px #ff2a2a;
            background: #2d1818e6;
        }

        .emoji-icon {
            font-size: 4rem;
            filter: drop-shadow(2px 4px 8px black);
        }

        .character-name {
            font-size: 1.7rem;
            font-weight: bold;
            letter-spacing: 2px;
            color: #ffc9c9;
            text-shadow: 2px 2px 0 #5a1e1e;
            margin: 8px 0;
        }

        .health-bar {
            background: #2b0c0c;
            border-radius: 40px;
            height: 20px;
            width: 100%;
            overflow: hidden;
            margin: 15px 0;
            box-shadow: inset 0 0 5px black;
        }

        .health-fill {
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, #e34d4d, #b91c1c);
            border-radius: 40px;
            transition: width 0.25s cubic-bezier(0.2, 1.2, 0.8, 1);
        }

        .health-text {
            font-size: 1.2rem;
            font-weight: bold;
            color: #ffb7b7;
            background: #2e0b0bb3;
            display: inline-block;
            padding: 4px 12px;
            border-radius: 30px;
        }

        .bullet-chamber {
            background: #0f0404b3;
            border-radius: 60px;
            margin: 20px 0;
            padding: 10px 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 15px;
            border: 1px solid #a03a3a;
        }

        .bullet-info {
            display: flex;
            align-items: center;
            gap: 12px;
            background: #00000066;
            padding: 5px 15px;
            border-radius: 40px;
        }

        .bullet-icon {
            font-size: 2rem;
            filter: drop-shadow(0 0 3px red);
        }

        .bullet-count {
            font-size: 1.6rem;
            font-weight: bold;
            color: #ff7b7b;
        }

        .damage-buff {
            background: #3c1e1e;
            padding: 6px 12px;
            border-radius: 30px;
            font-size: 1rem;
            color: #ffbf69;
            font-weight: bold;
        }

        .items-area {
            background: #160a0ae0;
            border-radius: 2rem;
            padding: 15px;
            margin: 20px 0;
            border: 1px solid #ac4c4c;
        }

        .items-title {
            font-size: 1.3rem;
            margin-bottom: 12px;
            color: #e4b363;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .items-list {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            justify-content: center;
        }

        .item-btn {
            background: #2a1515;
            border: 2px solid #ad4d4d;
            color: #ffdede;
            font-size: 1rem;
            font-weight: bold;
            padding: 8px 20px;
            border-radius: 40px;
            cursor: pointer;
            font-family: monospace;
            transition: 0.1s linear;
            box-shadow: 0 4px 0 #3a1212;
            position: relative;
            overflow: hidden;
        }

        .item-btn:hover:not(:disabled) {
            background: #612b2b;
            transform: scale(1.02);
            border-color: #ff8c8c;
        }

        .item-btn:active:not(:disabled) {
            transform: translateY(2px);
            box-shadow: 0 1px 0 #3a1212;
        }

        .item-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .item-flash {
            animation: itemUseFlash 0.3s ease-out;
        }

        @keyframes itemUseFlash {
            0% { background-color: #ffae00; box-shadow: 0 0 0 0 gold; }
            100% { background-color: #2a1515; box-shadow: 0 0 10px 5px rgba(255,215,0,0); }
        }

        .action-buttons {
            display: flex;
            justify-content: center;
            gap: 25px;
            margin: 15px 0;
        }

        .action-btn {
            background: #1e0e0e;
            border: none;
            font-size: 1.3rem;
            font-weight: bold;
            padding: 12px 28px;
            border-radius: 80px;
            font-family: inherit;
            cursor: pointer;
            transition: 0.1s;
            color: #ffe0e0;
            box-shadow: 0 6px 0 #270606;
            border-bottom: 1px solid #aa5555;
        }

        .action-btn.shoot-self { background: #643434; }
        .action-btn.shoot-enemy { background: #8b2c2c; }
        .action-btn:active:not(:disabled) { transform: translateY(3px); box-shadow: 0 2px 0 #270606; }
        .action-btn:disabled { opacity: 0.5; cursor: not-allowed; }

        .log-area {
            background: #060101aa;
            border-radius: 20px;
            padding: 12px;
            margin-top: 20px;
            font-size: 0.9rem;
            color: #f5bcbc;
            max-height: 100px;
            overflow-y: auto;
            font-weight: bold;
        }

        .reset-btn {
            background: #592121;
            border: none;
            padding: 8px 20px;
            border-radius: 60px;
            font-size: 1.1rem;
            color: white;
            font-weight: bold;
            cursor: pointer;
            margin-top: 10px;
            width: fit-content;
            transition: 0.1s;
        }
        .reset-btn:active { transform: scale(0.96); }

        .shoot-animation { animation: shootFlash 0.2s ease-out; }
        @keyframes shootFlash {
            0% { filter: brightness(1);}
            50% { filter: brightness(2) drop-shadow(0 0 10px orange); text-shadow: 0 0 8px red;}
            100% { filter: brightness(1);}
        }

        .hit-effect { animation: hitShake 0.2s ease-in-out; }
        @keyframes hitShake {
            0% { transform: translateX(0);}
            25% { transform: translateX(-5px);}
            75% { transform: translateX(5px);}
            100% { transform: translateX(0);}
        }

        .magnify-glow { animation: pulseGlow 0.4s ease-out; }
        @keyframes pulseGlow {
            0% { text-shadow: 0 0 0 gold; background-color: rgba(255,215,0,0);}
            100% { text-shadow: 0 0 12px #ffd966; background-color: rgba(255,200,0,0.3);}
        }

        .saw-effect::after {
            content: "⚡🔪⚡";
            position: absolute;
            top: -20px;
            left: 20%;
            font-size: 2rem;
            animation: sawSlice 0.3s forwards;
            pointer-events: none;
        }
        @keyframes sawSlice {
            0% { opacity: 1; transform: translateX(-20px) rotate(0deg);}
            100% { opacity: 0; transform: translateX(40px) rotate(180deg);}
        }

        footer {
            text-align: center;
            font-size: 0.7rem;
            color: #a77373;
            margin-top: 15px;
        }
        @media (max-width: 750px) {
            .character-name { font-size: 1.2rem; }
            .action-btn { padding: 8px 18px; font-size: 1rem; }
            .item-btn { padding: 5px 12px; font-size: 0.8rem; }
        }
    </style>
</head>
<body>
<div class="game-container" id="gameRoot">
    <div class="characters">
        <div class="character-card" id="playerCard">
            <div class="emoji-icon">😈</div>
            <div class="character-name">赌徒 · 你</div>
            <div class="health-bar"><div class="health-fill" id="playerHealthFill" style="width: 100%"></div></div>
            <div class="health-text">❤️ <span id="playerHp">5</span> / 5</div>
        </div>
        <div class="character-card" id="demonCard">
            <div class="emoji-icon">👹</div>
            <div class="character-name">恶魔 · 轮盘主</div>
            <div class="health-bar"><div class="health-fill" id="demonHealthFill" style="width: 100%"></div></div>
            <div class="health-text">💀 <span id="demonHp">5</span> / 5</div>
        </div>
    </div>

    <div class="bullet-chamber">
        <div class="bullet-info">
            <span class="bullet-icon">🔫</span>
            <span class="bullet-count" id="bulletsRemain">0</span>
            <span>发弹药</span>
        </div>
        <div class="damage-buff" id="damageBuffIndicator">⚡ 额外伤害: +0</div>
        <div class="bullet-info" id="nextBulletHint">
            <span>🎲 当前子弹: </span>
            <span id="bulletTypeUnknown">❓ 未知</span>
        </div>
    </div>

    <div class="items-area">
        <div class="items-title">🎰 恶魔契约道具 🎴</div>
        <div class="items-list" id="itemsContainer"></div>
    </div>

    <div class="action-buttons">
        <button class="action-btn shoot-self" id="shootSelfBtn">🔫 对自己开枪</button>
        <button class="action-btn shoot-enemy" id="shootEnemyBtn">💀 对恶魔开枪</button>
    </div>
    <div style="display: flex; justify-content: center;">
        <button class="reset-btn" id="resetGameBtn">♻️ 重开轮盘赌局</button>
    </div>
    <div class="log-area" id="logMessages">
        > 恶魔低语: 开始你的轮盘赌局...<br>
        > 修复版: 空包不换回合,恶魔AI不再卡死
    </div>
    <footer>🔮 锯子增伤 | 手铐锁敌 | 放大镜窥弹 | 动画满配</footer>
</div>

<script>
    // ---------- 游戏核心 ----------
    let playerHP = 5, demonHP = 5, maxHP = 5;
    let currentBullets = [];          // 'live' or 'blank'
    let currentBulletIndex = 0;
    let turn = 'player';               // 'player' 或 'demon'
    let gameOver = false;
    let extraDamage = 0;
    let skipDemonTurn = false;         // 手铐标记
    let inventory = [];
    let processingAction = false;
    let revealedBullet = false;

    // DOM 元素
    const playerHpSpan = document.getElementById('playerHp');
    const demonHpSpan = document.getElementById('demonHp');
    const playerHealthFill = document.getElementById('playerHealthFill');
    const demonHealthFill = document.getElementById('demonHealthFill');
    const bulletsRemainSpan = document.getElementById('bulletsRemain');
    const damageBuffSpan = document.getElementById('damageBuffIndicator');
    const itemsContainer = document.getElementById('itemsContainer');
    const logDiv = document.getElementById('logMessages');
    const shootSelfBtn = document.getElementById('shootSelfBtn');
    const shootEnemyBtn = document.getElementById('shootEnemyBtn');
    const resetBtn = document.getElementById('resetGameBtn');
    const playerCard = document.getElementById('playerCard');
    const demonCard = document.getElementById('demonCard');
    const bulletTypeUnknownSpan = document.getElementById('bulletTypeUnknown');

    function addLog(msg, isError = false) {
        const p = document.createElement('div');
        p.innerHTML = `> ${msg}`;
        p.style.color = isError ? '#ff9696' : '#f0cf9f';
        p.style.marginTop = '4px';
        logDiv.appendChild(p);
        p.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        while(logDiv.children.length > 20) logDiv.removeChild(logDiv.firstChild);
    }

    function updateHealthUI() {
        playerHpSpan.innerText = playerHP;
        demonHpSpan.innerText = demonHP;
        playerHealthFill.style.width = `${(playerHP/maxHP)*100}%`;
        demonHealthFill.style.width = `${(demonHP/maxHP)*100}%`;
    }

    function updateBulletUI() {
        let remain = currentBullets.length - currentBulletIndex;
        bulletsRemainSpan.innerText = Math.max(0, remain);
        if (!revealedBullet || currentBulletIndex >= currentBullets.length) {
            bulletTypeUnknownSpan.innerText = '❓ 未知';
        } else {
            let type = currentBullets[currentBulletIndex] === 'live' ? '💥实弹' : '🍃空包';
            bulletTypeUnknownSpan.innerText = type;
        }
    }

    function updateDamageBuffUI() {
        damageBuffSpan.innerHTML = `⚡ 额外伤害: +${extraDamage}`;
        damageBuffSpan.style.color = extraDamage > 0 ? '#ffb347' : '#ffbf69';
    }

    function reloadBullets() {
        const total = Math.floor(Math.random() * 4) + 3;
        let liveCount = Math.floor(Math.random() * (total-1)) + 1;
        let blankCount = total - liveCount;
        if(blankCount === 0) { blankCount = 1; liveCount = total-1; }
        if(liveCount === 0) { liveCount = 1; blankCount = total-1; }
        let newBullets = [];
        for(let i=0;i<liveCount;i++) newBullets.push('live');
        for(let i=0;i<blankCount;i++) newBullets.push('blank');
        for(let i=newBullets.length-1;i>0;i--) {
            const j = Math.floor(Math.random()*(i+1));
            [newBullets[i], newBullets[j]] = [newBullets[j], newBullets[i]];
        }
        currentBullets = newBullets;
        currentBulletIndex = 0;
        revealedBullet = false;
        updateBulletUI();
        addLog(`🔄 恶魔重新装填了霰弹枪,装入 ${currentBullets.length} 发子弹 (实弹 ${liveCount} / 空包 ${blankCount})`, false);
    }

    function consumeBullet() {
        if(currentBulletIndex >= currentBullets.length) reloadBullets();
        if(currentBulletIndex >= currentBullets.length) return 'blank';
        const bullet = currentBullets[currentBulletIndex];
        currentBulletIndex++;
        if(currentBulletIndex >= currentBullets.length) {
            addLog(`⚙️ 弹匣已空,恶魔快速重新装填!`, false);
            reloadBullets();
        }
        updateBulletUI();
        return bullet;
    }

    function playGunTransferAnimation(fromElement, toElement) {
        const fromRect = fromElement.getBoundingClientRect();
        const toRect = toElement.getBoundingClientRect();
        const gunDiv = document.createElement('div');
        gunDiv.className = 'gun-transfer';
        gunDiv.innerText = '🔫';
        gunDiv.style.left = fromRect.left + fromRect.width/2 - 20 + 'px';
        gunDiv.style.top = fromRect.top + fromRect.height/2 - 30 + 'px';
        gunDiv.style.opacity = '1';
        document.body.appendChild(gunDiv);
        const deltaX = toRect.left + toRect.width/2 - (fromRect.left + fromRect.width/2);
        const deltaY = toRect.top + toRect.height/2 - (fromRect.top + fromRect.height/2);
        gunDiv.style.transform = `translate(${deltaX}px, ${deltaY}px) rotate(20deg) scale(1.2)`;
        setTimeout(() => {
            gunDiv.style.opacity = '0';
            setTimeout(() => gunDiv.remove(), 400);
        }, 350);
    }

    function shakeScreen() {
        document.body.classList.add('shake-effect');
        setTimeout(() => document.body.classList.remove('shake-effect'), 300);
    }

    function playItemAnimation(buttonElement, effectName) {
        if(buttonElement) {
            buttonElement.classList.add('item-flash');
            setTimeout(() => buttonElement.classList.remove('item-flash'), 400);
        }
        if(effectName === 'saw') {
            const container = document.querySelector('.game-container');
            const mark = document.createElement('div');
            mark.className = 'saw-effect';
            mark.style.position = 'absolute';
            mark.style.left = '30%';
            mark.style.top = '-10px';
            container.appendChild(mark);
            setTimeout(() => mark.remove(), 400);
        } else if(effectName === 'magnify') {
            const hint = document.getElementById('nextBulletHint');
            hint.classList.add('magnify-glow');
            setTimeout(() => hint.classList.remove('magnify-glow'), 500);
        } else if(effectName === 'heal') {
            playerCard.classList.add('hit-effect');
            setTimeout(() => playerCard.classList.remove('hit-effect'), 300);
        }
    }

    // 核心射击结算,返回 { gameEnded, wasLive }
    async function resolveShoot(target) {
        let bullet = consumeBullet();
        let isLive = (bullet === 'live');
        let damage = isLive ? (1 + extraDamage) : 0;
        let usedDamage = extraDamage;
        extraDamage = 0;
        updateDamageBuffUI();
        
        if(damage > 0) {
            addLog(`💥 子弹命中! [${isLive ? '实弹' : '空包'}] 造成 ${damage} 点伤害!${usedDamage>0 ? ' (+锯子增伤)' : ''}`, true);
            if(target === 'player') {
                playerHP = Math.max(0, playerHP - damage);
                addLog(`🔥 你受到了 ${damage} 伤害!`, true);
                playerCard.classList.add('hit-effect');
                setTimeout(()=> playerCard.classList.remove('hit-effect'), 250);
                shakeScreen();
            } else {
                demonHP = Math.max(0, demonHP - damage);
                addLog(`😈 恶魔遭受 ${damage} 重伤!`, false);
                demonCard.classList.add('hit-effect');
                setTimeout(()=> demonCard.classList.remove('hit-effect'), 250);
                shakeScreen();
            }
        } else {
            addLog(`🍃 空包!!! 没有造成伤害...`, false);
        }
        updateHealthUI();
        
        if(playerHP <= 0) {
            gameOver = true;
            addLog(`☠️ 你已死亡... 恶魔轮盘赢走了你的灵魂 ☠️`, true);
            disableGameActions(true);
            return { gameEnded: true, wasLive: isLive };
        } else if(demonHP <= 0) {
            gameOver = true;
            addLog(`🎉 胜利!你击溃了恶魔,夺回灵魂契约! 🎉`, false);
            disableGameActions(true);
            return { gameEnded: true, wasLive: isLive };
        }
        return { gameEnded: false, wasLive: isLive };
    }

    // 统一回合切换逻辑 + 射击
    async function performShoot(target, shooterIsPlayer) {
        if(gameOver) return;
        if(shooterIsPlayer && turn !== 'player') {
            addLog(`⚠️ 现在不是你的回合!`, true);
            return;
        }
        if(processingAction) return;
        processingAction = true;
        disableButtonsDuringAction(true);
        
        // 开枪动画
        const shooterCard = (shooterIsPlayer ? (target === 'player' ? playerCard : demonCard) : demonCard);
        shooterCard.classList.add('shoot-animation');
        setTimeout(() => shooterCard.classList.remove('shoot-animation'), 200);
        await new Promise(r => setTimeout(r, 100));
        
        const result = await resolveShoot(target);
        if(result.gameEnded) {
            processingAction = false;
            disableButtonsDuringAction(false);
            return;
        }
        
        // 回合切换判断:实弹(命中)才换回合;空包继续当前角色行动
        let shouldSwitch = result.wasLive;
        
        if(shouldSwitch) {
            // 枪权转移动画
            playGunTransferAnimation(shooterCard, (turn === 'player') ? demonCard : playerCard);
            await new Promise(r => setTimeout(r, 200));
            // 切换turn
            if(turn === 'player') turn = 'demon';
            else turn = 'player';
            updateTurnHighlight();
            addLog(`🔫 枪权转移!${turn === 'player' ? '你的回合' : '恶魔的回合'}`, false);
            if(turn === 'player' && !gameOver) await replenishPlayerItems();
            else if(turn === 'demon' && !gameOver) {
                // 延迟启动恶魔回合,避免与当前异步重叠
                setTimeout(() => { if(!gameOver && turn === 'demon') demonTurnLoop(); }, 200);
            }
        } else {
            // 空包,不换回合,当前行动者继续
            addLog(`🔁 空包未造成伤害,${turn === 'player' ? '你继续持有枪!' : '恶魔继续行动!'}`, false);
            if(turn === 'player' && !gameOver) {
                // 玩家继续,直接解锁按钮
                // 什么都不做,按钮已恢复
            } else if(turn === 'demon' && !gameOver) {
                // 恶魔继续行动(延迟调用避免递归栈)
                setTimeout(() => { if(!gameOver && turn === 'demon') demonTurnLoop(); }, 300);
            }
        }
        processingAction = false;
        disableButtonsDuringAction(false);
    }
    
    // 恶魔行动循环(非递归,可重复触发)
    async function demonTurnLoop() {
        if(gameOver) return;
        if(turn !== 'demon') return;
        if(processingAction) return;
        // 手铐跳过检测
        if(skipDemonTurn) {
            skipDemonTurn = false;
            addLog(`⛓️ 手铐生效!恶魔被禁锢,跳过回合!回合回到你手中`, false);
            playGunTransferAnimation(demonCard, playerCard);
            turn = 'player';
            updateTurnHighlight();
            await replenishPlayerItems();
            return;
        }
        // 恶魔射击玩家
        await performShoot('player', false);
    }
    
    // 玩家主动射击
    async function playerShoot(targetType) {
        const target = (targetType === 'self') ? 'player' : 'demon';
        await performShoot(target, true);
    }
    
    // ---------- 道具系统 ----------
    const itemEffects = {
        '🔪 锯子': (btn) => {
            if(extraDamage < 3) {
                extraDamage++;
                playItemAnimation(btn, 'saw');
                updateDamageBuffUI();
                addLog(`⚔️ 锯子锯断枪管!下次射击伤害+1`, false);
                return true;
            } else { addLog(`⚠️ 伤害加成已达上限`, true); return false; }
        },
        '⛓️ 手铐': (btn) => {
            if(turn === 'player') {
                skipDemonTurn = true;
                playItemAnimation(btn, '');
                addLog(`🔗 手铐锁住恶魔!下一回合恶魔将无法行动`, false);
                return true;
            } else { addLog(`⛔ 只能在自己的回合使用手铐`, true); return false; }
        },
        '🚬 香烟': (btn) => {
            if(playerHP >= maxHP) { addLog(`生命已满`, true); return false; }
            playerHP = Math.min(maxHP, playerHP + 1);
            updateHealthUI();
            playItemAnimation(btn, 'heal');
            addLog(`🚬 香烟恢复 1 点生命`, false);
            return true;
        },
        '💊 医药包': (btn) => {
            if(playerHP >= maxHP) { addLog(`生命已满`, true); return false; }
            let heal = Math.min(2, maxHP - playerHP);
            playerHP += heal;
            updateHealthUI();
            playItemAnimation(btn, 'heal');
            addLog(`💊 医药包恢复 ${heal} 点生命`, false);
            return true;
        },
        '🔍 放大镜': (btn) => {
            if(currentBulletIndex < currentBullets.length) {
                let type = currentBullets[currentBulletIndex];
                let msg = type === 'live' ? '💥 实弹 (致命)' : '🍃 空包 (安全)';
                addLog(`🔍 放大镜窥视: ${msg}`, false);
                revealedBullet = true;
                updateBulletUI();
                playItemAnimation(btn, 'magnify');
                return true;
            } else { addLog(`无法窥探`, true); return false; }
        }
    };
    
    async function replenishPlayerItems() {
        if(gameOver) return;
        if(inventory.length < 6 && turn === 'player') {
            const allItems = ['🔪 锯子', '⛓️ 手铐', '🚬 香烟', '💊 医药包', '🔍 放大镜'];
            const newItem = allItems[Math.floor(Math.random() * allItems.length)];
            inventory.push(newItem);
            addLog(`✨ 恶魔契约献礼,你获得了道具: ${newItem}`, false);
            renderInventory();
        }
    }
    
    function useItem(index, btnElement) {
        if(gameOver) return;
        if(turn !== 'player') { addLog(`只能在自己的回合使用道具`, true); return; }
        if(processingAction) return;
        const itemName = inventory[index];
        if(!itemName) return;
        const effect = itemEffects[itemName];
        if(effect) {
            const success = effect(btnElement);
            if(success) {
                inventory.splice(index,1);
                renderInventory();
                if(itemName === '⛓️ 手铐') {
                    // 手铐使用后立即强制结束玩家回合(但恶魔被跳过)
                    (async () => {
                        processingAction = true;
                        disableButtonsDuringAction(true);
                        addLog(`⛓️ 手铐生效,强制结束回合,恶魔被跳过`, false);
                        playGunTransferAnimation(playerCard, demonCard);
                        await new Promise(r => setTimeout(r, 200));
                        if(!gameOver) {
                            turn = 'demon';
                            updateTurnHighlight();
                            if(skipDemonTurn) {
                                skipDemonTurn = false;
                                addLog(`⛓️ 恶魔被锁,跳过回合回到你的回合`, false);
                                turn = 'player';
                                updateTurnHighlight();
                                playGunTransferAnimation(demonCard, playerCard);
                                await replenishPlayerItems();
                            } else {
                                // 正常恶魔回合,但手铐已经跳过,实际不会到这里
                                if(!gameOver && turn === 'demon') demonTurnLoop();
                            }
                        }
                        processingAction = false;
                        disableButtonsDuringAction(false);
                    })();
                }
            }
        }
    }
    
    function renderInventory() {
        itemsContainer.innerHTML = '';
        if(inventory.length === 0) {
            const emptyDiv = document.createElement('div');
            emptyDiv.innerText = '无道具,每回合开始自动获得一个';
            emptyDiv.style.color = '#c28484';
            itemsContainer.appendChild(emptyDiv);
            return;
        }
        inventory.forEach((item, idx) => {
            const btn = document.createElement('button');
            btn.className = 'item-btn';
            btn.innerText = item;
            btn.onclick = (e) => useItem(idx, btn);
            if(gameOver || turn !== 'player') btn.disabled = true;
            itemsContainer.appendChild(btn);
        });
    }
    
    function updateTurnHighlight() {
        if(turn === 'player') {
            playerCard.classList.add('active-turn');
            demonCard.classList.remove('active-turn');
        } else {
            demonCard.classList.add('active-turn');
            playerCard.classList.remove('active-turn');
        }
        const btnsEnabled = (!gameOver && turn === 'player' && !processingAction);
        shootSelfBtn.disabled = !btnsEnabled;
        shootEnemyBtn.disabled = !btnsEnabled;
        document.querySelectorAll('.item-btn').forEach(btn => btn.disabled = !btnsEnabled);
    }
    
    function disableButtonsDuringAction(disable) {
        if(gameOver) return;
        const playerTurn = turn === 'player';
        shootSelfBtn.disabled = disable || !playerTurn;
        shootEnemyBtn.disabled = disable || !playerTurn;
        document.querySelectorAll('.item-btn').forEach(btn => btn.disabled = disable || !playerTurn);
    }
    
    function disableGameActions(disableGame) {
        shootSelfBtn.disabled = disableGame;
        shootEnemyBtn.disabled = disableGame;
        document.querySelectorAll('.item-btn').forEach(btn => btn.disabled = disableGame);
    }
    
    function resetGame() {
        gameOver = false;
        processingAction = false;
        playerHP = maxHP;
        demonHP = maxHP;
        extraDamage = 0;
        skipDemonTurn = false;
        turn = 'player';
        inventory = [];
        revealedBullet = false;
        updateHealthUI();
        updateDamageBuffUI();
        reloadBullets();
        inventory = ['🔪 锯子', '🔍 放大镜'];
        renderInventory();
        addLog(`🔥 赌局重启!规则: 实弹换回合,空包继续行动,恶魔AI不再卡死`, false);
        updateTurnHighlight();
        disableGameActions(false);
        while(logDiv.children.length > 8) logDiv.removeChild(logDiv.firstChild);
    }
    
    // 绑定事件
    shootSelfBtn.onclick = () => playerShoot('self');
    shootEnemyBtn.onclick = () => playerShoot('enemy');
    resetBtn.onclick = () => resetGame();
    
    function initGame() { resetGame(); }
    initGame();
</script>
</body>
</html>