Ac wing AC 自动机

· · 个人记录

// ==UserScript==
// @name         GenGen AcWing 自动机
// @namespace    http://tampermonkey.net/
// @version      2.1.1
// @match        https://www.acwing.com/*
// @grant        none
// ==/UserScript==

(function () {
    'use strict';

    const API_KEY = 'sk-PrJRPBgNcAXcRJnIKAiWIC9e5pkTfxbOTOAZkOCmMPX1lyrh';
    const MODEL = 'zai-org/GLM-4.5';
    const PROMPT_PREFIX = '请根据以下题目 HTML 内容,用 C++ 编写解决方案。只返回完整可运行代码,不要解释。要求:1) 代码风格紧凑;2) 所有变量名(包括函数参数、局部变量、全局变量)长度不超过3个字符;3) 少用 vector(尤其二维),图用 vector<int>g[N];4) 可使用 map 等 STL;5) 使用 cin/cout;6) 尽量使用 #include<bits/stdc++.h>。7) 使用tab而不是空格 8) 不用return 0在主函数';

    let isRunning = false;
    let autoEnabled = localStorage.getItem('genGenAutoEnabled') !== 'false';
    let nextRunInstant = false;

    function getRealEditor() {
        const aceDiv = document.querySelector('.ace_editor');
        return aceDiv?.env?.editor || null;
    }

    async function simulateTyping(editor, fullCode) {
        if (nextRunInstant) {
            editor.setValue(fullCode, -1);
            const lines = fullCode.split('\n');
            editor.selection.moveTo(lines.length - 1, lines[lines.length - 1].length);
            await new Promise(r => setTimeout(r, 50));
            const submitBtn = document.querySelector('button.btn.btn-success.ac-saber-submit-code-btn');
            if (submitBtn) {
                submitBtn.click();
                console.log('已提交');
            }
            nextRunInstant = false;
            updateUI();
            return;
        }

        const chars = fullCode.split('');
        let current = '';
        let i = 0;

        const getCharDelay = () => 233 + Math.floor(Math.random() * 82);

        const typeNext = () => {
            if (i >= chars.length) {
                setTimeout(() => {
                    const submitBtn = document.querySelector('button.btn.btn-success.ac-saber-submit-code-btn');
                    if (submitBtn) {
                        submitBtn.click();
                        console.log('已提交');
                    }
                }, 200);
                return;
            }

            current += chars[i];
            i++;
            editor.setValue(current, -1);
            const lines = current.split('\n');
            const row = lines.length - 1;
            const column = lines[row].length;
            editor.selection.moveTo(row, column);

            setTimeout(typeNext, getCharDelay());
        };

        typeNext();
    }

    function extractCode(md) {
        const m = md.match(/```(?:\w+)?\s*([\s\S]*?)\s*```/);
        return m ? m[1].trim() : md.trim();
    }

    async function runAI() {
        if (isRunning) return;
        isRunning = true;
        console.clear();
        console.log('=== GenGen v2.1.1 (支持发送编辑器内容) ===');

        const martor = document.querySelector('.section-martor');
        const editor = getRealEditor();
        if (!martor || !editor) {
            isRunning = false;
            return;
        }

        try {
            editor.setOption('enableBasicAutocompletion', false);
            editor.setOption('enableLiveAutocompletion', false);
            editor.setOption('enableSnippets', false);
            editor.getSession().setMode('ace/mode/c_cpp');
        } catch (e) {
            console.warn('无法设置 ACE 选项:', e);
        }

        // ✅ 读取当前编辑器内容(即使要清空,也先发给 AI)
        const existingCode = editor.getValue().trim();

        // ✅ 清空编辑器(按你要求)
        editor.setValue('', -1);

        const html = martor.innerHTML.trim();

        // ✅ 如果有已有代码,附加到 prompt 中
        const context = existingCode
            ? `\n\n【注意:当前编辑器已有以下代码,请基于此上下文生成完整解决方案】\n\`\`\`cpp\n${existingCode}\n\`\`\``
            : '';

        const prompt = PROMPT_PREFIX + html + context + '/no_think';
        const preview = createPreview();

        let rawResponse = '';

        try {
            const res = await fetch('https://api.suanli.cn/v1/chat/completions', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${API_KEY}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    model: MODEL,
                    messages: [{ role: 'user', content: prompt }],
                    stream: true
                })
            });

            if (!res.ok) {
                const errText = await res.text();
                console.error('[AI] HTTP Error:', res.status, errText);
                isRunning = false;
                return;
            }

            const reader = res.body.getReader();
            const decoder = new TextDecoder();

            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                const chunk = decoder.decode(value, { stream: true });
                const lines = chunk.split('\n').filter(line => {
                    return line.trim() !== '' && line !== ': keep-alive';
                });

                for (const line of lines) {
                    let jsonStr = '';
                    if (line.startsWith('data:')) {
                        jsonStr = line.substring(5).trim();
                    } else if (line.startsWith('{')) {
                        jsonStr = line.trim();
                    } else {
                        continue;
                    }

                    if (jsonStr === '[DONE]') continue;

                    try {
                        const parsed = JSON.parse(jsonStr);
                        const token = parsed.choices?.[0]?.delta?.content || '';
                        if (token) {
                            rawResponse += token;
                            preview.textContent = rawResponse;
                        }
                    } catch (e) {
                        console.warn('[JSON Parse Error]', e, 'Line:', line);
                    }
                }
            }

            let code = extractCode(rawResponse);
            console.log('[原始 AI 代码]', code);

            if (code) {
                await simulateTyping(editor, code);
                console.log("OK");
            }
        } catch (err) {
            console.error('[AI] Fatal Error:', err);
        } finally {
            isRunning = false;
            setTimeout(() => {
                const el = document.getElementById('genGen-raw-preview');
                if (el) el.remove();
            }, 5000);
        }
    }

    function createPreview() {
        let el = document.getElementById('genGen-raw-preview');
        if (!el) {
            el = document.createElement('div');
            el.id = 'genGen-raw-preview';
            el.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                width: 550px;
                max-height: 450px;
                background: #0d0d0d;
                color: #ff6600;
                padding: 14px;
                border-radius: 8px;
                font-family: 'Courier New', monospace;
                font-size: 13px;
                white-space: pre-wrap;
                overflow: auto;
                z-index: 9999999;
                border: 1px solid #ff6600;
                box-shadow: 0 0 15px rgba(255, 102, 0, 0.4);
                line-height: 1.4;
            `;
            document.body.appendChild(el);
        }
        el.textContent = '[AI 正在生成...]';
        return el;
    }

    function createControlPanel() {
        if (document.getElementById('genGen-panel')) return;

        const panel = document.createElement('div');
        panel.id = 'genGen-panel';
        panel.style.cssText = `
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 9999999;
            background: rgba(0,0,0,0.85);
            color: white;
            padding: 10px;
            border-radius: 10px;
            font-size: 13px;
            display: flex;
            align-items: center;
            gap: 10px;
            backdrop-filter: blur(5px);
            box-shadow: 0 2px 10px rgba(0,0,0,0.6);
        `;

        const toggle = document.createElement('label');
        toggle.innerHTML = `
            <input type="checkbox" id="genGen-auto" style="display:none;">
            <span style="
                width: 36px;
                height: 18px;
                background: ${autoEnabled ? '#ff6600' : '#555'};
                display: inline-block;
                border-radius: 9px;
                position: relative;
                cursor: pointer;
            ">
                <span style="
                    position: absolute;
                    top: 2px;
                    left: ${autoEnabled ? '18px' : '2px'};
                    width: 14px;
                    height: 14px;
                    background: white;
                    border-radius: 50%;
                    transition: transform 0.3s;
                "></span>
            </span>
        `;
        const autoCheckbox = toggle.querySelector('input');
        autoCheckbox.checked = autoEnabled;
        autoCheckbox.addEventListener('change', () => {
            autoEnabled = autoCheckbox.checked;
            localStorage.setItem('genGenAutoEnabled', autoEnabled ? 'true' : 'false');
            updateUI();
        });

        const instantBtn = document.createElement('button');
        instantBtn.id = 'genGen-instant-btn';
        instantBtn.textContent = '⚡ 极速';
        instantBtn.style.cssText = `
            padding: 4px 10px;
            background: #333;
            color: #ffcc00;
            border: 1px solid #ffcc00;
            border-radius: 5px;
            cursor: pointer;
            font-size: 12px;
            font-weight: bold;
        `;
        instantBtn.addEventListener('click', () => {
            nextRunInstant = true;
            instantBtn.textContent = '⚡ 已激活';
            instantBtn.style.background = '#ffcc00';
            instantBtn.style.color = '#000';
            console.log('下次运行启用极速模式');
            setTimeout(() => {
                if (nextRunInstant) updateUI();
            }, 3000);
        });

        panel.appendChild(document.createTextNode('GenGen AC 自动机'));
        panel.appendChild(toggle);
        panel.appendChild(instantBtn);
        document.body.appendChild(panel);
    }

    function updateUI() {
        const instantBtn = document.getElementById('genGen-instant-btn');
        if (instantBtn) {
            instantBtn.textContent = '⚡ 极速';
            instantBtn.style.background = '#333';
            instantBtn.style.color = '#ffcc00';
        }
        const autoEl = document.getElementById('genGen-auto');
        if (autoEl) {
            const span = autoEl.parentElement.querySelector('span');
            const dot = span.querySelector('span');
            if (autoEnabled) {
                span.style.background = '#ff6600';
                dot.style.left = '18px';
            } else {
                span.style.background = '#555';
                dot.style.left = '2px';
            }
        }
    }

    createControlPanel();

    let lastProblemHash = '';

    const autoCheck = setInterval(() => {
        if (!autoEnabled || isRunning) return;

        const martor = document.querySelector('.section-martor');
        const editor = getRealEditor();
        if (!martor || !editor) return;

        const problemText = martor.innerText.trim().substring(0, 200);
        const problemHash = problemText ? btoa(unescape(encodeURIComponent(problemText))) : '';

        if (problemHash === lastProblemHash) return;

        lastProblemHash = problemHash;
        runAI();
    }, 800);
})();