跳到正文

科技·工程

洛谷题目难度自定义(稳定版)

jiangyunuo约 31 分钟
原文

这是 2026年2月8日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

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

版本

  1. v3当前
  2. v2
  3. v1
C++
// ==UserScript==
// @name         洛谷题目难度自定义(稳定版)
// @namespace    http://tampermonkey.net/
// @version      8.2
// @description  自定义洛谷题目难度图标,稳定可靠
// @author       You
// @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';

    // 默认配置
    const defaultConfig = {
        '入门': { 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' }
    };

    // 加载配置
    let config = GM_getValue('luogu_difficulty_config', defaultConfig);

    // 添加样式
    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-settings-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: 500px !important;
            max-width: 90vw !important;
            max-height: 80vh !important;
            overflow-y: auto !important;
        }

        .luogu-settings-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-refresh-btn {
            position: fixed !important;
            bottom: 15px !important;
            right: 15px !important;
            padding: 6px 12px !important;
            background: #4CAF50 !important;
            color: white !important;
            border: none !important;
            border-radius: 4px !important;
            cursor: pointer !important;
            font-size: 12px !important;
            z-index: 1000 !important;
            font-weight: bold !important;
        }
    `);

    // 注册菜单命令
    GM_registerMenuCommand('自定义难度显示', showSettings);

    // 标准化难度文本
    function normalizeDifficultyText(text) {
        if (!text) return '';

        // 移除空白字符
        text = text.replace(/\s+/g, '');

        // 将Unicode减号转换为普通减号
        text = text.replace(/[\u2212]/g, '-');

        return text;
    }

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

        const difficulties = [
            '入门', '普及-', '普及/提高-', '普及+/提高',
            '提高+/省选-', '省选/NOI-', 'NOI/NOI+/CTSC', '暂无评定'
        ];

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

        return null;
    }

    // 查找难度元素 - 简化版
    function findDifficultyElements() {
        const elements = [];

        // 1. 题目列表页的难度标签
        const difficultySpans = document.querySelectorAll('.difficulty');
        difficultySpans.forEach(el => {
            if (!el.classList.contains('luogu-processed')) {
                elements.push(el);
            }
        });

        // 2. 包含难度文本的span
        const allSpans = document.querySelectorAll('span');
        allSpans.forEach(span => {
            if (span.classList.contains('luogu-processed')) return;

            const text = span.textContent.trim();
            const difficulty = getDifficultyLevel(text);

            if (difficulty) {
                // 检查是否有背景色或特定类名,避免误匹配
                const style = span.getAttribute('style') || '';
                const className = span.className || '';

                if (style.includes('background-color') ||
                    className.includes('lcolor--') ||
                    span.parentElement?.classList?.contains('difficulty') ||
                    span.closest('a[href*="difficulty"]')) {
                    elements.push(span);
                }
            }
        });

        // 3. 包含难度文本的a标签
        const allLinks = document.querySelectorAll('a');
        allLinks.forEach(link => {
            if (link.classList.contains('luogu-processed')) return;

            const text = link.textContent.trim();
            const difficulty = getDifficultyLevel(text);

            if (difficulty && link.href.includes('difficulty')) {
                elements.push(link);
            }
        });

        // 去重
        return [...new Set(elements)];
    }

    // 获取对比色
    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);
            const brightness = (r * 299 + g * 587 + b * 114) / 1000;

            return brightness > 128 ? '#000000' : '#ffffff';
        } catch (e) {
            return '#ffffff';
        }
    }

    // 替换难度元素
    function replaceDifficultyElement(element) {
        const text = element.textContent.trim();
        const difficulty = getDifficultyLevel(text);

        if (!difficulty) return false;

        const configItem = config[difficulty];
        if (!configItem) return false;

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

            // 保存原始内容
            element.setAttribute('data-luogu-original', element.innerHTML);

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

            // 清除样式
            element.style.cssText = '';
            element.style.display = 'inline-block';
            element.style.verticalAlign = 'middle';

            // 创建新内容
            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';
                element.appendChild(img);
            } else {
                // 文字模式
                const span = document.createElement('span');
                span.textContent = configItem.value || difficulty;
                span.className = 'luogu-custom-difficulty';
                span.style.backgroundColor = configItem.color;
                span.style.color = getContrastColor(configItem.color);
                element.appendChild(span);
            }

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

    // 恢复难度元素
    function restoreDifficultyElement(element) {
        const original = element.getAttribute('data-luogu-original');
        if (original) {
            element.innerHTML = original;
        }
        element.classList.remove('luogu-processed');
        element.removeAttribute('data-luogu-original');
        element.style.cssText = '';
    }

    // 主处理函数
    function processAllDifficulties() {
        console.log('开始处理难度标签...');

        // 查找所有难度元素
        const elements = findDifficultyElements();
        console.log(`找到 ${elements.length} 个难度元素`);

        if (elements.length === 0) {
            // 如果没有找到,稍后再试一次
            setTimeout(processAllDifficulties, 1000);
            return;
        }

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

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

    // 强制刷新
    function forceRefresh() {
        // 恢复所有已处理的元素
        const processedElements = document.querySelectorAll('.luogu-processed');
        processedElements.forEach(restoreDifficultyElement);

        // 重新处理
        setTimeout(processAllDifficulties, 100);
    }

    // 添加刷新按钮
    function addRefreshButton() {
        // 移除已存在的按钮
        const existingBtn = document.querySelector('.luogu-refresh-btn');
        if (existingBtn) existingBtn.remove();

        // 创建新按钮
        const btn = document.createElement('button');
        btn.className = 'luogu-refresh-btn';
        btn.textContent = '🔄 刷新难度显示';
        btn.onclick = forceRefresh;
        document.body.appendChild(btn);
    }

    // 显示设置面板
    function showSettings() {
        // 移除已存在的面板
        const oldOverlay = document.querySelector('.luogu-settings-overlay');
        const oldPanel = document.querySelector('#luogu-settings-panel');
        if (oldOverlay) oldOverlay.remove();
        if (oldPanel) oldPanel.remove();

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

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

        // 构建设置内容
        let html = '<h2 style="margin-top:0">洛谷难度自定义设置</h2>';
        html += '<p>为每个难度等级设置自定义显示:</p>';
        html += '<div style="max-height:400px;overflow-y:auto">';

        const difficulties = Object.keys(defaultConfig);
        difficulties.forEach(diff => {
            const configItem = config[diff] || defaultConfig[diff];
            html += `
                <div style="margin-bottom:10px;padding:10px;border:1px solid #ddd;border-radius:5px">
                    <div style="font-weight:bold;margin-bottom:5px">${diff}</div>
                    <div>
                        <select style="margin-right:10px" data-diff="${diff}">
                            <option value="text" ${configItem.type === 'text' ? 'selected' : ''}>文字</option>
                            <option value="image" ${configItem.type === 'image' ? 'selected' : ''}>图片</option>
                        </select>
                        <input type="text" data-diff="${diff}" value="${configItem.value || ''}"
                               placeholder="${configItem.type === 'text' ? '输入文字' : '输入图片URL'}"
                               style="width:200px;margin-right:10px">
                        ${configItem.type === 'text' ?
                            `<input type="color" data-diff="${diff}" value="${configItem.color}" style="vertical-align:middle">` : ''}
                    </div>
                </div>
            `;
        });

        html += '</div>';
        html += `
            <div style="margin-top:15px;text-align:right">
                <button id="luogu-save" style="margin-right:10px">保存</button>
                <button id="luogu-reset">恢复默认</button>
                <button id="luogu-close" style="margin-left:10px">关闭</button>
            </div>
        `;

        panel.innerHTML = html;

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

        // 事件处理
        panel.querySelectorAll('select').forEach(select => {
            select.addEventListener('change', function() {
                const diff = this.getAttribute('data-diff');
                const input = panel.querySelector(`input[type="text"][data-diff="${diff}"]`);
                input.placeholder = this.value === 'image' ? '输入图片URL' : '输入文字';
            });
        });

        panel.querySelector('#luogu-save').addEventListener('click', function() {
            const newConfig = {};
            difficulties.forEach(diff => {
                const select = panel.querySelector(`select[data-diff="${diff}"]`);
                const input = panel.querySelector(`input[type="text"][data-diff="${diff}"]`);
                const colorInput = panel.querySelector(`input[type="color"][data-diff="${diff}"]`);

                if (select && input) {
                    const type = select.value;
                    const value = input.value.trim();
                    const color = colorInput ? colorInput.value : undefined;

                    newConfig[diff] = {
                        type: type,
                        value: value || defaultConfig[diff].value,
                        color: type === 'text' ? (color || defaultConfig[diff].color) : undefined
                    };
                }
            });

            GM_setValue('luogu_difficulty_config', newConfig);
            config = newConfig;
            forceRefresh();
            alert('设置已保存!');

            overlay.remove();
            panel.remove();
        });

        panel.querySelector('#luogu-reset').addEventListener('click', function() {
            if (confirm('恢复默认设置?')) {
                GM_setValue('luogu_difficulty_config', defaultConfig);
                config = defaultConfig;
                forceRefresh();
                alert('已恢复默认');
                overlay.remove();
                panel.remove();
            }
        });

        panel.querySelector('#luogu-close').addEventListener('click', function() {
            overlay.remove();
            panel.remove();
        });

        overlay.addEventListener('click', function() {
            overlay.remove();
            panel.remove();
        });
    }

    // 初始化
    function init() {
        console.log('洛谷难度自定义脚本启动');

        // 初始处理
        setTimeout(() => {
            processAllDifficulties();
            addRefreshButton();
        }, 2000);

        // 监听DOM变化
        const observer = new MutationObserver(() => {
            // 延迟处理,避免频繁执行
            setTimeout(processAllDifficulties, 500);
        });

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

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