JavaScript// ==UserScript==
// @name 洛谷随机跳题(全标签树+历史记录+折叠+自适应难度+青题支持)
// @namespace luogu-random-filter-v10.9
// @version 10.9.0
// @description 在洛谷按完整标签库和难度随机跳转题目,支持树形级联标签选择、已选标签chip取消、历史记录激活/取消、展开折叠、完整标签分类、标签搜索、匹配模式、自适应难度,适配洛谷最新9级难度体系(含青题)。
// @author Assistant
// @match https://www.luogu.com.cn/*
// @grant GM_xmlhttpRequest
// @grant GM_setValue
// @grant GM_getValue
// @connect www.luogu.com.cn
// @run-at document-idle
// ==/UserScript==
(function () {
'use strict';
// ==================== 难度映射 ====================
const DIFFICULTY_MAP = {
0: { name: '暂无评定', color: '#BFBFBF' },
1: { name: '入门', color: '#FE4C61' },
2: { name: '普及-', color: '#F39C11' },
3: { name: '普及', color: '#FFC116' },
4: { name: '普及+/提高-', color: '#52C41A' },
5: { name: '提高', color: '#13D1D1' },
6: { name: '提高+/省选-', color: '#3498DB' },
7: { name: '省选/NOI-', color: '#9D3DCF' },
8: { name: 'NOI/NOI+/CTS', color: '#0E1D69' }
};
// ==================== 全局状态 ====================
let ALL_TAGS = [];
let TAG_TREE = { byId: {}, rootsByType: {} };
let SELECTED_TAG_IDS = new Set();
let COLLAPSED_TAG_IDS = new Set();
let TAG_HISTORY = [];
let ACTIVE_HISTORY_SIG = null;
let tagsLoaded = false;
// ==================== 缓存键 ====================
const CACHE_KEY = 'luogu_random_cache_v109';
const USER_CACHE_KEY = 'luogu_user_difficulty_v109';
const TAG_CACHE_KEY = 'luogu_tags_dict_v109';
const SELECTED_STATE_KEY = 'luogu_selected_tags_v109';
const COLLAPSED_STATE_KEY = 'luogu_collapsed_tags_v109';
const HISTORY_KEY = 'luogu_tag_history_v109';
const CACHE_TTL = 1000 * 60 * 60 * 6;
const TAG_CACHE_TTL = 1000 * 60 * 60 * 24;
const HISTORY_MAX = 8;
// ==================== Cookie / UID ====================
function getUserId() {
const m = document.cookie.match(/(?:^|;\s*)_uid=([^;]+)/);
if (m && m[1] && m[1] !== '0') return m[1];
try {
let inj = window._feInjection;
if (typeof inj === 'string') inj = JSON.parse(inj);
if (inj) {
const candidates = [
inj?.currentUser?.uid, inj?.currentData?.currentUser?.uid,
inj?.currentData?.user?.uid, inj?.user?.uid
];
for (const c of candidates) if (c) return String(c);
}
} catch (e) { /* ignore */ }
try {
const links = document.querySelectorAll('a[href^="/user/"]');
for (const link of links) {
const m2 = (link.getAttribute('href') || '').match(/\/user\/(\d+)/);
if (m2 && m2[1] && m2[1] !== '0') return m2[1];
}
} catch (e) { /* ignore */ }
try {
for (const key of ['__lentille_ctx', 'user_info', 'luogu_user']) {
const v = localStorage.getItem(key);
if (v) {
const obj = JSON.parse(v);
const uid = obj?.uid || obj?.user?.uid || obj?.currentUser?.uid;
if (uid) return String(uid);
}
}
} catch (e) { /* ignore */ }
return null;
}
// ==================== GM 请求 ====================
function gmFetch(url, options = {}) {
return new Promise((resolve, reject) => {
const headers = {
'x-lentille-request': 'content-only',
'x-luogu-type': 'content-only',
'X-Requested-With': 'XMLHttpRequest',
'Referer': 'https://www.luogu.com.cn/',
'User-Agent': navigator.userAgent,
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'zh-CN,zh;q=0.9',
...(options.headers || {})
};
GM_xmlhttpRequest({
method: options.method || 'GET',
url: url,
headers: headers,
timeout: 20000,
onload: (res) => {
if (res.status >= 200 && res.status < 300) resolve(res);
else reject(new Error(`HTTP ${res.status}`));
},
onerror: () => reject(new Error('网络请求失败')),
ontimeout: () => reject(new Error('请求超时'))
});
});
}
// ==================== 加载标签字典 ====================
async function loadTagDictionary() {
const cached = GM_getValue(TAG_CACHE_KEY, null);
if (cached && Date.now() - cached.ts < TAG_CACHE_TTL && cached.tags && cached.tags.length > 0) {
console.log('[标签] 使用缓存的标签字典,共', cached.tags.length, '个标签');
buildTagTree(cached.tags);
tagsLoaded = true;
return true;
}
console.log('[标签] 从洛谷接口获取最新标签字典...');
try {
const res = await gmFetch('https://www.luogu.com.cn/_lfe/tags/zh-CN');
const data = JSON.parse(res.responseText);
if (!data.tags || !Array.isArray(data.tags)) throw new Error('标签字典格式异常');
const allRawTags = data.tags.map(t => ({
id: t.id, name: t.name, type: t.type, parent: t.parent
}));
const validTags = allRawTags.filter(t => {
if (!t.name || typeof t.name !== 'string' || t.name.trim() === '') return false;
if (![1, 2, 4].includes(t.type)) return false;
return true;
});
const topCount = validTags.filter(t => !t.parent || t.parent === 0).length;
const childCount = validTags.length - topCount;
console.log(`[标签] 接口返回 ${allRawTags.length} 个标签,有效 ${validTags.length} 个(顶层 ${topCount},子标签 ${childCount})`);
const finalTags = validTags.length > 0 ? validTags : allRawTags;
GM_setValue(TAG_CACHE_KEY, { ts: Date.now(), tags: finalTags });
buildTagTree(finalTags);
tagsLoaded = true;
return true;
} catch (e) {
console.error('[标签] 获取失败:', e.message);
buildTagTree(getFallbackTags());
tagsLoaded = true;
return true;
}
}
function getFallbackTags() {
return [
{ id: 1, name: '模拟', type: 2, parent: null },
{ id: 3, name: '动态规划,dp', type: 2, parent: null },
{ id: 4, name: '贪心', type: 2, parent: null },
{ id: 5, name: '数学', type: 2, parent: null },
{ id: 6, name: '图论', type: 2, parent: null },
{ id: 7, name: '字符串', type: 2, parent: null },
{ id: 8, name: '搜索', type: 2, parent: null },
{ id: 9, name: '数据结构', type: 2, parent: null },
{ id: 200, name: 'NOIP', type: 2, parent: null },
{ id: 202, name: 'CSP', type: 2, parent: null },
{ id: 207, name: 'USACO', type: 2, parent: null },
{ id: 500, name: '交互题', type: 2, parent: null },
];
}
// ==================== 构建标签树 ====================
function buildTagTree(tags) {
TAG_TREE = { byId: {}, rootsByType: {} };
ALL_TAGS = [];
for (const t of tags) {
TAG_TREE.byId[t.id] = {
id: t.id, name: t.name, type: t.type,
parent: t.parent, children: []
};
ALL_TAGS.push({ id: t.id, name: t.name, type: t.type, parent: t.parent });
}
for (const t of tags) {
const node = TAG_TREE.byId[t.id];
if (t.parent && TAG_TREE.byId[t.parent]) {
TAG_TREE.byId[t.parent].children.push(node);
} else {
if (!TAG_TREE.rootsByType[t.type]) TAG_TREE.rootsByType[t.type] = [];
TAG_TREE.rootsByType[t.type].push(node);
}
}
for (const type of Object.keys(TAG_TREE.rootsByType)) {
sortTree(TAG_TREE.rootsByType[type]);
}
ALL_TAGS.sort((a, b) => a.name.localeCompare(b.name, 'zh'));
const saved = GM_getValue(SELECTED_STATE_KEY, null);
if (Array.isArray(saved)) {
SELECTED_TAG_IDS = new Set(saved.map(String).filter(id => TAG_TREE.byId[id]));
}
const savedCollapsed = GM_getValue(COLLAPSED_STATE_KEY, null);
if (Array.isArray(savedCollapsed)) {
COLLAPSED_TAG_IDS = new Set(savedCollapsed.map(String).filter(id => TAG_TREE.byId[id]));
}
const savedHistory = GM_getValue(HISTORY_KEY, null);
if (Array.isArray(savedHistory)) {
TAG_HISTORY = savedHistory.filter(h => h && Array.isArray(h.ids));
}
recalibrateAllParents();
console.log('[标签] 分类统计:', getCategoryStats());
}
function sortTree(nodes) {
nodes.sort((a, b) => a.name.localeCompare(b.name, 'zh'));
for (const n of nodes) if (n.children.length) sortTree(n.children);
}
// ==================== 顶层根节点分类 ====================
function classifyRoot(node) {
const name = node.name || '';
if (/^\d{4}$/.test(name)) return '时间';
if (/(NOIP|NOI|CSP|IOI|USACO|Codeforces|AtCoder|SPOJ|UVa|UVA|洛谷|省选|WC|CTSC|APIO|CEOI|JOI|POI|COCI|Baltic|月赛|原创|ICPC|CCPC|ACM|THUWC|PKUWC|THUPC|牛客|联合省选|集训队|北大|清华|NOI Online|ISIJ|EGOI|RMI|Balkan|Nordic|Rookie|CodeChef|Topcoder|HDU|POJ|ZOJ|LibreOJ|UOJ|QOJ)/i.test(name)) {
return '来源';
}
if (/(交互题|提交答案|Special Judge|语言入门|文本题|具有翻译|通信题|自适应|非传统题|IO 交互|IOI 交互)/.test(name)) {
return '特殊题目';
}
return '算法';
}
function getCategoryStats() {
const groups = groupRoots();
return Object.entries(groups).map(([k, v]) => {
let n = 0;
const walk = (nodes) => { for (const x of nodes) { n++; walk(x.children); } };
walk(v);
return `${k}(${n})`;
}).join('、');
}
function groupRoots() {
const groups = { '算法': [], '来源': [], '时间': [], '区域': [], '特殊题目': [] };
for (const [type, roots] of Object.entries(TAG_TREE.rootsByType)) {
const t = Number(type);
if (t === 1) groups['区域'].push(...roots);
else if (t === 4) groups['时间'].push(...roots);
else if (t === 2) {
for (const r of roots) groups[classifyRoot(r)].push(r);
}
}
return groups;
}
// ==================== 树操作 ====================
function getAllDescendantIds(nodeId) {
const result = [];
const node = TAG_TREE.byId[nodeId];
if (!node) return result;
const walk = (n) => { for (const c of n.children) { result.push(String(c.id)); walk(c); } };
walk(node);
return result;
}
function getAncestors(nodeId) {
const result = [];
let id = nodeId;
while (true) {
const node = TAG_TREE.byId[id];
if (!node || !node.parent) break;
const parent = TAG_TREE.byId[node.parent];
if (!parent) break;
result.push(parent);
id = parent.id;
}
return result;
}
function allDescendantsSelected(node) {
const walk = (n) => {
for (const c of n.children) {
if (!SELECTED_TAG_IDS.has(String(c.id))) return false;
if (!walk(c)) return false;
}
return true;
};
return walk(node);
}
function recalibrateAllParents() {
const allNodes = Object.values(TAG_TREE.byId);
const depthMap = {};
const calcDepth = (node) => {
if (depthMap[node.id] !== undefined) return depthMap[node.id];
if (!node.parent || !TAG_TREE.byId[node.parent]) {
depthMap[node.id] = 0;
return 0;
}
const d = calcDepth(TAG_TREE.byId[node.parent]) + 1;
depthMap[node.id] = d;
return d;
};
for (const n of allNodes) calcDepth(n);
allNodes.sort((a, b) => depthMap[b.id] - depthMap[a.id]);
for (const node of allNodes) {
if (!node.children || node.children.length === 0) continue;
if (allDescendantsSelected(node)) {
SELECTED_TAG_IDS.add(String(node.id));
} else {
SELECTED_TAG_IDS.delete(String(node.id));
}
}
}
// ==================== 级联勾选 ====================
function handleTagToggle(id, checked, panel) {
const idStr = String(id);
const node = TAG_TREE.byId[id];
if (!node) return;
// 用户手动修改 → 清除历史记录激活状态
if (ACTIVE_HISTORY_SIG !== null) {
ACTIVE_HISTORY_SIG = null;
renderHistory(panel);
}
if (checked) {
SELECTED_TAG_IDS.add(idStr);
for (const did of getAllDescendantIds(id)) SELECTED_TAG_IDS.add(did);
} else {
SELECTED_TAG_IDS.delete(idStr);
for (const did of getAllDescendantIds(id)) SELECTED_TAG_IDS.delete(did);
}
for (const ancestor of getAncestors(id)) {
if (allDescendantsSelected(ancestor)) {
SELECTED_TAG_IDS.add(String(ancestor.id));
} else {
SELECTED_TAG_IDS.delete(String(ancestor.id));
}
}
updateAllCheckboxes(panel);
GM_setValue(SELECTED_STATE_KEY, Array.from(SELECTED_TAG_IDS));
updateSelectedDisplay(panel);
}
function updateAllCheckboxes(panel) {
const allCbs = panel.querySelectorAll('.tag-checkbox');
for (const cb of allCbs) {
const id = cb.value;
const node = TAG_TREE.byId[id];
if (!node) continue;
const hasChildren = node.children && node.children.length > 0;
if (!hasChildren) {
cb.checked = SELECTED_TAG_IDS.has(String(id));
} else {
cb.checked = allDescendantsSelected(node);
}
cb.indeterminate = false;
const label = cb.closest('label');
if (label) {
label.style.background = cb.checked ? '#e8f4fd' : '';
}
}
}
// ==================== 历史记录 ====================
function recordHistory() {
const ids = Array.from(SELECTED_TAG_IDS).map(String).sort();
if (ids.length === 0) return;
const sig = ids.join(',');
if (TAG_HISTORY.length > 0 && TAG_HISTORY[0].sig === sig) return;
TAG_HISTORY = TAG_HISTORY.filter(h => h.sig !== sig);
const labels = ids.slice(0, 4).map(id => {
const t = TAG_TREE.byId[id];
return t ? t.name : id;
});
TAG_HISTORY.unshift({ ids, sig, ts: Date.now(), labels });
if (TAG_HISTORY.length > HISTORY_MAX) TAG_HISTORY = TAG_HISTORY.slice(0, HISTORY_MAX);
GM_setValue(HISTORY_KEY, TAG_HISTORY);
}
function restoreHistory(idx, panel) {
const entry = TAG_HISTORY[idx];
if (!entry) return;
const status = panel.querySelector('#panel-status');
// 二次点击:取消激活
if (ACTIVE_HISTORY_SIG === entry.sig) {
SELECTED_TAG_IDS.clear();
ACTIVE_HISTORY_SIG = null;
updateAllCheckboxes(panel);
GM_setValue(SELECTED_STATE_KEY, []);
updateSelectedDisplay(panel);
renderHistory(panel);
if (status) {
status.textContent = '已取消勾选该历史记录';
status.style.color = '#888';
setTimeout(() => {
if (status.textContent === '已取消勾选该历史记录') status.textContent = '';
}, 2000);
}
return;
}
// 首次点击:清空 + 激活
SELECTED_TAG_IDS.clear();
let restored = 0;
for (const id of entry.ids) {
if (TAG_TREE.byId[id]) {
SELECTED_TAG_IDS.add(String(id));
restored++;
}
}
recalibrateAllParents();
ACTIVE_HISTORY_SIG = entry.sig;
updateAllCheckboxes(panel);
GM_setValue(SELECTED_STATE_KEY, Array.from(SELECTED_TAG_IDS));
updateSelectedDisplay(panel);
renderHistory(panel);
if (status) {
status.textContent = `已恢复历史记录(${restored} 个标签)`;
status.style.color = '#27ae60';
setTimeout(() => {
if (status.textContent && status.textContent.startsWith('已恢复历史记录')) {
status.textContent = '';
}
}, 2000);
}
}
function deleteHistory(idx, panel) {
const entry = TAG_HISTORY[idx];
if (entry && ACTIVE_HISTORY_SIG === entry.sig) {
SELECTED_TAG_IDS.clear();
ACTIVE_HISTORY_SIG = null;
updateAllCheckboxes(panel);
GM_setValue(SELECTED_STATE_KEY, []);
updateSelectedDisplay(panel);
}
TAG_HISTORY.splice(idx, 1);
GM_setValue(HISTORY_KEY, TAG_HISTORY);
renderHistory(panel);
}
function clearHistory(panel) {
if (!confirm('确定要清空所有历史记录吗?')) return;
if (ACTIVE_HISTORY_SIG !== null) {
SELECTED_TAG_IDS.clear();
ACTIVE_HISTORY_SIG = null;
updateAllCheckboxes(panel);
GM_setValue(SELECTED_STATE_KEY, []);
updateSelectedDisplay(panel);
}
TAG_HISTORY = [];
GM_setValue(HISTORY_KEY, []);
renderHistory(panel);
}
function formatTime(ts) {
const diff = Date.now() - ts;
if (diff < 60000) return '刚刚';
if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前';
if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前';
return Math.floor(diff / 86400000) + '天前';
}
// ==================== 请求解析 ====================
async function fetchAndParse(url, context = '') {
const res = await gmFetch(url);
const text = res.responseText.trim();
if (text.startsWith('{') || text.startsWith('[')) return JSON.parse(text);
const patterns = [
/window\._feInjection\s*=\s*JSON\.parse\(['"](.+?)['"]\)/s,
/window\._feInjection\s*=\s*(\{.+?\});/s,
];
for (const pattern of patterns) {
const match = text.match(pattern);
if (match) {
try {
let jsonStr = match[1];
if (!jsonStr.startsWith('{')) jsonStr = jsonStr.replace(/\\"/g, '"').replace(/\\'/g, "'").replace(/\\\\/g, '\\');
return JSON.parse(jsonStr);
} catch (e) { /* next */ }
}
}
throw new Error(`${context}:无法解析响应`);
}
function extractRecords(data) {
if (!data) return null;
const paths = [
() => data?.currentData?.practice?.records,
() => data?.currentData?.records,
() => data?.records,
() => data?.practice?.records,
() => data?.currentData?.practice,
() => data?.currentData?.user?.practice,
() => data?.currentData?.practice?.result,
() => data?.currentData?.result,
];
for (const fn of paths) {
try {
const r = fn();
if (!r) continue;
if (Array.isArray(r) && r.length > 0) return { records: r, total: r.length, perPage: r.length };
if (Array.isArray(r.result)) return { records: r.result, total: r.count || r.total || r.result.length, perPage: r.perPage || 20 };
if (Array.isArray(r.records)) return { records: r.records, total: r.records.length, perPage: r.records.length };
if (r.records && Array.isArray(r.records.result)) return { records: r.records.result, total: r.records.count || r.records.total || r.records.result.length, perPage: r.records.perPage || 20 };
} catch (e) { /* ignore */ }
}
return findResultArray(data, 0);
}
function findResultArray(obj, depth) {
if (depth > 5 || !obj || typeof obj !== 'object') return null;
if (Array.isArray(obj)) {
if (obj.length > 0 && obj[0] && typeof obj[0] === 'object') return { records: obj, total: obj.length, perPage: obj.length };
return null;
}
if (Array.isArray(obj.result) && obj.result.length > 0) return { records: obj.result, total: obj.count || obj.total || obj.result.length, perPage: obj.perPage || 20 };
for (const key of Object.keys(obj)) {
const found = findResultArray(obj[key], depth + 1);
if (found) return found;
}
return null;
}
function parseProblemList(data) {
const cd = data?.currentData || data?.data || data;
const pc = cd?.problems || cd?.result;
let list = [];
if (Array.isArray(pc)) list = pc;
else if (pc && Array.isArray(pc.result)) list = pc.result;
else if (pc && Array.isArray(pc.problems)) list = pc.problems;
const pageInfo = cd?.page || pc?.page || {};
const totalPage = pageInfo.totalPage || pageInfo.count || pageInfo.pages || 1;
return { list, totalPage };
}
// ==================== 难度分析 ====================
function extractDifficultyFromRecord(rec) {
const candidates = [rec?.problem?.difficulty, rec?.difficulty, rec?.problem?.difficultyLevel, rec?.problem?.level];
for (const d of candidates) if (d !== undefined && d !== null && d !== '') return Number(d);
return null;
}
function isAccepted(rec) {
if (!rec) return false;
if (rec.status === 12 || rec.status === 'Accepted' || rec.status === 'AC') return true;
if (rec.score === 100 || rec.score === '100') return true;
if (rec.verdict === 'Accepted') return true;
return false;
}
async function analyzeUserDifficulty() {
const uid = await resolveUserId();
if (!uid) throw new Error('无法识别当前用户,请确认已登录洛谷');
const cached = GM_getValue(USER_CACHE_KEY, null);
if (cached && cached.uid === uid && Date.now() - cached.ts < CACHE_TTL) return cached.difficulty;
const diffCount = {};
console.log('[难度分析] 策略1:练习记录...');
if (await tryPracticeRecords(uid, diffCount) && Object.keys(diffCount).length > 0) return finalizeDifficulty(uid, diffCount);
console.log('[难度分析] 策略2:提交记录...');
if (await trySubmissionRecords(uid, diffCount) && Object.keys(diffCount).length > 0) return finalizeDifficulty(uid, diffCount);
throw new Error('未获取到有效做题记录');
}
async function resolveUserId() {
const local = getUserId();
if (local) return local;
try {
const res = await gmFetch('https://www.luogu.com.cn/');
const html = res.responseText;
const m1 = html.match(/window\._feInjection\s*=\s*JSON\.parse\(['"](.+?)['"]\)/s);
if (m1) {
try {
const d = JSON.parse(m1[1].replace(/\\"/g, '"').replace(/\\'/g, "'").replace(/\\\\/g, '\\'));
const u = d?.currentUser?.uid || d?.currentData?.currentUser?.uid;
if (u) return String(u);
} catch (e) { /* ignore */ }
}
const m2 = html.match(/\/user\/(\d{1,10})/);
if (m2 && m2[1] !== '0') return m2[1];
} catch (e) { /* ignore */ }
return null;
}
async function tryPracticeRecords(uid, diffCount) {
let page = 1;
const maxPages = 15;
let totalPages = maxPages;
let gotAny = false;
while (page <= maxPages && page <= totalPages) {
const url = `https://www.luogu.com.cn/user/${uid}/practice?page=${page}`;
try {
const data = await fetchAndParse(url, `练习记录第 ${page} 页`);
const result = extractRecords(data);
if (!result || !result.records || result.records.length === 0) break;
if (page === 1 && result.total > 0 && result.perPage > 0) totalPages = Math.min(Math.ceil(result.total / result.perPage), maxPages);
for (const rec of result.records) {
if (!isAccepted(rec)) continue;
const d = extractDifficultyFromRecord(rec);
if (d === null) continue;
diffCount[d] = (diffCount[d] || 0) + 1;
gotAny = true;
}
if (result.records.length < (result.perPage || 20)) break;
page++;
await new Promise(r => setTimeout(r, 250));
} catch (e) { break; }
}
return gotAny;
}
async function trySubmissionRecords(uid, diffCount) {
const seenPids = new Set();
let page = 1;
const maxPages = 15;
let gotAny = false;
while (page <= maxPages) {
const url = `https://www.luogu.com.cn/record/list?user=${uid}&status=12&page=${page}`;
try {
const data = await fetchAndParse(url, `提交记录第 ${page} 页`);
const result = extractRecords(data);
if (!result || !result.records || result.records.length === 0) break;
for (const rec of result.records) {
if (!isAccepted(rec)) continue;
const pid = rec?.problem?.pid || rec?.pid;
if (!pid || seenPids.has(pid)) continue;
seenPids.add(pid);
const d = extractDifficultyFromRecord(rec);
if (d === null) continue;
diffCount[d] = (diffCount[d] || 0) + 1;
gotAny = true;
}
if (result.records.length < (result.perPage || 20)) break;
page++;
await new Promise(r => setTimeout(r, 300));
} catch (e) { break; }
}
return gotAny;
}
function finalizeDifficulty(uid, diffCount) {
let wSum = 0, wTotal = 0;
for (const [d, c] of Object.entries(diffCount)) {
const dn = Number(d);
const w = c * (1 + dn * 0.15);
wSum += dn * w;
wTotal += w;
}
const base = Math.round(wSum / wTotal);
GM_setValue(USER_CACHE_KEY, { uid, ts: Date.now(), difficulty: base, distribution: diffCount });
console.log('[难度分析] 分布:', diffCount, '基准:', base);
return base;
}
// ==================== 拉取题目 ====================
async function fetchAllProblems(difficulties, tags, tagMode) {
const cacheKey = `${CACHE_KEY}_${difficulties.join('_')}_${tags.join('_')}_${tagMode}`;
const cached = GM_getValue(cacheKey, null);
if (cached && Date.now() - cached.ts < CACHE_TTL) return cached.problems;
const all = [];
const seenPids = new Set();
let page = 1;
const maxPages = 60;
let totalPages = 1;
let firstDone = false;
while (page <= maxPages && page <= totalPages) {
const params = new URLSearchParams();
params.set('page', String(page));
params.set('_contentOnly', '1');
if (difficulties.length) params.set('difficulty', difficulties.join(','));
if (tags.length) params.set('tag', tags.join(','));
const url = `https://www.luogu.com.cn/problem/list?${params.toString()}`;
console.log(`[随机跳题] 请求第 ${page} 页:${url}`);
try {
const data = await fetchAndParse(url, `题目列表第 ${page} 页`);
const { list, totalPage } = parseProblemList(data);
if (!firstDone) {
totalPages = Math.min(totalPage, maxPages);
firstDone = true;
}
if (list.length === 0) break;
for (const p of list) {
if (!p.pid || seenPids.has(p.pid)) continue;
seenPids.add(p.pid);
const title = p.title || p.content?.name || p.name || '';
all.push({ pid: p.pid, title, difficulty: p.difficulty });
}
} catch (e) {
console.warn(`[随机跳题] 第 ${page} 页失败:`, e.message);
if (page === 1) throw e;
}
page++;
await new Promise(r => setTimeout(r, 150));
}
if (all.length === 0) {
if (tags.length > 0) {
const names = tags.map(id => {
const t = ALL_TAGS.find(x => String(x.id) === String(id));
return t ? `${t.name}(${id})` : id;
}).join(', ');
throw new Error(`标签筛选后无题目。已选标签:${names}`);
}
throw new Error('未获取到任何题目');
}
GM_setValue(cacheKey, { ts: Date.now(), problems: all });
return all;
}
// ==================== 悬浮按钮 ====================
function createFloatingButton() {
if (document.getElementById('luogu-random-btn')) return;
const btn = document.createElement('div');
btn.id = 'luogu-random-btn';
btn.textContent = '🎲 随机跳题';
btn.style.cssText = `
position: fixed; bottom: 120px; right: 20px; z-index: 99999;
background: #3498db; color: #fff; padding: 10px 16px;
border-radius: 24px; cursor: pointer; font-size: 14px;
box-shadow: 0 2px 8px rgba(0,0,0,.2); user-select: none;
transition: transform .2s;
`;
btn.onmouseenter = () => btn.style.transform = 'scale(1.05)';
btn.onmouseleave = () => btn.style.transform = 'scale(1)';
btn.onclick = openPanel;
document.body.appendChild(btn);
}
// ==================== 打开面板 ====================
async function openPanel() {
const old = document.getElementById('luogu-random-panel');
if (old) { old.remove(); return; }
await loadTagDictionary();
ACTIVE_HISTORY_SIG = null;
const panel = document.createElement('div');
panel.id = 'luogu-random-panel';
panel.style.cssText = `
position: fixed; bottom: 170px; right: 20px; z-index: 99999;
background: #fff; border: 1px solid #ddd; border-radius: 12px;
padding: 16px; width: 490px; max-height: 82vh; overflow-y: auto;
box-shadow: 0 4px 20px rgba(0,0,0,.15); font-size: 13px;
color: #333;
`;
const difficultyCheckboxes = Object.entries(DIFFICULTY_MAP).map(([v, info]) =>
`<label style="display:inline-flex;align-items:center;gap:4px;padding:2px 6px;border:1px solid #ddd;border-radius:4px;cursor:pointer;font-size:12px;">
<input type="checkbox" class="diff-checkbox" value="${v}">
<span style="display:inline-block;width:10px;height:10px;border-radius:2px;background-color:${info.color};"></span>
${info.name}
</label>`
).join('');
panel.innerHTML = `
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
<strong style="font-size:15px;">随机跳题设置</strong>
<span id="close-panel" style="cursor:pointer;color:#999;font-size:20px;line-height:1;">×</span>
</div>
<div id="adaptive-section" style="margin-bottom:12px;padding:10px;background:#f0f7ff;border-radius:8px;border:1px solid #d0e3ff;">
<div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">
<label style="display:inline-flex;align-items:center;gap:4px;cursor:pointer;font-weight:bold;font-size:13px;">
<input type="checkbox" id="adaptive-enable" checked> 启用自适应难度
</label>
<span id="adaptive-status" style="font-size:11px;color:#666;"></span>
</div>
<div id="adaptive-controls" style="display:flex;align-items:center;gap:10px;">
<button id="adaptive-decrease" style="width:34px;height:34px;border:1px solid #ccc;border-radius:6px;background:#fff;cursor:pointer;font-size:18px;font-weight:bold;">−</button>
<div style="flex:1;text-align:center;">
<div style="font-size:11px;color:#666;">当前难度</div>
<div id="adaptive-current" style="font-size:16px;font-weight:bold;color:#3498db;padding:2px 0;">--</div>
</div>
<button id="adaptive-increase" style="width:34px;height:34px;border:1px solid #ccc;border-radius:6px;background:#fff;cursor:pointer;font-size:18px;font-weight:bold;">+</button>
</div>
</div>
<div id="manual-difficulty" style="margin-bottom:10px;opacity:0.4;pointer-events:none;">
<div style="font-weight:bold;margin-bottom:6px;font-size:12px;color:#555;">难度(手动选择)</div>
<div id="difficulty-selector" style="display:flex;flex-wrap:wrap;gap:4px;">
${difficultyCheckboxes}
</div>
</div>
<div style="margin-bottom:8px;">
<div style="font-weight:bold;margin-bottom:6px;font-size:12px;color:#555;">
标签搜索 <span style="font-weight:normal;color:#999;font-size:11px;">(名称模糊匹配)</span>
</div>
<div style="display:flex;gap:6px;">
<input id="tag-search" type="text" placeholder="输入标签名搜索..."
style="flex:1;padding:5px 8px;border:1px solid #ddd;border-radius:6px;font-size:12px;outline:none;">
<button id="clear-tags" style="padding:5px 10px;background:#eee;color:#333;border:none;border-radius:6px;cursor:pointer;font-size:12px;">清空已选</button>
</div>
</div>
<div style="margin-bottom:10px;display:flex;align-items:center;gap:12px;font-size:12px;">
<span style="font-weight:bold;color:#555;">标签匹配:</span>
<label style="display:inline-flex;align-items:center;gap:3px;cursor:pointer;">
<input type="radio" name="tag-mode" value="any" checked> 命中任一
</label>
<label style="display:inline-flex;align-items:center;gap:3px;cursor:pointer;">
<input type="radio" name="tag-mode" value="all"> 命中全部
</label>
</div>
<div id="tag-container" style="margin-bottom:10px;"></div>
<!-- 已选标签 chip 区 -->
<div id="selected-tags-display" style="margin-bottom:6px;">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:3px;">
<span style="font-size:11px;color:#999;">已选标签(点击标签可取消勾选)</span>
<span id="selected-tags-count" style="font-size:11px;color:#999;"></span>
</div>
<div id="selected-tags-list" style="max-height:120px;overflow-y:auto;padding:2px 0;line-height:1.6;"></div>
</div>
<div id="history-section" style="margin-bottom:10px;display:none;">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:4px;">
<span style="font-size:12px;color:#555;font-weight:bold;">🕒 最近使用</span>
<button id="clear-history" style="padding:2px 8px;background:transparent;color:#999;border:1px solid #ddd;border-radius:4px;cursor:pointer;font-size:10px;">清空历史</button>
</div>
<div id="history-list"></div>
</div>
<div style="display:flex;gap:8px;margin-top:8px;">
<button id="do-random" style="flex:1;padding:10px;background:#3498db;color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:14px;font-weight:bold;">开始随机</button>
</div>
<div id="panel-status" style="margin-top:8px;color:#888;font-size:12px;text-align:center;min-height:16px;"></div>
`;
document.body.appendChild(panel);
renderTagContainer(panel);
renderHistory(panel);
updateSelectedDisplay(panel);
let adaptiveBase = null;
let adaptiveOffset = 0;
const adaptiveEnable = panel.querySelector('#adaptive-enable');
const adaptiveStatus = panel.querySelector('#adaptive-status');
const adaptiveCurrent = panel.querySelector('#adaptive-current');
const manualDiff = panel.querySelector('#manual-difficulty');
const controls = panel.querySelector('#adaptive-controls');
function updateAdaptiveDisplay() {
if (adaptiveBase === null) return;
const eff = Math.max(0, Math.min(8, adaptiveBase + adaptiveOffset));
const info = DIFFICULTY_MAP[eff];
adaptiveCurrent.textContent = `难度 ${eff}:${info.name}`;
adaptiveCurrent.style.color = info.color;
}
async function loadAdaptive() {
adaptiveStatus.textContent = '正在分析...';
adaptiveStatus.style.color = '#666';
try {
adaptiveBase = await analyzeUserDifficulty();
adaptiveStatus.textContent = '分析完成';
adaptiveStatus.style.color = '#27ae60';
updateAdaptiveDisplay();
} catch (e) {
adaptiveStatus.textContent = e.message;
adaptiveStatus.style.color = '#e74c3c';
adaptiveBase = 4;
updateAdaptiveDisplay();
}
}
adaptiveEnable.onchange = () => {
const on = adaptiveEnable.checked;
manualDiff.style.opacity = on ? '0.4' : '1';
manualDiff.style.pointerEvents = on ? 'none' : 'auto';
controls.style.opacity = on ? '1' : '0.4';
controls.style.pointerEvents = on ? 'auto' : 'none';
if (on && adaptiveBase === null) loadAdaptive();
};
panel.querySelector('#adaptive-decrease').onclick = () => {
adaptiveOffset = Math.max(-4, adaptiveOffset - 1);
updateAdaptiveDisplay();
};
panel.querySelector('#adaptive-increase').onclick = () => {
adaptiveOffset = Math.min(4, adaptiveOffset + 1);
updateAdaptiveDisplay();
};
loadAdaptive();
panel.querySelector('#close-panel').onclick = () => panel.remove();
panel.querySelector('#clear-tags').onclick = () => {
SELECTED_TAG_IDS.clear();
ACTIVE_HISTORY_SIG = null;
GM_setValue(SELECTED_STATE_KEY, []);
updateAllCheckboxes(panel);
updateSelectedDisplay(panel);
renderHistory(panel);
};
panel.querySelector('#tag-search').oninput = (e) => {
renderTagContainer(panel, e.target.value.trim());
updateAllCheckboxes(panel);
};
panel.querySelectorAll('input[name="tag-mode"]').forEach(r => {
r.onchange = () => updateSelectedDisplay(panel);
});
panel.querySelector('#do-random').onclick = () => {
doRandomJump(panel, adaptiveEnable, () => adaptiveBase, () => adaptiveOffset);
};
panel.querySelector('#clear-history').onclick = () => clearHistory(panel);
panel.querySelector('#history-list').addEventListener('click', (e) => {
const delBtn = e.target.closest('.history-delete');
if (delBtn) {
e.stopPropagation();
deleteHistory(Number(delBtn.dataset.idx), panel);
return;
}
const entry = e.target.closest('.history-entry');
if (entry) {
restoreHistory(Number(entry.dataset.idx), panel);
}
});
// ===== 已选标签 chip 点击事件(取消勾选) =====
panel.querySelector('#selected-tags-list').addEventListener('click', (e) => {
const chip = e.target.closest('.selected-tag-chip');
if (!chip) return;
e.preventDefault();
e.stopPropagation();
const id = chip.dataset.id;
// 用 checked=false 调用级联逻辑:向下取消子孙、向上重算父标签
handleTagToggle(id, false, panel);
});
panel.addEventListener('change', (e) => {
if (e.target.classList.contains('tag-checkbox')) {
handleTagToggle(e.target.value, e.target.checked, panel);
}
});
panel.addEventListener('click', (e) => {
const btn = e.target.closest('.expand-btn');
if (!btn) return;
e.preventDefault();
e.stopPropagation();
const id = btn.dataset.target;
const childContainer = panel.querySelector(`.tag-children[data-parent="${id}"]`);
if (!childContainer) return;
if (COLLAPSED_TAG_IDS.has(String(id))) {
COLLAPSED_TAG_IDS.delete(String(id));
btn.textContent = '▼';
childContainer.style.display = 'block';
} else {
COLLAPSED_TAG_IDS.add(String(id));
btn.textContent = '▶';
childContainer.style.display = 'none';
}
GM_setValue(COLLAPSED_STATE_KEY, Array.from(COLLAPSED_TAG_IDS));
});
setTimeout(() => updateAllCheckboxes(panel), 0);
}
// ==================== 渲染历史记录 ====================
function renderHistory(panel) {
const section = panel.querySelector('#history-section');
const list = panel.querySelector('#history-list');
if (!section || !list) return;
if (TAG_HISTORY.length === 0) {
section.style.display = 'none';
return;
}
section.style.display = 'block';
list.innerHTML = TAG_HISTORY.map((h, idx) => {
const preview = h.labels.slice(0, 3).join('、') + (h.labels.length > 3 ? '…' : '');
const timeStr = formatTime(h.ts);
const isActive = ACTIVE_HISTORY_SIG === h.sig;
const bg = isActive ? '#d4ecff' : '#f8f9fa';
const border = isActive ? '#3498db' : '#eee';
const textColor = isActive ? '#1a5490' : '#333';
const prefix = isActive ? '☑ ' : '';
return `<div class="history-entry" data-idx="${idx}"
style="display:flex;align-items:center;gap:6px;padding:5px 8px;margin-bottom:3px;background:${bg};border:1px solid ${border};border-radius:5px;cursor:pointer;font-size:11px;transition:background .15s;"
onmouseover="this.style.background='${isActive ? '#c2e2ff' : '#e8f4fd'}'"
onmouseout="this.style.background='${bg}'"
title="${isActive ? '再次点击取消勾选' : '点击勾选该组标签'}">
<span style="flex:1;color:${textColor};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:${isActive ? 'bold' : 'normal'};" title="${h.labels.join('、')}">${prefix}${preview}</span>
<span style="color:#999;font-size:10px;flex:0 0 auto;">${h.ids.length}个</span>
<span style="color:#bbb;font-size:10px;flex:0 0 auto;">${timeStr}</span>
<span class="history-delete" data-idx="${idx}" style="color:#ccc;font-size:12px;flex:0 0 auto;padding:0 2px;" title="删除">×</span>
</div>`;
}).join('');
}
// ==================== 渲染标签容器 ====================
function renderTagContainer(panel, keyword = '') {
const container = panel.querySelector('#tag-container');
if (!container) return;
const kw = keyword.toLowerCase();
const groups = groupRoots();
const groupOrder = ['算法', '来源', '时间', '区域', '特殊题目'];
let html = '';
let totalShown = 0;
for (const groupName of groupOrder) {
const roots = groups[groupName] || [];
if (roots.length === 0) continue;
const filteredRoots = kw ? filterTree(roots, kw) : roots;
if (filteredRoots.length === 0) continue;
const count = countNodes(filteredRoots);
totalShown += count;
html += `
<details style="margin-bottom:6px;border:1px solid #eee;border-radius:6px;overflow:hidden;" ${kw ? 'open' : ''}>
<summary style="padding:6px 10px;cursor:pointer;font-weight:bold;font-size:12px;color:#3498db;background:#f8f9fa;user-select:none;">
${groupName} <span style="font-weight:normal;color:#999;font-size:11px;">(${count})</span>
</summary>
<div style="padding:8px;max-height:400px;overflow-y:auto;">
${renderTreeNodes(filteredRoots, 0)}
</div>
</details>`;
}
if (!html) {
html = `<div style="color:#999;text-align:center;padding:20px;font-size:12px;">没有匹配的标签</div>`;
} else if (kw) {
html = `<div style="font-size:11px;color:#666;margin-bottom:6px;padding:4px 8px;background:#fffbf0;border-radius:4px;border:1px solid #ffe7ba;">
搜索 "<b>${kw}</b>" 找到 ${totalShown} 个标签
</div>` + html;
}
container.innerHTML = html;
}
function filterTree(nodes, kw) {
const result = [];
for (const node of nodes) {
const selfMatch = node.name.toLowerCase().includes(kw);
const filteredChildren = node.children.length > 0 ? filterTree(node.children, kw) : [];
if (selfMatch || filteredChildren.length > 0) {
result.push({
...node,
children: selfMatch ? node.children : filteredChildren
});
}
}
return result;
}
function countNodes(nodes) {
let n = 0;
for (const node of nodes) {
n += 1;
if (node.children.length) n += countNodes(node.children);
}
return n;
}
function renderTreeNodes(nodes, depth) {
let html = '';
for (const node of nodes) {
html += renderTreeNode(node, depth);
}
return html;
}
function renderTreeNode(node, depth) {
const hasChildren = node.children && node.children.length > 0;
const isCollapsed = COLLAPSED_TAG_IDS.has(String(node.id));
let isSelected;
if (hasChildren) {
isSelected = allDescendantsSelected(node);
} else {
isSelected = SELECTED_TAG_IDS.has(String(node.id));
}
const indent = depth * 14;
const bg = isSelected ? '#e8f4fd' : '';
const fontWeight = hasChildren ? '600' : '400';
const fontSize = depth === 0 ? '12px' : '11px';
let html = `<div style="padding-left:${indent}px;margin:2px 0;">`;
html += `<div style="display:flex;align-items:center;gap:4px;">
<label style="display:inline-flex;align-items:center;gap:4px;padding:2px 6px;border-radius:4px;cursor:pointer;font-size:${fontSize};flex:0 0 auto;${bg ? `background:${bg};` : ''}">
<input type="checkbox" class="tag-checkbox" data-id="${node.id}" value="${node.id}" ${isSelected ? 'checked' : ''}>
<span style="font-weight:${fontWeight};color:${hasChildren ? '#333' : '#555'};">${node.name}</span>
${hasChildren ? `<span style="color:#bbb;font-size:10px;font-weight:normal;">(${node.children.length})</span>` : ''}
</label>`;
if (hasChildren) {
html += `<button class="expand-btn" data-target="${node.id}"
style="width:18px;height:18px;padding:0;border:none;background:transparent;cursor:pointer;font-size:10px;color:#888;line-height:1;border-radius:3px;flex:0 0 auto;"
title="${isCollapsed ? '展开' : '折叠'}">${isCollapsed ? '▶' : '▼'}</button>`;
}
html += `</div>`;
if (hasChildren) {
const childDisplay = isCollapsed ? 'none' : 'block';
html += `<div class="tag-children" data-parent="${node.id}"
style="display:${childDisplay};border-left:1px dashed #e0e0e0;margin-left:8px;padding-left:2px;">
${renderTreeNodes(node.children, depth + 1)}
</div>`;
}
html += `</div>`;
return html;
}
// ================================================================
// 【新版】已选标签 chip 渲染
// - 每个标签渲染为可点击的 chip
// - 点击 chip 会取消勾选该标签(事件在 openPanel 中委托)
// - 父标签与子标签用不同颜色区分
// ================================================================
function updateSelectedDisplay(panel) {
const container = panel.querySelector('#selected-tags-list');
const countEl = panel.querySelector('#selected-tags-count');
if (!container) return;
// 统计数量
if (countEl) {
countEl.textContent = SELECTED_TAG_IDS.size > 0 ? `共 ${SELECTED_TAG_IDS.size} 个` : '';
}
if (SELECTED_TAG_IDS.size === 0) {
container.innerHTML = '<span style="color:#999;font-size:11px;">无</span>';
return;
}
// 收集标签信息
const items = [];
for (const id of SELECTED_TAG_IDS) {
const t = TAG_TREE.byId[id];
if (!t) continue;
items.push({
id: String(t.id),
name: t.name,
isChild: !!(t.parent && t.parent !== 0)
});
}
// 排序:父标签在前(按名称),子标签在后(按名称)
items.sort((a, b) => {
if (a.isChild !== b.isChild) return a.isChild ? 1 : -1;
return a.name.localeCompare(b.name, 'zh');
});
// 渲染 chip
container.innerHTML = items.map(it => {
const bg = it.isChild ? '#f3f0ff' : '#e8f4fd';
const border = it.isChild ? '#d0c0f0' : '#b8daf5';
const color = it.isChild ? '#5a3a9a' : '#1a5490';
const prefix = it.isChild ? '·' : '';
return `<span class="selected-tag-chip" data-id="${it.id}"
style="display:inline-flex;align-items:center;gap:3px;padding:2px 6px;margin:2px 3px 2px 0;background:${bg};border:1px solid ${border};border-radius:10px;font-size:11px;color:${color};cursor:pointer;user-select:none;transition:background .15s;"
onmouseover="this.style.background='#ffe0e0';this.style.borderColor='#f5a8a8';"
onmouseout="this.style.background='${bg}';this.style.borderColor='${border}';"
title="点击取消勾选该标签">
<span>${prefix}${it.name}</span>
<span style="color:#c0392b;font-size:11px;font-weight:bold;line-height:1;">×</span>
</span>`;
}).join('');
}
// ==================== 执行随机 ====================
async function doRandomJump(panel, adaptiveEnable, getBase, getOffset) {
const status = panel.querySelector('#panel-status');
const btn = panel.querySelector('#do-random');
const tags = Array.from(SELECTED_TAG_IDS);
const mode = panel.querySelector('input[name="tag-mode"]:checked').value;
let diffs = [];
if (adaptiveEnable.checked) {
const base = getBase();
if (base === null) {
status.textContent = '自适应难度尚未分析完成,请稍候';
status.style.color = '#e74c3c';
return;
}
const eff = Math.max(0, Math.min(8, base + getOffset()));
diffs = [String(eff)];
const info = DIFFICULTY_MAP[eff];
status.textContent = `自适应难度:${info.name}`;
status.style.color = info.color;
} else {
diffs = [...panel.querySelectorAll('.diff-checkbox:checked')].map(c => c.value);
if (!diffs.length) {
status.textContent = '请至少选择一个难度,或启用自适应难度';
status.style.color = '#e74c3c';
return;
}
}
recordHistory();
btn.disabled = true;
btn.textContent = '抽取中...';
status.textContent = '正在获取题目列表...';
status.style.color = '#888';
try {
const problems = await fetchAllProblems(diffs, tags, mode);
if (!problems.length) {
status.textContent = '没有符合条件的题目';
status.style.color = '#e74c3c';
btn.disabled = false;
btn.textContent = '开始随机';
return;
}
const picked = problems[Math.floor(Math.random() * problems.length)];
const pickedInfo = DIFFICULTY_MAP[picked.difficulty] || { name: '未知', color: '#888' };
status.innerHTML = `抽中:<span style="color:${pickedInfo.color};font-weight:bold;">[${pickedInfo.name}]</span> ${picked.pid} ${picked.title}`;
renderHistory(panel);
setTimeout(() => {
window.location.href = `https://www.luogu.com.cn/problem/${picked.pid}`;
}, 800);
} catch (e) {
console.error('[随机跳题]', e);
status.textContent = '获取失败:' + e.message;
status.style.color = '#e74c3c';
btn.disabled = false;
btn.textContent = '开始随机';
}
}
// ==================== 初始化 ====================
function init() {
if (document.getElementById('luogu-random-btn')) return;
createFloatingButton();
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
let lastUrl = location.href;
new MutationObserver(() => {
if (location.href !== lastUrl) {
lastUrl = location.href;
setTimeout(init, 500);
}
}).observe(document.body, { childList: true, subtree: true });
})();