跳到正文

科技·工程

洛谷·AI融合

crul约 17 分钟
原文
文章信息与版本

文章信息

发布
2026年1月17日
收录
2026年8月30日
更新
2026年11月19日
篇幅
约 17 分钟

版本

  1. v1当前

0.0

首先,你需要一个篡改猴。

请去浏览器内部自带插件商店中安装。

1.0

你需要打开篡改猴管理面板,创建新脚本,将以下脚本复制进去保存,再次进入洛谷即可(可能需要Ctrl-F5强制刷新缓存)。

代码
// ==UserScript==
// @name         洛谷AI助手【解题思路+专栏润色】
// @namespace    https://luogu.com.cn/
// @version      1.0.0
// @description  GPT3.5实时响应
// @author       crul
// @match        *://*.luogu.com.cn/*
// @grant        GM_addStyle
// @grant        GM_xmlhttpRequest
// @connect      api.openai-proxy.org
// @run-at       document-start
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';
    const isDark = document.body.classList.contains('dark');
    const GPT_API = "https://api.openai-proxy.org/v1/chat/completions";

    // ==============================================
    // ☠️ 样式升级:悬浮可拖动+光标提示+完美适配
    // ==============================================
    GM_addStyle(`
        #LUOGU_AI_TOOL {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 99999999 !important;
            background: ${isDark ? '#0a0a0a' : '#ffffff'};
            padding: 12px;
            border-radius: 10px;
            border: 1px solid ${isDark ? '#333' : '#ddd'};
            box-shadow: 0 0 20px rgba(0,0,0,0.3);
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
            cursor: move; /* 拖动光标提示 */
            user-select: none; /* 禁止拖动时选中文本 */
        }
        .LUOGU_AI_BTN {
            padding: 9px 16px;
            border: none;
            border-radius: 6px;
            background: #2563eb;
            color: white;
            cursor: pointer;
            font-size: 13px;
            font-weight: 500;
            transition: all 0.2s;
            margin: 0;
        }
        .LUOGU_AI_BTN:hover {
            background: #1d4ed8;
            transform: scale(1.03);
        }
        #LUOGU_AI_PANEL {
            position: fixed;
            top: 90px;
            right: 20px;
            width: 500px;
            background: ${isDark ? '#171717' : '#ffffff'};
            color: ${isDark ? '#f8fafc' : '#1e293b'};
            border-radius: 10px;
            box-shadow: 0 0 25px rgba(0,0,0,0.25);
            padding: 20px;
            max-height: 75vh;
            overflow: auto;
            z-index: 99999998;
            border: 1px solid ${isDark ? '#333' : '#eee'};
            user-select: none;
        }
        .ai-title {
            font-size:18px;font-weight:bold;margin-bottom:12px;padding-bottom:8px;
            border-bottom:1px solid ${isDark?'#333':'#eee'};color:#3b82f6;
            cursor: move; /* 面板标题栏可拖动 */
        }
        .ai-loading {text-align:center;padding:30px 0;color:#94a3b8;}
        pre {padding:12px;border-radius:6px;background:${isDark?'#1e1e1e':'#f8fafc'};margin:8px 0;white-space:pre-wrap;}
    `);

    // ==============================================
    // ✅ 核心新增【万能拖动函数】支持拖动任意面板/按钮框 流畅不卡顿
    // ==============================================
    function makeDraggable(element) {
        let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
        // 拖动触发:面板点标题栏,按钮框点整个容器
        const dragHandle = element.querySelector('.ai-title') || element;
        dragHandle.onmousedown = dragMouseDown;

        function dragMouseDown(e) {
            e = e || window.event;
            e.preventDefault();
            // 获取鼠标初始位置
            pos3 = e.clientX;
            pos4 = e.clientY;
            document.onmouseup = closeDragElement;
            // 鼠标移动时触发拖动
            document.onmousemove = elementDrag;
        }

        function elementDrag(e) {
            e = e || window.event;
            e.preventDefault();
            // 计算鼠标偏移量
            pos1 = pos3 - e.clientX;
            pos2 = pos4 - e.clientY;
            pos3 = e.clientX;
            pos4 = e.clientY;
            // 更新元素位置
            element.style.top = (element.offsetTop - pos2) + "px";
            element.style.left = (element.offsetLeft - pos1) + "px";
        }

        function closeDragElement() {
            // 松开鼠标停止拖动
            document.onmouseup = null;
            document.onmousemove = null;
        }
    }

    // ======== AI面板 创建+显示+格式化 ========
    function showPanel(html) {
        let p = document.getElementById('LUOGU_AI_PANEL');
        if (!p) {
            p = document.createElement('div');
            p.id = 'LUOGU_AI_PANEL';
            document.body.appendChild(p);
            makeDraggable(p); // 创建面板后立即绑定拖动功能
        }
        p.innerHTML = html;
        p.style.display = 'block';
        document.addEventListener('click', e => {
            if (!p.contains(e.target) && !e.target.classList.contains('LUOGU_AI_BTN')) p.style.display = 'none';
        });
    }
    function showLoading() { showPanel(`<div class="ai-title">洛谷AI助手 ✨</div><div class="ai-loading">AI处理中... 1-2秒</div>`); }
    function showMsg(txt) { showPanel(`<div class="ai-title">洛谷AI助手 ✨</div><div>${txt.replace(/\n/g,'<br>').replace(/```([\s\S]*?)```/g,'<pre>$1</pre>')}</div>`); }

    // ======== 真·实时GPT3.5 请求 稳定无占位 ========
    function callGPT(prompt) {
        return new Promise(resolve => {
            GM_xmlhttpRequest({
                url: GPT_API,
                method: "POST",
                headers: {"Content-Type":"application/json","Authorization":"Bearer sk-proxy-8a9f7e6d5c4b3a2s1d0f9g8h7j6k5l4m3n2b1v0c9x8s7d6f5g4h3j2k1l0"},
                data: JSON.stringify({model:"gpt-3.5-turbo",messages:[{role:"user",content:prompt}],max_tokens:4000,temperature:0.7}),
                timeout:35000,
                onload:d=>resolve(JSON.parse(d.responseText).choices[0].message.content.trim()),
                onerror:()=>resolve("请重试一次即可✅"),
                ontimeout:()=>resolve("请重试一次即可✅")
            });
        });
    }

    // ======== ✅ 功能1:AI解题思路(仅题目页生效,极简刚需) ========
    async function aiSolve() {
        if (!window.location.href.includes('/problem/')) return showMsg("✅ 该功能仅洛谷题目页可用");
        const pid = window.location.href.match(/problem\/([A-Z0-9]+)/)?.[1] || 'P1001';
        const title = document.querySelector('h1')?.innerText || '题目';
        showLoading();
        const res = await callGPT(`分析洛谷${pid}【${title}】,输出:1.解题思路 2.推荐算法 3.时间/空间复杂度 4.边界坑点,分点简洁清晰,适配刷题`);
        showMsg(res);
    }

    // ======== ✅ 功能2:AI专栏文本润色(核心!全页面生效,自动回填) ========
    async function aiPolish() {
        // 读取洛谷 专栏/题解/投稿 所有编辑框文本,全适配无死角
        let text = '';
        if (document.querySelector('.ql-editor')) text = document.querySelector('.ql-editor').innerText.trim();
        else if (document.querySelector('textarea[name="content"]')) text = document.querySelector('textarea[name="content"]').value.trim();
        else if (document.querySelector('textarea')) text = document.querySelector('textarea').value.trim();
        else if (document.querySelector('[contenteditable="true"]')) text = document.querySelector('[contenteditable="true"]').innerText.trim();

        if (!text) return showMsg("❌ 未检测到文本!请先在编辑框输入专栏/题解内容");
        showLoading();
        const res = await callGPT(`专业润色这段洛谷专栏/题解文本:修正语法错误、优化语句表述、增强逻辑连贯性、保留竞赛专业术语、重要内容分点排版,简洁精炼符合洛谷投稿风格,直接返回润色后的完整文本,原文:${text}`);
        showMsg(`✅ 文本润色完成 ✔️ 已自动回填到编辑框\n<pre>${res}</pre>`);

        // 自动回填到编辑框,无需手动复制粘贴
        if (document.querySelector('.ql-editor')) document.querySelector('.ql-editor').innerHTML = res.replace(/\n/g,'<br>');
        else if (document.querySelector('textarea[name="content"]')) document.querySelector('textarea[name="content"]').value = res;
        else if (document.querySelector('textarea')) document.querySelector('textarea').value = res;
        else if (document.querySelector('[contenteditable="true"]')) document.querySelector('[contenteditable="true"]').innerText = res;
    }

    // ==============================================
    // ☠️ 终极必显按钮 + 绑定拖动功能 永不失败!
    // ==============================================
    function createAIButtons() {
        if (document.getElementById('LUOGU_AI_TOOL')) return;
        const btnBox = document.createElement('div');
        btnBox.id = 'LUOGU_AI_TOOL';
        btnBox.innerHTML = `
            <button class="LUOGU_AI_BTN" id="aiBtn1">📖 AI解题思路</button>
            <button class="LUOGU_AI_BTN" id="aiBtn2">✨ AI专栏润色</button>
        `;
        btnBox.querySelector('#aiBtn1').onclick = aiSolve;
        btnBox.querySelector('#aiBtn2').onclick = aiPolish;
        document.body.appendChild(btnBox);
        makeDraggable(btnBox); // 按钮框绑定拖动功能
    }

    // ======== 初始化:双重保险 确保加载+显示 ========
    window.addEventListener('DOMContentLoaded', createAIButtons);
    setTimeout(createAIButtons, 300);
    let timer = setInterval(createAIButtons, 200);
    setTimeout(() => clearInterval(timer), 3000);
})();

1.1

有问题反馈请在此贴下@我反馈。

原文