我们都知道,大部分编程类竞赛都是需要经过初赛(笔试)的选拔才能参加复赛,相应的,OIer们都会去做一些真题以获得经验与教训,但如果想要把提交记录分享给他人(如教练),让别人帮忙补缺补漏却极其困难,因此,我利用ds写了一份插件(其中本人贡献不低于AI),可以快速导出你的答卷(包括答题卡,你所选择的答案与正确答案)。
代码(1.1)
// ==UserScript==
// @name 洛谷有题记录导出
// @namespace https://ti.luogu.com.cn/
// @version 1.1
// @description 导出洛谷有题做题记录
// @author Columnina_Hyposelnia
// @match https://ti.luogu.com.cn/problemset/*
// @grant none
// @run-at document-end
// ==/UserScript==
(function () {
'use strict';
const CONFIG = { buttonPosition: { bottom: '100px', right: '20px' }, filePrefix: 'luogu_ti_record_' };
// ===== 颜色 =====
function rgb(s) { const m = (s || '').match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/); return m ? { r: +m[1], g: +m[2], b: +m[3] } : null; }
function isRed(s) { const c = rgb(s); return c && c.r > 140 && (c.r - c.g) > 40 && (c.r - c.b) > 40; }
function isGreen(s) { const c = rgb(s); return c && c.g > 100 && (c.g - c.r) > 40 && (c.g - c.b) > 40; }
function getStatusMap() {
const map = new Map();
document.querySelectorAll('span.clickable').forEach(el => {
const m = (el.textContent || '').trim().match(/^第\s*(\d+)\s*题$/);
if (!m) return;
const num = +m[1];
if (map.has(num)) return;
const cs = getComputedStyle(el);
const bg = cs.backgroundColor, color = cs.color;
if (isGreen(bg) || isGreen(color)) map.set(num, 'green');
else if (isRed(bg) || isRed(color)) map.set(num, 'red');
else map.set(num, 'gray');
});
return map;
}
// ===== 题名:根据题号返回题型名称 =====
function getProblemTypeName(num) {
if (num >= 16 && num <= 18) return '阅读程序题';
if (num >= 19 && num <= 20) return '完善程序题';
return '';
}
function isProgramProblem(num) { return num >= 16; }
// ===== DOM 兜底:保留 LaTeX 的文本提取 =====
function extractTextWithLatex(el) {
if (!el) return '';
const clone = el.cloneNode(true);
clone.querySelectorAll('pre').forEach(pre => {
const tbl = pre.querySelector('table.hljs-ln');
if (!tbl) return;
const lines = [];
tbl.querySelectorAll('tr').forEach(tr => {
const cell = tr.querySelector('.hljs-ln-code');
lines.push(cell ? cell.textContent : '');
});
const rep = document.createElement('pre');
rep.textContent = lines.join('\n');
pre.replaceWith(rep);
});
clone.querySelectorAll('.katex').forEach(k => {
const ann = k.querySelector('annotation[encoding="application/x-tex"]');
const tex = ann ? ann.textContent : '';
const isD = !!k.closest('.katex-display');
const sp = document.createElement('span');
sp.textContent = isD ? '$$' + tex + '$$' : '$' + tex + '$';
k.replaceWith(sp);
});
clone.querySelectorAll('.katex-mathml, .katex-html').forEach(n => n.remove());
const tmp = document.createElement('div');
tmp.style.cssText = 'position:fixed;left:-99999px;top:0;white-space:pre-wrap;font-size:14px;line-height:1.5;';
tmp.appendChild(clone);
document.body.appendChild(tmp);
const text = tmp.innerText || clone.textContent || '';
document.body.removeChild(tmp);
return text.replace(/\n{3,}/g, '\n\n').trim();
}
function findProblemContainer(titleEl) {
let p = titleEl.parentElement;
for (let i = 0; i < 12 && p && p !== document.body; i++) {
if (p.querySelector('.marked') && p.querySelector('span.option')) return p;
p = p.parentElement;
}
p = titleEl.parentElement;
for (let i = 0; i < 12 && p && p !== document.body; i++) {
if (p.querySelector('.marked')) return p;
p = p.parentElement;
}
return titleEl.parentElement;
}
function extractSubProblemsFromDOM(container) {
const allLis = Array.from(container.querySelectorAll('li'));
const topLis = allLis.filter(li => !allLis.some(o => o !== li && o.contains(li)));
const qLis = topLis.filter(li => !li.querySelector('span.option'));
const oLis = topLis.filter(li => li.querySelector('span.option'));
const h3s = Array.from(container.querySelectorAll('h3'));
function getType(el) {
let t = '';
for (const h of h3s) {
if (h.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING) {
const txt = (h.textContent || '').trim();
if (/判断题/.test(txt)) t = '判断题';
else if (/单选题/.test(txt)) t = '单选题';
else if (/选择题/.test(txt)) t = '选择题';
}
}
return t;
}
const n = Math.min(qLis.length, oLis.length);
const subs = [];
for (let i = 0; i < n; i++) {
const q = qLis[i], o = oLis[i];
const options = [];
o.querySelectorAll('span.option').forEach(opt => {
const input = opt.querySelector('input');
const label = opt.querySelector('label');
const letter = (input?.value || '').toUpperCase();
const m = label?.querySelector('.marked');
const text = m ? extractTextWithLatex(m) : (label?.textContent || '').replace(/^[A-Z][.、\s]+/, '').trim();
if (letter && !options.some(x => x.letter === letter)) options.push({ letter, text });
});
const caM = (o.textContent || '').match(/正确答案[::]\s*([A-D])/);
subs.push({
num: i + 1,
type: getType(q),
content: extractTextWithLatex(q),
choices: options.map(o => o.text),
correctAnswer: caM ? caM[1] : '',
});
}
return subs;
}
// ===== 核心 =====
function extractProblems() {
const sub = window._feInjection?.currentData?.submission;
if (!sub) return null;
const answers = sub.submissionAnswers || {};
const problemList = sub.problemset?.problems || [];
const titleEls = Array.from(document.querySelectorAll('span.problem-idx'));
const total = problemList.length || titleEls.length;
if (total === 0) return [];
const problems = [];
for (let i = 0; i < total; i++) {
const num = i + 1;
const baseProblem = problemList[i] || null;
const probId = baseProblem?.id;
const answerItem = probId ? answers[probId] : null;
const prob = answerItem?.problem || baseProblem || {};
const questions = prob.questions || [];
const description = prob.description || '';
const ansList = answerItem?.answers || [];
const judge = answerItem?.judgeResult || [];
// 从 DOM 拿题型
const typeMap = {};
const titleEl = titleEls[i];
let container = null;
if (titleEl) {
container = findProblemContainer(titleEl);
if (container) {
const allLis = Array.from(container.querySelectorAll('li'));
const topLis = allLis.filter(li => !allLis.some(o => o !== li && o.contains(li)));
const oLis = topLis.filter(li => li.querySelector('span.option'));
const h3s = Array.from(container.querySelectorAll('h3'));
function getType(el) {
let cur = '';
for (const h of h3s) {
if (h.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING) {
const txt = (h.textContent || '').trim();
if (/判断题/.test(txt)) cur = '判断题';
else if (/单选题/.test(txt)) cur = '单选题';
else if (/选择题/.test(txt)) cur = '选择题';
}
}
return cur;
}
oLis.forEach((li, ii) => { typeMap[ii] = getType(li); });
}
}
let subProblems = questions.map((q, si) => {
const choices = q.choices || [];
const correct = (q.correctAnswers || []).join('');
const user = ansList[si] || '';
const hasAnswer = !!user;
const isCorrect = judge[si] === true;
return {
num: si + 1,
type: typeMap[si] || q.type || '',
choices,
correctAnswer: correct,
userAnswer: user,
isCorrect,
hasAnswer,
score: q.score || 0,
gotScore: isCorrect ? (q.score || 0) : 0,
};
});
if (subProblems.length === 0 && container) {
const domSubs = extractSubProblemsFromDOM(container);
subProblems = domSubs.map(sp => ({
num: sp.num,
type: sp.type,
choices: sp.choices,
correctAnswer: sp.correctAnswer,
userAnswer: '',
isCorrect: false,
hasAnswer: false,
score: 0,
gotScore: 0,
}));
}
let fullScore = subProblems.reduce((s, q) => s + (q.score || 0), 0);
if (fullScore === 0) {
const allText = container ? (container.textContent || '') : '';
const sm = allText.match(/得分[::]\s*(\d+(?:\.\d+)?)\s*\/\s*(\d+(?:\.\d+)?)/);
if (sm) fullScore = parseFloat(sm[2]);
else fullScore = num >= 16 ? 15 : 2;
if (subProblems.length > 0) {
const per = fullScore / subProblems.length;
subProblems.forEach(sp => { sp.score = per; });
}
}
const answered = !!answerItem;
const gotScore = answerItem?.score || 0;
const status = answered ? (judge.length > 0 && judge.every(r => r === true) ? 'green' : 'red') : 'gray';
problems.push({
index: num,
problemId: probId,
title: prob.name || baseProblem?.name || '',
description,
subProblems,
isProgram: isProgramProblem(num),
gotScore,
fullScore,
status,
answered,
});
}
return problems;
}
function letterOf(i) { return String.fromCharCode(65 + i); }
// ===== Markdown =====
function toMarkdown(problems) {
let gotScore = 0, totalScore = 0, totalSubs = 0, correctSubs = 0;
const L = [];
L.push('# 洛谷有题 - 做题记录\n');
L.push(`> 导出时间:${new Date().toLocaleString('zh-CN')} `);
L.push(`> 题目总数:${problems.length} `);
L.push('');
L.push('---\n');
problems.forEach(p => {
const typeName = getProblemTypeName(p.index);
L.push(`## 第 ${p.index} 题${typeName ? `(${typeName})` : ''}\n`);
if (p.description) { L.push(p.description); L.push(''); }
if (p.isProgram) {
if (p.subProblems.length > 0) {
L.push('### 子题\n');
p.subProblems.forEach(sp => {
totalSubs++;
if (sp.isCorrect) correctSubs++;
const mk = !sp.hasAnswer ? '∅' : (sp.isCorrect ? '✓' : '✗');
L.push(`#### ${p.index}-${sp.num}${sp.type ? ` 【${sp.type}】` : ''} ${mk}\n`);
if (sp.choices && sp.choices.length > 0) {
sp.choices.forEach((text, i) => {
L.push(`- ${letterOf(i)}. ${text}`);
});
L.push('');
}
L.push(`- **正确答案:** ${sp.correctAnswer || '∅'} `);
L.push(`- **用户答案:** ${sp.hasAnswer ? sp.userAnswer : '未填写'} `);
L.push(`- **得分:** ${sp.gotScore} / ${sp.score}`);
L.push('');
});
}
L.push(`**整题得分:** ${p.gotScore} / ${p.fullScore}\n`);
gotScore += p.gotScore;
totalScore += p.fullScore;
} else {
const sp = p.subProblems[0];
if (!sp) { L.push('\n---\n'); return; }
totalSubs++;
if (sp.isCorrect) correctSubs++;
if (sp.choices && sp.choices.length > 0) {
sp.choices.forEach((text, i) => {
L.push(`- ${letterOf(i)}. ${text}`);
});
L.push('');
}
L.push(`**正确答案:** ${sp.correctAnswer || '∅'} `);
L.push(`**用户答案:** ${sp.hasAnswer ? sp.userAnswer : '未填写'} `);
L.push(`**得分:** ${sp.gotScore} / ${sp.score}`);
gotScore += sp.gotScore;
totalScore += sp.score;
}
L.push('\n---\n');
});
// 答题卡
L.push('## 答题卡\n');
L.push('| 题号 | 用户答案 | 正确答案 | 对错 | 得分 |');
L.push('|:---:|:---:|:---:|:---:|:---:|');
problems.forEach(p => {
if (p.isProgram) {
p.subProblems.forEach(sp => {
const mk = !sp.hasAnswer ? '∅' : (sp.isCorrect ? '✓' : '✗');
const ua = sp.hasAnswer ? sp.userAnswer : '∅';
L.push(`| ${p.index}-${sp.num} | ${ua} | ${sp.correctAnswer || '∅'} | ${mk} | ${sp.gotScore}/${sp.score} |`);
});
} else {
const sp = p.subProblems[0];
if (!sp) return;
const mk = !sp.hasAnswer ? '∅' : (sp.isCorrect ? '✓' : '✗');
const ua = sp.hasAnswer ? sp.userAnswer : '∅';
L.push(`| ${p.index} | ${ua} | ${sp.correctAnswer || '∅'} | ${mk} | ${sp.gotScore}/${sp.score} |`);
}
});
L.push('');
L.push(`**总分:** ${gotScore.toFixed(1)} / ${totalScore.toFixed(1)} `);
L.push(`**子题:** 共 ${totalSubs} 小题,答对 ${correctSubs} 个\n`);
return L.join('\n');
}
function download(text, filename) {
const blob = new Blob([text], { type: 'text/markdown;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a'); a.href = url; a.download = filename;
document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url);
}
async function copy(text) {
try { await navigator.clipboard.writeText(text); }
catch (e) { const ta = document.createElement('textarea'); ta.value = text; ta.style.position='fixed'; ta.style.opacity='0'; document.body.appendChild(ta); ta.select(); document.execCommand('copy'); document.body.removeChild(ta); }
}
function createUI() {
if (document.getElementById('luogu-ti-export-container')) return;
const box = document.createElement('div');
box.id = 'luogu-ti-export-container';
box.style.cssText = `position:fixed;bottom:${CONFIG.buttonPosition.bottom};right:${CONFIG.buttonPosition.right};z-index:99999;display:flex;flex-direction:column;gap:8px;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif`;
const s = 'padding:10px 16px;color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:14px;font-weight:500;box-shadow:0 2px 8px rgba(0,0,0,0.15);';
const bMd = document.createElement('button'); bMd.textContent = '📄 导出 Markdown (.md)'; bMd.style.cssText = s + 'background:#1a73e8;';
const bCp = document.createElement('button'); bCp.textContent = '📋 复制到剪贴板'; bCp.style.cssText = s + 'background:#34a853;';
const bDbg = document.createElement('button'); bDbg.textContent = '🐞 调试输出'; bDbg.style.cssText = s + 'background:#f59e0b;font-size:12px;padding:6px 12px;';
const st = document.createElement('div');
st.style.cssText = 'padding:6px 12px;background:rgba(0,0,0,0.75);color:#fff;border-radius:4px;font-size:12px;text-align:center;display:none;max-width:320px;line-height:1.5;';
function go(action) {
st.style.display = 'block'; st.textContent = '正在解析...';
setTimeout(async () => {
try {
const problems = extractProblems();
if (!problems || problems.length === 0) {
st.textContent = '❌ 未找到题目数据';
setTimeout(() => st.style.display = 'none', 4000);
return;
}
if (action === 'debug') {
console.log('=== 洛谷有题导出 调试 ===');
console.log('题目总数:', problems.length);
problems.forEach(p => {
const tn = getProblemTypeName(p.index);
console.log(`第${p.index}题${tn ? `(${tn})` : ''}: 作答=${p.answered}, 子题=${p.subProblems.length}, 得分=${p.gotScore}/${p.fullScore}, 子题类型=${p.subProblems.map(x=>x.type||'?').join(',')}`);
});
st.innerHTML = '🐞 已打印到控制台 (F12)';
setTimeout(() => st.style.display = 'none', 5000);
return;
}
const md = toMarkdown(problems);
if (action === 'md') download(md, CONFIG.filePrefix + new Date().toISOString().slice(0, 10) + '.md');
else await copy(md);
const subCount = problems.reduce((s, p) => s + p.subProblems.length, 0);
const corrCount = problems.reduce((s, p) => s + p.subProblems.filter(x => x.isCorrect).length, 0);
const unans = problems.filter(p => !p.answered).length;
st.innerHTML = `✅ 完成,${problems.length} 题 / ${subCount} 子题<br>✓ 答对 ${corrCount} 子题 / 未作答 ${unans} 题`;
} catch (e) { console.error(e); st.textContent = '❌ ' + e.message; }
setTimeout(() => st.style.display = 'none', 6000);
}, 50);
}
bMd.onclick = () => go('md');
bCp.onclick = () => go('copy');
bDbg.onclick = () => go('debug');
box.appendChild(bMd); box.appendChild(bCp); box.appendChild(bDbg); box.appendChild(st);
document.body.appendChild(box);
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', createUI);
else createUI();
new MutationObserver(() => {
if (!document.getElementById('luogu-ti-export-container')) setTimeout(createUI, 500);
}).observe(document.body, { childList: true, subtree: true });
})();目前更新至1.1版本。
注意到下载完本插件所产生的 markdown 数据后需要将其复制进洛谷专栏内才能得到正确的格式。
因任何使用本插件所造成的后果,作者(Columbina_Hyposelnia)概不负责。
更新日志:
1.0:首次发布。
1.1:修改了一些在调试中发现的bug