OI System
请不要使用,使用者机房IP将会被封禁一段时间,让我思考一下怎么用别的方法实现
点击
你是否也梦想过,绑定一个系统,从此变强之路清晰可见?
你是否也厌倦了每天打开洛谷却不知道该练什么,刷了
998244353道题还是心里没底?
检测到符合条件的宿主。
OI System 正在与你建立连接。
本系统不会告诉你“加油”这种废话。系统只会做三件事:锁定你的弱项,发布你跳一跳才能够到的任务,然后用你想要的方式帮你突破瓶颈。
没有日复一日的无效刷题,没有打开题解就放弃思考的依赖。每一次练习都有意义,每一个任务都在推着你向前走。
从现在开始,你的训练进度由系统接管。任务栏会始终挂着三个目标,完成一个就刷新一个,永远不让你停下来发呆。
油猴脚本
// ==UserScript==
// @name OI System
// @namespace https://www.luogu.com.cn/
// @version 1.0.2
// @description 洛谷智能化训练系统
// @author OI System
// @match https://www.luogu.com.cn/*
// @grant GM_xmlhttpRequest
// @grant GM_addStyle
// @grant unsafeWindow
// @connect api.deepseek.com
// @connect www.luogu.com.cn
// @license MIT
// ==/UserScript==
(function() {
'use strict';
// ============================================================
// 一、常量与配置
// ============================================================
const DIFFICULTY_SCORE = {
1: 2, 2: 10, 3: 30, 4: 60,
5: 80, 6: 150, 7: 400, 8: 800
};
const DIFFICULTY_NAME = {
1: '入门', 2: '普及-', 3: '普及', 4: '普及+/提高-',
5: '提高', 6: '提高+/省选-', 7: '省选/NOI-', 8: 'NOI/NOI+/CTSC'
};
const DEEPSEEK_API_URL = 'https://api.deepseek.com/chat/completions';
const DEEPSEEK_MODEL = 'deepseek-v4-flash';
const INITIAL_HINT_COUNT = 3;
const MAX_TASKS = 3;
const MAX_HINTS_PER_PROBLEM = 3;
const STORAGE_KEYS = {
UID: 'oi_system_uid',
API_KEY: 'oi_system_api_key',
TOTAL_SCORE: 'oi_system_total_score',
TAG_SCORES: 'oi_system_tag_scores',
AC_COUNT: 'oi_system_ac_count',
DIFFICULTY_DIST: 'oi_system_difficulty_dist',
TASKS: 'oi_system_tasks',
COMPLETED_TASKS: 'oi_system_completed_tasks',
HINT_COUNT: 'oi_system_hint_count',
HINT_HISTORY: 'oi_system_hint_history',
SUBMITTED_PROBLEMS: 'oi_system_submitted_problems',
LAST_SYNC: 'oi_system_last_sync',
PROBLEM_CACHE: 'oi_system_problem_cache',
SYNC_PROGRESS: 'oi_system_sync_progress',
PROCESSED_PIDS: 'oi_system_processed_pids'
};
// ============================================================
// 二、标签映射表
// ============================================================
const TAG_MAP = {
'-2': '语言入门',
'1': '模拟',
'2': '字符串',
'3': '动态规划 DP',
'4': '搜索',
'5': '数学',
'6': '图论',
'7': '贪心',
'8': '计算几何',
'9': '暴力数据结构',
'10': '高精度',
'11': '树形数据结构',
'12': '递推',
'13': '博弈论',
'41': '莫队',
'42': '线段树',
'43': '倍增',
'44': '线性数据结构',
'45': '二分',
'47': '并查集',
'49': '点分治',
'50': '平衡树',
'51': '堆',
'53': '树状数组',
'54': '递归',
'55': '树上启发式合并',
'56': '单调队列',
'65': '珂朵莉树',
'67': '三分',
'68': 'Kruskal 重构树',
'69': '多项式',
'71': '矩阵运算',
'72': '数论',
'78': '离散化',
'79': '网络流',
'100': 'cdq 分治',
'101': '后缀自动机',
'110': '基础算法',
'111': '枚举',
'112': '分治',
'113': '排序',
'126': 'BFS',
'127': 'DFS',
'128': '剪枝',
'129': '记忆化搜索',
'130': '启发式搜索',
'131': '迭代加深',
'132': 'IDA*',
'133': 'Dancing Links',
'134': '爬山',
'135': '模拟退火',
'136': '随机调整',
'137': '遗传算法',
'139': '背包 DP',
'141': '数位 DP',
'144': '区间 DP',
'146': 'DP 优化',
'148': '优先队列',
'149': '矩阵加速',
'150': '斜率优化',
'151': '状态合并',
'152': '树形 DP',
'153': 'wqs 二分',
'154': '四边形不等式',
'155': '图论建模',
'158': '图遍历',
'159': '拓扑排序',
'160': '最短路',
'166': '生成树',
'172': '平面图',
'173': '最小环',
'174': '负权环',
'175': '连通块',
'176': '2-SAT',
'177': '欧拉公式',
'179': '强连通分量',
'180': 'Tarjan',
'181': '双连通分量',
'182': '欧拉回路',
'185': '差分约束',
'186': '仙人掌',
'187': '二分图',
'189': '一般图匹配',
'197': '上下界网络流',
'198': '最小割',
'202': '分数规划',
'204': '费用流',
'208': '树的遍历',
'211': 'LCA',
'213': '树的直径',
'214': '霍夫曼树',
'215': '可并堆',
'228': '树链剖分',
'229': 'LCT',
'230': '树论',
'232': '树套树',
'233': '可持久化线段树',
'234': '可持久化',
'235': '哈希',
'239': '素数判断',
'241': 'gcd',
'242': '扩展欧几里得',
'243': '不定方程',
'244': '进制',
'246': '群论',
'247': '置换',
'248': 'Polya 定理',
'249': '虚树',
'250': 'CRT',
'251': '莫比乌斯反演',
'252': '组合数学',
'253': '排列组合',
'254': '前缀和',
'255': '二项式定理',
'256': '康托展开',
'258': '鸽笼原理',
'259': '容斥原理',
'260': 'Fibonacci',
'261': 'Catalan',
'262': 'Stirling',
'263': 'A*',
'264': '生成函数',
'265': '线性规划',
'266': '概率论',
'270': '期望',
'271': '线性代数',
'272': '矩阵乘法',
'273': '线性递推',
'274': '高斯消元',
'276': '逆元',
'277': '线性基',
'278': '微积分',
'280': '导数',
'281': '积分',
'282': '定积分',
'283': '三维计算几何',
'284': '级数',
'286': '向量',
'287': '栈',
'288': '队列',
'289': '分块',
'290': 'ST表',
'291': '凸包',
'292': '叉积',
'293': '线段相交',
'295': '半平面交',
'298': '扫描线',
'299': '旋转卡壳',
'300': 'Trie',
'301': 'AC自动机',
'302': 'KMP',
'303': '后缀数组',
'304': '后缀树',
'305': '有限状态自动机',
'308': '其它技巧',
'309': '随机化',
'311': '博弈树',
'313': 'FFT',
'314': '位运算',
'316': '整体二分',
'318': '构造',
'320': '基环树',
'321': 'KD-Tree',
'322': 'Lucas',
'323': '轮廓线DP',
'324': 'NTT',
'325': 'PAM',
'326': 'FWT',
'327': 'FMT',
'329': 'Manacher',
'330': '差分',
'345': '双指针',
'350': '圆方树',
'353': '顺序结构',
'354': '分支结构',
'355': '循环结构',
'356': '数组',
'357': '字符串(入门)',
'358': '结构体',
'359': '函数与递归',
'360': '链表',
'364': 'Dilworth',
'365': 'Ad-hoc',
'368': '笛卡尔树',
'369': '拟阵',
'370': 'Nim积',
'371': '根号分治',
'372': '拉格朗日反演',
'373': '模拟费用流',
'374': '分散层叠',
'375': '均摊分析',
'376': '分类讨论',
'377': '李超线段树',
'378': '吉司机线段树',
'379': '线段树合并',
'380': 'meet in the middle',
'382': '动态树分治',
'385': '单调栈',
'387': '杨表',
'388': '类欧几里得',
'391': 'BM算法',
'396': '梯度下降',
'410': 'Pruefer序列',
'411': '调和级数',
'412': '拉格朗日乘数法',
'413': '近似算法',
'415': '欧拉降幂',
'416': '集合幂级数',
'417': '拉格朗日插值',
'419': 'Lyndon分解',
'423': 'Stern-Brocot树',
'435': 'DP套DP',
'443': '动态DP',
'444': '线性DP',
'445': 'SG函数',
'446': '线段树分治',
'447': '离线处理',
'448': '整除分块',
'449': '极角排序',
'450': '弦图',
'451': 'Dirichlet卷积',
'452': 'BSGS',
'453': '二次剩余',
'454': '行列式',
'455': 'Bezout定理',
'457': '马尔可夫链',
'458': '鞅',
'461': '杜教筛',
'462': '欧拉函数',
'463': '决策单调性',
'464': '状压DP',
'465': 'bitset',
'466': '特征值',
'467': '组合优化',
'468': '整数规划',
'470': '原始对偶',
'471': '最大流最小割定理',
'472': '全局平衡二叉树',
'473': '哈希表',
'474': 'Z函数',
'475': '线性筛法',
'476': 'Floyd',
'477': '启发式合并',
'480': '单位根反演',
'482': '平面几何',
'483': '树的重心',
'484': '保序回归',
'496': '后缀平衡树',
'504': 'STL',
'507': '整体转移',
'508': 'slope trick',
'524': '反悔贪心',
'525': '闵可夫斯基和',
'530': '广义串并联',
'531': '猫树分治',
'539': 'KTT',
'540': '亚线性求和',
'541': 'Hall定理',
'46': 'USACO',
'48': '省选',
'52': '集训队互测',
'57': 'POI',
'70': '福建夏令营',
'77': 'NOI',
'81': '洛谷原创',
'82': 'NOIP普及组',
'83': 'NOIP提高组',
'85': 'APIO',
'99': 'NOI导刊',
'102': 'IOI',
'115': 'CCO',
'116': 'CCC',
'117': 'CEOI',
'118': 'eJOI',
'331': 'CTT',
'332': '网络流24题',
'333': 'COCI',
'334': 'BalticOI',
'335': 'ICPC',
'336': 'JOI',
'337': '洛谷月赛',
'342': 'CSP-S',
'343': 'CSP-J',
'346': 'AGM',
'347': 'NOI Online',
'348': 'Ynoi',
'361': '蓝桥杯国赛',
'363': '蓝桥杯省赛',
'381': '省赛/邀请赛',
'383': '传智杯',
'386': '语言月赛',
'389': 'PA',
'390': 'THUPC',
'393': 'ROI',
'394': 'EGOI',
'409': 'GESP',
'426': 'NOI系列',
'427': '经典套题',
'428': '国际赛事',
'429': '洛谷比赛',
'430': '大学竞赛',
'431': '其他竞赛',
'432': 'THUSC',
'434': '高校校赛',
'436': 'NOISG',
'437': 'NordicOI',
'438': 'THUWC',
'439': 'BalkanOI',
'440': 'KOI',
'441': 'RMI',
'442': 'CSP-X',
'459': 'WC',
'460': 'CTSC',
'478': 'COI',
'479': 'ROIR',
'485': 'Code+',
'486': '梦熊杯',
'487': '信息与未来',
'488': '科创活动',
'489': 'BCSP-X',
'492': '小学活动',
'493': '初中活动',
'494': '科大国创杯',
'495': '蓝桥杯青少年组',
'500': 'NERC',
'501': 'SEERC',
'502': 'CERC',
'503': 'NWRRC',
'505': 'INOI',
'506': 'UOI',
'509': 'EC Final',
'510': 'WF',
'511': 'NAC',
'512': 'JOISC',
'513': 'COTS',
'514': 'Google Code Jam',
'515': 'Moscow Olympiad',
'516': 'CSPro',
'518': 'PO',
'519': 'PAIO',
'523': '模板题',
'526': 'CCPC',
'532': 'SWERC',
'533': 'MCC/MCO',
'535': 'KTSC',
'537': 'IATI',
'538': 'Google Kick Start',
'14': '1997',
'15': '1998',
'16': '1999',
'17': '2000',
'18': '2001',
'19': '2002',
'20': '2003',
'21': '2004',
'22': '2005',
'23': '2006',
'24': '2007',
'25': '2008',
'26': '2009',
'27': '2010',
'28': '2011',
'29': '2012',
'30': '2013',
'31': '2014',
'32': '2015',
'33': '2016',
'34': '2017',
'35': '2018',
'36': '2019',
'37': '2020',
'58': '2021',
'59': '2022',
'60': '2023',
'61': '2024',
'62': '2025',
'338': '2026',
'339': '2027',
'340': '2028',
'341': '2077',
'344': '1996',
'362': '2078',
'367': '2029',
'424': '2079',
'38': '重庆',
'39': '四川',
'40': '河南',
'88': '浙江',
'89': '上海',
'90': '福建',
'91': '江苏',
'92': '安徽',
'93': '湖南',
'94': '北京',
'95': '河北',
'96': '广东',
'97': '山东',
'98': '吉林',
'114': '山西',
'161': '江西',
'162': '贵州',
'163': '广西',
'164': '陕西',
'167': '辽宁',
'168': '云南',
'328': '天津',
'397': '湖北',
'398': '黑龙江',
'399': '海南',
'400': '甘肃',
'401': '青海',
'402': '台湾',
'403': '内蒙古',
'404': '西藏',
'405': '宁夏',
'406': '新疆',
'407': '香港',
'408': '澳门',
'420': '济南',
'421': '南京',
'422': '青岛',
'497': '国内省市',
'498': '国内赛站',
'499': '国际赛区',
'520': '杭州',
'521': '昆明',
'522': '西安',
'527': '哈尔滨',
'528': '首尔',
'529': '横滨',
'534': '成都',
'536': '雅加达',
'103': '交互题',
'104': '提交答案',
'107': 'Special Judge',
'108': 'O2优化',
'351': '通信题'
};
// ============================================================
// 三、工具函数
// ============================================================
function log(msg, data) {
console.log('[OI System]', msg, data || '');
}
function getStorage(key, defaultVal) {
try {
const val = localStorage.getItem(key);
return val !== null ? JSON.parse(val) : defaultVal;
} catch {
return defaultVal;
}
}
function setStorage(key, val) {
try {
localStorage.setItem(key, JSON.stringify(val));
} catch (e) {
log('存储失败', e);
}
}
function getTagName(id) {
return TAG_MAP[String(id)] || '未知(' + id + ')';
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function extractLentilleContext(html) {
const match = html.match(/<script id="lentille-context" type="application\/json">([\s\S]*?)<\/script>/);
if (!match) return null;
try {
return JSON.parse(match[1]);
} catch {
return null;
}
}
function extractFeInjection(html) {
const match = html.match(/window\._feInjection = JSON\.parse\(decodeURIComponent\("([^"]+)"\)\);/);
if (!match) return null;
try {
return JSON.parse(decodeURIComponent(match[1]));
} catch {
return null;
}
}
// ============================================================
// 四、数据爬取模块
// ============================================================
function fetchPage(url) {
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: 'GET',
url: url,
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Referer': 'https://www.luogu.com.cn/'
},
withCredentials: true,
onload: function(resp) {
if (resp.status === 200) {
if (resp.responseText.includes('lentille-context')) {
resolve(resp.responseText);
} else if (resp.responseText.includes('登录') || resp.responseText.includes('Login')) {
reject(new Error('请求被重定向到登录页,请确保已登录洛谷'));
} else {
reject(new Error('页面内容不完整,可能触发了反爬机制'));
}
} else {
reject(new Error('HTTP ' + resp.status));
}
},
onerror: reject
});
});
}
async function fetchUserPractice(uid) {
const scriptEl = document.getElementById('lentille-context');
if (scriptEl) {
try {
const data = JSON.parse(scriptEl.textContent);
if (data && data.data && data.data.passed && data.data.passed.length > 0) {
log('从DOM读取到练习数据', data.data.passed.length);
return data.data.passed;
}
} catch (e) {
log('DOM解析失败', e);
}
}
const html = await fetchPage('https://www.luogu.com.cn/user/' + uid);
const ctx = extractLentilleContext(html);
if (!ctx || !ctx.data || !ctx.data.passed) {
throw new Error('未找到练习数据,请确认已公开或登录');
}
return ctx.data.passed;
}
async function fetchProblemDetail(pid) {
const html = await fetchPage('https://www.luogu.com.cn/problem/' + pid);
const ctx = extractLentilleContext(html);
if (!ctx || !ctx.data || !ctx.data.problem) {
throw new Error('无法解析题目详情');
}
const p = ctx.data.problem;
return {
pid: p.pid,
name: p.name,
difficulty: p.difficulty,
tags: p.tags || [],
accepted: p.accepted || false
};
}
// ============================================================
// 五、积分计算
// ============================================================
function calculateScores(passedProblems) {
let totalScore = 0;
let acCount = 0;
const difficultyDist = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0};
const tagScores = {};
passedProblems.forEach(function(p) {
const diff = p.difficulty || 1;
const score = DIFFICULTY_SCORE[diff] || 0;
totalScore += score;
acCount++;
difficultyDist[diff] = (difficultyDist[diff] || 0) + 1;
if (p.tags && Array.isArray(p.tags)) {
p.tags.forEach(function(tid) {
// 只保留算法标签(type=2),过滤来源、时间、区域、特殊题目标签
var algorithmTagIds = [
-2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 41, 42, 43, 44, 45,
47, 49, 50, 51, 53, 54, 55, 56, 65, 67, 68, 69, 71, 72, 78, 79, 100,
101, 110, 111, 112, 113, 126, 127, 128, 129, 130, 131, 132, 133, 134,
135, 136, 137, 139, 141, 144, 146, 148, 149, 150, 151, 152, 153, 154,
155, 158, 159, 160, 166, 172, 173, 174, 175, 176, 177, 179, 180, 181,
182, 185, 186, 187, 189, 197, 198, 202, 204, 208, 211, 213, 214, 215,
228, 229, 230, 232, 233, 234, 235, 239, 241, 242, 243, 244, 246, 247,
248, 249, 250, 251, 252, 253, 254, 255, 256, 258, 259, 260, 261, 262,
263, 264, 265, 266, 270, 271, 272, 273, 274, 276, 277, 278, 280, 281,
282, 283, 284, 286, 287, 288, 289, 290, 291, 292, 293, 295, 298, 299,
300, 301, 302, 303, 304, 305, 308, 309, 311, 313, 314, 316, 318, 320,
321, 322, 323, 324, 325, 326, 327, 329, 330, 345, 350, 353, 354, 355,
356, 357, 358, 359, 360, 364, 365, 368, 369, 370, 371, 372, 373, 374,
375, 376, 377, 378, 379, 380, 382, 385, 387, 388, 391, 396, 410, 411,
412, 413, 415, 416, 417, 419, 423, 435, 443, 444, 445, 446, 447, 448,
449, 450, 451, 452, 453, 454, 455, 457, 458, 461, 462, 463, 464, 465,
466, 467, 468, 470, 471, 472, 473, 474, 475, 476, 477, 480, 482, 483,
484, 496, 504, 507, 508, 524, 525, 530, 531, 539, 540, 541
];
if (algorithmTagIds.indexOf(tid) !== -1) {
var key = String(tid);
tagScores[key] = (tagScores[key] || 0) + score;
}
});
}
});
return {
totalScore: totalScore,
acCount: acCount,
difficultyDist: difficultyDist,
tagScores: tagScores
};
}
function calculateUserProfile(stats) {
const entries = Object.entries(stats.tagScores).sort(function(a, b) {
return b[1] - a[1];
});
const topTags = entries.slice(0, 5).map(function(item) {
return {id: parseInt(item[0]), name: getTagName(item[0]), score: item[1]};
});
const weakTags = entries.slice(-5).filter(function(item) {
return item[1] > 0;
}).map(function(item) {
return {id: parseInt(item[0]), name: getTagName(item[0]), score: item[1]};
});
let maxDiff = 1;
Object.keys(stats.difficultyDist).forEach(function(d) {
if (stats.difficultyDist[d] > 0) {
maxDiff = Math.max(maxDiff, parseInt(d));
}
});
return {
uid: getStorage(STORAGE_KEYS.UID, ''),
totalScore: stats.totalScore,
acCount: stats.acCount,
maxDifficulty: maxDiff,
maxDifficultyName: DIFFICULTY_NAME[maxDiff] || '未知',
difficultyDist: stats.difficultyDist,
topTags: topTags,
weakTags: weakTags,
tagCount: Object.keys(stats.tagScores).filter(function(k) {
return stats.tagScores[k] > 0;
}).length
};
}
// ============================================================
// 六、AI 交互模块
// ============================================================
function callDeepSeek(apiKey, messages, options) {
return new Promise(function(resolve, reject) {
var payload = {
model: DEEPSEEK_MODEL,
messages: messages,
thinking: {type: (options && options.thinking) || 'enabled'},
reasoning_effort: (options && options.reasoningEffort) || 'medium',
stream: false,
max_tokens: (options && options.maxTokens) || 4096
};
GM_xmlhttpRequest({
method: 'POST',
url: DEEPSEEK_API_URL,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + apiKey
},
data: JSON.stringify(payload),
onload: function(resp) {
if (resp.status === 200) {
try {
var data = JSON.parse(resp.responseText);
if (data.choices && data.choices.length > 0) {
resolve(data.choices[0].message.content);
} else {
reject(new Error('API返回格式异常'));
}
} catch (e) {
reject(new Error('解析响应失败: ' + e.message));
}
} else {
reject(new Error('API请求失败: ' + resp.status + ' ' + resp.responseText));
}
},
onerror: reject
});
});
}
async function generateTasks(apiKey, profile, currentTasks, completedTasks, hintCount) {
var systemPrompt = '你是一个智能训练系统,负责为OI选手生成个性化的训练任务。\n\n' +
'用户当前数据:\n' +
'- 总积分: ' + profile.totalScore + '\n' +
'- AC题数: ' + profile.acCount + '\n' +
'- 最高难度: ' + profile.maxDifficultyName + '\n' +
'- 覆盖标签数: ' + profile.tagCount + '\n' +
'- 当前剩余积分券: ' + hintCount + '\n\n' +
'用户强项标签: ' + profile.topTags.map(function(t) { return t.name + '(' + t.score + '分)'; }).join('、') + '\n' +
'用户弱项标签: ' + profile.weakTags.map(function(t) { return t.name + '(' + t.score + '分)'; }).join('、') + '\n\n' +
'当前未完成任务: ' + (currentTasks.length > 0 ? currentTasks.map(function(t) { return '["' + t.display + '"' + (t.completed ? '已完成' : '进行中') + ']'; }).join('、') : '无') + '\n' +
'已完成任务: ' + (completedTasks.length > 0 ? completedTasks.slice(-5).map(function(t) { return t.display; }).join('、') : '无') + '\n\n' +
'请生成3个新的训练任务。任务要求:\n' +
'1. 具体化,包含难度和具体知识点(如"完成一道提高难度的状压DP")\n' +
'2. 至少1个任务针对用户的弱项标签\n' +
'3. 至少1个任务略高于用户当前水平(激励突破)\n' +
'4. 至少1个任务巩固强项\n' +
'5. 任务难度要适中,用户跳一跳能够到\n' +
'6. 避免与最近已完成的任务重复\n' +
'7. 如果积分券少于3张,生成更容易完成的任务帮助用户获取积分券\n' +
'8. 每个任务需要有明确的检测条件(难度和标签)\n\n' +
'请以JSON格式输出,格式如下:\n' +
'[\n' +
' {\n' +
' "display": "任务显示文本",\n' +
' "condition": { "difficulty": 难度ID或null, "tag": "标签名称或null", "minCount": 数量 }\n' +
' }\n' +
']\n\n' +
'注意:\n' +
'- difficulty: 1-8的数字ID,或null(不限制难度)\n' +
'- tag: 标签名称(必须是存在的标签名),或null(不限制标签)\n' +
'- minCount: 默认为1\n\n' +
'只输出JSON数组,不要其他内容。';
var result = await callDeepSeek(apiKey, [
{role: 'system', content: systemPrompt},
{role: 'user', content: '请根据我的训练数据生成3个任务。'}
], {thinking: 'enabled', reasoningEffort: 'high', maxTokens: 2048});
try {
var match = result.match(/\[[\s\S]*\]/);
if (match) {
var arr = JSON.parse(match[0]);
if (Array.isArray(arr) && arr.length === 3) {
return arr.map(function(t) {
return {
id: 'task_' + Date.now() + '_' + Math.random().toString(36).substr(2, 4),
display: t.display || '完成一个训练任务',
condition: t.condition || {difficulty: null, tag: null, minCount: 1},
completed: false,
createdAt: Date.now()
};
});
}
}
throw new Error('JSON解析失败');
} catch (e) {
log('任务生成JSON解析失败,使用默认任务', e);
return generateDefaultTasks(profile);
}
}
function generateDefaultTasks(profile) {
var target = Math.min(8, profile.maxDifficulty + 1);
var weak = profile.weakTags.length ? profile.weakTags[0].name : '动态规划 DP';
var strong = profile.topTags.length ? profile.topTags[0].name : '模拟';
var tasks = [];
tasks.push({
id: 'task_' + Date.now() + '_a',
display: '完成一道' + DIFFICULTY_NAME[target] + '难度的' + weak,
condition: {difficulty: target, tag: weak, minCount: 1},
completed: false,
createdAt: Date.now()
});
var easy = Math.max(1, target - 1);
tasks.push({
id: 'task_' + Date.now() + '_b',
display: '完成两道' + DIFFICULTY_NAME[easy] + '难度的' + strong,
condition: {difficulty: easy, tag: strong, minCount: 2},
completed: false,
createdAt: Date.now()
});
tasks.push({
id: 'task_' + Date.now() + '_c',
display: '完成一道' + DIFFICULTY_NAME[Math.min(8, target + 1)] + '难度的题目',
condition: {difficulty: Math.min(8, target + 1), tag: null, minCount: 1},
completed: false,
createdAt: Date.now()
});
return tasks;
}
async function generateHint(apiKey, pid, problemName, hintHistory) {
var level = hintHistory ? hintHistory.length + 1 : 1;
var desc = '';
if (level === 1) {
desc = '这是第一次提示,请给出解题的算法方向,不要透露具体实现细节。因为只是一个hint,因此不要超过50字';
} else if (level === 2) {
desc = '这是第二次提示,请在算法方向基础上给出状态设计或关键思路,仍不要给完整代码。因为只是一个hint,因此不要超过50字';
} else {
desc = '这是第三次提示,请给出实现时的注意事项、边界条件、常见错误点,仍不要给完整代码。因为只是一个hint,因此不要超过70字';
}
var sys = '你是OI训练助手。题目:' + pid + ' ' + problemName + '。当前第' + level + '次提示。' + desc + ' 不要给完整代码。';
var msgs = [{role: 'system', content: sys}];
if (hintHistory) {
hintHistory.forEach(function(h) {
msgs.push({role: 'assistant', content: '第' + (msgs.length) + '次提示: ' + h.content});
});
}
msgs.push({role: 'user', content: '请给我第' + level + '次提示'});
return await callDeepSeek(apiKey, msgs, {thinking: 'enabled', reasoningEffort: 'medium', maxTokens: 2048});
}
// ============================================================
// 七、任务系统
// ============================================================
function getTasks() {
return getStorage(STORAGE_KEYS.TASKS, []);
}
function saveTasks(t) {
setStorage(STORAGE_KEYS.TASKS, t);
}
function getCompletedTasks() {
return getStorage(STORAGE_KEYS.COMPLETED_TASKS, []);
}
function saveCompletedTasks(t) {
setStorage(STORAGE_KEYS.COMPLETED_TASKS, t);
}
function getHintCount() {
return getStorage(STORAGE_KEYS.HINT_COUNT, INITIAL_HINT_COUNT);
}
function setHintCount(c) {
setStorage(STORAGE_KEYS.HINT_COUNT, Math.max(0, c));
}
function getSubmittedProblems() {
return getStorage(STORAGE_KEYS.SUBMITTED_PROBLEMS, []);
}
function addSubmittedProblem(pid) {
var list = getSubmittedProblems();
if (!list.includes(pid)) {
list.push(pid);
setStorage(STORAGE_KEYS.SUBMITTED_PROBLEMS, list);
}
}
function isProblemSubmitted(pid) {
return getSubmittedProblems().includes(pid);
}
function getHintHistory(pid) {
var h = getStorage(STORAGE_KEYS.HINT_HISTORY, {});
return h[pid] || [];
}
function addHintHistory(pid, content) {
var h = getStorage(STORAGE_KEYS.HINT_HISTORY, {});
if (!h[pid]) h[pid] = [];
if (h[pid].length < MAX_HINTS_PER_PROBLEM) {
h[pid].push({content: content, time: Date.now()});
setStorage(STORAGE_KEYS.HINT_HISTORY, h);
}
}
function canGetHint(pid) {
return getHintHistory(pid).length < MAX_HINTS_PER_PROBLEM;
}
async function verifyProblem(uid, pid) {
try {
var passed = await fetchUserPractice(uid);
var found = passed.find(function(p) { return p.pid === pid; });
if (found) {
return {exists: true, accepted: true, difficulty: found.difficulty};
}
var detail = await fetchProblemDetail(pid);
return {exists: true, accepted: detail.accepted || false, difficulty: detail.difficulty};
} catch (e) {
return {exists: false, accepted: false, difficulty: null};
}
}
async function submitProblem(uid, pid) {
var verify = await verifyProblem(uid, pid);
if (!verify.exists) {
return {success: false, message: '题号不存在'};
}
if (!verify.accepted) {
return {success: false, message: '该题尚未通过'};
}
if (isProblemSubmitted(pid)) {
return {success: false, message: '该题已提交过'};
}
var tags = [];
var diff = verify.difficulty;
try {
var d = await fetchProblemDetail(pid);
tags = d.tags || [];
diff = d.difficulty || diff;
} catch (e) {}
var tasks = getTasks();
var completedIds = [];
tasks.forEach(function(task) {
if (task.completed) return;
var match = true;
if (task.condition.difficulty !== null && task.condition.difficulty !== undefined) {
if (diff !== task.condition.difficulty) match = false;
}
if (task.condition.tag !== null && task.condition.tag !== undefined) {
var tagNames = tags.map(function(id) { return getTagName(id); });
var found = tagNames.some(function(name) {
return name.includes(task.condition.tag) || task.condition.tag.includes(name);
});
if (!found) match = false;
}
if (match) {
completedIds.push(task.id);
}
});
if (completedIds.length === 0) {
return {success: false, message: '该题不满足任何当前任务'};
}
var updated = tasks.map(function(task) {
if (completedIds.includes(task.id) && !task.completed) {
return {id: task.id, display: task.display, condition: task.condition, completed: true, completedAt: Date.now(), completedWith: pid, createdAt: task.createdAt};
}
return task;
});
var newly = updated.filter(function(t) {
return completedIds.includes(t.id);
});
var completedTasks = getCompletedTasks();
newly.forEach(function(t) {
if (!completedTasks.some(function(ct) { return ct.id === t.id; })) {
completedTasks.push({id: t.id, display: t.display, condition: t.condition, completedWith: pid, completedAt: Date.now(), createdAt: t.createdAt});
}
});
var reward = newly.length;
setHintCount(getHintCount() + reward);
addSubmittedProblem(pid);
var remaining = updated.filter(function(t) {
return !t.completed;
});
saveTasks(remaining);
saveCompletedTasks(completedTasks);
var apiKey = getStorage(STORAGE_KEYS.API_KEY, '');
if (apiKey && remaining.length < MAX_TASKS) {
try {
var stats = getStats();
var practice = await fetchUserPractice(uid);
var profile = calculateUserProfile(stats);
var newTasks = await generateTasks(apiKey, profile, remaining, completedTasks, getHintCount());
var all = remaining.concat(newTasks).filter(function(t) { return !t.completed; }).slice(0, MAX_TASKS);
saveTasks(all);
} catch (e) {
log('补充任务失败', e);
saveTasks(remaining);
}
} else {
saveTasks(remaining);
}
return {
success: true,
message: pid + ' 已完成任务: ' + newly.map(function(t) { return t.display; }).join('、'),
reward: reward,
hintCount: getHintCount()
};
}
// ============================================================
// 八、数据统计管理
// ============================================================
function getStats() {
return {
totalScore: getStorage(STORAGE_KEYS.TOTAL_SCORE, 0),
acCount: getStorage(STORAGE_KEYS.AC_COUNT, 0),
difficultyDist: getStorage(STORAGE_KEYS.DIFFICULTY_DIST, {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0}),
tagScores: getStorage(STORAGE_KEYS.TAG_SCORES, {})
};
}
function saveStats(s) {
setStorage(STORAGE_KEYS.TOTAL_SCORE, s.totalScore);
setStorage(STORAGE_KEYS.AC_COUNT, s.acCount);
setStorage(STORAGE_KEYS.DIFFICULTY_DIST, s.difficultyDist);
setStorage(STORAGE_KEYS.TAG_SCORES, s.tagScores);
}
function showSyncBar(total) {
var bar = document.getElementById('oi-system-sync-bar');
if (!bar) {
bar = document.createElement('div');
bar.id = 'oi-system-sync-bar';
bar.className = 'oi-system-sync-bar';
bar.innerHTML = '<span class="sync-label">OI System</span><div class="sync-progress-wrap"><div class="sync-progress-track"><div class="sync-progress-fill" id="oi-sync-fill"></div></div></div><span class="sync-text" id="oi-sync-text">0/' + total + '</span><span class="sync-close" id="oi-sync-close">X</span>';
document.body.appendChild(bar);
document.getElementById('oi-sync-close').addEventListener('click', function() {
bar.classList.remove('show');
});
}
bar.classList.add('show');
return bar;
}
function updateSyncBar(processed, total, currentPid) {
var fill = document.getElementById('oi-sync-fill');
var text = document.getElementById('oi-sync-text');
if (fill) {
fill.style.width = Math.min(100, (processed / total * 100)) + '%';
}
if (text) {
text.textContent = processed + '/' + total + (currentPid ? ' (' + currentPid + ')' : '');
}
}
function hideSyncBar() {
var bar = document.getElementById('oi-system-sync-bar');
if (bar) bar.classList.remove('show');
}
async function syncUserData(uid, onProgress) {
// 1. 获取AC列表
var scriptEl = document.getElementById('lentille-context');
var passed = null;
if (scriptEl) {
try {
var data = JSON.parse(scriptEl.textContent);
if (data && data.data && data.data.passed) {
passed = data.data.passed;
}
} catch (e) {}
}
if (!passed) {
var html = await fetchPage('https://www.luogu.com.cn/user/' + uid);
var ctx = extractLentilleContext(html);
if (ctx && ctx.data && ctx.data.passed) {
passed = ctx.data.passed;
} else {
throw new Error('无法获取练习数据');
}
}
var total = passed.length;
onProgress && onProgress('已获取 ' + total + ' 道题目', 10);
// 2. 读取永久存储的已处理列表
var processedPids = getStorage(STORAGE_KEYS.PROCESSED_PIDS, []);
var problemCache = getStorage(STORAGE_KEYS.PROBLEM_CACHE, {});
// 3. 找出未处理的题目
var uncached = passed.filter(function(p) {
return !processedPids.includes(p.pid);
});
log('总题目 ' + total + ',已处理 ' + processedPids.length + ',待处理 ' + uncached.length);
// 4. 如果全部已处理,直接完成
if (uncached.length === 0) {
var taggedAll = passed.map(function(p) {
var cached = problemCache[p.pid];
return {pid: p.pid, name: p.name, difficulty: p.difficulty, type: p.type, tags: (cached && cached.tags) || []};
});
var statsFinal = calculateScores(taggedAll);
saveStats(statsFinal);
setStorage(STORAGE_KEYS.LAST_SYNC, Date.now());
onProgress && onProgress('同步完成!总积分: ' + statsFinal.totalScore, 100);
return statsFinal;
}
// 5. 显示进度条并开始处理未缓存的题目
showSyncBar(total);
var processedCount = 0;
var totalNew = uncached.length;
for (var i = 0; i < uncached.length; i++) {
var p = uncached[i];
var pid = p.pid;
try {
var detail = await fetchProblemDetail(pid);
problemCache[pid] = {
tags: detail.tags || [],
name: detail.name || p.name,
difficulty: detail.difficulty || p.difficulty
};
processedPids.push(pid);
processedCount++;
} catch (e) {
log('获取标签失败: ' + pid, e);
problemCache[pid] = {tags: []};
processedPids.push(pid);
processedCount++;
}
if (processedCount % 5 === 0 || processedCount === totalNew) {
setStorage(STORAGE_KEYS.PROBLEM_CACHE, problemCache);
setStorage(STORAGE_KEYS.PROCESSED_PIDS, processedPids);
var pct = Math.min(90, 20 + 70 * (processedCount / totalNew));
updateSyncBar(processedCount, totalNew, pid);
onProgress && onProgress('获取标签 ' + processedCount + '/' + totalNew + ' (' + pid + ')', pct);
}
await sleep(200);
}
// 6. 保存最终结果
setStorage(STORAGE_KEYS.PROBLEM_CACHE, problemCache);
setStorage(STORAGE_KEYS.PROCESSED_PIDS, processedPids);
setStorage(STORAGE_KEYS.LAST_SYNC, Date.now());
var taggedAll2 = passed.map(function(p) {
var cached = problemCache[p.pid];
return {pid: p.pid, name: p.name, difficulty: p.difficulty, type: p.type, tags: (cached && cached.tags) || []};
});
var statsFinal2 = calculateScores(taggedAll2);
saveStats(statsFinal2);
hideSyncBar();
onProgress && onProgress('同步完成!总积分: ' + statsFinal2.totalScore + ',已处理 ' + processedPids.length + '/' + total + ' 题', 100);
return statsFinal2;
}
// ============================================================
// 九、自动生成任务
// ============================================================
async function autoGenerateTasks(apiKey, uid) {
try {
var tasks = getTasks();
var pending = tasks.filter(function(t) { return !t.completed; });
if (pending.length >= MAX_TASKS) {
log('已有足够任务,跳过生成');
return;
}
var stats = getStats();
if (Object.keys(stats.tagScores).length === 0) {
log('标签数据为空,跳过任务生成');
showNotification('请先同步数据获取标签信息');
return;
}
var profile = calculateUserProfile(stats);
var completed = getCompletedTasks();
var newTasks = await generateTasks(apiKey, profile, pending, completed, getHintCount());
var all = pending.concat(newTasks).filter(function(t) { return !t.completed; }).slice(0, MAX_TASKS);
saveTasks(all);
log('自动生成任务完成', all);
showNotification('新任务已生成,去看看吧!');
} catch (e) {
log('自动生成任务失败', e);
}
}
// ============================================================
// 十、UI 组件
// ============================================================
function addStyles() {
var style = document.createElement('style');
style.textContent = '.oi-system-button{position:fixed;z-index:99999;cursor:grab;user-select:none;width:56px;height:30px;border-radius:8px;background:rgba(255,255,255,0.85);backdrop-filter:blur(8px);border:1px solid rgba(200,200,200,0.3);box-shadow:0 2px 12px rgba(0,0,0,0.08);display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:600;color:#2c3e50;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;transition:transform 0.15s,box-shadow 0.15s;letter-spacing:0.3px}.oi-system-button:hover{transform:scale(1.05);box-shadow:0 4px 20px rgba(0,0,0,0.15);background:rgba(255,255,255,0.95)}.oi-system-button:active{cursor:grabbing}.dark .oi-system-button{background:rgba(30,40,60,0.85);color:#e8e8e8;border-color:rgba(100,120,160,0.3)}.dark .oi-system-button:hover{background:rgba(40,50,70,0.95)}.oi-system-panel{position:fixed;top:0;right:-380px;width:370px;max-width:92vw;height:100vh;z-index:100000;background:#ffffff;box-shadow:-4px 0 30px rgba(0,0,0,0.12);transition:right 0.3s cubic-bezier(0.4,0,0.2,1);font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;color:#1a1a2e;overflow-y:auto;border-left:1px solid rgba(200,200,200,0.2)}.oi-system-panel.open{right:0}.dark .oi-system-panel{background:#1a1a2e;color:#e8e8e8;border-left-color:rgba(80,80,120,0.3)}.oi-system-panel-header{padding:16px 20px;border-bottom:1px solid rgba(200,200,200,0.2);display:flex;justify-content:space-between;align-items:center;background:rgba(248,248,252,0.8);backdrop-filter:blur(8px);position:sticky;top:0;z-index:10}.dark .oi-system-panel-header{background:rgba(26,26,46,0.9);border-bottom-color:rgba(80,80,120,0.3)}.oi-system-panel-title{font-size:16px;font-weight:700;letter-spacing:0.5px}.oi-system-panel-close{cursor:pointer;width:32px;height:32px;border-radius:50%;border:none;background:rgba(0,0,0,0.05);font-size:18px;color:#666;display:flex;align-items:center;justify-content:center;transition:background 0.15s}.oi-system-panel-close:hover{background:rgba(0,0,0,0.1)}.dark .oi-system-panel-close{background:rgba(255,255,255,0.05);color:#aaa}.dark .oi-system-panel-close:hover{background:rgba(255,255,255,0.1)}.oi-system-panel-body{padding:16px 20px}.oi-system-tabs{display:flex;gap:2px;margin-bottom:16px;background:rgba(240,240,248,0.5);border-radius:10px;padding:4px}.dark .oi-system-tabs{background:rgba(40,40,60,0.5)}.oi-system-tab{flex:1;padding:8px 4px;text-align:center;border:none;border-radius:8px;background:transparent;font-size:12px;font-weight:500;color:#888;cursor:pointer;transition:all 0.15s}.oi-system-tab:hover{color:#555}.oi-system-tab.active{background:#ffffff;color:#1a1a2e;box-shadow:0 2px 8px rgba(0,0,0,0.06)}.dark .oi-system-tab.active{background:#2a2a4a;color:#e8e8e8}.oi-system-stat-card{background:rgba(240,240,248,0.4);border-radius:10px;padding:14px 16px;margin-bottom:12px;border:1px solid rgba(200,200,200,0.1)}.dark .oi-system-stat-card{background:rgba(40,40,60,0.4);border-color:rgba(80,80,120,0.15)}.oi-system-stat-row{display:flex;justify-content:space-between;padding:4px 0;font-size:13px}.oi-system-stat-label{color:#888}.dark .oi-system-stat-label{color:#99a}.oi-system-stat-value{font-weight:600}.oi-system-progress{height:6px;background:rgba(200,200,200,0.2);border-radius:4px;overflow:hidden;margin-top:6px}.oi-system-progress-bar{height:100%;border-radius:4px;transition:width 0.5s;background:linear-gradient(90deg,#6c5ce7,#a29bfe)}.oi-system-task-item{background:rgba(240,240,248,0.3);border-radius:8px;padding:12px 14px;margin-bottom:8px;border-left:3px solid #6c5ce7;font-size:13px}.dark .oi-system-task-item{background:rgba(40,40,60,0.3);border-left-color:#8c7cf7}.oi-system-task-item .task-status{font-size:11px;color:#6c5ce7}.dark .oi-system-task-item .task-status{color:#8c7cf7}.oi-system-task-item.completed{border-left-color:#00b894;opacity:0.7}.oi-system-task-item.completed .task-status{color:#00b894}.oi-system-tag-item{display:flex;justify-content:space-between;padding:3px 0;font-size:12px;border-bottom:1px solid rgba(200,200,200,0.1)}.oi-system-tag-item .tag-name{color:#555}.dark .oi-system-tag-item .tag-name{color:#aab}.oi-system-tag-item .tag-score{font-weight:500}.oi-system-input-group{display:flex;gap:8px;margin-top:8px}.oi-system-input-group input{flex:1;padding:8px 12px;border:1px solid rgba(200,200,200,0.3);border-radius:6px;font-size:13px;background:rgba(255,255,255,0.6);color:#1a1a2e;outline:none;transition:border-color 0.15s}.dark .oi-system-input-group input{background:rgba(40,40,60,0.6);color:#e8e8e8;border-color:rgba(80,80,120,0.3)}.oi-system-input-group input:focus{border-color:#6c5ce7}.oi-system-input-group button{padding:8px 16px;border:none;border-radius:6px;background:#6c5ce7;color:#fff;font-size:13px;font-weight:500;cursor:pointer;transition:background 0.15s;white-space:nowrap}.oi-system-input-group button:hover{background:#5a4bd1}.oi-system-input-group button:disabled{opacity:0.5;cursor:not-allowed}.oi-system-notification{position:fixed;bottom:24px;left:50%;transform:translateX(-50%);z-index:100001;background:rgba(0,0,0,0.8);backdrop-filter:blur(8px);color:#fff;padding:12px 24px;border-radius:12px;font-size:14px;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;max-width:90vw;box-shadow:0 8px 32px rgba(0,0,0,0.2);opacity:0;transition:opacity 0.3s,transform 0.3s;transform:translateX(-50%) translateY(20px);pointer-events:none}.oi-system-notification.show{opacity:1;transform:translateX(-50%) translateY(0)}.dark .oi-system-notification{background:rgba(20,20,40,0.9)}.oi-system-sync-bar{position:fixed;top:0;left:0;width:100%;z-index:999999;background:rgba(30,30,50,0.92);backdrop-filter:blur(8px);padding:10px 20px;display:none;align-items:center;gap:16px;box-shadow:0 2px 20px rgba(0,0,0,0.3);font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;border-bottom:2px solid #6c5ce7}.oi-system-sync-bar.show{display:flex}.oi-system-sync-bar .sync-label{color:#ccc;font-size:13px;white-space:nowrap}.oi-system-sync-bar .sync-progress-wrap{flex:1;min-width:100px}.oi-system-sync-bar .sync-progress-track{height:6px;background:rgba(255,255,255,0.1);border-radius:4px;overflow:hidden}.oi-system-sync-bar .sync-progress-fill{height:100%;background:linear-gradient(90deg,#6c5ce7,#a29bfe);border-radius:4px;transition:width 0.3s;width:0%}.oi-system-sync-bar .sync-text{color:#fff;font-size:12px;font-weight:500;white-space:nowrap;min-width:100px;text-align:right}.oi-system-sync-bar .sync-close{cursor:pointer;color:#888;font-size:18px;padding:0 8px;transition:color 0.2s}.oi-system-sync-bar .sync-close:hover{color:#fff}.oi-system-solution-overlay{padding:40px 20px;text-align:center;background:rgba(248,248,252,0.9);border-radius:12px;margin:20px 0;min-height:200px;display:flex;flex-direction:column;align-items:center;justify-content:center}.dark .oi-system-solution-overlay{background:rgba(26,26,46,0.9)}.oi-system-solution-overlay .lock-icon{font-size:40px;margin-bottom:12px}.oi-system-solution-overlay .hint-title{font-size:18px;font-weight:600;margin-bottom:8px}.oi-system-solution-overlay .hint-sub{font-size:13px;color:#888;margin-bottom:16px}.dark .oi-system-solution-overlay .hint-sub{color:#99a}.oi-system-solution-overlay .hint-content{text-align:left;background:rgba(0,0,0,0.03);padding:16px;border-radius:8px;max-width:100%;width:100%;margin-top:12px;font-size:14px;line-height:1.7;white-space:pre-wrap;word-break:break-word}.dark .oi-system-solution-overlay .hint-content{background:rgba(255,255,255,0.03)}.oi-system-solution-overlay .hint-history{margin-top:12px;width:100%;text-align:left}.oi-system-solution-overlay .hint-history-item{font-size:13px;padding:8px 12px;background:rgba(0,0,0,0.02);border-radius:6px;margin-bottom:4px;border-left:3px solid #6c5ce7}.dark .oi-system-solution-overlay .hint-history-item{background:rgba(255,255,255,0.02);border-left-color:#8c7cf7}.oi-system-solution-overlay .hint-history-item .hint-level{font-size:11px;color:#888}.dark .oi-system-solution-overlay .hint-history-item .hint-level{color:#99a}.oi-system-solution-overlay .hint-btn{padding:10px 28px;border:none;border-radius:8px;background:#6c5ce7;color:#fff;font-size:14px;font-weight:600;cursor:pointer;transition:background 0.15s}.oi-system-solution-overlay .hint-btn:hover{background:#5a4bd1}.oi-system-solution-overlay .hint-btn:disabled{opacity:0.5;cursor:not-allowed}.oi-system-sync-progress{background:rgba(0,0,0,0.05);border-radius:8px;padding:12px;margin-top:8px;font-size:13px}.dark .oi-system-sync-progress{background:rgba(255,255,255,0.03)}.oi-system-sync-progress .progress-text{color:#666}.dark .oi-system-sync-progress .progress-text{color:#99a}@media (max-width:480px){.oi-system-panel{width:100vw;max-width:100vw;right:-100vw}.oi-system-panel.open{right:0}.oi-system-button{width:48px;height:28px;font-size:10px}}';
document.head.appendChild(style);
}
function showNotification(msg, duration) {
duration = duration || 3000;
var el = document.querySelector('.oi-system-notification');
if (!el) {
el = document.createElement('div');
el.className = 'oi-system-notification';
document.body.appendChild(el);
}
el.textContent = msg;
el.classList.add('show');
clearTimeout(el._hideTimeout);
el._hideTimeout = setTimeout(function() {
el.classList.remove('show');
}, duration);
}
// ============================================================
// 十一、面板 UI
// ============================================================
function createEntryButton() {
var button = document.createElement('div');
button.className = 'oi-system-button';
button.textContent = 'OI';
button.title = 'OI System - 点击打开训练面板';
var pos = getStorage('oi_system_button_pos', {x: 20, y: 100});
button.style.left = pos.x + 'px';
button.style.top = pos.y + 'px';
var isDragging = false;
var startX, startY, startLeft, startTop;
button.addEventListener('mousedown', function(e) {
if (e.button !== 0) return;
isDragging = true;
startX = e.clientX;
startY = e.clientY;
var rect = button.getBoundingClientRect();
startLeft = rect.left;
startTop = rect.top;
button.style.cursor = 'grabbing';
e.preventDefault();
});
document.addEventListener('mousemove', function(e) {
if (!isDragging) return;
var dx = e.clientX - startX;
var dy = e.clientY - startY;
var newLeft = startLeft + dx;
var newTop = startTop + dy;
var bw = button.offsetWidth || 56;
var bh = button.offsetHeight || 30;
var maxX = window.innerWidth - bw - 4;
var maxY = window.innerHeight - bh - 4;
newLeft = Math.max(4, Math.min(maxX, newLeft));
newTop = Math.max(4, Math.min(maxY, newTop));
button.style.left = newLeft + 'px';
button.style.top = newTop + 'px';
});
document.addEventListener('mouseup', function(e) {
if (isDragging) {
isDragging = false;
button.style.cursor = 'grab';
var rect = button.getBoundingClientRect();
setStorage('oi_system_button_pos', {x: rect.left, y: rect.top});
}
});
button.addEventListener('click', function(e) {
if (!isDragging) {
togglePanel();
}
});
document.body.appendChild(button);
return button;
}
var panelInstance = null;
var currentTab = 'overview';
function createPanel() {
if (panelInstance) {
panelInstance.classList.toggle('open');
return;
}
var panel = document.createElement('div');
panel.className = 'oi-system-panel';
panel.id = 'oi-system-panel';
panel.innerHTML = '<div class="oi-system-panel-header"><span class="oi-system-panel-title">OI System</span><button class="oi-system-panel-close">×</button></div><div class="oi-system-panel-body"><div class="oi-system-tabs"><button class="oi-system-tab active" data-tab="overview">总览</button><button class="oi-system-tab" data-tab="tasks">任务</button><button class="oi-system-tab" data-tab="tags">能力</button><button class="oi-system-tab" data-tab="settings">配置</button></div><div id="oi-system-tab-content"></div></div>';
document.body.appendChild(panel);
panelInstance = panel;
panel.querySelector('.oi-system-panel-close').addEventListener('click', function() {
panel.classList.remove('open');
});
panel.querySelectorAll('.oi-system-tab').forEach(function(tab) {
tab.addEventListener('click', function() {
panel.querySelectorAll('.oi-system-tab').forEach(function(t) { t.classList.remove('active'); });
this.classList.add('active');
currentTab = this.dataset.tab;
renderTab(currentTab);
});
});
document.addEventListener('click', function(e) {
if (panel.classList.contains('open')) {
var target = e.target;
if (!panel.contains(target) && !target.closest('.oi-system-button')) {
panel.classList.remove('open');
}
}
});
renderTab('overview');
setTimeout(function() {
panel.classList.add('open');
}, 50);
}
function togglePanel() {
if (panelInstance) {
panelInstance.classList.toggle('open');
if (panelInstance.classList.contains('open')) {
renderTab(currentTab);
}
} else {
createPanel();
}
}
function renderTab(tab) {
var content = document.getElementById('oi-system-tab-content');
if (!content) return;
if (tab === 'overview') renderOverview(content);
else if (tab === 'tasks') renderTasks(content);
else if (tab === 'tags') renderTags(content);
else if (tab === 'settings') renderSettings(content);
}
function renderOverview(container) {
var uid = getStorage(STORAGE_KEYS.UID, '');
var stats = getStats();
var hintCount = getHintCount();
var tasks = getTasks();
var completedCount = tasks.filter(function(t) { return t.completed; }).length;
var totalTasks = tasks.length;
var diffHtml = '';
var diffKeys = Object.keys(DIFFICULTY_NAME);
for (var i = 0; i < diffKeys.length; i++) {
var d = diffKeys[i];
diffHtml += '<div class="oi-system-stat-row"><span class="oi-system-stat-label">' + DIFFICULTY_NAME[d] + '</span><span class="oi-system-stat-value">' + (stats.difficultyDist[d] || 0) + ' 题</span></div>';
}
container.innerHTML = '<div class="oi-system-stat-card"><div class="oi-system-stat-row"><span class="oi-system-stat-label">洛谷 UID</span><span class="oi-system-stat-value">' + (uid || '未设置') + '</span></div><div class="oi-system-stat-row"><span class="oi-system-stat-label">总积分</span><span class="oi-system-stat-value" style="color:#6c5ce7;">' + stats.totalScore + '</span></div><div class="oi-system-stat-row"><span class="oi-system-stat-label">AC 题数</span><span class="oi-system-stat-value">' + stats.acCount + '</span></div><div class="oi-system-stat-row"><span class="oi-system-stat-label">积分券</span><span class="oi-system-stat-value" style="color:#f39c12;">' + hintCount + '</span></div><div class="oi-system-stat-row"><span class="oi-system-stat-label">任务进度</span><span class="oi-system-stat-value">' + completedCount + '/' + totalTasks + '</span></div></div><div class="oi-system-stat-card"><div style="font-size:13px;font-weight:600;margin-bottom:8px;">难度分布</div>' + diffHtml + '</div><div style="margin-top:12px;font-size:12px;color:#aaa;text-align:center;">上次同步: ' + (getStorage(STORAGE_KEYS.LAST_SYNC, 0) ? new Date(getStorage(STORAGE_KEYS.LAST_SYNC, 0)).toLocaleString() : '从未同步') + '</div><div style="margin-top:8px;text-align:center;"><button onclick="window._oiSystemSync()" style="padding:6px 20px;border:none;border-radius:6px;background:#6c5ce7;color:#fff;font-size:12px;cursor:pointer;">同步数据</button></div>';
}
function renderTasks(container) {
var tasks = getTasks();
var hintCount = getHintCount();
var uid = getStorage(STORAGE_KEYS.UID, '');
var pendingTasks = tasks.filter(function(t) { return !t.completed; });
var completedTasks = tasks.filter(function(t) { return t.completed; });
var html = '<div style="font-size:13px;color:#888;margin-bottom:12px;">积分券: <span style="color:#f39c12;font-weight:600;">' + hintCount + '</span>' + (tasks.length > 0 ? ' | 进行中: ' + pendingTasks.length + ' | 已完成: ' + completedTasks.length : '') + '</div>';
if (pendingTasks.length === 0 && completedTasks.length === 0) {
html += '<div style="text-align:center;padding:30px 0;color:#aaa;font-size:14px;">暂无任务</div>';
}
if (pendingTasks.length > 0) {
html += '<div style="font-size:13px;font-weight:600;margin:8px 0 4px;">进行中</div>';
for (var i = 0; i < pendingTasks.length; i++) {
var task = pendingTasks[i];
html += '<div class="oi-system-task-item"><div>' + task.display + '</div><div style="font-size:11px;color:#888;margin-top:4px;">条件: ' + (task.condition.difficulty ? DIFFICULTY_NAME[task.condition.difficulty] : '不限难度') + (task.condition.tag ? ' + ' + task.condition.tag : '') + (task.condition.minCount > 1 ? ' x' + task.condition.minCount : '') + '</div></div>';
}
}
if (completedTasks.length > 0) {
html += '<div style="font-size:13px;font-weight:600;margin:12px 0 4px;">已完成</div>';
var last5 = completedTasks.slice(-5);
for (var j = 0; j < last5.length; j++) {
var task2 = last5[j];
html += '<div class="oi-system-task-item completed"><div>' + task2.display + '</div><div style="font-size:11px;color:#00b894;margin-top:4px;">已完成 ' + (task2.completedWith ? '(' + task2.completedWith + ')' : '') + '</div></div>';
}
if (completedTasks.length > 5) {
html += '<div style="font-size:11px;color:#aaa;text-align:center;margin-top:4px;">还有 ' + (completedTasks.length - 5) + ' 个已完成任务</div>';
}
}
if (uid) {
html += '<div style="margin-top:16px;border-top:1px solid rgba(200,200,200,0.2);padding-top:16px;"><div style="font-size:13px;font-weight:600;margin-bottom:8px;">提交已完成题目</div><div style="font-size:12px;color:#888;margin-bottom:6px;">输入题号(如 P1000),系统会自动匹配任务</div><div class="oi-system-input-group"><input type="text" id="oi-task-input" placeholder="输入题号..." style="text-transform:uppercase;"><button id="oi-task-submit-btn">提交</button></div><div id="oi-task-result" style="font-size:13px;margin-top:8px;min-height:20px;"></div></div>';
} else {
html += '<div style="margin-top:16px;padding:12px;background:rgba(255,200,200,0.1);border-radius:8px;font-size:13px;color:#e74c3c;text-align:center;">请先在「配置」中设置洛谷 UID</div>';
}
container.innerHTML = html;
var submitBtn = document.getElementById('oi-task-submit-btn');
var input = document.getElementById('oi-task-input');
if (submitBtn && input) {
var handleSubmit = async function() {
var pid = input.value.trim().toUpperCase();
if (!pid) {
document.getElementById('oi-task-result').textContent = '请输入题号';
return;
}
submitBtn.disabled = true;
document.getElementById('oi-task-result').textContent = '验证中...';
try {
var result = await submitProblem(uid, pid);
document.getElementById('oi-task-result').innerHTML = result.success ? '<span style="color:#00b894;">' + result.message + ' (获得 ' + result.reward + ' 张积分券)</span>' : '<span style="color:#e74c3c;">' + result.message + '</span>';
if (result.success) {
input.value = '';
setTimeout(function() { renderTasks(container); }, 1000);
}
} catch (e) {
document.getElementById('oi-task-result').innerHTML = '<span style="color:#e74c3c;">提交失败: ' + e.message + '</span>';
}
submitBtn.disabled = false;
};
submitBtn.addEventListener('click', handleSubmit);
input.addEventListener('keydown', function(e) {
if (e.key === 'Enter') handleSubmit();
});
}
}
function renderTags(container) {
var stats = getStats();
var tagScores = stats.tagScores || {};
var entries = Object.entries(tagScores).filter(function(item) { return item[1] > 0; }).sort(function(a, b) { return b[1] - a[1]; });
var top = entries.slice(0, 15);
var bottom = entries.slice(-10).filter(function(item) { return item[1] > 0; });
var html = '<div style="font-size:13px;font-weight:600;margin-bottom:8px;">最强标签 (Top 15)</div><div style="margin-bottom:16px;">';
if (top.length > 0) {
for (var i = 0; i < top.length; i++) {
html += '<div class="oi-system-tag-item"><span class="tag-name">' + getTagName(top[i][0]) + '</span><span class="tag-score">' + top[i][1] + '</span></div>';
}
} else {
html += '<div style="color:#aaa;font-size:13px;">暂无标签数据,请先同步</div>';
}
html += '</div>';
if (bottom.length > 0) {
html += '<div style="font-size:13px;font-weight:600;margin-bottom:8px;color:#e74c3c;">待加强标签 (Bottom 10)</div><div>';
for (var j = 0; j < bottom.length; j++) {
html += '<div class="oi-system-tag-item"><span class="tag-name">' + getTagName(bottom[j][0]) + '</span><span class="tag-score" style="color:#e74c3c;">' + bottom[j][1] + '</span></div>';
}
html += '</div>';
}
container.innerHTML = html;
}
function renderSettings(container) {
var uid = getStorage(STORAGE_KEYS.UID, '');
var apiKey = getStorage(STORAGE_KEYS.API_KEY, '');
var hintCount = getHintCount();
container.innerHTML = '<div style="margin-bottom:12px;"><label style="font-size:13px;font-weight:500;display:block;margin-bottom:4px;">洛谷 UID</label><input type="text" id="oi-setting-uid" value="' + uid + '" placeholder="输入你的洛谷UID" style="width:100%;padding:8px 12px;border:1px solid rgba(200,200,200,0.3);border-radius:6px;font-size:13px;background:rgba(255,255,255,0.6);color:#1a1a2e;outline:none;box-sizing:border-box;"></div><div style="margin-bottom:12px;"><label style="font-size:13px;font-weight:500;display:block;margin-bottom:4px;">DeepSeek API Key</label><input type="password" id="oi-setting-api" value="' + apiKey + '" placeholder="输入你的DeepSeek API Key" style="width:100%;padding:8px 12px;border:1px solid rgba(200,200,200,0.3);border-radius:6px;font-size:13px;background:rgba(255,255,255,0.6);color:#1a1a2e;outline:none;box-sizing:border-box;"><div style="font-size:11px;color:#888;margin-top:4px;">获取地址: https://platform.deepseek.com/api_keys</div></div><div style="margin-bottom:12px;"><label style="font-size:13px;font-weight:500;display:block;margin-bottom:4px;">积分券</label><div style="font-size:16px;font-weight:600;color:#f39c12;">' + hintCount + ' 张</div></div><button id="oi-setting-save" style="width:100%;padding:10px;border:none;border-radius:6px;background:#6c5ce7;color:#fff;font-size:14px;font-weight:500;cursor:pointer;transition:background 0.15s;">保存配置</button><div id="oi-setting-result" style="font-size:13px;margin-top:8px;min-height:20px;"></div><div style="margin-top:12px;border-top:1px solid rgba(200,200,200,0.2);padding-top:12px;"><button id="oi-setting-sync" style="width:100%;padding:8px;border:1px solid #6c5ce7;border-radius:6px;background:transparent;color:#6c5ce7;font-size:13px;cursor:pointer;transition:all 0.15s;">手动同步数据</button></div><div id="oi-sync-progress" style="margin-top:8px;display:none;"></div>';
document.getElementById('oi-setting-save').addEventListener('click', function() {
var newUid = document.getElementById('oi-setting-uid').value.trim();
var newApi = document.getElementById('oi-setting-api').value.trim();
if (newUid) setStorage(STORAGE_KEYS.UID, newUid);
if (newApi) setStorage(STORAGE_KEYS.API_KEY, newApi);
document.getElementById('oi-setting-result').innerHTML = '<span style="color:#00b894;">配置已保存</span>';
setTimeout(function() { renderTab('overview'); }, 500);
});
document.getElementById('oi-setting-sync').addEventListener('click', function() {
var uid2 = getStorage(STORAGE_KEYS.UID, '');
if (!uid2) {
document.getElementById('oi-setting-result').innerHTML = '<span style="color:#e74c3c;">请先设置UID</span>';
return;
}
var progressEl = document.getElementById('oi-sync-progress');
progressEl.style.display = 'block';
progressEl.innerHTML = '<div class="oi-system-sync-progress"><div class="progress-text">准备同步...</div></div>';
syncUserData(uid2, function(msg, progress) {
progressEl.innerHTML = '<div class="oi-system-sync-progress"><div class="progress-text">' + msg + '</div><div class="oi-system-progress"><div class="oi-system-progress-bar" style="width:' + progress + '%;"></div></div></div>';
}).then(function(stats) {
progressEl.innerHTML = '<div class="oi-system-sync-progress"><div class="progress-text" style="color:#00b894;">同步完成!总积分: ' + stats.totalScore + '</div></div>';
renderTab('overview');
renderTab('tasks');
renderTab('tags');
var apiKey2 = getStorage(STORAGE_KEYS.API_KEY, '');
if (apiKey2) {
autoGenerateTasks(apiKey2, uid2);
}
}).catch(function(e) {
progressEl.innerHTML = '<div class="oi-system-sync-progress"><div class="progress-text" style="color:#e74c3c;">同步失败: ' + e.message + '</div></div>';
});
});
}
// ============================================================
// 十二、题解页面拦截
// ============================================================
function interceptSolutionPage() {
if (!window.location.pathname.includes('/problem/solution/')) return;
var pidMatch = window.location.pathname.match(/\/problem\/solution\/(P\d+)/);
if (!pidMatch) return;
var problemId = pidMatch[1];
var observer = new MutationObserver(function() {
var container = document.querySelector('#app');
if (container) {
observer.disconnect();
injectSolutionOverlay(problemId, container);
}
});
observer.observe(document.body, {childList: true, subtree: true});
setTimeout(function() {
var container = document.querySelector('#app');
if (container) {
observer.disconnect();
injectSolutionOverlay(problemId, container);
}
}, 2000);
}
function injectSolutionOverlay(pid, container) {
if (document.querySelector('.oi-system-solution-overlay')) return;
var target = container.querySelector('.lg-container') || container;
var children = target.children;
for (var i = 0; i < children.length; i++) {
if (children[i].tagName !== 'SCRIPT') {
children[i].style.display = 'none';
}
}
var hintHistory = getHintHistory(pid);
var canGet = canGetHint(pid);
var hintCount = getHintCount();
var overlay = document.createElement('div');
overlay.className = 'oi-system-solution-overlay';
var historyHtml = '';
if (hintHistory.length > 0) {
historyHtml = '<div class="hint-history">';
for (var j = 0; j < hintHistory.length; j++) {
historyHtml += '<div class="hint-history-item"><span class="hint-level">第 ' + (j + 1) + ' 次提示</span><div style="margin-top:4px;">' + hintHistory[j].content + '</div></div>';
}
historyHtml += '</div>';
}
var buttonHtml = '';
if (canGet) {
buttonHtml = '<button class="hint-btn" id="oi-hint-get-btn">消耗 1 张积分券获取提示 (剩余 ' + hintCount + ' 张)</button>';
} else {
buttonHtml = '<div style="color:#e74c3c;font-size:14px;font-weight:500;">已获取 ' + MAX_HINTS_PER_PROBLEM + ' 次提示,已达到上限</div><div style="font-size:12px;color:#888;margin-top:4px;">每道题最多可获取 ' + MAX_HINTS_PER_PROBLEM + ' 次提示</div>';
}
overlay.innerHTML = '<div class="lock-icon">[锁]</div><div class="hint-title">题解已被 OI System 锁定</div><div class="hint-sub">通过完成任务获得积分券,兑换AI提示</div>' + historyHtml + '<div id="oi-hint-content" class="hint-content" style="display:none;"></div><div style="margin-top:16px;">' + buttonHtml + '</div><div id="oi-hint-status" style="margin-top:12px;font-size:13px;min-height:20px;"></div>';
target.appendChild(overlay);
var hintBtn = document.getElementById('oi-hint-get-btn');
if (hintBtn) {
hintBtn.addEventListener('click', async function() {
var currentHintCount = getHintCount();
if (currentHintCount < 1) {
document.getElementById('oi-hint-status').innerHTML = '<span style="color:#e74c3c;">积分券不足,请完成任务获取</span>';
return;
}
var apiKey = getStorage(STORAGE_KEYS.API_KEY, '');
if (!apiKey) {
document.getElementById('oi-hint-status').innerHTML = '<span style="color:#e74c3c;">请先在配置中设置 DeepSeek API Key</span>';
return;
}
this.disabled = true;
this.textContent = '生成中...';
document.getElementById('oi-hint-status').innerHTML = '<span style="color:#6c5ce7;">正在生成提示...</span>';
try {
var detail = await fetchProblemDetail(pid);
var history = getHintHistory(pid);
var hint = await generateHint(apiKey, pid, detail.name || pid, history);
setHintCount(currentHintCount - 1);
addHintHistory(pid, hint);
var contentEl = document.getElementById('oi-hint-content');
contentEl.style.display = 'block';
contentEl.innerHTML = hint;
this.textContent = '已获取提示';
this.disabled = true;
document.getElementById('oi-hint-status').innerHTML = '<span style="color:#00b894;">已消耗 1 张积分券,剩余 ' + (currentHintCount - 1) + ' 张</span>';
setTimeout(function() {
injectSolutionOverlay(pid, container);
}, 1000);
} catch (e) {
document.getElementById('oi-hint-status').innerHTML = '<span style="color:#e74c3c;">生成失败: ' + e.message + '</span>';
this.disabled = false;
this.textContent = '消耗 1 张积分券获取提示 (剩余 ' + getHintCount() + ' 张)';
}
});
}
}
// ============================================================
// 十三、初始化
// ============================================================
function init() {
log('OI System 初始化...');
addStyles();
createEntryButton();
interceptSolutionPage();
unsafeWindow._oiSystemSync = async function() {
var uid = getStorage(STORAGE_KEYS.UID, '');
var apiKey = getStorage(STORAGE_KEYS.API_KEY, '');
if (!uid) { showNotification('请先设置UID'); return; }
if (!apiKey) { showNotification('请先设置DeepSeek API Key'); return; }
showNotification('开始同步数据...');
try {
var stats = await syncUserData(uid, function(msg, progress) {});
showNotification('同步成功!总积分: ' + stats.totalScore);
await autoGenerateTasks(apiKey, uid);
renderTab(currentTab);
} catch (e) {
showNotification('同步失败: ' + e.message);
log('同步错误', e);
}
};
var uid = getStorage(STORAGE_KEYS.UID, '');
var apiKey = getStorage(STORAGE_KEYS.API_KEY, '');
var lastSync = getStorage(STORAGE_KEYS.LAST_SYNC, 0);
if (uid && apiKey) {
if (lastSync === 0 || Date.now() - lastSync > 24 * 60 * 60 * 1000) {
log('后台自动同步...');
setTimeout(function() {
syncUserData(uid, function() {})
.then(function(stats) {
log('自动同步完成', stats);
autoGenerateTasks(apiKey, uid);
})
.catch(function(e) {
log('自动同步失败', e);
});
}, 5000);
} else {
var tasks = getTasks();
var pending = tasks.filter(function(t) { return !t.completed; });
if (pending.length < MAX_TASKS) {
setTimeout(function() {
autoGenerateTasks(apiKey, uid);
}, 5000);
}
}
}
log('OI System 初始化完成');
}
if (document.readyState === 'complete') {
init();
} else {
window.addEventListener('load', init);
}
var lastUrl = window.location.href;
setInterval(function() {
var currentUrl = window.location.href;
if (currentUrl !== lastUrl) {
lastUrl = currentUrl;
if (currentUrl.includes('/problem/solution/')) {
setTimeout(interceptSolutionPage, 1000);
}
}
}, 1000);
})();注意事项
- 配置的时候请前往【个人中心】-> 【练习】,等于访问
https://www.luogu.com.cn/user/你的uid/practice。 - 关掉完隐
- 你需要一个deepseek的API key
- 首次加载速度极慢,平均每秒一个题,请不要在加载的时候随便刷新
纯属娱乐,代码由deepseek完成,本人只起到了思路设计与调教deepseek的作用。