跳到正文

科技·工程

洛谷题目难度自定义脚本

jiangyunuo约 119 分钟
原文
文章信息与版本

文章信息

发布
2026年2月8日
收录
2026年2月8日
更新
2026年11月11日
篇幅
约 119 分钟

版本

  1. v3当前
  2. v2
  3. v1

我看了许多优化,可以让洛谷更美丽,比如氧洛谷,或是洛谷提交优化,对于我这个喜爱后室的人来说,这些可以帮我体验后室风格的洛谷。我用氧洛谷将背景改为了后室层级 level 0,提交记录改成了别的层级,让洛谷更具有后室味。

但,我总觉得还是少了点什么。

可到底少了什么呢?

我想啊想,终于,我想到了,对啊,后室那么多个层级是有生存等级的,洛谷的这些难度显然对不上,没感觉,所以,我决定,在 Deepseek 的帮助下,以及其他机房成员的辅助下,我们成功制造出了一个难度主题管理器脚本,用法还是直接放入篡改猴。

脚本启动后,我们要刷新页面,接着,右下角会出现几个选项,点击管理,即可选择难度的主题,很好操作。

同时,我们不只搞了后室,我们还搞了 SCP,对于 SCP 了解较深的可以使用,否则我怕你看不懂难易程度,当然,你也可以现场记忆下来。

同时,大家也可以自定义主题,选择颜色,文字或者可以放上图片。让洛谷变得更美好

不过脚本有个缺陷,每到一个新的页面,我们都需要刷新,这是一个小缺点,不过习惯就好。

欢迎大家尝试同时提出更改意见,希望这个脚本可以发展的越来越好。

C++
// ==UserScript==
// @name         洛谷难度主题管理器 v10.3
// @namespace    http://tampermonkey.net/
// @version      10.3
// @description  自定义洛谷题目难度图标,支持多主题创建、切换和保存,新增后室和SCP主题
// @author       鸡腿,PCY和祥子
// @match        https://www.luogu.com.cn/*
// @match        https://luogu.com.cn/*
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_addStyle
// @grant        GM_registerMenuCommand
// @run-at       document-end
// ==/UserScript==

(function() {
    'use strict';

    // 后室主题图片URL
    const BACKROOMS_IMAGES = {
        '暂无评定': 'https://cdn.luogu.com.cn/upload/image_hosting/k83scvdj.png',
        '入门': 'https://cdn.luogu.com.cn/upload/image_hosting/3pkufhwg.png',
        '普及-': 'https://cdn.luogu.com.cn/upload/image_hosting/bnpb43dd.png',
        '普及/提高-': 'https://cdn.luogu.com.cn/upload/image_hosting/dkj0la0b.png',
        '普及+/提高': 'https://cdn.luogu.com.cn/upload/image_hosting/w6fakokc.png',
        '提高+/省选-': 'https://cdn.luogu.com.cn/upload/image_hosting/95438ck0.png',
        '省选/NOI-': 'https://cdn.luogu.com.cn/upload/image_hosting/0pzb08o8.png',
        'NOI/NOI+/CTSC': 'https://cdn.luogu.com.cn/upload/image_hosting/i21hupri.png'
    };

    // 默认主题配置
    const DEFAULT_THEMES = {
        '经典图标主题': {
            name: '经典图标主题',
            created: new Date().toISOString(),
            updated: new Date().toISOString(),
            config: {
                '入门': { type: 'text', value: '🔰入门', color: '#3498db' },
                '普及-': { type: 'text', value: '📘普及-', color: '#2ecc71' },
                '普及/提高-': { type: 'text', value: '📗普及/提高-', color: '#f1c40f' },
                '普及+/提高': { type: 'text', value: '📒普及+/提高', color: '#f39c12' },
                '提高+/省选-': { type: 'text', value: '📙提高+/省选-', color: '#e67e22' },
                '省选/NOI-': { type: 'text', value: '📕省选/NOI-', color: '#e74c3c' },
                'NOI/NOI+/CTSC': { type: 'text', value: '💎NOI/NOI+/CTSC', color: '#9b59b6' },
                '暂无评定': { type: 'text', value: '❓暂无评定', color: '#95a5a6' }
            }
        },
        '简约文字主题': {
            name: '简约文字主题',
            created: new Date().toISOString(),
            updated: new Date().toISOString(),
            config: {
                '入门': { type: 'text', value: '入门', color: '#3498db' },
                '普及-': { type: 'text', value: '普及-', color: '#2ecc71' },
                '普及/提高-': { type: 'text', value: '普及/提高-', color: '#f1c40f' },
                '普及+/提高': { type: 'text', value: '普及+/提高', color: '#f39c12' },
                '提高+/省选-': { type: 'text', value: '提高+/省选-', color: '#e67e22' },
                '省选/NOI-': { type: 'text', value: '省选/NOI-', color: '#e74c3c' },
                'NOI/NOI+/CTSC': { type: 'text', value: 'NOI/NOI+/CTSC', color: '#9b59b6' },
                '暂无评定': { type: 'text', value: '暂无评定', color: '#95a5a6' }
            }
        },
        'Emoji主题': {
            name: 'Emoji主题',
            created: new Date().toISOString(),
            updated: new Date().toISOString(),
            config: {
                '入门': { type: 'text', value: '🐣入门', color: '#3498db' },
                '普及-': { type: 'text', value: '📚普及-', color: '#2ecc71' },
                '普及/提高-': { type: 'text', value: '📖普及/提高-', color: '#f1c40f' },
                '普及+/提高': { type: 'text', value: '📝普及+/提高', color: '#f39c12' },
                '提高+/省选-': { type: 'text', value: '🏆提高+/省选-', color: '#e67e22' },
                '省选/NOI-': { type: 'text', value: '🎯省选/NOI-', color: '#e74c3c' },
                'NOI/NOI+/CTSC': { type: 'text', value: '👑NOI/NOI+/CTSC', color: '#9b59b6' },
                '暂无评定': { type: 'text', value: '❓暂无评定', color: '#95a5a6' }
            }
        },
        '后室主题': {
            name: '后室主题',
            created: new Date().toISOString(),
            updated: new Date().toISOString(),
            config: {
                '入门': { type: 'image', value: BACKROOMS_IMAGES['入门'], color: '#3498db' },
                '普及-': { type: 'image', value: BACKROOMS_IMAGES['普及-'], color: '#2ecc71' },
                '普及/提高-': { type: 'image', value: BACKROOMS_IMAGES['普及/提高-'], color: '#f1c40f' },
                '普及+/提高': { type: 'image', value: BACKROOMS_IMAGES['普及+/提高'], color: '#f39c12' },
                '提高+/省选-': { type: 'image', value: BACKROOMS_IMAGES['提高+/省选-'], color: '#e67e22' },
                '省选/NOI-': { type: 'image', value: BACKROOMS_IMAGES['省选/NOI-'], color: '#e74c3c' },
                'NOI/NOI+/CTSC': { type: 'image', value: BACKROOMS_IMAGES['NOI/NOI+/CTSC'], color: '#9b59b6' },
                '暂无评定': { type: 'image', value: BACKROOMS_IMAGES['暂无评定'], color: '#95a5a6' }
            }
        },
        'SCP主题': {
            name: 'SCP主题',
            created: new Date().toISOString(),
            updated: new Date().toISOString(),
            config: {
                '入门': { type: 'text', value: 'Explained', color: '#ffffff' },
                '普及-': { type: 'text', value: 'Safe', color: '#2ecc71' },
                '普及/提高-': { type: 'text', value: 'Euclid', color: '#f1c40f' },
                '普及+/提高': { type: 'text', value: 'Keter', color: '#e74c3c' },
                '提高+/省选-': { type: 'text', value: 'Thaumiel', color: '#9b59b6' },
                '省选/NOI-': { type: 'text', value: 'Archon', color: '#3498db' },
                'NOI/NOI+/CTSC': { type: 'text', value: 'Apollyon', color: '#000000' },
                '暂无评定': { type: 'text', value: 'Pending', color: '#95a5a6' }
            }
        }
    };

    // 难度等级列表
    const DIFFICULTIES = [
        '入门', '普及-', '普及/提高-', '普及+/提高',
        '提高+/省选-', '省选/NOI-', 'NOI/NOI+/CTSC', '暂无评定'
    ];

    // 存储结构
    let storage = {
        themes: {},
        currentTheme: '',
        settings: {
            autoRefresh: true,
            showRefreshButton: true
        }
    };

    // 加载存储数据
    function loadStorage() {
        try {
            const saved = GM_getValue('luogu_difficulty_storage');
            if (saved && saved.themes && Object.keys(saved.themes).length > 0) {
                storage = saved;
                console.log('已加载主题存储数据');
                return true;
            }
        } catch (e) {
            console.error('加载存储数据失败:', e);
        }

        // 初始化为默认主题
        storage.themes = JSON.parse(JSON.stringify(DEFAULT_THEMES));
        storage.currentTheme = '经典图标主题';
        saveStorage();
        console.log('使用默认主题数据');
        return false;
    }

    // 保存存储数据
    function saveStorage() {
        try {
            GM_setValue('luogu_difficulty_storage', storage);
            console.log('存储数据已保存');
            return true;
        } catch (e) {
            console.error('保存存储数据失败:', e);
            return false;
        }
    }

    // 获取当前主题配置
    function getCurrentConfig() {
        const theme = storage.themes[storage.currentTheme];
        return theme ? theme.config : DEFAULT_THEMES['经典图标主题'].config;
    }

    // 更新当前主题配置
    function updateCurrentConfig(config) {
        if (storage.themes[storage.currentTheme]) {
            storage.themes[storage.currentTheme].config = config;
            storage.themes[storage.currentTheme].updated = new Date().toISOString();
            saveStorage();
            return true;
        }
        return false;
    }

    // 添加样式
    GM_addStyle(`
        /* 自定义难度标签样式 */
        .luogu-custom-difficulty {
            display: inline-block !important;
            padding: 2px 8px !important;
            border-radius: 3px !important;
            font-weight: bold !important;
            font-size: 12px !important;
            text-align: center !important;
            min-width: 85px !important;
            color: white !important;
            line-height: 1.4 !important;
            border: none !important;
            box-shadow: none !important;
        }

        /* 自定义图片样式 */
        .luogu-custom-img {
            height: 20px !important;
            width: auto !important;
            vertical-align: middle !important;
            border: none !important;
            background: transparent !important;
            padding: 0 !important;
            margin: 0 !important;
            display: inline-block !important;
        }

        /* 后室主题图片放大样式 - 用于题目背景之上 */
        .luogu-backrooms-enlarged {
            max-width: 200px !important;
            max-height: 200px !important;
            width: auto !important;
            height: auto !important;
            display: block !important;
            margin: 10px auto !important;
            border: 2px solid #666 !important;
            border-radius: 8px !important;
            box-shadow: 0 4px 8px rgba(0,0,0,0.3) !important;
        }

        /* 后室主题标题样式 */
        .luogu-backrooms-title {
            font-size: 20px !important;
            font-weight: bold !important;
            text-align: center !important;
            color: #333 !important;
            margin: 15px 0 10px 0 !important;
            padding-bottom: 8px !important;
            border-bottom: 2px solid #3498db !important;
        }

        /* SCP主题特殊文字样式 */
        .luogu-scp-text {
            font-family: 'Courier New', monospace !important;
            font-weight: bold !important;
            letter-spacing: 1px !important;
            text-transform: uppercase !important;
        }

        /* 设置面板样式 */
        #luogu-main-panel {
            position: fixed !important;
            top: 50% !important;
            left: 50% !important;
            transform: translate(-50%, -50%) !important;
            background: white !important;
            padding: 20px !important;
            border-radius: 8px !important;
            box-shadow: 0 0 20px rgba(0,0,0,0.3) !important;
            z-index: 10000 !important;
            width: 800px !important;
            max-width: 95vw !important;
            max-height: 90vh !important;
            overflow: hidden !important;
        }

        .luogu-panel-overlay {
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            right: 0 !important;
            bottom: 0 !important;
            background: rgba(0,0,0,0.5) !important;
            z-index: 9999 !important;
        }

        /* 选项卡样式 */
        .luogu-tabs {
            display: flex !important;
            border-bottom: 2px solid #eee !important;
            margin-bottom: 20px !important;
        }

        .luogu-tab {
            padding: 10px 20px !important;
            cursor: pointer !important;
            border: none !important;
            background: none !important;
            font-size: 14px !important;
            color: #666 !important;
            border-bottom: 2px solid transparent !important;
            transition: all 0.3s !important;
            margin-right: 5px !important;
        }

        .luogu-tab:hover {
            color: #2196F3 !important;
        }

        .luogu-tab.active {
            color: #2196F3 !important;
            border-bottom: 2px solid #2196F3 !important;
            font-weight: bold !important;
        }

        /* 主题管理样式 */
        .luogu-themes-list {
            max-height: 300px !important;
            overflow-y: auto !important;
            margin-bottom: 20px !important;
            border: 1px solid #eee !important;
            border-radius: 5px !important;
        }

        .luogu-theme-item {
            padding: 12px 15px !important;
            border-bottom: 1px solid #f0f0f0 !important;
            display: flex !important;
            justify-content: space-between !important;
            align-items: center !important;
            transition: background 0.3s !important;
        }

        .luogu-theme-item:hover {
            background: #f9f9f9 !important;
        }

        .luogu-theme-item.current {
            background: #e3f2fd !important;
            border-left: 4px solid #2196F3 !important;
        }

        .luogu-theme-info {
            flex: 1 !important;
        }

        .luogu-theme-name {
            font-weight: bold !important;
            color: #333 !important;
            margin-bottom: 3px !important;
        }

        .luogu-theme-meta {
            font-size: 12px !important;
            color: #888 !important;
        }

        .luogu-theme-actions {
            display: flex !important;
            gap: 5px !important;
        }

        .luogu-action-btn {
            padding: 5px 10px !important;
            border: none !important;
            border-radius: 3px !important;
            cursor: pointer !important;
            font-size: 12px !important;
        }

        .luogu-action-btn.apply {
            background: #4CAF50 !important;
            color: white !important;
        }

        .luogu-action-btn.delete {
            background: #f44336 !important;
            color: white !important;
        }

        .luogu-action-btn.rename {
            background: #ff9800 !important;
            color: white !important;
        }

        /* 主题编辑样式 */
        .luogu-difficulty-editor {
            display: grid !important;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr)) !important;
            gap: 15px !important;
            max-height: 400px !important;
            overflow-y: auto !important;
            padding: 10px !important;
        }

        .luogu-difficulty-item {
            padding: 15px !important;
            border: 1px solid #ddd !important;
            border-radius: 5px !important;
            background: #f9f9f9 !important;
        }

        .luogu-difficulty-header {
            font-weight: bold !important;
            color: #333 !important;
            margin-bottom: 10px !important;
            padding-bottom: 5px !important;
            border-bottom: 1px solid #eee !important;
        }

        .luogu-option-group {
            display: flex !important;
            align-items: center !important;
            gap: 10px !important;
            margin-bottom: 8px !important;
            flex-wrap: wrap !important;
        }

        .luogu-option-label {
            min-width: 60px !important;
            font-size: 13px !important;
        }

        .luogu-option-input {
            flex: 1 !important;
            min-width: 200px !important;
            padding: 6px !important;
            border: 1px solid #ddd !important;
            border-radius: 3px !important;
        }

        .luogu-color-input {
            width: 50px !important;
            height: 30px !important;
            cursor: pointer !important;
        }

        /* 按钮样式 */
        .luogu-panel-btn {
            padding: 8px 15px !important;
            border: none !important;
            border-radius: 4px !important;
            cursor: pointer !important;
            font-weight: bold !important;
            margin-left: 5px !important;
        }

        .luogu-panel-btn.primary {
            background: #2196F3 !important;
            color: white !important;
        }

        .luogu-panel-btn.success {
            background: #4CAF50 !important;
            color: white !important;
        }

        .luogu-panel-btn.danger {
            background: #f44336 !important;
            color: white !important;
        }

        .luogu-panel-btn.secondary {
            background: #9e9e9e !important;
            color: white !important;
        }

        .luogu-panel-footer {
            margin-top: 20px !important;
            padding-top: 15px !important;
            border-top: 1px solid #eee !important;
            text-align: right !important;
        }

        /* 快速切换菜单 */
        .luogu-quick-menu {
            position: fixed !important;
            bottom: 15px !important;
            right: 15px !important;
            display: flex !important;
            gap: 5px !important;
            z-index: 1000 !important;
        }

        .luogu-quick-btn {
            padding: 6px 12px !important;
            background: #2196F3 !important;
            color: white !important;
            border: none !important;
            border-radius: 4px !important;
            cursor: pointer !important;
            font-size: 12px !important;
            font-weight: bold !important;
        }

        .luogu-quick-btn.theme-switch {
            background: #9c27b0 !important;
        }

        .luogu-quick-btn.reprocess {
            background: #ff9800 !important;
        }

        .luogu-quick-btn:hover {
            opacity: 0.9 !important;
        }

        /* 模态框样式 */
        .luogu-modal {
            position: fixed !important;
            top: 50% !important;
            left: 50% !important;
            transform: translate(-50%, -50%) !important;
            background: white !important;
            padding: 20px !important;
            border-radius: 8px !important;
            box-shadow: 0 0 20px rgba(0,0,0,0.3) !important;
            z-index: 10001 !important;
            min-width: 300px !important;
        }

        .luogu-modal-title {
            font-size: 18px !important;
            font-weight: bold !important;
            margin-bottom: 15px !important;
            color: #333 !important;
        }

        .luogu-modal-input {
            width: 100% !important;
            padding: 8px !important;
            margin-bottom: 15px !important;
            border: 1px solid #ddd !important;
            border-radius: 4px !important;
            box-sizing: border-box !important;
        }

        .luogu-modal-footer {
            text-align: right !important;
            margin-top: 20px !important;
        }

        /* 全屏刷新遮罩 */
        .luogu-refresh-overlay {
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            right: 0 !important;
            bottom: 0 !important;
            background: rgba(0, 0, 0, 0.8) !important;
            z-index: 100000 !important;
            display: flex !important;
            justify-content: center !important;
            align-items: center !important;
            color: white !important;
            font-size: 24px !important;
            flex-direction: column !important;
        }

        .luogu-refresh-overlay span {
            margin-bottom: 20px !important;
            text-align: center !important;
        }
    `);

    // 注册菜单命令
    GM_registerMenuCommand('主题管理器', showThemeManager);
    GM_registerMenuCommand('快速切换主题', showQuickSwitch);
    GM_registerMenuCommand('编辑当前主题', showThemeEditor);
    GM_registerMenuCommand('重新处理难度标签', () => {
        processAllDifficulties();
        alert('已重新处理当前页面的难度标签');
    });
    GM_registerMenuCommand('刷新页面', fullRefreshPage);

    // 所有可能的颜色类名
    const COLOR_CLASSES = [
        'lcolor--grey-3',     // 暂无评定
        'lcolor--pink-3',     // 入门
        'lcolor--orange-3',   // 普及-
        'lcolor--gold-3',     // 普及/提高-
        'lcolor--green-3',    // 普及+/提高
        'lcolor--blue-3',     // 提高+/省选-
        'lcolor--purple-3',   // 省选/NOI-
        'lcolor--lapis-4',    // NOI/NOI+/CTSC
        'lcolor--red-3',
        'lcolor--yellow-3',
        'lcolor--black-3'
    ];

    // 获取对比色
    function getContrastColor(hexColor) {
        if (!hexColor) return '#ffffff';
        hexColor = hexColor.replace('#', '');
        if (hexColor.length === 3) {
            hexColor = hexColor.split('').map(c => c + c).join('');
        }
        try {
            const r = parseInt(hexColor.substr(0, 2), 16);
            const g = parseInt(hexColor.substr(2, 2), 16);
            const b = parseInt(hexColor.substr(4, 2), 16);
            return (r * 299 + g * 587 + b * 114) / 1000 > 128 ? '#000000' : '#ffffff';
        } catch (e) {
            return '#ffffff';
        }
    }

    // 标准化难度文本
    function normalizeDifficultyText(text) {
        if (!text) return '';
        text = text.replace(/\s+/g, '');
        text = text.replace(/[\u2212\u2013\u2014]/g, '-');
        text = text.replace(/[\uFF0D\uFE63\u2212]/g, '-');
        return text;
    }

    // 获取难度等级
    function getDifficultyLevel(text) {
        const normalized = normalizeDifficultyText(text);

        for (const diff of DIFFICULTIES) {
            const normalizedDiff = normalizeDifficultyText(diff);
            if (normalized === normalizedDiff) {
                return diff;
            }
        }

        return null;
    }

    // 判断是否为题目页面
    function isProblemPage() {
        return window.location.pathname.includes('/problem/');
    }

    // 判断是否为题目背景之上的难度元素
    function isProblemHeaderDifficulty(element) {
        // 检查元素是否在题目标题附近
        const problemTitle = document.querySelector('.header .title, .problem-title, h1');
        if (!problemTitle) return false;

        // 检查元素是否在标题附近
        const rect1 = element.getBoundingClientRect();
        const rect2 = problemTitle.getBoundingClientRect();

        // 判断两个元素是否在垂直方向上相近
        const verticalDistance = Math.abs(rect1.top - rect2.top);
        return verticalDistance < 100; // 在100像素范围内视为标题附近的元素
    }

    // 查找难度元素
    function findDifficultyElements() {
        const elements = new Set();

        // 方法1: 专门处理.difficulty-tags结构
        const difficultyTags = document.querySelectorAll('.difficulty-tags .row span:not(.problem-count)');

        difficultyTags.forEach(el => {
            if (!el.classList.contains('luogu-processed')) {
                const text = el.textContent.trim();
                if (text && getDifficultyLevel(text)) {
                    elements.add(el);
                }
            }
        });

        // 方法2: 通过颜色类名查找
        COLOR_CLASSES.forEach(className => {
            try {
                document.querySelectorAll(`.${className}`).forEach(el => {
                    if (!el.classList.contains('luogu-processed')) {
                        elements.add(el);
                    }
                });
            } catch (e) {}
        });

        // 方法3: 通过常见选择器查找
        const selectors = [
            '.difficulty',
            '.tag.difficulty',
            'span.difficulty',
            'a[href*="difficulty"]',
            'span[class*="difficulty"]',
            '.problem-tags span',
            '.am-badge'
        ];

        selectors.forEach(selector => {
            try {
                document.querySelectorAll(selector).forEach(el => {
                    const text = el.textContent.trim();
                    if (text && getDifficultyLevel(text) && !el.classList.contains('luogu-processed')) {
                        elements.add(el);
                    }
                });
            } catch (e) {}
        });

        return Array.from(elements);
    }

    // 替换难度元素 - 增强版,支持后室主题的特殊显示
    function replaceDifficultyElement(element) {
        // 获取难度文本
        let difficultyText = element.textContent.trim();

        // 获取难度等级
        const difficulty = getDifficultyLevel(difficultyText);
        if (!difficulty) {
            return false;
        }

        // 获取当前主题配置
        const config = getCurrentConfig();
        const configItem = config[difficulty];
        if (!configItem) {
            return false;
        }

        try {
            // 标记为已处理
            element.classList.add('luogu-processed');

            // 保存原始内容
            const originalHTML = element.innerHTML;
            const originalStyle = element.getAttribute('style');

            element.setAttribute('data-luogu-original', originalHTML);
            if (originalStyle) {
                element.setAttribute('data-luogu-original-style', originalStyle);
            }

            // 保存problem-count兄弟元素(如果有)
            const parent = element.parentElement;
            let problemCountElement = null;
            if (parent && parent.classList.contains('row')) {
                const problemCount = parent.querySelector('.problem-count');
                if (problemCount) {
                    problemCountElement = problemCount.cloneNode(true);
                    element.setAttribute('data-luogu-problem-count', problemCount.outerHTML);
                }
            }

            // 清空内容
            element.innerHTML = '';

            // 清除样式
            const currentStyle = window.getComputedStyle(element);
            element.style.cssText = '';

            // 恢复必要的布局样式
            element.style.display = currentStyle.display;
            element.style.verticalAlign = 'middle';
            element.style.margin = '0';
            element.style.padding = '0';
            element.style.border = 'none';
            element.style.boxShadow = 'none';
            element.style.backgroundColor = 'transparent';

            // 检查是否为后室主题且在题目背景之上
            const isBackroomsTheme = storage.currentTheme === '后室主题';
            const isProblemHeader = isProblemPage() && isProblemHeaderDifficulty(element);

            if (isBackroomsTheme && isProblemHeader) {
                // 后室主题在题目背景之上的特殊显示
                const container = document.createElement('div');
                container.style.textAlign = 'center';
                container.style.margin = '10px 0';

                // 添加标题
                const title = document.createElement('div');
                title.className = 'luogu-backrooms-title';
                title.textContent = difficulty;
                container.appendChild(title);

                // 添加放大图片
                const img = document.createElement('img');
                img.src = configItem.value || BACKROOMS_IMAGES[difficulty] || '';
                img.alt = difficulty;
                img.title = difficulty;
                img.className = 'luogu-backrooms-enlarged';
                container.appendChild(img);

                element.appendChild(container);
                element.style.display = 'block';
                element.style.textAlign = 'center';
            } else if (configItem.type === 'image' && configItem.value) {
                // 图片模式
                const img = document.createElement('img');
                img.src = configItem.value;
                img.alt = difficulty;
                img.title = difficulty;
                img.className = 'luogu-custom-img';
                img.style.display = 'inline-block';
                img.style.verticalAlign = 'middle';

                // 如果是SCP主题,不应用图片
                if (storage.currentTheme === 'SCP主题') {
                    console.log('SCP主题使用文字模式,忽略图片配置');
                    // 回退到文字模式
                    createTextElement(element, difficulty, configItem);
                } else {
                    element.appendChild(img);
                }
            } else {
                // 文字模式
                createTextElement(element, difficulty, configItem);
            }

            // 恢复problem-count元素
            if (problemCountElement && parent && parent.classList.contains('row')) {
                const existingProblemCount = parent.querySelector('.problem-count');
                if (existingProblemCount) {
                    existingProblemCount.style.display = 'inline';
                } else {
                    parent.appendChild(problemCountElement);
                }
            }

            return true;
        } catch (error) {
            console.error('替换难度元素出错:', error);

            try {
                const original = element.getAttribute('data-luogu-original');
                if (original) {
                    element.innerHTML = original;
                }
                element.classList.remove('luogu-processed');
            } catch (e) {}

            return false;
        }
    }

    // 创建文字元素
    function createTextElement(element, difficulty, configItem) {
        const span = document.createElement('span');
        span.textContent = configItem.value || difficulty;
        span.className = 'luogu-custom-difficulty';

        // SCP主题特殊样式
        if (storage.currentTheme === 'SCP主题') {
            span.classList.add('luogu-scp-text');
        }

        span.style.backgroundColor = configItem.color;
        span.style.color = getContrastColor(configItem.color);

        // 保持原有的内联样式
        if (element.hasAttribute('data-luogu-original-style')) {
            const originalStyleText = element.getAttribute('data-luogu-original-style');
            if (originalStyleText && originalStyleText.includes('border-color')) {
                span.style.border = '1px solid ' + configItem.color;
            }
        }

        element.appendChild(span);
    }

    // 恢复所有已处理的元素
    function restoreAllProcessedElements() {
        const processedElements = document.querySelectorAll('.luogu-processed');

        processedElements.forEach(element => {
            const original = element.getAttribute('data-luogu-original');
            const originalStyle = element.getAttribute('data-luogu-original-style');

            if (original) {
                element.innerHTML = original;
            }

            if (originalStyle) {
                element.setAttribute('style', originalStyle);
            }

            element.classList.remove('luogu-processed');
            element.removeAttribute('data-luogu-original');
            element.removeAttribute('data-luogu-original-style');

            // 恢复problem-count显示
            const parent = element.parentElement;
            if (parent && parent.classList.contains('row')) {
                const problemCount = parent.querySelector('.problem-count');
                if (problemCount) {
                    problemCount.style.display = 'inline';
                }
            }
        });
    }

    // 处理所有难度元素
    function processAllDifficulties() {
        console.log('开始处理难度标签...当前主题:', storage.currentTheme);

        // 恢复所有已处理的元素
        restoreAllProcessedElements();

        // 查找所有难度元素
        const elements = findDifficultyElements();

        if (elements.length === 0) {
            console.log('没有找到难度元素,稍后重试');
            setTimeout(processAllDifficulties, 2000);
            return;
        }

        // 处理每个元素
        let processedCount = 0;
        elements.forEach(element => {
            if (replaceDifficultyElement(element)) {
                processedCount++;
            }
        });

        console.log(`成功处理 ${processedCount} 个难度标签`);
    }

    // 全屏刷新页面
    function fullRefreshPage() {
        // 创建全屏遮罩
        const overlay = document.createElement('div');
        overlay.className = 'luogu-refresh-overlay';

        const message = document.createElement('span');
        message.textContent = '正在应用主题更改,刷新页面...';
        overlay.appendChild(message);

        document.body.appendChild(overlay);

        // 保存当前主题到本地存储
        saveStorage();

        // 等待一下让用户看到消息
        setTimeout(() => {
            location.reload();
        }, 1500);
    }

    // 添加快速切换菜单
    function addQuickMenu() {
        // 移除已存在的菜单
        const existingMenu = document.querySelector('.luogu-quick-menu');
        if (existingMenu) existingMenu.remove();

        // 创建菜单容器
        const menu = document.createElement('div');
        menu.className = 'luogu-quick-menu';

        // 主题切换按钮
        const themeBtn = document.createElement('button');
        themeBtn.className = 'luogu-quick-btn theme-switch';
        themeBtn.textContent = `主题: ${storage.currentTheme}`;
        themeBtn.title = '点击切换主题';
        themeBtn.addEventListener('click', showQuickSwitch);

        // 重新处理按钮
        const reprocessBtn = document.createElement('button');
        reprocessBtn.className = 'luogu-quick-btn reprocess';
        reprocessBtn.textContent = '🔄 重处理';
        reprocessBtn.title = '重新处理当前页面的难度标签';
        reprocessBtn.addEventListener('click', () => {
            reprocessBtn.textContent = '处理中...';
            reprocessBtn.disabled = true;
            setTimeout(() => {
                processAllDifficulties();
                reprocessBtn.textContent = '🔄 重处理';
                reprocessBtn.disabled = false;
            }, 300);
        });

        // 刷新页面按钮
        const refreshBtn = document.createElement('button');
        refreshBtn.className = 'luogu-quick-btn';
        refreshBtn.textContent = '♻️ 刷新';
        refreshBtn.title = '刷新整个页面';
        refreshBtn.addEventListener('click', fullRefreshPage);

        // 管理按钮
        const manageBtn = document.createElement('button');
        manageBtn.className = 'luogu-quick-btn';
        manageBtn.textContent = '⚙️ 管理';
        manageBtn.title = '打开主题管理器';
        manageBtn.addEventListener('click', showThemeManager);

        menu.appendChild(themeBtn);
        menu.appendChild(reprocessBtn);
        menu.appendChild(refreshBtn);
        menu.appendChild(manageBtn);

        document.body.appendChild(menu);
    }

    // 显示主题管理器
    function showThemeManager() {
        removeExistingPanels();

        // 创建遮罩层
        const overlay = document.createElement('div');
        overlay.className = 'luogu-panel-overlay';

        // 创建主面板
        const panel = document.createElement('div');
        panel.id = 'luogu-main-panel';

        // 构建选项卡
        let html = `
            <div class="luogu-tabs">
                <button class="luogu-tab active" data-tab="themes">主题管理</button>
                <button class="luogu-tab" data-tab="editor">主题编辑</button>
                <button class="luogu-tab" data-tab="settings">设置</button>
            </div>
            <div id="luogu-tab-content" style="min-height: 400px;"></div>
        `;

        panel.innerHTML = html;

        // 添加到页面
        document.body.appendChild(overlay);
        document.body.appendChild(panel);

        // 初始化选项卡内容
        showTabContent('themes');

        // 选项卡点击事件
        panel.querySelectorAll('.luogu-tab').forEach(tab => {
            tab.addEventListener('click', function() {
                panel.querySelectorAll('.luogu-tab').forEach(t => t.classList.remove('active'));
                this.classList.add('active');
                showTabContent(this.getAttribute('data-tab'));
            });
        });

        // 点击遮罩层关闭
        overlay.addEventListener('click', () => {
            removeExistingPanels();
        });
    }

    // 显示选项卡内容
    function showTabContent(tabName) {
        const content = document.querySelector('#luogu-tab-content');
        if (!content) return;

        switch(tabName) {
            case 'themes':
                content.innerHTML = getThemesManagementContent();
                setupThemesManagementEvents();
                break;
            case 'editor':
                content.innerHTML = getThemeEditorContent();
                setupThemeEditorEvents();
                break;
            case 'settings':
                content.innerHTML = getSettingsContent();
                setupSettingsEvents();
                break;
        }
    }

    // 获取主题管理内容
    function getThemesManagementContent() {
        const themes = storage.themes;
        const currentTheme = storage.currentTheme;

        let html = `
            <h3 style="margin-top:0">主题管理</h3>
            <div style="margin-bottom:15px">
                <button id="luogu-new-theme" class="luogu-panel-btn primary">新建主题</button>
                <button id="luogu-duplicate-theme" class="luogu-panel-btn secondary">复制当前主题</button>
                <button id="luogu-reprocess-btn" class="luogu-panel-btn success">重新处理标签</button>
                <button id="luogu-full-refresh" class="luogu-panel-btn danger">刷新页面</button>
            </div>
            <div class="luogu-themes-list">
        `;

        Object.values(themes).forEach(theme => {
            const isCurrent = theme.name === currentTheme;
            const createdDate = new Date(theme.created).toLocaleDateString();
            const updatedDate = new Date(theme.updated).toLocaleDateString();

            html += `
                <div class="luogu-theme-item ${isCurrent ? 'current' : ''}" data-theme="${theme.name}">
                    <div class="luogu-theme-info">
                        <div class="luogu-theme-name">${theme.name}</div>
                        <div class="luogu-theme-meta">
                            创建: ${createdDate} | 更新: ${updatedDate}
                        </div>
                    </div>
                    <div class="luogu-theme-actions">
                        ${!isCurrent ?
                            `<button class="luogu-action-btn apply" data-action="apply">应用</button>` :
                            `<span style="color:#4CAF50;font-weight:bold">✓ 当前</span>`
                        }
                        <button class="luogu-action-btn rename" data-action="rename">重命名</button>
                        ${Object.keys(themes).length > 1 ?
                            `<button class="luogu-action-btn delete" data-action="delete">删除</button>` :
                            ''
                        }
                    </div>
                </div>
            `;
        });

        html += `
            </div>
            <div class="luogu-panel-footer">
                <button id="luogu-close-panel" class="luogu-panel-btn secondary">关闭</button>
            </div>
        `;

        return html;
    }

    // 设置主题管理事件
    function setupThemesManagementEvents() {
        const panel = document.querySelector('#luogu-main-panel');
        if (!panel) return;

        // 新建主题
        panel.querySelector('#luogu-new-theme')?.addEventListener('click', () => {
            showCreateThemeModal();
        });

        // 复制当前主题
        panel.querySelector('#luogu-duplicate-theme')?.addEventListener('click', () => {
            showDuplicateThemeModal();
        });

        // 重新处理标签
        panel.querySelector('#luogu-reprocess-btn')?.addEventListener('click', () => {
            removeExistingPanels();
            processAllDifficulties();
            alert('已重新处理难度标签');
        });

        // 刷新页面
        panel.querySelector('#luogu-full-refresh')?.addEventListener('click', () => {
            removeExistingPanels();
            fullRefreshPage();
        });

        // 主题操作按钮
        panel.querySelectorAll('.luogu-action-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const themeItem = this.closest('.luogu-theme-item');
                const themeName = themeItem.getAttribute('data-theme');
                const action = this.getAttribute('data-action');

                switch(action) {
                    case 'apply':
                        applyTheme(themeName);
                        break;
                    case 'rename':
                        showRenameThemeModal(themeName);
                        break;
                    case 'delete':
                        deleteTheme(themeName);
                        break;
                }
            });
        });

        // 关闭面板
        panel.querySelector('#luogu-close-panel')?.addEventListener('click', () => {
            removeExistingPanels();
        });
    }

    // 获取主题编辑内容
    function getThemeEditorContent() {
        const config = getCurrentConfig();

        let html = `
            <h3 style="margin-top:0">编辑当前主题: ${storage.currentTheme}</h3>
            <p style="color:#666;margin-bottom:15px">修改当前主题的难度显示配置</p>
            <div class="luogu-difficulty-editor">
        `;

        DIFFICULTIES.forEach(diff => {
            const configItem = config[diff] || { type: 'text', value: diff, color: '#95a5a6' };

            html += `
                <div class="luogu-difficulty-item" data-difficulty="${diff}">
                    <div class="luogu-difficulty-header">${diff}</div>
                    <div class="luogu-option-group">
                        <span class="luogu-option-label">类型:</span>
                        <select class="luogu-option-input type-select">
                            <option value="text" ${configItem.type === 'text' ? 'selected' : ''}>文字</option>
                            <option value="image" ${configItem.type === 'image' ? 'selected' : ''}>图片</option>
                        </select>
                    </div>
                    <div class="luogu-option-group">
                        <span class="luogu-option-label">内容:</span>
                        <input type="text" class="luogu-option-input content-input"
                               value="${configItem.value || diff}"
                               placeholder="${configItem.type === 'text' ? '输入文字' : '输入图片URL'}">
                    </div>
                    ${configItem.type === 'text' ? `
                        <div class="luogu-option-group">
                            <span class="luogu-option-label">颜色:</span>
                            <input type="color" class="luogu-color-input color-input"
                                   value="${configItem.color || '#95a5a6'}">
                        </div>
                    ` : ''}
                </div>
            `;
        });

        html += `
            </div>
            <div class="luogu-panel-footer">
                <button id="luogu-save-config" class="luogu-panel-btn success">保存更改</button>
                <button id="luogu-reset-config" class="luogu-panel-btn secondary">重置为默认</button>
                <button id="luogu-reprocess-btn2" class="luogu-panel-btn primary">重新处理</button>
                <button id="luogu-full-refresh2" class="luogu-panel-btn danger">刷新页面</button>
                <button id="luogu-close-panel2" class="luogu-panel-btn secondary">关闭</button>
            </div>
        `;

        return html;
    }

    // 设置主题编辑事件
    function setupThemeEditorEvents() {
        const panel = document.querySelector('#luogu-main-panel');
        if (!panel) return;

        // 类型选择改变事件
        panel.querySelectorAll('.type-select').forEach(select => {
            select.addEventListener('change', function() {
                const item = this.closest('.luogu-difficulty-item');
                const colorInput = item.querySelector('.color-input');
                const contentInput = item.querySelector('.content-input');

                if (this.value === 'image') {
                    if (colorInput) colorInput.style.display = 'none';
                    contentInput.placeholder = '输入图片URL';
                } else {
                    if (colorInput) {
                        colorInput.style.display = 'block';
                        colorInput.value = colorInput.value || '#95a5a6';
                    }
                    contentInput.placeholder = '输入文字';
                }
            });
        });

        // 保存配置
        panel.querySelector('#luogu-save-config')?.addEventListener('click', () => {
            saveThemeConfig();
        });

        // 重置配置
        panel.querySelector('#luogu-reset-config')?.addEventListener('click', () => {
            if (confirm('确定要重置当前主题的配置为默认值吗?')) {
                const defaultTheme = DEFAULT_THEMES[storage.currentTheme] || DEFAULT_THEMES['经典图标主题'];
                updateCurrentConfig(JSON.parse(JSON.stringify(defaultTheme.config)));
                showTabContent('editor'); // 刷新编辑器
                setTimeout(() => {
                    processAllDifficulties();
                    updateQuickMenu();
                }, 100);
            }
        });

        // 重新处理
        panel.querySelector('#luogu-reprocess-btn2')?.addEventListener('click', () => {
            removeExistingPanels();
            processAllDifficulties();
            alert('已重新处理难度标签');
        });

        // 刷新页面
        panel.querySelector('#luogu-full-refresh2')?.addEventListener('click', () => {
            removeExistingPanels();
            fullRefreshPage();
        });

        // 关闭面板
        panel.querySelector('#luogu-close-panel2')?.addEventListener('click', () => {
            removeExistingPanels();
        });
    }

    // 获取设置内容
    function getSettingsContent() {
        return `
            <h3 style="margin-top:0">设置</h3>
            <div style="margin-bottom:15px">
                <label style="display:flex;align-items:center;margin-bottom:10px">
                    <input type="checkbox" id="auto-refresh" ${storage.settings.autoRefresh ? 'checked' : ''}
                           style="margin-right:8px">
                    <span>自动刷新页面变化</span>
                </label>
                <label style="display:flex;align-items:center;margin-bottom:10px">
                    <input type="checkbox" id="show-refresh-btn" ${storage.settings.showRefreshButton ? 'checked' : ''}
                           style="margin-right:8px">
                    <span>显示快速切换菜单</span>
                </label>
            </div>
            <div class="luogu-panel-footer">
                <button id="luogu-save-settings" class="luogu-panel-btn success">保存设置</button>
                <button id="luogu-close-panel3" class="luogu-panel-btn secondary">关闭</button>
            </div>
        `;
    }

    // 设置设置事件
    function setupSettingsEvents() {
        const panel = document.querySelector('#luogu-main-panel');
        if (!panel) return;

        // 保存设置
        panel.querySelector('#luogu-save-settings')?.addEventListener('click', () => {
            const autoRefresh = panel.querySelector('#auto-refresh').checked;
            const showRefreshBtn = panel.querySelector('#show-refresh-btn').checked;

            storage.settings.autoRefresh = autoRefresh;
            storage.settings.showRefreshButton = showRefreshBtn;
            saveStorage();

            if (showRefreshBtn) {
                addQuickMenu();
            } else {
                const quickMenu = document.querySelector('.luogu-quick-menu');
                if (quickMenu) quickMenu.remove();
            }

            alert('设置已保存');
        });

        // 关闭面板
        panel.querySelector('#luogu-close-panel3')?.addEventListener('click', () => {
            removeExistingPanels();
        });
    }

    // 显示快速切换主题面板
    function showQuickSwitch() {
        removeExistingPanels();

        const overlay = document.createElement('div');
        overlay.className = 'luogu-panel-overlay';

        const modal = document.createElement('div');
        modal.className = 'luogu-modal';
        modal.innerHTML = `
            <div class="luogu-modal-title">快速切换主题</div>
            <div style="max-height:300px;overflow-y:auto;margin-bottom:15px">
                ${Object.values(storage.themes).map(theme => {
                    const isCurrent = theme.name === storage.currentTheme;
                    return `
                        <div style="padding:10px;border-bottom:1px solid #eee;cursor:pointer;background:${isCurrent ? '#e3f2fd' : 'white'}"
                             class="luogu-quick-theme" data-theme="${theme.name}">
                            <div style="font-weight:bold">${theme.name}</div>
                            ${isCurrent ? '<div style="color:#4CAF50;font-size:12px">✓ 当前主题</div>' : ''}
                        </div>
                    `;
                }).join('')}
            </div>
            <div class="luogu-modal-footer">
                <button id="luogu-cancel-switch" class="luogu-panel-btn secondary">取消</button>
            </div>
        `;

        document.body.appendChild(overlay);
        document.body.appendChild(modal);

        // 主题点击事件
        modal.querySelectorAll('.luogu-quick-theme').forEach(item => {
            item.addEventListener('click', function() {
                const themeName = this.getAttribute('data-theme');
                applyTheme(themeName);
                removeExistingPanels();
            });
        });

        // 取消按钮
        modal.querySelector('#luogu-cancel-switch')?.addEventListener('click', () => {
            removeExistingPanels();
        });

        // 遮罩层点击关闭
        overlay.addEventListener('click', () => {
            removeExistingPanels();
        });
    }

    // 应用主题
    function applyTheme(themeName) {
        if (!storage.themes[themeName]) {
            alert('主题不存在');
            return;
        }

        storage.currentTheme = themeName;
        saveStorage();

        console.log(`已切换到主题: ${themeName}`);
        processAllDifficulties();
        updateQuickMenu();

        // 如果主题管理器开着,刷新它
        const panel = document.querySelector('#luogu-main-panel');
        if (panel) {
            showTabContent('themes');
        }
    }

    // 更新快速菜单
    function updateQuickMenu() {
        const themeBtn = document.querySelector('.luogu-quick-btn.theme-switch');
        if (themeBtn) {
            themeBtn.textContent = `主题: ${storage.currentTheme}`;
        }
    }

    // 显示创建主题模态框
    function showCreateThemeModal() {
        removeExistingPanels();

        const overlay = document.createElement('div');
        overlay.className = 'luogu-panel-overlay';

        const modal = document.createElement('div');
        modal.className = 'luogu-modal';
        modal.innerHTML = `
            <div class="luogu-modal-title">新建主题</div>
            <input type="text" id="luogu-new-theme-name" class="luogu-modal-input"
                   placeholder="输入主题名称" maxlength="20">
            <div style="margin-bottom:15px">
                <label style="display:block;margin-bottom:5px">基于现有主题:</label>
                <select id="luogu-base-theme" class="luogu-modal-input">
                    <option value="">空主题</option>
                    ${Object.values(storage.themes).map(theme =>
                        `<option value="${theme.name}">${theme.name}</option>`
                    ).join('')}
                </select>
            </div>
            <div class="luogu-modal-footer">
                <button id="luogu-confirm-create" class="luogu-panel-btn success">创建</button>
                <button id="luogu-cancel-create" class="luogu-panel-btn secondary">取消</button>
            </div>
        `;

        document.body.appendChild(overlay);
        document.body.appendChild(modal);

        // 创建按钮
        modal.querySelector('#luogu-confirm-create')?.addEventListener('click', () => {
            const themeName = modal.querySelector('#luogu-new-theme-name').value.trim();
            const baseTheme = modal.querySelector('#luogu-base-theme').value;

            if (!themeName) {
                alert('请输入主题名称');
                return;
            }

            if (storage.themes[themeName]) {
                alert('主题名称已存在');
                return;
            }

            // 创建新主题
            const now = new Date().toISOString();
            let config;

            if (baseTheme && storage.themes[baseTheme]) {
                config = JSON.parse(JSON.stringify(storage.themes[baseTheme].config));
            } else {
                config = JSON.parse(JSON.stringify(DEFAULT_THEMES['经典图标主题'].config));
            }

            storage.themes[themeName] = {
                name: themeName,
                created: now,
                updated: now,
                config: config
            };

            saveStorage();
            removeExistingPanels();
            showThemeManager();
        });

        // 取消按钮
        modal.querySelector('#luogu-cancel-create')?.addEventListener('click', () => {
            removeExistingPanels();
            showThemeManager();
        });

        // 遮罩层点击关闭
        overlay.addEventListener('click', () => {
            removeExistingPanels();
            showThemeManager();
        });
    }

    // 显示复制主题模态框
    function showDuplicateThemeModal() {
        const currentTheme = storage.themes[storage.currentTheme];
        const newName = `${currentTheme.name} 副本`;

        showCreateThemeModal();

        // 设置默认值
        setTimeout(() => {
            const nameInput = document.querySelector('#luogu-new-theme-name');
            const baseSelect = document.querySelector('#luogu-base-theme');
            if (nameInput && baseSelect) {
                nameInput.value = newName;
                baseSelect.value = storage.currentTheme;
            }
        }, 50);
    }

    // 显示重命名主题模态框
    function showRenameThemeModal(themeName) {
        removeExistingPanels();

        const overlay = document.createElement('div');
        overlay.className = 'luogu-panel-overlay';

        const modal = document.createElement('div');
        modal.className = 'luogu-modal';
        modal.innerHTML = `
            <div class="luogu-modal-title">重命名主题</div>
            <input type="text" id="luogu-rename-theme-name" class="luogu-modal-input"
                   value="${themeName}" placeholder="输入新的主题名称" maxlength="20">
            <div class="luogu-modal-footer">
                <button id="luogu-confirm-rename" class="luogu-panel-btn success">确定</button>
                <button id="luogu-cancel-rename" class="luogu-panel-btn secondary">取消</button>
            </div>
        `;

        document.body.appendChild(overlay);
        document.body.appendChild(modal);

        // 重命名按钮
        modal.querySelector('#luogu-confirm-rename')?.addEventListener('click', () => {
            const newName = modal.querySelector('#luogu-rename-theme-name').value.trim();

            if (!newName) {
                alert('请输入新的主题名称');
                return;
            }

            if (newName === themeName) {
                removeExistingPanels();
                showThemeManager();
                return;
            }

            if (storage.themes[newName]) {
                alert('主题名称已存在');
                return;
            }

            // 重命名主题
            const theme = storage.themes[themeName];
            theme.name = newName;
            theme.updated = new Date().toISOString();

            // 更新主题列表
            storage.themes[newName] = theme;
            delete storage.themes[themeName];

            // 如果当前主题被重命名,更新当前主题
            if (storage.currentTheme === themeName) {
                storage.currentTheme = newName;
            }

            saveStorage();
            removeExistingPanels();
            showThemeManager();
        });

        // 取消按钮
        modal.querySelector('#luogu-cancel-rename')?.addEventListener('click', () => {
            removeExistingPanels();
            showThemeManager();
        });

        // 遮罩层点击关闭
        overlay.addEventListener('click', () => {
            removeExistingPanels();
            showThemeManager();
        });
    }

    // 删除主题
    function deleteTheme(themeName) {
        if (Object.keys(storage.themes).length <= 1) {
            alert('不能删除最后一个主题');
            return;
        }

        if (storage.currentTheme === themeName) {
            alert('不能删除当前正在使用的主题,请先切换到其他主题');
            return;
        }

        if (confirm(`确定要删除主题 "${themeName}" 吗?`)) {
            delete storage.themes[themeName];
            saveStorage();

            // 刷新主题管理器
            const panel = document.querySelector('#luogu-main-panel');
            if (panel) {
                showTabContent('themes');
            }
        }
    }

    // 保存主题配置
    function saveThemeConfig() {
        const config = {};

        DIFFICULTIES.forEach(diff => {
            const item = document.querySelector(`[data-difficulty="${diff}"]`);
            if (item) {
                const type = item.querySelector('.type-select').value;
                const value = item.querySelector('.content-input').value.trim();
                const color = type === 'text' ? item.querySelector('.color-input')?.value : undefined;

                config[diff] = {
                    type: type,
                    value: value || diff,
                    color: color || '#95a5a6'
                };
            }
        });

        if (updateCurrentConfig(config)) {
            alert('配置已保存');
            processAllDifficulties();
        } else {
            alert('保存失败');
        }
    }

    // 显示主题编辑器
    function showThemeEditor() {
        removeExistingPanels();

        const overlay = document.createElement('div');
        overlay.className = 'luogu-panel-overlay';

        const panel = document.createElement('div');
        panel.id = 'luogu-main-panel';
        panel.innerHTML = getThemeEditorContent();

        document.body.appendChild(overlay);
        document.body.appendChild(panel);

        setupThemeEditorEvents();

        overlay.addEventListener('click', () => {
            removeExistingPanels();
        });
    }

    // 移除所有面板
    function removeExistingPanels() {
        const panels = [
            '.luogu-panel-overlay',
            '#luogu-main-panel',
            '.luogu-modal'
        ];

        panels.forEach(selector => {
            const element = document.querySelector(selector);
            if (element) element.remove();
        });
    }

    // 监听页面变化
    function setupPageChangeListener() {
        if (!storage.settings.autoRefresh) return;

        const observer = new MutationObserver(() => {
            // 检查是否有新的难度标签出现
            const selectors = [
                '.difficulty-tags .row span:not(.problem-count):not(.luogu-processed)',
                '.lcolor--grey-3:not(.luogu-processed)',
                '.lcolor--pink-3:not(.luogu-processed)',
                '.lcolor--orange-3:not(.luogu-processed)',
                '.lcolor--gold-3:not(.luogu-processed)',
                '.lcolor--green-3:not(.luogu-processed)',
                '.lcolor--blue-3:not(.luogu-processed)',
                '.lcolor--purple-3:not(.luogu-processed)',
                '.lcolor--lapis-4:not(.luogu-processed)',
                '.difficulty:not(.luogu-processed)'
            ].join(',');

            const unprocessed = document.querySelectorAll(selectors);

            if (unprocessed.length > 0) {
                console.log(`检测到 ${unprocessed.length} 个新的难度元素,重新处理`);
                setTimeout(processAllDifficulties, 500);
            }
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    }

    // 初始化
    function init() {
        console.log('洛谷难度主题管理器 v10.3 启动 - 作者:鸡腿,PCY和祥子');

        // 加载存储数据
        loadStorage();

        // 初始处理
        setTimeout(() => {
            console.log('开始初始处理难度标签');
            processAllDifficulties();
            if (storage.settings.showRefreshButton) {
                addQuickMenu();
            }
        }, 2000);

        // 监听页面变化
        setupPageChangeListener();
    }

    // 启动
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        setTimeout(init, 1000);
    }
})();

事实上,脚本是 Deepseek 写的,不过,你会发现,版本号为 10.3,其实我们反复调教你好几次,确认每个页面的难度都可以正常显示,同时保证不会有内容识别出错,所以,即使是 AI 来干,我们也花费了三天时间来完善和扩展,也就变成了你现在看到的这样。

希望大家能喜欢这个脚本,谢谢了。我今天入谷时长两年半,感谢各位。

原文