在你自己的电脑上运行《群星连结》

· · 休闲·娱乐

想玩《群星连结》但机房没外网?没关系,《群星连结》完全离线,你可以在自己的电脑上运行,而且十分简单。

新建文件夹

新建一个文件夹(其实不建也没关系),打开“显示文件扩展名”

index.html

在文件夹中创建一个文本文档,粘贴下面这坨东西,并重命名index.html:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>群星连结</title>
    <link rel="stylesheet" href="style.css" />
</head>
<body>
    <div id="app">
        <header class="header">
            <h1>✦ 群星连结 ✦ </h1>
            <div class="info">
                <span>🏁 回合 <span id="turnDisplay" class="badge">0</span></span>
                <span>⚔️ <span id="phaseDisplay" class="badge">等待开始</span></span>
                <span>📦 状态 <span id="statusDisplay" class="badge" style="background:#2a3344;">准备</span></span>
            </div>
            <div class="controls">
                <button class="primary" id="btnStep">▶ 下一步</button>
                <button class="primary" id="btnAuto">⏩ 自动 (AI Alice)</button>
                <button id="btnEdit">✎ 编辑阵容</button>
                <button id="btnCodex">📖 图鉴</button>
                <button id="btnReset">⟳ 重置</button>
            </div>
        </header>
        <div class="battlefield">
            <div class="side alice-side">
                <div class="side-title">
                    <span>🌌 Alice <span style="font-weight:400;font-size:13px;color:#8899bb;">(点击角色行动)</span></span>
                    <span class="tag">玩家</span>
                </div>
                <div class="char-grid" id="aliceGrid"></div>
            </div>
            <div class="side bob-side">
                <div class="side-title"><span>🌠 Bob</span><span class="tag">AI</span></div>
                <div class="char-grid" id="bobGrid"></div>
            </div>
        </div>
        <div id="actionHint" class="action-hint">点击 Alice 角色进行行动</div>
        <div class="log-section">
            <div class="log-header">
                <h3>📜 战斗日志</h3>
                <button class="log-clear" id="btnClearLog">清除</button>
            </div>
            <div class="log-box" id="logBox"></div>
        </div>
    </div>

    <!-- ====== 配置 & 教程模态框 ====== -->
    <div id="setupModal" class="modal open">
        <div class="modal-content setup-content">
            <h2 id="setupTitle">⚙️ 阵容配置</h2>
            <!-- 教程区域 -->
            <div id="tutorialArea" style="display:none;">
                <div id="tutorialStep" style="font-size:15px;line-height:1.8;color:#c8d0dd;margin-bottom:16px;"></div>
                <div style="display:flex;gap:12px;justify-content:center;">
                    <button id="tutorialPrev" style="padding:6px 20px;background:#2a3344;border:none;border-radius:30px;color:#c8d0dd;cursor:pointer;">上一步</button>
                    <button id="tutorialNext" class="primary" style="padding:6px 20px;background:#3a6ea5;border:none;border-radius:30px;color:#fff;cursor:pointer;">下一步</button>
                    <button id="tutorialSkip" style="padding:6px 20px;background:#a5433a;border:none;border-radius:30px;color:#fff;cursor:pointer;">跳过教程</button>
                </div>
            </div>
            <!-- 配置表单 -->
            <div id="setupEditor" style="display:none;">
                <!-- 难度选择 -->
                <div style="display:flex;align-items:center;gap:16px;margin-bottom:20px;background:#10161f;padding:10px 16px;border-radius:12px;border:1px solid #2a3344;">
                    <label style="font-weight:600;color:#f0c674;">🎯 难度</label>
                    <select id="difficultySelect" style="background:#0d121c;color:#e8edf5;border:1px solid #2a3344;border-radius:6px;padding:4px 12px;font-size:15px;">
                        <option value="easy">简单</option>
                        <option value="normal" selected>普通</option>
                        <option value="hard">困难</option>
                    </select>
                    <span style="font-size:13px;color:#8899bb;margin-left:8px;">(影响 Bob 的强度/策略)</span>
                </div>
                <div id="editForm"></div>
                <div class="modal-actions">
                    <button id="btnStartGame" class="primary" style="background:#6ab07a;border-color:#6ab07a;">🚀 开始游戏</button>
                    <button id="btnSetupCodex" style="background:#2a3344;color:#c8d0dd;">📖 查看图鉴</button>
                </div>
            </div>
            <!-- 欢迎 -->
            <div id="welcomeArea">
                <p style="color:#b0c0dd;text-align:center;font-size:16px;margin:12px 0 20px;">欢迎来到群星连结!请先配置你的 Alice 阵容。</p>
                <div style="display:flex;gap:16px;justify-content:center;flex-wrap:wrap;">
                    <button id="btnStartTutorial" class="primary" style="background:#f0c674;color:#1a212d;">🎓 新手教程</button>
                    <button id="btnSkipToConfig" style="background:#3a6ea5;color:#fff;padding:6px 24px;">跳过教程,开始配置</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 图鉴模态框 -->
    <div id="codexModal" class="modal">
        <div class="modal-content codex-content">
            <h2>📖 天赋 & 技能图鉴</h2>
            <div class="codex-grid">
                <div class="codex-col">
                    <h3>🌟 天赋</h3>
                    <div id="talentCodex"></div>
                </div>
                <div class="codex-col">
                    <h3>⚡ 技能</h3>
                    <div id="skillCodex"></div>
                </div>
            </div>
            <div class="modal-actions">
                <button id="btnCloseCodex">关闭</button>
            </div>
        </div>
    </div>

    <script src="script.js"></script>
</body>
</html>

style.css

在文件夹中创建一个文本文档,粘贴下面这坨东西,并重命名style.css:

/* ========== 全局 ========== */
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}
body {
    font-family: 'Segoe UI', 'PingFang SC', Roboto, sans-serif;
    background: #0b0e14;
    color: #e8edf5;
    padding: 20px;
    min-height: 100vh;
    display: flex;
    justify-content: center;
}
#app {
    max-width: 1400px;
    width: 100%;
    background: #141a24;
    border-radius: 24px;
    padding: 24px 28px 32px;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.7);
    border: 1px solid #2a3344;
}

/* ========== 头部 ========== */
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 12px 20px;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #2a3344;
}
.header h1 {
    font-weight: 600;
    font-size: 26px;
    background: linear-gradient(135deg, #f0c674, #e6b450);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    letter-spacing: 1px;
}
.header .info {
    display: flex;
    gap: 20px;
    font-size: 15px;
    background: #1e2633;
    padding: 6px 18px;
    border-radius: 40px;
    border: 1px solid #2f3a4e;
}
.header .info span {
    display: flex;
    align-items: center;
    gap: 6px;
}
.badge {
    background: #2f3a4e;
    padding: 2px 12px;
    border-radius: 30px;
    font-weight: 600;
    font-size: 14px;
}
.badge.alice {
    background: #3a6ea5;
}
.badge.bob {
    background: #a5433a;
}
.controls {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}
.controls button {
    padding: 8px 20px;
    border: none;
    border-radius: 30px;
    font-weight: 600;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.2s;
    background: #2a3344;
    color: #c8d0dd;
    border: 1px solid #3d4a60;
}
.controls button:hover {
    background: #3d4a60;
    color: #fff;
}
.controls button.primary {
    background: #3a6ea5;
    border-color: #4a8ac0;
    color: #fff;
}
.controls button.primary:hover {
    background: #4a8ac0;
}
.controls button.danger {
    background: #a5433a;
    border-color: #c55a4a;
    color: #fff;
}
.controls button.danger:hover {
    background: #c55a4a;
}
.controls button:disabled {
    opacity: 0.4;
    cursor: not-allowed;
}

/* ========== 战场 ========== */
.battlefield {
    display: flex;
    gap: 20px;
    margin-top: 12px;
    min-height: 360px;
}
.side {
    flex: 1;
    background: #10161f;
    border-radius: 16px;
    padding: 16px 14px;
    border: 1px solid #232d3d;
    min-width: 0;
}
.side.alice-side {
    border-color: #3a6ea5;
}
.side.bob-side {
    border-color: #a5433a;
}
.side-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.side-title .tag {
    font-size: 12px;
    background: #1e2633;
    padding: 2px 14px;
    border-radius: 30px;
    color: #8899bb;
}
.char-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(170px, 1fr));
    gap: 12px;
}

/* ========== 角色卡 ========== */
.char-card {
    background: #1a212d;
    border-radius: 14px;
    padding: 14px 12px 12px;
    border: 1px solid #2a3344;
    transition: all 0.15s;
    position: relative;
    cursor: default;
}
.char-card.clickable {
    cursor: pointer;
    border-color: #f0c674;
    box-shadow: 0 0 12px rgba(240, 198, 116, 0.3);
}
.char-card.clickable:hover {
    background: #232d3d;
    transform: scale(1.02);
}
.char-card.dead {
    opacity: 0.35;
    filter: grayscale(0.7);
    border-color: #3a2a2a;
    cursor: default;
    pointer-events: none;
}
.char-card .char-id {
    font-weight: 700;
    font-size: 13px;
    color: #8899bb;
    display: inline-block;
    background: #232d3d;
    padding: 0 10px;
    border-radius: 20px;
    margin-bottom: 6px;
}
.char-card .char-name {
    font-weight: 600;
    font-size: 15px;
    margin-bottom: 4px;
}
.bar-row {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    margin-top: 4px;
}
.bar-row .label {
    width: 28px;
    font-weight: 600;
    color: #8899bb;
    flex-shrink: 0;
}
.bar-track {
    flex: 1;
    height: 10px;
    background: #2a3344;
    border-radius: 20px;
    overflow: hidden;
    position: relative;
}
.bar-track .fill {
    height: 100%;
    border-radius: 20px;
    transition: width 0.25s ease;
}
.bar-track .fill.hp {
    background: linear-gradient(90deg, #d45a4a, #e07a5a);
}
.bar-track .fill.mp {
    background: linear-gradient(90deg, #4a8ac0, #6ab0e6);
}
.bar-row .value {
    min-width: 36px;
    text-align: right;
    font-size: 11px;
    color: #b0c0dd;
    flex-shrink: 0;
}
.stats-row {
    display: flex;
    gap: 12px;
    font-size: 11px;
    color: #8899bb;
    margin-top: 6px;
    flex-wrap: wrap;
}
.stats-row span {
    background: #10161f;
    padding: 0 8px;
    border-radius: 12px;
    border: 1px solid #1e2633;
}
.stats-row .highlight {
    color: #e8edf5;
}
.talent-skill {
    font-size: 11px;
    margin-top: 6px;
    color: #99aac8;
    display: flex;
    flex-wrap: wrap;
    gap: 2px 8px;
}
.talent-skill .ts-label {
    color: #6a7a99;
}
.talent-skill .ts-val {
    color: #d0dcee;
}

/* ========== 提示 ========== */
.action-hint {
    text-align: center;
    font-size: 16px;
    font-weight: 500;
    padding: 10px;
    margin: 10px 0 0;
    background: #1e2633;
    border-radius: 40px;
    border: 1px solid #2f3a4e;
    color: #f0c674;
    transition: all 0.2s;
    min-height: 48px;
}
.action-hint.idle {
    color: #8899bb;
    border-color: #2a3344;
}

/* ========== 日志 ========== */
.log-section {
    margin-top: 20px;
    border-top: 1px solid #232d3d;
    padding-top: 16px;
}
.log-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
}
.log-header h3 {
    font-size: 15px;
    font-weight: 500;
    color: #99aac8;
}
.log-header .log-clear {
    background: none;
    border: none;
    color: #5a6a88;
    cursor: pointer;
    font-size: 12px;
}
.log-header .log-clear:hover {
    color: #99aac8;
}
.log-box {
    background: #0d121c;
    border-radius: 12px;
    padding: 10px 14px;
    max-height: 220px;
    overflow-y: auto;
    font-size: 13px;
    line-height: 1.6;
    font-family: 'JetBrains Mono', 'Consolas', monospace;
    border: 1px solid #1a212d;
}
.log-box .log-entry {
    padding: 2px 0;
    border-bottom: 1px solid #141a24;
}
.log-box .log-entry .time {
    color: #4a5a78;
    margin-right: 10px;
}
.log-box .log-entry .msg .hl-dead {
    color: #d45a4a;
    font-weight: 700;
}
.log-box .log-entry .msg .hl-heal {
    color: #6ab07a;
}
.log-box .log-entry .msg .hl-energy {
    color: #6ab0e6;
}
.log-box .log-entry .msg .hl-dmg {
    color: #e07a5a;
}

/* ========== 模态框(通用) ========== */
.modal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.7);
    align-items: center;
    justify-content: center;
}
.modal.open {
    display: flex;
}
.modal-content {
    background: #1a212d;
    padding: 30px;
    border-radius: 24px;
    max-width: 700px;
    width: 90%;
    max-height: 80vh;
    overflow-y: auto;
    border: 1px solid #2a3344;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.8);
}
.modal-content h2 {
    margin-bottom: 20px;
    color: #f0c674;
    text-align: center;
}
.modal-actions {
    display: flex;
    gap: 14px;
    justify-content: flex-end;
    margin-top: 20px;
}
.modal-actions button {
    padding: 8px 24px;
    border: none;
    border-radius: 30px;
    font-weight: 600;
    font-size: 14px;
    cursor: pointer;
    transition: 0.2s;
}
.modal-actions #btnApplyEdit {
    background: #3a6ea5;
    color: #fff;
}
.modal-actions #btnApplyEdit:hover {
    background: #4a8ac0;
}
.modal-actions #btnCloseEdit,
.modal-actions #btnCloseCodex {
    background: #2a3344;
    color: #c8d0dd;
}
.modal-actions #btnCloseEdit:hover,
.modal-actions #btnCloseCodex:hover {
    background: #3d4a60;
}

/* ========== 配置 & 教程 ========== */
.setup-content {
    max-width: 800px;
}

/* ---- 教程 ---- */
#tutorialArea {
    background: linear-gradient(145deg, #1a212d, #10161f);
    border-radius: 20px;
    padding: 10px 10px 20px 10px;
    border: 1px solid #2f3a4e;
    box-shadow: inset 0 2px 8px rgba(0,0,0,0.4);
}
#tutorialStep {
    background: #0d121c;
    padding: 20px 24px;
    border-radius: 14px;
    border: 1px solid #2a3344;
    min-height: 130px;
    margin: 12px 0 16px 0;
    font-size: 16px;
    line-height: 1.8;
    box-shadow: 0 4px 12px rgba(0,0,0,0.3);
}
#tutorialStep .highlight {
    color: #f0c674;
    font-weight: 600;
}
#tutorialStep .em {
    color: #6ab0e6;
    font-weight: 500;
}
#tutorialStep .title {
    font-size: 20px;
    font-weight: 700;
    color: #f0c674;
    display: block;
    margin-bottom: 6px;
    border-bottom: 1px solid #2a3344;
    padding-bottom: 6px;
}
.tutorial-progress {
    display: flex;
    justify-content: center;
    gap: 10px;
    margin: 12px 0 16px 0;
}
.tutorial-dot {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background: #2a3344;
    transition: background 0.3s;
    border: 1px solid #3d4a60;
}
.tutorial-dot.active {
    background: #f0c674;
    border-color: #f0c674;
    box-shadow: 0 0 12px rgba(240,198,116,0.5);
}
.tutorial-dot.done {
    background: #6ab07a;
    border-color: #6ab07a;
}
#tutorialPrev, #tutorialNext, #tutorialSkip {
    padding: 6px 24px;
    border: none;
    border-radius: 30px;
    font-weight: 600;
    font-size: 14px;
    cursor: pointer;
    transition: 0.2s;
}
#tutorialPrev {
    background: #2a3344;
    color: #c8d0dd;
}
#tutorialPrev:hover {
    background: #3d4a60;
}
#tutorialNext {
    background: #3a6ea5;
    color: #fff;
}
#tutorialNext:hover {
    background: #4a8ac0;
}
#tutorialSkip {
    background: #a5433a;
    color: #fff;
}
#tutorialSkip:hover {
    background: #c55a4a;
}

/* ---- 配置表单 ---- */
.char-edit {
    background: #10161f;
    border-radius: 12px;
    padding: 14px;
    margin-bottom: 14px;
    border: 1px solid #2a3344;
}
.char-edit h3 {
    color: #99aac8;
    margin-bottom: 10px;
    font-size: 16px;
}
.edit-row {
    display: flex;
    flex-wrap: wrap;
    gap: 8px 14px;
    margin: 6px 0;
    align-items: center;
}
.edit-row label {
    font-size: 13px;
    color: #8899bb;
    min-width: 60px;
}
.edit-row input, .edit-row select {
    background: #0d121c;
    border: 1px solid #2a3344;
    border-radius: 6px;
    padding: 4px 8px;
    color: #e8edf5;
    font-size: 13px;
}
.edit-row input {
    width: 60px;
}
.edit-row select {
    width: 140px;
    min-width: 100px;
    cursor: pointer;
}
.edit-row select option {
    background: #1a212d;
}
.edit-row input[type="number"] {
    -moz-appearance: textfield;
}
.edit-row input[type="number"]::-webkit-inner-spin-button,
.edit-row input[type="number"]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}
.edit-row .info-btn {
    background: #2a3344;
    border: none;
    border-radius: 30px;
    color: #99aac8;
    cursor: pointer;
    font-size: 14px;
    padding: 0 10px;
    line-height: 28px;
}
.edit-row .info-btn:hover {
    background: #3d4a60;
    color: #e8edf5;
}

/* ========== 图鉴(修复样式) ========== */
.codex-content {
    max-width: 900px;
}
.codex-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 30px;
}
.codex-col h3 {
    color: #f0c674;
    border-bottom: 1px solid #2a3344;
    padding-bottom: 8px;
    margin-bottom: 12px;
    font-size: 18px;
}
.codex-item {
    background: #10161f;
    border-radius: 10px;
    padding: 10px 14px;
    margin-bottom: 10px;
    border-left: 3px solid #3a6ea5;
}
.codex-item .codex-id {
    font-weight: 700;
    color: #8899bb;
    display: inline-block;
    background: #232d3d;
    padding: 0 10px;
    border-radius: 20px;
    font-size: 12px;
    margin-right: 8px;
}
.codex-item .codex-name {
    font-weight: 600;
    font-size: 15px;
    color: #e8edf5;
}
.codex-item .codex-desc {
    font-size: 13px;
    color: #b0c0dd;
    margin-top: 4px;
}
.codex-item .codex-params {
    font-size: 12px;
    color: #6a7a99;
    margin-top: 2px;
}
.codex-item .codex-params em {
    color: #f0c674;
    font-style: normal;
}

/* ========== 响应式 ========== */
@media (max-width: 700px) {
    .codex-grid {
        grid-template-columns: 1fr;
        gap: 16px;
    }
}
@media (max-width: 600px) {
    #app {
        padding: 12px;
    }
    .header h1 {
        font-size: 20px;
    }
    .header .info {
        font-size: 12px;
        padding: 4px 12px;
        flex-wrap: wrap;
    }
    .controls button {
        font-size: 12px;
        padding: 6px 14px;
    }
    .char-grid {
        grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
    }
    .modal-content {
        padding: 16px;
    }
    .setup-content {
        max-width: 100%;
    }
    .edit-row select {
        width: 110px;
    }
}
.log-box::-webkit-scrollbar {
    width: 4px;
}
.log-box::-webkit-scrollbar-track {
    background: #0d121c;
}
.log-box::-webkit-scrollbar-thumb {
    background: #2a3344;
    border-radius: 10px;
}

script.js

在文件夹中创建一个文本文档,粘贴下面这坨东西,并重命名script.js:

// ---------- 工具 ----------
function clamp(v, lo, hi) { return Math.max(lo, Math.min(hi, v)); }
function deepClone(obj) { return JSON.parse(JSON.stringify(obj)); }

// ---------- 全局状态 ----------
const G = {
    turn: 0,
    phase: 'idle',
    winner: null,
    alice: [],
    bob: [],
    effects: [],
    log: [],
    autoTimer: null,
    stepLock: false,
    waitingForPlayer: false,
    aliceConfig: null,
    selectingChar: null,
    selectedTarget: null,
    tutorialStep: 0,
    tutorialTotal: 6,
    difficulty: 'normal',
};

// ---------- 创建角色 ----------
function makeChar(id, hp, mp, atk, def, priority, talent, skill) {
    return {
        id: id,
        HP: hp,
        hp: hp,
        MP: mp,
        mp: 0,
        atk: atk,
        def: def,
        dAtk: 0,
        dDef: 0,
        priority: priority.slice(),
        talent: { type: talent[0], x: talent[1] || 0, y: talent[2] || 0, z: talent[3] || 0 },
        skill: { type: skill[0], x: skill[1] || 0, y: skill[2] || 0, z: skill[3] || 0 },
        alive: true,
        skillReplaced: false,
        side: null,
    };
}

function getA(c) { return Math.max(c.atk + c.dAtk, 1); }
function getD(c) { return Math.max(c.def + c.dDef, 0); }
function isAlive(c) { return c && c.alive && c.hp > 0; }
function getAlive(side) { return side.filter(c => isAlive(c)); }
function allDead(side) { return side.every(c => !isAlive(c)); }

function getPriorityTarget(attacker, enemySide) {
    const alive = getAlive(enemySide);
    if (alive.length === 0) return null;
    const order = attacker.priority;
    for (let idx of order) {
        const target = enemySide.find(c => c.id === idx && isAlive(c));
        if (target) return target;
    }
    return alive[0];
}

function applyDamage(target, dmg, realDmg) {
    if (!isAlive(target)) return { hpLost: 0, realReduced: 0 };
    const D = getD(target);
    let dmgAfter = Math.max(dmg - D, 0);
    let realAfter = realDmg;
    if (target.talent.type === 1) {
        realAfter = realAfter - Math.floor(realAfter / 2);
    }
    const total = dmgAfter + realAfter;
    if (total <= 0) return { hpLost: 0, realReduced: 0 };
    const old = target.hp;
    target.hp = Math.max(0, target.hp - total);
    const lost = old - target.hp;
    if (target.hp <= 0) {
        target.alive = false;
        target.hp = 0;
    }
    return { hpLost: lost, realReduced: realAfter };
}

function addEnergy(target, amount) {
    if (!isAlive(target)) return 0;
    const old = target.mp;
    target.mp = Math.min(target.MP, target.mp + amount);
    return target.mp - old;
}
function spendEnergy(target) {
    if (!isAlive(target) || target.mp < target.MP) return false;
    target.mp = 0;
    return true;
}

// ---------- 执行技能(完整,略) ----------
function executeSkill(caster, enemySide, logCb, turn) {
    const sk = caster.skill;
    const type = sk.type;
    const x = sk.x, y = sk.y, z = sk.z;
    const A = getA(caster);
    const aliveEnemy = getAlive(enemySide);

    function damageAllEnemy(dmg, realDmg) {
        let total = 0;
        for (let e of aliveEnemy) {
            const r = applyDamage(e, dmg, realDmg);
            total += r.hpLost;
            if (!isAlive(e)) logCb(`💀 ${e.id} 死亡`, 'dead');
        }
        return total;
    }
    function damagePriority(realDmg) {
        const target = getPriorityTarget(caster, enemySide);
        if (!target) return 0;
        const r = applyDamage(target, 0, realDmg);
        if (!isAlive(target)) logCb(`💀 ${target.id} 死亡`, 'dead');
        return r.hpLost;
    }
    function healAllFriend(amount) {
        const friends = (caster.side === 'alice') ? G.alice : G.bob;
        let total = 0;
        for (let f of getAlive(friends)) {
            const old = f.hp;
            f.hp = Math.min(f.HP, f.hp + amount);
            total += f.hp - old;
        }
        return total;
    }
    function healLowestFriend(amount) {
        const friends = (caster.side === 'alice') ? G.alice : G.bob;
        const alive = getAlive(friends);
        if (alive.length === 0) return 0;
        let lowest = alive[0];
        for (let f of alive) {
            if (f.hp < lowest.hp || (f.hp === lowest.hp && f.id < lowest.id)) lowest = f;
        }
        const old = lowest.hp;
        lowest.hp = Math.min(lowest.HP, lowest.hp + amount);
        return lowest.hp - old;
    }
    function addEffect(type, target, side, x, y, z, duration, sourceId) {
        if (duration <= 0) return;
        const effect = {
            type, target, side, x, y, z, remain: duration, sourceId,
            deltaAtk: 0,
            deltaDef: 0,
        };
        if (type === 'atk_buff' || type === 'def_buff' || type === 'atk_debuff' || type === 'def_debuff') {
            const targets = (target === 'self') ? ((side === 'alice') ? G.alice : G.bob) : ((side === 'alice') ? G.bob : G.alice);
            const alive = getAlive(targets);
            let delta = 0;
            if (type === 'atk_buff') delta = y;
            else if (type === 'def_buff') delta = y;
            else if (type === 'atk_debuff') delta = -y;
            else if (type === 'def_debuff') delta = -y;
            for (let c of alive) {
                if (type === 'atk_buff' || type === 'atk_debuff') {
                    c.dAtk += delta;
                } else {
                    c.dDef += delta;
                }
            }
            if (type === 'atk_buff' || type === 'atk_debuff') {
                effect.deltaAtk = delta;
            } else {
                effect.deltaDef = delta;
            }
        }
        G.effects.push(effect);
    }

    logCb(`✨ ${caster.id} 发动技能 ${type} (${['心态崩了','格林炸裂','日昇之雨','天楼霸断剑','演出开始','天狼噬斩','地球蓝闪电','极光绽放','流星','精灵庇护','全力超全开'][type] || type})`);

    switch (type) {
        case 0: logCb(`  毫无效果...`); break;
        case 1: {
            const dmg = x;
            let total = 0;
            for (let e of aliveEnemy) {
                const r = applyDamage(e, dmg, 0);
                total += r.hpLost;
                if (!isAlive(e)) logCb(`💀 ${e.id} 死亡`, 'dead');
            }
            logCb(`  造成 ${total} 点伤害`);
            for (let e of getAlive(enemySide)) {
                const reduce = Math.floor(e.mp / 10);
                e.mp = Math.max(0, e.mp - reduce);
                logCb(`  ${e.id} 能量减少 ${reduce}`);
            }
            break;
        }
        case 2: {
            const real = A;
            let total = 0;
            for (let e of aliveEnemy) {
                const r = applyDamage(e, 0, real);
                total += r.hpLost;
                if (!isAlive(e)) logCb(`💀 ${e.id} 死亡`, 'dead');
            }
            logCb(`  造成 ${total} 点真实伤害`);
            break;
        }
        case 3: {
            let total = 0;
            for (let e of aliveEnemy) {
                const dmg = Math.min(Math.floor(e.HP / 10), x * A);
                const r = applyDamage(e, dmg, 0);
                total += r.hpLost;
                if (!isAlive(e)) logCb(`💀 ${e.id} 死亡`, 'dead');
            }
            logCb(`  造成 ${total} 点伤害`);
            break;
        }
        case 4: {
            addEffect('energy_regen', 'self', caster.side, 0, y, 0, x, caster.id);
            logCb(`  持续 ${x} 回合,己方行动结束额外回复 ${y} 能量`);
            break;
        }
        case 5: {
            const target = getPriorityTarget(caster, enemySide);
            if (target) {
                target.dDef = Math.max(-1000, target.dDef - x);
                logCb(`  ${target.id} 防御力增益 -${x} → ${target.dDef}`);
                const r = applyDamage(target, 0, A);
                if (!isAlive(target)) logCb(`💀 ${target.id} 死亡`, 'dead');
                logCb(`  造成 ${r.hpLost} 点真实伤害`);
            }
            break;
        }
        case 6: {
            const target = getPriorityTarget(caster, enemySide);
            if (target) {
                const r = applyDamage(target, 0, A);
                if (!isAlive(target)) logCb(`💀 ${target.id} 死亡`, 'dead');
                logCb(`  对 ${target.id} 造成 ${r.hpLost} 点真实伤害`);
            }
            addEffect('atk_debuff', 'enemy', caster.side, 0, y, 0, x, caster.id);
            logCb(`  敌方全体攻击力 -${y} 持续 ${x} 回合`);
            break;
        }
        case 7: {
            const healed = healLowestFriend(z);
            logCb(`  己方生命最低回复 ${healed} 点`);
            addEffect('atk_buff', 'self', caster.side, 0, y, 0, x, caster.id);
            logCb(`  己方全体攻击力 +${y} 持续 ${x} 回合`);
            break;
        }
        case 8: {
            let total = 0;
            for (let e of aliveEnemy) {
                const r = applyDamage(e, A, 0);
                total += r.hpLost;
                if (!isAlive(e)) logCb(`💀 ${e.id} 死亡`, 'dead');
            }
            logCb(`  造成 ${total} 点伤害`);
            addEffect('def_debuff', 'enemy', caster.side, 0, y, 0, x, caster.id);
            logCb(`  敌方全体防御力 -${y} 持续 ${x} 回合`);
            break;
        }
        case 9: {
            const healed = healAllFriend(z);
            logCb(`  己方全体回复 ${healed} 点`);
            addEffect('def_buff', 'self', caster.side, 0, y, 0, x, caster.id);
            logCb(`  己方全体防御力 +${y} 持续 ${x} 回合`);
            break;
        }
        case 10: {
            const friends = (caster.side === 'alice') ? G.alice : G.bob;
            for (let f of friends) {
                f.atk = f.atk * 2;
                f.def = f.def * 2;
                f.hp = Math.max(Math.floor(f.HP / 2), f.hp);
                f.mp = Math.max(Math.floor(f.MP / 2), f.mp);
                if (!f.skillReplaced) {
                    f.skill.type = 0;
                    f.skill.x = f.skill.y = f.skill.z = 0;
                    f.skillReplaced = true;
                }
            }
            logCb(`  己方全体 atk/def 翻倍, hp/mp 提升至一半`);
            addEffect('ult_end', 'self', caster.side, 0, 0, 0, x, caster.id);
            addEffect('energy_regen_ult', 'self', caster.side, 0, 1, 0, x, caster.id);
            logCb(`  持续 ${x} 回合,结束时若敌方存活则己方全灭`);
            break;
        }
        default: logCb(`  未知技能类型`);
    }

    if (isAlive(caster) && caster.talent.type === 5) {
        const added = addEnergy(caster, caster.talent.y);
        if (added > 0) logCb(`  [科技至上] ${caster.id} 额外回复 ${added} 能量`);
    }
    if (isAlive(caster)) {
        const after = addEnergy(caster, 1);
        if (after > 0) logCb(`  ${caster.id} 能量 +1 (行动后)`);
    }
}

function executeAttack(attacker, target, dmg, realDmg, logCb) {
    logCb(`⚔️ ${attacker.id} 攻击 ${target.id} (伤害:${dmg} 真实:${realDmg})`);
    const r = applyDamage(target, dmg, realDmg);
    if (r.hpLost > 0) logCb(`  ${target.id} 失去 ${r.hpLost} 点生命 (当前 ${target.hp})`);
    if (!isAlive(target)) logCb(`💀 ${target.id} 死亡`, 'dead');
    if (isAlive(attacker) && attacker.talent.type === 5) {
        const healed = Math.min(attacker.HP - attacker.hp, attacker.talent.x);
        if (healed > 0) { attacker.hp += healed; logCb(`  [科技至上] ${attacker.id} 回复 ${healed} 点生命`); }
    }
    if (isAlive(attacker)) {
        const after = addEnergy(attacker, 1);
        if (after > 0) logCb(`  ${attacker.id} 能量 +1 (行动后)`);
    }
}

function performAction(action, side, enemySide, logCb, turn) {
    const sideChars = (side === 'alice') ? G.alice : G.bob;
    if (action.type === 'skill') {
        const caster = action.char;
        spendEnergy(caster);
        executeSkill(caster, enemySide, logCb, turn);
        for (let c of getAlive(sideChars)) {
            if (c.talent.type === 3) {
                const h = Math.min(c.HP - c.hp, c.talent.x);
                if (h > 0) { c.hp += h; logCb(`  [心胜于物] ${c.id} 回复 ${h} HP`); }
                const e = addEnergy(c, c.talent.y);
                if (e > 0) logCb(`  [心胜于物] ${c.id} 额外回复 ${e} 能量`);
            }
        }
        for (let e of G.effects) {
            if (e.side === side && (e.type === 'energy_regen' || e.type === 'energy_regen_ult')) {
                for (let c of getAlive(sideChars)) {
                    const added = addEnergy(c, e.y);
                    if (added > 0) logCb(`  [持续效果] ${c.id} 额外回复 ${added} 能量`);
                }
            }
        }
    } else if (action.type === 'attack') {
        executeAttack(action.char, action.target, action.dmg, action.realDmg, logCb);
        for (let c of getAlive(sideChars)) {
            if (c.talent.type === 3) {
                const h = Math.min(c.HP - c.hp, c.talent.x);
                if (h > 0) { c.hp += h; logCb(`  [心胜于物] ${c.id} 回复 ${h} HP`); }
                const e = addEnergy(c, c.talent.y);
                if (e > 0) logCb(`  [心胜于物] ${c.id} 额外回复 ${e} 能量`);
            }
        }
        for (let e of G.effects) {
            if (e.side === side && (e.type === 'energy_regen' || e.type === 'energy_regen_ult')) {
                for (let c of getAlive(sideChars)) {
                    const added = addEnergy(c, e.y);
                    if (added > 0) logCb(`  [持续效果] ${c.id} 额外回复 ${added} 能量`);
                }
            }
        }
    }
}

// ---------- AI 行动选择(含困难策略) ----------
function selectAction(side, enemySide, difficulty) {
    const casters = getAlive(side).filter(c => c.mp >= c.MP);
    if (casters.length > 0) {
        casters.sort((a, b) => b.skill.type - a.skill.type || b.id - a.id);
        const chosen = casters[0];
        return { type: 'skill', char: chosen };
    } else {
        const alive = getAlive(side);
        if (alive.length === 0) return null;

        if (difficulty === 'hard') {
            let attacker = alive[0];
            for (let c of alive) {
                if (getA(c) > getA(attacker)) attacker = c;
            }
            const enemyAlive = getAlive(enemySide);
            if (enemyAlive.length === 0) return null;
            let target = enemyAlive[0];
            for (let e of enemyAlive) {
                if (e.hp < target.hp) target = e;
            }
            const A = getA(attacker);
            let dmg = Math.max(A - getD(target), 0);
            let realDmg = 0;
            if (attacker.talent.type === 4) {
                realDmg = A;
                dmg = 0;
            }
            if (attacker.talent.type === 2) realDmg += attacker.talent.x;
            if (target.talent.type === 1) realDmg = realDmg - Math.floor(realDmg / 2);
            return { type: 'attack', char: attacker, target: target, dmg: dmg, realDmg: realDmg };
        }

        let best = null, bestScore = -1;
        for (let c of alive) {
            const target = getPriorityTarget(c, enemySide);
            if (!target) continue;
            const A = getA(c);
            let dmg = Math.max(A - getD(target), 0);
            let realDmg = 0;
            if (c.talent.type === 4) { realDmg = A; dmg = 0; }
            if (c.talent.type === 2) realDmg += c.talent.x;
            if (target.talent.type === 1) realDmg = realDmg - Math.floor(realDmg / 2);
            const totalDmg = Math.max(dmg - getD(target), 0) + realDmg;
            const score = target.hp * 10000 + totalDmg * 100 + c.id;
            if (score > bestScore) {
                bestScore = score;
                best = { char: c, target, dmg, realDmg, totalDmg };
            }
        }
        if (!best) return null;
        return { type: 'attack', char: best.char, target: best.target, dmg: best.dmg, realDmg: best.realDmg };
    }
}

// ---------- 持续效果(正确过期) ----------
function applyEffects(logCb) {
    const toRemove = [];
    for (let i = 0; i < G.effects.length; i++) {
        const e = G.effects[i];
        e.remain--;
        if (e.remain <= 0) {
            if (e.type === 'atk_buff' || e.type === 'def_buff' || e.type === 'atk_debuff' || e.type === 'def_debuff') {
                const targets = (e.target === 'self') ? ((e.side === 'alice') ? G.alice : G.bob) : ((e.side === 'alice') ? G.bob : G.alice);
                const alive = getAlive(targets);
                if (e.type === 'atk_buff' || e.type === 'atk_debuff') {
                    const delta = -e.deltaAtk;
                    for (let c of alive) {
                        c.dAtk += delta;
                    }
                } else {
                    const delta = -e.deltaDef;
                    for (let c of alive) {
                        c.dDef += delta;
                    }
                }
                logCb(`  [效果结束] ${e.type} 已移除`);
            }
            toRemove.push(i);
            continue;
        }
    }
    toRemove.sort((a, b) => b - a);
    for (let idx of toRemove) G.effects.splice(idx, 1);
}

function endTurn(logCb) {
    const toRemove = [];
    for (let i = 0; i < G.effects.length; i++) {
        const e = G.effects[i];
        if (e.type === 'ult_end' && e.remain === 0) {
            const side = (e.side === 'alice') ? G.alice : G.bob;
            const enemySide = (e.side === 'alice') ? G.bob : G.alice;
            if (!allDead(enemySide)) {
                for (let c of getAlive(side)) {
                    c.hp = 0;
                    c.alive = false;
                    logCb(`💀 ${c.id} 被全力超全开反噬死亡`, 'dead');
                }
            }
            toRemove.push(i);
        }
    }
    toRemove.sort((a, b) => b - a);
    for (let idx of toRemove) G.effects.splice(idx, 1);
}

// ---------- 日志 ----------
function log(msg, cls = '') {
    G.log.push({ msg, cls, time: G.turn });
    renderLog();
}
function renderLog() {
    const box = document.getElementById('logBox');
    box.innerHTML = G.log.map(e => {
        let cls = '';
        if (e.msg.includes('死亡')) cls = 'hl-dead';
        else if (e.msg.includes('回复')) cls = 'hl-heal';
        else if (e.msg.includes('能量')) cls = 'hl-energy';
        else if (e.msg.includes('伤害') || e.msg.includes('失去')) cls = 'hl-dmg';
        return `<div class="log-entry"><span class="time">[${e.time}]</span><span class="msg ${cls}">${e.msg}</span></div>`;
    }).join('');
    box.scrollTop = box.scrollHeight;
}

// ---------- UI 更新 ----------
function updateUI() {
    document.getElementById('turnDisplay').textContent = G.turn;
    const phaseMap = {
        'idle': '⏳ 等待',
        'alice_select': '👆 请选择 Alice 行动角色',
        'alice_target_select': '🎯 选择目标与行动',
        'alice_executed': '✅ Alice 已行动',
        'bob_action': '🤖 Bob 行动中',
        'ended': '🏁 已结束'
    };
    document.getElementById('phaseDisplay').textContent = phaseMap[G.phase] || G.phase;
    const status = G.winner ? `🏆 ${G.winner} 胜利` : (G.phase === 'ended' ? '平局?' : '进行中');
    document.getElementById('statusDisplay').textContent = status;
    renderChars('aliceGrid', G.alice, 'alice');
    renderChars('bobGrid', G.bob, 'bob');
    const btnStep = document.getElementById('btnStep');
    const btnAuto = document.getElementById('btnAuto');
    if (G.phase === 'ended') {
        btnStep.disabled = true;
        btnAuto.disabled = true;
    } else {
        btnStep.disabled = false;
        btnAuto.disabled = false;
    }
    const hint = document.getElementById('actionHint');
    if (G.phase === 'alice_select') {
        hint.textContent = '👆 点击 Alice 阵营中高亮的角色进行行动';
        hint.className = 'action-hint';
    } else if (G.phase === 'alice_target_select') {
        hint.textContent = `🎯 选择敌方目标,然后点击下方按钮执行`;
        hint.className = 'action-hint';
    } else if (G.phase === 'idle') {
        hint.textContent = '点击「下一步」开始回合';
        hint.className = 'action-hint idle';
    } else if (G.phase === 'bob_action') {
        hint.textContent = '🤖 Bob 正在思考...';
        hint.className = 'action-hint';
    } else if (G.phase === 'ended') {
        hint.textContent = `🏁 游戏结束!${G.winner || '平局'}`;
        hint.className = 'action-hint';
    } else {
        hint.textContent = '⏳ 处理中...';
        hint.className = 'action-hint';
    }
    updateActionPanel();
}

function renderChars(containerId, side, sideName) {
    const container = document.getElementById(containerId);
    container.innerHTML = side.map(c => {
        const alive = isAlive(c);
        const hpPct = c.HP > 0 ? Math.min(100, (c.hp / c.HP) * 100) : 0;
        const mpPct = c.MP > 0 ? Math.min(100, (c.mp / c.MP) * 100) : 0;
        const A = getA(c);
        const D = getD(c);
        const talentNames = ['自闭', '血肉皮囊', '星河投射', '心胜于物', '超凡入圣', '科技至上'];
        const skillNames = ['心态崩了', '格林炸裂', '日昇之雨', '天楼霸断剑', '演出开始', '天狼噬斩', '地球蓝闪电', '极光绽放', '流星', '精灵庇护', '全力超全开'];
        const tName = talentNames[c.talent.type] || '?';
        const sName = skillNames[c.skill.type] || '?';
        const tParams = c.talent.type === 2 ? `x${c.talent.x}` :
            c.talent.type === 3 ? `${c.talent.x},${c.talent.y}` :
            c.talent.type === 5 ? `${c.talent.x},${c.talent.y}` : '';
        const sParams = c.skill.type === 1 ? `x${c.skill.x}` :
            c.skill.type === 3 ? `x${c.skill.x}` :
            c.skill.type === 4 ? `${c.skill.x},${c.skill.y}` :
            c.skill.type === 5 ? `x${c.skill.x}` :
            c.skill.type === 6 ? `${c.skill.x},${c.skill.y}` :
            c.skill.type === 7 ? `${c.skill.x},${c.skill.y},${c.skill.z}` :
            c.skill.type === 8 ? `${c.skill.x},${c.skill.y}` :
            c.skill.type === 9 ? `${c.skill.x},${c.skill.y},${c.skill.z}` :
            c.skill.type === 10 ? `x${c.skill.x}` : '';
        const deadClass = alive ? '' : 'dead';
        let clickable = false;
        if (sideName === 'alice' && alive && G.phase === 'alice_select') clickable = true;
        if (sideName === 'bob' && alive && G.phase === 'alice_target_select') clickable = true;
        const clickClass = clickable ? 'clickable' : '';
        const dataAttr = `data-char-id="${c.id}" data-side="${sideName}"`;
        return `
            <div class="char-card ${deadClass} ${clickClass}" ${dataAttr}>
                <div class="char-id">#${c.id}</div>
                <div class="char-name">${alive ? '✦' : '✟'} ${c.id}</div>
                <div class="bar-row">
                    <span class="label">HP</span>
                    <div class="bar-track"><div class="fill hp" style="width:${hpPct}%"></div></div>
                    <span class="value">${c.hp}/${c.HP}</span>
                </div>
                <div class="bar-row">
                    <span class="label">MP</span>
                    <div class="bar-track"><div class="fill mp" style="width:${mpPct}%"></div></div>
                    <span class="value">${c.mp}/${c.MP}</span>
                </div>
                <div class="stats-row">
                    <span>⚔️ A=<span class="highlight">${A}</span></span>
                    <span>🛡️ D=<span class="highlight">${D}</span></span>
                    <span>Δatk=${c.dAtk}</span>
                    <span>Δdef=${c.dDef}</span>
                </div>
                <div class="talent-skill">
                    <span><span class="ts-label">天赋</span> ${tName}${tParams ? ' ('+tParams+')' : ''}</span>
                    <span><span class="ts-label">技能</span> ${sName}${sParams ? ' ('+sParams+')' : ''}</span>
                </div>
            </div>
        `;
    }).join('');
    if (sideName === 'alice') {
        container.querySelectorAll('.char-card.clickable').forEach(el => {
            el.addEventListener('click', () => {
                const id = parseInt(el.dataset.charId);
                if (G.phase === 'alice_select' && !G.stepLock) startTargetSelection(id);
            });
        });
    }
    if (sideName === 'bob') {
        container.querySelectorAll('.char-card.clickable').forEach(el => {
            el.addEventListener('click', () => {
                const id = parseInt(el.dataset.charId);
                if (G.phase === 'alice_target_select' && !G.stepLock) selectTarget(id);
            });
        });
    }
}

// ===================== 目标选择与行动 =====================
function createActionPanel() {
    const panel = document.createElement('div');
    panel.id = 'actionPanel';
    panel.style.cssText = `
        display: none;
        position: fixed;
        bottom: 30px;
        left: 50%;
        transform: translateX(-50%);
        background: #1a212d;
        border: 2px solid #f0c674;
        border-radius: 16px;
        padding: 16px 24px;
        z-index: 1000;
        box-shadow: 0 8px 40px rgba(0,0,0,0.9);
        min-width: 320px;
        text-align: center;
        color: #e8edf5;
    `;
    panel.innerHTML = `
        <div style="font-weight:600;margin-bottom:6px;color:#f0c674;">⚡ 选择行动</div>
        <div id="actionTargetInfo" style="font-size:14px;color:#b0c0dd;margin-bottom:10px;"></div>
        <div style="display:flex;gap:12px;justify-content:center;flex-wrap:wrap;">
            <button id="btnPlayerAttack" class="action-btn" style="padding:6px 20px;border:none;border-radius:30px;font-weight:600;background:#3a6ea5;color:#fff;cursor:pointer;">⚔️ 普通攻击</button>
            <button id="btnPlayerSkill" class="action-btn" style="padding:6px 20px;border:none;border-radius:30px;font-weight:600;background:#e6b450;color:#1a212d;cursor:pointer;">✨ 发动技能</button>
            <button id="btnCancelTarget" style="padding:6px 16px;border:none;border-radius:30px;background:#2a3344;color:#c8d0dd;cursor:pointer;">取消</button>
        </div>
    `;
    document.getElementById('app').appendChild(panel);
    document.getElementById('btnPlayerAttack').addEventListener('click', () => executePlayerAction('attack'));
    document.getElementById('btnPlayerSkill').addEventListener('click', () => executePlayerAction('skill'));
    document.getElementById('btnCancelTarget').addEventListener('click', cancelTargetSelection);
}

function updateActionPanel() {
    const panel = document.getElementById('actionPanel');
    const info = document.getElementById('actionTargetInfo');
    if (G.phase === 'alice_target_select' && G.selectingChar) {
        panel.style.display = 'block';
        const char = G.selectingChar;
        const target = G.selectedTarget;
        let targetText = target ? `🎯 目标: ${target.id} (HP ${target.hp}/${target.HP})` : '👆 请点击敌方角色选择目标';
        info.innerHTML = `<span style="color:#f0c674;">${char.id}</span> (能量 ${char.mp}/${char.MP}) &nbsp;→&nbsp; ${targetText}`;
        const skillBtn = document.getElementById('btnPlayerSkill');
        if (char.mp >= char.MP) {
            skillBtn.disabled = false;
            skillBtn.style.opacity = '1';
        } else {
            skillBtn.disabled = true;
            skillBtn.style.opacity = '0.5';
        }
    } else {
        panel.style.display = 'none';
    }
}

function startTargetSelection(charId) {
    if (G.stepLock) return;
    const char = G.alice.find(c => c.id === charId);
    if (!char || !isAlive(char)) { log(`⚠️ 角色 ${charId} 已无法行动`, ''); return; }
    G.selectingChar = char;
    G.selectedTarget = null;
    G.phase = 'alice_target_select';
    G.stepLock = false;
    updateUI();
    log(`🎯 选择 ${char.id} 的行动目标`, '');
}

function selectTarget(charId) {
    if (G.phase !== 'alice_target_select') return;
    const target = G.bob.find(c => c.id === charId);
    if (!target || !isAlive(target)) { log(`⚠️ 目标 ${charId} 已死亡`, ''); return; }
    G.selectedTarget = target;
    updateUI();
    log(`🎯 选中目标 ${target.id}`, '');
}

function cancelTargetSelection() {
    G.selectingChar = null;
    G.selectedTarget = null;
    G.phase = 'alice_select';
    updateUI();
    log(`❌ 取消选择`, '');
}

function executePlayerAction(actionType) {
    if (G.phase !== 'alice_target_select') return;
    if (!G.selectingChar || !isAlive(G.selectingChar)) { log(`⚠️ 己方角色已不可用`, ''); cancelTargetSelection(); return; }
    if (!G.selectedTarget || !isAlive(G.selectedTarget)) { log(`⚠️ 未选择有效目标`, ''); return; }
    const char = G.selectingChar;
    const target = G.selectedTarget;
    let action;
    if (actionType === 'skill') {
        if (char.mp < char.MP) { log(`⚠️ ${char.id} 能量不足,无法发动技能`, ''); return; }
        action = { type: 'skill', char: char };
    } else if (actionType === 'attack') {
        const A = getA(char);
        let dmg = Math.max(A - getD(target), 0);
        let realDmg = 0;
        if (char.talent.type === 4) { realDmg = A; dmg = 0; }
        if (char.talent.type === 2) realDmg += char.talent.x;
        if (target.talent.type === 1) realDmg = realDmg - Math.floor(realDmg / 2);
        action = { type: 'attack', char: char, target: target, dmg: dmg, realDmg: realDmg };
    } else return;
    G.stepLock = true;
    try {
        G.selectingChar = null;
        G.selectedTarget = null;
        G.phase = 'alice_executed';
        updateUI();
        performAction(action, 'alice', G.bob, log, G.turn);
        if (allDead(G.bob)) {
            G.phase = 'ended';
            G.winner = 'Alice';
            updateUI();
            G.stepLock = false;
            if (G.autoTimer) clearInterval(G.autoTimer);
            return;
        }
        G.phase = 'bob_action';
        updateUI();
        setTimeout(() => {
            try {
                if (G.phase === 'ended') { G.stepLock = false; return; }
                bobTurn();
            } catch (err) {
                console.error('Bob 行动异常:', err);
                G.phase = 'idle';
                G.stepLock = false;
                updateUI();
                log(`❌ 异常: ${err.message}`, '');
            }
        }, 300);
    } catch (err) {
        console.error('执行行动异常:', err);
        G.phase = 'idle';
        G.stepLock = false;
        updateUI();
        log(`❌ 异常: ${err.message}`, '');
    }
}

// ===================== Bob 生成 =====================
function randInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function generateRandomBob(difficulty) {
    let hp, mp, atk, def, tX, tY, sX, sY, sZ;
    let talentType, skillType;

    switch (difficulty) {
        case 'easy':
            hp = randInt(5, 15);
            mp = randInt(3, 8);
            atk = randInt(1, 3);
            def = randInt(0, 2);
            talentType = randInt(0, 5);
            skillType = randInt(0, 10);
            break;
        case 'hard':
            hp = randInt(10, 22);
            mp = randInt(6, 12);
            atk = randInt(3, 6);
            def = randInt(1, 4);
            talentType = randInt(1, 5);
            skillType = randInt(1, 9);
            break;
        default:
            hp = randInt(8, 20);
            mp = randInt(5, 10);
            atk = randInt(2, 5);
            def = randInt(0, 3);
            talentType = randInt(1, 5);
            skillType = randInt(1, 9);
            break;
    }

    if (talentType === 2) tX = randInt(1, 3);
    else if (talentType === 3) { tX = randInt(1, 3); tY = randInt(1, 2); }
    else if (talentType === 5) { tX = randInt(1, 3); tY = randInt(1, 2); }
    else { tX = 0; tY = 0; }

    if (skillType === 1 || skillType === 3 || skillType === 5 || skillType === 10) sX = randInt(1, 4);
    else if (skillType === 4 || skillType === 6 || skillType === 7 || skillType === 8 || skillType === 9) {
        sX = randInt(1, 3);
        sY = randInt(1, 3);
        if (skillType === 7 || skillType === 9) sZ = randInt(1, 4);
        else sZ = 0;
    } else {
        sX = 0; sY = 0; sZ = 0;
    }

    return {
        hp, mp, atk, def,
        priority: [1, 2, 3],
        talentType, talentX: tX || 0, talentY: tY || 0,
        skillType, skillX: sX || 0, skillY: sY || 0, skillZ: sZ || 0,
    };
}

function showBobAction(message) {
    const old = document.getElementById('bobActionFloat');
    if (old) old.remove();
    const div = document.createElement('div');
    div.id = 'bobActionFloat';
    div.style.cssText = `
        position: fixed;
        top: 20%;
        left: 50%;
        transform: translateX(-50%);
        background: rgba(165, 67, 58, 0.95);
        color: #fff;
        padding: 18px 36px;
        border-radius: 40px;
        font-size: 22px;
        font-weight: 700;
        z-index: 999;
        border: 2px solid #f0c674;
        box-shadow: 0 0 40px rgba(165,67,58,0.8);
        pointer-events: none;
        text-shadow: 0 2px 8px rgba(0,0,0,0.5);
        white-space: nowrap;
        animation: fadeInOut 2.5s ease forwards;
    `;
    div.textContent = '🤖 ' + message;
    document.body.appendChild(div);
    setTimeout(() => { if (div.parentNode) div.remove(); }, 2800);
}

(function injectBobAnim() {
    if (!document.getElementById('bobAnimStyle')) {
        const style = document.createElement('style');
        style.id = 'bobAnimStyle';
        style.textContent = `
            @keyframes fadeInOut {
                0% { opacity: 0; transform: translateX(-50%) scale(0.8); }
                15% { opacity: 1; transform: translateX(-50%) scale(1); }
                85% { opacity: 1; transform: translateX(-50%) scale(1); }
                100% { opacity: 0; transform: translateX(-50%) scale(0.9); }
            }
        `;
        document.head.appendChild(style);
    }
})();

function bobTurn() {
    if (G.phase === 'ended') { G.stepLock = false; return; }
    try {
        const bobAlive = getAlive(G.bob);
        if (bobAlive.length > 0) {
            const action = selectAction(G.bob, G.alice, G.difficulty);
            if (action) {
                let desc = '';
                if (action.type === 'skill') {
                    const skillNames = ['心态崩了', '格林炸裂', '日昇之雨', '天楼霸断剑', '演出开始', '天狼噬斩', '地球蓝闪电', '极光绽放', '流星', '精灵庇护', '全力超全开'];
                    desc = `${action.char.id} 使用技能「${skillNames[action.char.skill.type] || '?'}」`;
                } else {
                    desc = `${action.char.id} 普通攻击 ${action.target.id}`;
                }
                performAction(action, 'bob', G.alice, log, G.turn);
                showBobAction(desc);
                if (allDead(G.alice)) {
                    G.phase = 'ended';
                    G.winner = 'Bob';
                    updateUI();
                    G.stepLock = false;
                    if (G.autoTimer) clearInterval(G.autoTimer);
                    return;
                }
            } else {
                showBobAction('等待中...');
            }
        } else {
            showBobAction('无存活角色');
        }
        G.phase = 'end';
        applyEffects(log);
        endTurn(log);
        if (allDead(G.alice) || allDead(G.bob)) {
            G.phase = 'ended';
            G.winner = allDead(G.alice) ? 'Bob' : 'Alice';
            updateUI();
            G.stepLock = false;
            return;
        }
        for (let c of getAlive(G.alice)) addEnergy(c, 1);
        for (let c of getAlive(G.bob)) addEnergy(c, 1);
        G.phase = 'idle';
        G.stepLock = false;
        updateUI();
        log(`——— 第 ${G.turn} 回合结束 ———`);
    } catch (err) {
        console.error('bobTurn 异常:', err);
        G.phase = 'idle';
        G.stepLock = false;
        updateUI();
        log(`❌ Bob 行动异常: ${err.message}`, '');
    }
}

// ===================== 重置游戏 =====================
function resetGame() {
    if (G.autoTimer) {
        clearInterval(G.autoTimer);
        G.autoTimer = null;
        document.getElementById('btnAuto').textContent = '⏩ 自动 (AI Alice)';
    }
    G.turn = 0;
    G.phase = 'idle';
    G.winner = null;
    G.effects = [];
    G.log = [];
    G.stepLock = false;
    G.waitingForPlayer = false;
    G.selectingChar = null;
    G.selectedTarget = null;

    const config = G.aliceConfig || getDefaultConfig();
    G.alice = config.map((p, idx) => {
        const c = makeChar(idx+1, p.hp, p.mp, p.atk, p.def, p.priority, [p.talentType, p.talentX, p.talentY, 0], [p.skillType, p.skillX, p.skillY, p.skillZ]);
        c.side = 'alice';
        return c;
    });

    const bobConfigs = [generateRandomBob(G.difficulty), generateRandomBob(G.difficulty), generateRandomBob(G.difficulty)];
    G.bob = bobConfigs.map((p, idx) => {
        const c = makeChar(idx+1, p.hp, p.mp, p.atk, p.def, p.priority, [p.talentType, p.talentX, p.talentY, 0], [p.skillType, p.skillX, p.skillY, p.skillZ]);
        c.side = 'bob';
        return c;
    });

    log(`🔄 游戏已重置(难度: ${G.difficulty})`);
    updateUI();
}

// ===================== 模板系统 =====================
const TEMPLATES = {
    warrior: { name:'战士', hp:12, mp:6, atk:4, def:3, talentType:5, talentX:2, talentY:1, skillType:3, skillX:2, skillY:0, skillZ:0 },
    mage: { name:'法师', hp:6, mp:12, atk:3, def:1, talentType:3, talentX:2, talentY:2, skillType:2, skillX:0, skillY:0, skillZ:0 },
    assassin: { name:'刺客', hp:8, mp:8, atk:6, def:0, talentType:4, talentX:0, talentY:0, skillType:5, skillX:2, skillY:0, skillZ:0 },
    tank: { name:'坦克', hp:20, mp:6, atk:2, def:5, talentType:1, talentX:0, talentY:0, skillType:9, skillX:2, skillY:2, skillZ:3 },
    archer: { name:'射手', hp:8, mp:8, atk:5, def:1, talentType:2, talentX:2, talentY:0, skillType:8, skillX:2, skillY:2, skillZ:0 },
    custom: { name:'自定义', hp:1, mp:1, atk:0, def:0, talentType:0, talentX:0, talentY:0, skillType:0, skillX:0, skillY:0, skillZ:0 }
};

const TALENT_NAMES = ['我自闭了', '血肉皮囊', '星河力量投射', '心胜于物', '超凡入圣', '科技至上'];
const SKILL_NAMES = ['心态崩了', '格林炸裂', '日昇之雨', '天楼霸断剑', '演出开始', '天狼噬斩', '地球蓝闪电', '极光绽放', '流星', '精灵庇护', '全力超全开'];

function applyTemplate(idx, templateKey) {
    const tmpl = TEMPLATES[templateKey];
    const container = document.querySelector(`#editForm .char-edit[data-char-index="${idx}"]`);
    if (!container) return;
    const inputs = container.querySelectorAll('input');
    const selects = container.querySelectorAll('select');
    const map = {};
    inputs.forEach(inp => { map[inp.dataset.field] = inp; });
    selects.forEach(sel => { map[sel.dataset.field] = sel; });

    if (templateKey === 'custom') {
        // 自定义模式:启用所有字段(保持当前值不变)
        inputs.forEach(inp => inp.disabled = false);
        selects.forEach(sel => sel.disabled = false);
        return;
    }
    // 填充模板数值(不禁用任何字段,让用户可继续微调)
    if (map.hp) map.hp.value = tmpl.hp;
    if (map.mp) map.mp.value = tmpl.mp;
    if (map.atk) map.atk.value = tmpl.atk;
    if (map.def) map.def.value = tmpl.def;
    if (map.talentType) map.talentType.value = tmpl.talentType;
    if (map.talentX) map.talentX.value = tmpl.talentX;
    if (map.talentY) map.talentY.value = tmpl.talentY;
    if (map.skillType) map.skillType.value = tmpl.skillType;
    if (map.skillX) map.skillX.value = tmpl.skillX;
    if (map.skillY) map.skillY.value = tmpl.skillY;
    if (map.skillZ) map.skillZ.value = tmpl.skillZ;
    // 确保所有字段可编辑
    inputs.forEach(inp => inp.disabled = false);
    selects.forEach(sel => sel.disabled = false);
}

function renderEditForm() {
    const config = G.aliceConfig || getDefaultConfig();
    const form = document.getElementById('editForm');

    const talentOptions = TALENT_NAMES.map((name, i) => `<option value="${i}">${i} - ${name}</option>`).join('');
    const skillOptions = SKILL_NAMES.map((name, i) => `<option value="${i}">${i} - ${name}</option>`).join('');

    form.innerHTML = config.map((p, idx) => {
        return `
            <div class="char-edit" data-char-index="${idx}">
                <h3>角色 ${idx+1}</h3>
                <div class="edit-row">
                    <label>模板</label>
                    <select class="template-select" data-idx="${idx}">
                        <option value="warrior">战士</option>
                        <option value="mage">法师</option>
                        <option value="assassin">刺客</option>
                        <option value="tank">坦克</option>
                        <option value="archer">射手</option>
                        <option value="custom" selected>自定义</option>
                    </select>
                </div>
                <div class="edit-row">
                    <label>HP</label><input type="number" value="${p.hp}" min="1" data-field="hp" data-idx="${idx}" />
                    <label>MP</label><input type="number" value="${p.mp}" min="1" data-field="mp" data-idx="${idx}" />
                    <label>ATK</label><input type="number" value="${p.atk}" min="0" data-field="atk" data-idx="${idx}" />
                    <label>DEF</label><input type="number" value="${p.def}" min="0" data-field="def" data-idx="${idx}" />
                </div>
                <div class="edit-row" style="position:relative;">
                    <label>天赋</label>
                    <select data-field="talentType" data-idx="${idx}">
                        ${talentOptions}
                    </select>
                    <button class="info-btn" data-target="talent" data-idx="${idx}">📖</button>
                    <label>参数x</label><input type="number" value="${p.talentX}" min="0" data-field="talentX" data-idx="${idx}" />
                    <label>参数y</label><input type="number" value="${p.talentY}" min="0" data-field="talentY" data-idx="${idx}" />
                </div>
                <div class="edit-row" style="position:relative;">
                    <label>技能</label>
                    <select data-field="skillType" data-idx="${idx}">
                        ${skillOptions}
                    </select>
                    <button class="info-btn" data-target="skill" data-idx="${idx}">📖</button>
                    <label>参数x</label><input type="number" value="${p.skillX}" min="0" data-field="skillX" data-idx="${idx}" />
                    <label>参数y</label><input type="number" value="${p.skillY}" min="0" data-field="skillY" data-idx="${idx}" />
                    <label>参数z</label><input type="number" value="${p.skillZ}" min="0" data-field="skillZ" data-idx="${idx}" />
                </div>
            </div>
        `;
    }).join('');

    // 设置当前下拉值
    form.querySelectorAll('.char-edit').forEach((container, idx) => {
        const selectTalent = container.querySelector('select[data-field="talentType"]');
        const selectSkill = container.querySelector('select[data-field="skillType"]');
        const configItem = config[idx];
        if (selectTalent) selectTalent.value = configItem.talentType;
        if (selectSkill) selectSkill.value = configItem.skillType;
    });

    // 模板切换(只填充数值,不禁用)
    form.querySelectorAll('.template-select').forEach(sel => {
        const idx = parseInt(sel.dataset.idx);
        // 根据当前值匹配默认模板
        const container = sel.closest('.char-edit');
        const inputs = container.querySelectorAll('input');
        const selects = container.querySelectorAll('select');
        const vals = {};
        inputs.forEach(inp => { vals[inp.dataset.field] = parseInt(inp.value) || 0; });
        selects.forEach(sel2 => { vals[sel2.dataset.field] = parseInt(sel2.value) || 0; });
        let matched = 'custom';
        for (const [key, tmpl] of Object.entries(TEMPLATES)) {
            if (key === 'custom') continue;
            if (vals.hp === tmpl.hp && vals.mp === tmpl.mp && vals.atk === tmpl.atk &&
                vals.def === tmpl.def && vals.talentType === tmpl.talentType &&
                vals.talentX === tmpl.talentX && vals.talentY === tmpl.talentY &&
                vals.skillType === tmpl.skillType && vals.skillX === tmpl.skillX &&
                vals.skillY === tmpl.skillY && vals.skillZ === tmpl.skillZ) {
                matched = key;
                break;
            }
        }
        sel.value = matched;
        sel.addEventListener('change', (e) => {
            const val = e.target.value;
            applyTemplate(idx, val);
        });
    });

    // 信息按钮
    form.querySelectorAll('.info-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            e.stopPropagation();
            const idx = parseInt(btn.dataset.idx);
            const target = btn.dataset.target;
            const select = btn.parentElement.querySelector(`select[data-field="${target}Type"]`);
            const val = parseInt(select.value) || 0;
            const nameList = target === 'talent' ? TALENT_NAMES : SKILL_NAMES;
            const paramsList = target === 'talent' ?
                ['', '', 'x = 附加真实伤害', 'x = 回复生命, y = 额外能量', 'A = 攻击力', 'x = 普攻回血, y = 技能回能'] :
                ['', 'x = 伤害', 'A = 攻击力', 'x = 系数', 'x = 持续, y = 能量', 'x = 减防', 'x = 持续, y = 减攻', 'x = 持续, y = 加攻, z = 回复', 'x = 持续, y = 减防', 'x = 持续, y = 加防, z = 回复', 'x = 持续'];
            if (val >= 0 && val < nameList.length) {
                alert(`【${nameList[val]}】\n${paramsList[val] ? '参数: ' + paramsList[val] : '无参数'}`);
            } else {
                alert(`无效编号`);
            }
        });
    });
}

function getConfigFromEditor() {
    const inputs = document.querySelectorAll('#editForm input');
    const selects = document.querySelectorAll('#editForm select[data-field]');
    const config = [];
    const idxMap = {};
    inputs.forEach(inp => {
        const idx = parseInt(inp.dataset.idx);
        if (!idxMap[idx]) idxMap[idx] = {};
        idxMap[idx][inp.dataset.field] = parseInt(inp.value) || 0;
    });
    selects.forEach(sel => {
        const idx = parseInt(sel.dataset.idx);
        if (!idxMap[idx]) idxMap[idx] = {};
        idxMap[idx][sel.dataset.field] = parseInt(sel.value) || 0;
    });
    for (let i = 0; i < Object.keys(idxMap).length; i++) {
        const p = idxMap[i];
        config.push({
            hp: p.hp || 1,
            mp: p.mp || 1,
            atk: p.atk || 0,
            def: p.def || 0,
            priority: [1,2,3],
            talentType: p.talentType || 0,
            talentX: p.talentX || 0,
            talentY: p.talentY || 0,
            skillType: p.skillType || 0,
            skillX: p.skillX || 0,
            skillY: p.skillY || 0,
            skillZ: p.skillZ || 0,
        });
    }
    return config;
}

// ---------- 配置与教程 ----------
const TUTORIAL_STEPS = [
    { title: '🌟 欢迎', content: '欢迎来到 <span class="highlight">群星连结</span>!这是一个双人回合制对战游戏。你将操控 <span class="highlight">Alice</span> 对抗 AI 控制的 <span class="highlight">Bob</span>。' },
    { title: '⚔️ 战场', content: '上方是战场,左侧是你的 <span class="highlight">Alice</span> 队伍,右侧是敌方 <span class="highlight">Bob</span>。每个角色都有 <span class="em">HP</span>(生命)和 <span class="em">MP</span>(能量)条。' },
    { title: '🧙 角色属性', content: '每个角色拥有 <span class="highlight">攻击力 (A)</span>、<span class="em">防御力 (D)</span>、<span class="highlight">天赋</span> 和 <span class="em">技能</span>。天赋和技能的效果可在图鉴中查看。' },
    { title: '🎮 行动规则', content: '每回合你先行动,点击己方角色选择目标,然后选择 <span class="highlight">普通攻击</span> 或 <span class="em">发动技能</span>(需能量满)。随后 Bob 自动行动。' },
    { title: '⚡ 能量与技能', content: '行动后角色 <span class="em">能量 +1</span>,受到伤害也会 +1。能量满时即可发动技能,技能效果多种多样,请善用!' },
    { title: '🏆 胜利条件', content: '击败所有敌方角色即可获胜。现在,请 <span class="highlight">配置你的阵容</span>,开始战斗吧!' },
];

function showSetupModal(showTutorial = false) {
    const modal = document.getElementById('setupModal');
    modal.classList.add('open');
    document.getElementById('welcomeArea').style.display = showTutorial ? 'none' : 'block';
    document.getElementById('tutorialArea').style.display = showTutorial ? 'block' : 'none';
    document.getElementById('setupEditor').style.display = 'none';
    if (showTutorial) {
        G.tutorialStep = 0;
        renderTutorialStep();
    }
}

function renderTutorialStep() {
    const step = TUTORIAL_STEPS[G.tutorialStep];
    document.getElementById('tutorialStep').innerHTML = `
        <span class="title">${step.title}</span>
        ${step.content}
    `;
    const dots = document.querySelectorAll('.tutorial-dot');
    dots.forEach((dot, i) => {
        dot.className = 'tutorial-dot';
        if (i < G.tutorialStep) dot.classList.add('done');
        else if (i === G.tutorialStep) dot.classList.add('active');
    });
    document.getElementById('tutorialPrev').style.display = G.tutorialStep === 0 ? 'none' : 'inline-block';
    document.getElementById('tutorialNext').textContent = G.tutorialStep === G.tutorialTotal - 1 ? '开始配置' : '下一步';
}

function tutorialNext() {
    if (G.tutorialStep < G.tutorialTotal - 1) {
        G.tutorialStep++;
        renderTutorialStep();
    } else {
        showConfigEditor();
    }
}
function tutorialPrev() {
    if (G.tutorialStep > 0) {
        G.tutorialStep--;
        renderTutorialStep();
    }
}
function skipTutorial() {
    showConfigEditor();
}

function showConfigEditor() {
    document.getElementById('welcomeArea').style.display = 'none';
    document.getElementById('tutorialArea').style.display = 'none';
    document.getElementById('setupEditor').style.display = 'block';
    document.getElementById('setupTitle').textContent = '✎ 配置你的 Alice 阵容';
    renderEditForm();
}

function startGame() {
    const config = getConfigFromEditor();
    G.aliceConfig = config;
    const diff = document.getElementById('difficultySelect').value;
    G.difficulty = diff;
    document.getElementById('setupModal').classList.remove('open');
    resetGame();
}

function openEditor() {
    showConfigEditor();
    document.getElementById('setupModal').classList.add('open');
    document.getElementById('setupTitle').textContent = '✎ 编辑阵容 (将重置游戏)';
    const startBtn = document.getElementById('btnStartGame');
    startBtn.textContent = '🔄 应用并重置';
    startBtn.onclick = () => {
        const config = getConfigFromEditor();
        G.aliceConfig = config;
        const diff = document.getElementById('difficultySelect').value;
        G.difficulty = diff;
        document.getElementById('setupModal').classList.remove('open');
        resetGame();
    };
}

function getDefaultConfig() {
    return [
        { hp:12, mp:6, atk:4, def:3, priority:[1,2,3], talentType:5, talentX:2, talentY:1, skillType:3, skillX:2, skillY:0, skillZ:0 },
        { hp:6, mp:12, atk:3, def:1, priority:[1,2,3], talentType:3, talentX:2, talentY:2, skillType:2, skillX:0, skillY:0, skillZ:0 },
        { hp:8, mp:8, atk:5, def:1, priority:[1,2,3], talentType:2, talentX:2, talentY:0, skillType:8, skillX:2, skillY:2, skillZ:0 },
    ];
}

function stepTurn() {
    if (G.stepLock || G.phase === 'ended') return;
    if (G.phase !== 'idle') return;
    G.turn++;
    G.phase = 'alice_select';
    log(`\n——— 第 ${G.turn} 回合 ———`);
    updateUI();
}

function toggleAuto() {
    if (G.autoTimer) {
        clearInterval(G.autoTimer);
        G.autoTimer = null;
        document.getElementById('btnAuto').textContent = '⏩ 自动 (AI Alice)';
        return;
    }
    if (G.phase === 'ended') return;
    document.getElementById('btnAuto').textContent = '⏹ 停止';
    G.autoTimer = setInterval(() => {
        if (G.phase === 'ended') {
            clearInterval(G.autoTimer);
            G.autoTimer = null;
            document.getElementById('btnAuto').textContent = '⏩ 自动 (AI Alice)';
            return;
        }
        if (G.phase === 'idle' && !G.stepLock) {
            const action = selectAction(G.alice, G.bob, G.difficulty);
            if (action) {
                G.turn++;
                G.phase = 'alice_executed';
                log(`\n——— 第 ${G.turn} 回合 (AI Alice) ———`);
                try {
                    performAction(action, 'alice', G.bob, log, G.turn);
                    if (allDead(G.bob)) {
                        G.phase = 'ended';
                        G.winner = 'Alice';
                        updateUI();
                        clearInterval(G.autoTimer);
                        G.autoTimer = null;
                        document.getElementById('btnAuto').textContent = '⏩ 自动 (AI Alice)';
                        return;
                    }
                    G.phase = 'bob_action';
                    updateUI();
                    setTimeout(() => {
                        if (G.phase === 'ended') return;
                        bobTurn();
                    }, 300);
                } catch (err) {
                    console.error('自动Alice异常:', err);
                    G.phase = 'idle';
                    updateUI();
                }
            }
        }
    }, 600);
}

// ---------- 图鉴 ----------
const TALENT_DATA = [
    { id: 0, name: '我自闭了', desc: '该角色的天赋毫无作用', params: '' },
    { id: 1, name: '血肉皮囊', desc: '免疫一半真实伤害(真实伤害减半)', params: '' },
    { id: 2, name: '星河力量投射', desc: '普通攻击附加 x 点真实伤害', params: 'x = 附加真实伤害值' },
    { id: 3, name: '心胜于物', desc: '己方行动结束后回复 x 点生命值,并额外回复 y 点能量值', params: 'x = 回复生命值,y = 额外回复能量值' },
    { id: 4, name: '超凡入圣', desc: '普通攻击被视为真实伤害攻击(不造成伤害,造成 A 点真实伤害)', params: 'A = 攻击力' },
    { id: 5, name: '科技至上', desc: '普通攻击后回复 x 点生命值;发动技能后额外回复 y 点能量值', params: 'x = 普攻回血量,y = 技能额外回能量' },
];
const SKILL_DATA = [
    { id: 0, name: '心态崩了!', desc: '无效果,但仍消耗能量并触发能量回复', params: '' },
    { id: 1, name: '格林炸裂!', desc: '对敌方全体造成 x 点伤害,然后使敌方全体能量减少 floor(mp/10)', params: 'x = 伤害值' },
    { id: 2, name: '日昇之雨!', desc: '对敌方全体造成 A 点真实伤害', params: 'A = 攻击力' },
    { id: 3, name: '天楼霸断剑!', desc: '对敌方全体造成 min(floor(HP_enemy/10), x*A) 点伤害', params: 'x = 系数,A = 攻击力' },
    { id: 4, name: '演出开始!', desc: '持续 x 回合,己方行动结束全体额外回复 y 点能量', params: 'x = 持续回合,y = 额外能量' },
    { id: 5, name: '天狼噬斩!', desc: '优先目标防御力增益减 x,然后造成 A 点真实伤害', params: 'x = 防御力减少值,A = 攻击力' },
    { id: 6, name: '地球蓝闪电!', desc: '对优先目标造成 A 点真实伤害,敌方全体攻击力增益减 y 持续 x 回合', params: 'x = 持续回合,y = 攻击力减少值,A = 攻击力' },
    { id: 7, name: '极光绽放!', desc: '己方生命最低回复 z 点生命,己方全体攻击力增益 +y 持续 x 回合', params: 'x = 持续回合,y = 攻击力增加值,z = 回复量' },
    { id: 8, name: '流星!', desc: '对敌方全体造成 A 点伤害,敌方全体防御力增益减 y 持续 x 回合(先伤害后减益)', params: 'x = 持续回合,y = 防御力减少值,A = 攻击力' },
    { id: 9, name: '精灵庇护!', desc: '己方全体回复 z 点生命,己方全体防御力增益 +y 持续 x 回合', params: 'x = 持续回合,y = 防御力增加值,z = 回复量' },
    { id: 10, name: '全力超全开!轮回之终末!', desc: '己方全体基础 atk/def 翻倍,hp/mp 提升至一半,持续 x 回合,结束后若敌方存活则己方全灭,且替换技能为0号', params: 'x = 持续回合' },
];

function openCodex() {
    const talentContainer = document.getElementById('talentCodex');
    const skillContainer = document.getElementById('skillCodex');
    talentContainer.innerHTML = TALENT_DATA.map(t => `
        <div class="codex-item">
            <span class="codex-id">#${t.id}</span>
            <span class="codex-name">${t.name}</span>
            <div class="codex-desc">${t.desc}</div>
            ${t.params ? `<div class="codex-params">📌 参数:<em>${t.params}</em></div>` : ''}
        </div>
    `).join('');
    skillContainer.innerHTML = SKILL_DATA.map(s => `
        <div class="codex-item">
            <span class="codex-id">#${s.id}</span>
            <span class="codex-name">${s.name}</span>
            <div class="codex-desc">${s.desc}</div>
            ${s.params ? `<div class="codex-params">📌 参数:<em>${s.params}</em></div>` : ''}
        </div>
    `).join('');
    document.getElementById('codexModal').classList.add('open');
}
function closeCodex() { document.getElementById('codexModal').classList.remove('open'); }

// ---------- 初始化 ----------
document.addEventListener('DOMContentLoaded', () => {
    createActionPanel();

    document.getElementById('btnStartTutorial').addEventListener('click', () => showSetupModal(true));
    document.getElementById('btnSkipToConfig').addEventListener('click', showConfigEditor);
    document.getElementById('tutorialNext').addEventListener('click', tutorialNext);
    document.getElementById('tutorialPrev').addEventListener('click', tutorialPrev);
    document.getElementById('tutorialSkip').addEventListener('click', skipTutorial);
    document.getElementById('btnStartGame').addEventListener('click', startGame);
    document.getElementById('btnSetupCodex').addEventListener('click', openCodex);

    document.getElementById('btnStep').addEventListener('click', stepTurn);
    document.getElementById('btnAuto').addEventListener('click', toggleAuto);
    document.getElementById('btnReset').addEventListener('click', resetGame);
    document.getElementById('btnClearLog').addEventListener('click', () => { G.log = []; renderLog(); });
    document.getElementById('btnEdit').addEventListener('click', openEditor);
    document.getElementById('btnCodex').addEventListener('click', openCodex);
    document.getElementById('btnCloseCodex').addEventListener('click', closeCodex);

    G.aliceConfig = getDefaultConfig();
    showSetupModal(false);
    updateUI();
});

window.G = G;
window.resetGame = resetGame;

做完这一切并保存后,双击index.html,就可以在没外网的情况下体验《群星连结》了