JavaScript// ==UserScript==
// @name Codeforces Best
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Make Codeforces Better Become Better
// @author zjf
// @match https://codeforces.com/*
// @grant GM_xmlhttpRequest
// @grant GM_setValue
// @grant GM_getValue
// @run-at document-start
// ==/UserScript==
(function() {
'use strict';
// 完整脚本就这三行
//document.head.insertAdjacentHTML('beforeend', '<link rel="stylesheet" href="https://zjf.xo.je/css/codeforces.css">');
const friends=[
'zhangjinfeng',
'shichanghao2025',
'liang0504',
'cj180202',
'j23wuyifan',
'belief_honor_CC',
'a_foolish_oier',
'Benjamin_Jin',
'Suin_tryin',
'xgw120121',
];
document.addEventListener('click', function(e) {
const colors = ['#ff6b6b', '#feca57', '#48dbfb', '#ff9ff3', '#54a0ff', '#5f27cd'];
for (let i = 0; i < 20; i++) {
const star = document.createElement('div');
const size = Math.random() * 12 + 10;
const angle = Math.random() * Math.PI * 2;
const distance = Math.random() * 120 + 40;
star.textContent = ['✦', '✧', '✶', '✵', '✷'][Math.floor(Math.random() * 5)];
star.style.cssText = `
position: fixed;
left: ${e.clientX}px;
top: ${e.clientY}px;
font-size: ${size * 2}px;
color: ${colors[Math.floor(Math.random() * colors.length)]};
pointer-events: none;
z-index: 99999;
transition: all ${0.5 + Math.random() * 0.5}s ease-out;
opacity: 1;
transform: translate(0, 0) scale(0);
`;
document.body.appendChild(star);
const dx = Math.cos(angle) * distance;
const dy = Math.sin(angle) * distance - 30;
requestAnimationFrame(() => {
star.style.transform = `translate(${dx}px, ${dy}px) scale(1)`;
star.style.opacity = '0';
});
setTimeout(() => star.remove(), 1200);
}
});
async function GetProblems() {
let cached = GM_getValue('cf_problems');
if (cached) return JSON.parse(cached);
const res = await fetch('https://codeforces.com/api/problemset.problems');
const data = await res.json();
const problems = data.result.problems;
GM_setValue('cf_problems', JSON.stringify(problems));
return problems;
}
async function GetSubmissions(user, must) {
let cached = GM_getValue('cf_submissions_'+user);
if (cached && must==false) return JSON.parse(cached);
if (must==false) return [];
const res = await fetch('https://codeforces.com/api/user.status?handle='+user+'&count=10000');
const data = await res.json();
const problems = data.result;
GM_setValue('cf_submissions_'+user, JSON.stringify(problems));
return problems;
}
async function RandomProblem(min=800, max=3500, tags=[]) {
let __problems=await GetProblems();
let list = __problems.filter(p => (p.rating||0) >= min && (p.rating||0) <= max);
if (tags.length) list = list.filter(p => tags.every(t => p.tags.includes(t)));
if (!list.length) return null;
const p = list[Math.floor(Math.random() * list.length)];
window.location.pathname=`/problemset/problem/${p.contestId}/${p.index}`;
}
let flag_click_detail=false;
let flag_problem_id_fill=false;
let flag_problem_out_contest=false;
let flag_add_random_problem=false;
let flag_problem_standing=false;
function color(diff){
if(diff<1200)return "grey";
else if(diff<1400)return "green";
else if(diff<1600)return "#00CED1";
else if(diff<1900)return "blue";
else if(diff<2100)return "violet";
else if(diff<2400)return "orange";
else if(diff<2600)return "#FF6B6B";
else if(diff<3000)return "red";
return "black";
}
async function ProblemBetter(){
const problems=await GetProblems();
//console.log("★"+JSON.stringify(problems));
let links = [...document.querySelectorAll('a[href^="/problemset/problem/"]')].filter(el => !el.innerHTML.includes('</b>') && !el.innerHTML.includes('</p>') && !el.innerHTML.includes('退出比赛模式'));
links.forEach(link => {
const href = link.getAttribute('href');
let path = href;
if (href.startsWith('http://') || href.startsWith('https://'))
path = new URL(href).pathname;
const match = path.match(/^\/problemset\/problem\/([^\/]+)\/([^\/]+)$/);
//console.log('找到链接:', link.href, "match: ",match[2]);
const problem = problems.find(problems => problems.contestId == match[1] && problems.index == match[2]);
if(problem){
//console.log(problem);
if('rating' in problem){
const text=link.innerHTML;
let html="";
if(!text.includes('-')){
html+="<b style='color: "+color(problem.rating)+";'>";
html+=text+"</b>";
}else{
if(problem.tags.includes('interactive'))
html+="<b>[交互] </b>";
else if(problem.tags.includes('constructive algorithms'))
html+="<b>[构造] </b>";
else if(problem.tags.includes('math'))
html+="<b>[数学] </b>";
else if(problem.tags.includes('number theory'))
html+="<b>[数论] </b>";
else if(problem.tags.includes('greedy'))
html+="<b>[贪心] </b>";
else if(problem.tags.includes('dp'))
html+="<b>[动态规划] </b>";
else if(problem.tags.includes('data structures'))
html+="<b>[数据结构] </b>";
else if(problem.tags.includes('combinatorics'))
html+="<b>[组合] </b>";
html+="<b style='color: "+color(problem.rating)+";'>";
html+="[*"+problem.rating+"]";
html+=text+"</b>";
}
link.innerHTML=html;
}else{
const text=link.innerHTML;
link.innerHTML="<p style='color: black;'>"+text+"</p>";
}
}else{
const text=link.innerHTML;
link.innerHTML="<p style='color: black;'>"+text+"</p>";
}
});
Array.from(document.querySelectorAll('a[href^="/contest/"]'))
.filter(link => /\/contest\/\d+\/problem\/\w+/.test(link.href) && !link.innerHTML.includes('</b>') && !link.innerHTML.includes('</p>') && !link.innerHTML.includes('退出比赛模式'))
.forEach(link => {
const href = link.getAttribute('href');
let path = href;
if (href.startsWith('http://') || href.startsWith('https://'))
path = new URL(href).pathname;
const match = path.match(/^\/contest\/([^\/]+)\/problem\/([^\/]+)$/);
const problem = problems.find(problems => problems.contestId == match[1] && problems.index == match[2]);
if(problem){
//console.log(problem);
if('rating' in problem){
const text=link.innerHTML;
let html="";
if(!text.includes('-')){
html+="<b style='color: "+color(problem.rating)+";'>";
html+=text+"</b>";
}else{
if(problem.tags.includes('interactive'))
html+="<b>[交互] </b>";
else if(problem.tags.includes('constructive algorithms'))
html+="<b>[构造] </b>";
else if(problem.tags.includes('math'))
html+="<b>[数学] </b>";
else if(problem.tags.includes('number theory'))
html+="<b>[数论] </b>";
else if(problem.tags.includes('greedy'))
html+="<b>[贪心] </b>";
else if(problem.tags.includes('dp'))
html+="<b>[动态规划] </b>";
else if(problem.tags.includes('data structures'))
html+="<b>[数据结构] </b>";
else if(problem.tags.includes('combinatorics'))
html+="<b>[组合] </b>";
html+="<b style='color: "+color(problem.rating)+";'>";
html+="[*"+problem.rating+"]";
html+=text+"</b>";
}
link.innerHTML=html;
}else{
const text=link.innerHTML;
link.innerHTML="<p style='color: black;'>"+text+"</p>";
}
}else{
const text=link.innerHTML;
link.innerHTML="<p style='color: black;'>"+text+"</p>";
}
});
const menu=document.querySelector('.menu-list.main-menu-list');
if(/^\/problemset\/problem\/[^\/]+\/[^\/]+$/.test(location.pathname)&&flag_problem_id_fill==false){
const match = window.location.pathname.match(/\/problemset\/problem\/([^\/]+)\/([^\/]+)/);
flag_problem_id_fill=true;
if(match){
let div=document.querySelector('.title');
console.log(div);
div.innerText="CF"+match[1]+div.innerText;
}
}
if(/^\/problemset\/problem\/[^\/]+\/[^\/]+$/.test(location.pathname)){
const match = window.location.pathname.match(/\/problemset\/problem\/([^\/]+)\/([^\/]+)/);
[...document.querySelectorAll('.contest-state-regular')].filter(div => div.innerHTML.includes("img")).forEach(div =>
div.innerHTML='<a href="https://www.luogu.com.cn/problem/solution/CF'+match[1]+match[2]+'" style="font-size: 14px; color: var(--fc-color)"><button>查看题解</button></a>'
+'<a href="/contest/'+match[1]+'/status/'+match[2]+'?friends=on" style="font-size: 14px; color: var(--fc-color)"><button>通过统计</button></a>');
}
}
async function StatusBetter(){
let found = [...document.querySelectorAll('.verdict-rejected')].filter(el => el.innerHTML.includes('Wrong answer') && !el.innerHTML.includes('</b>'));
found.forEach(status =>{
const text = status.innerHTML;
status.innerHTML="<b style='color: red'>"+text+"</b>";
});
found = [...document.querySelectorAll('.verdict-rejected')].filter(el => el.innerHTML.includes('limit') && !el.innerHTML.includes('</b>'));
found.forEach(status =>{
const text = status.innerHTML;
status.innerHTML="<b>"+text+"</b>";
});
found = [...document.querySelectorAll('.submissionVerdictWrapper')].filter(el => el.innerHTML.includes('Compilation') && !el.innerHTML.includes('</b>'));
found.forEach(status =>{
const text = status.innerHTML;
status.innerHTML="<b style='color: orange'>"+text+"</b>";
});
found = [...document.querySelectorAll('.status-cell.status-small.status-verdict-cell.dark')].filter(el => el.innerHTML.includes('Compilation') && !el.innerHTML.includes('</b>'));
found.forEach(status =>{
const text = status.innerHTML;
status.innerHTML="<b style='color: orange'>"+text+"</b>";
});
found = [...document.querySelectorAll('.verdict-rejected')].filter(el => el.innerHTML.includes('Runtime error') && !el.innerHTML.includes('</b>'));
found.forEach(status =>{
const text = status.innerHTML;
status.innerHTML="<b style='color: purple'>"+text+"</b>";
});
found = [...document.querySelectorAll('.verdict-waiting')].filter(el => el.innerHTML.includes('Running') && !el.innerHTML.includes('</b>'));
found.forEach(status =>{
const text = status.innerHTML;
status.innerHTML="<b style='color: blue'>"+text+"</b>";
});
if(flag_click_detail==false)
document.querySelector('.click-to-view-tests')?.click(),
flag_click_detail=true;
return;
}
async function NavBetter(){
document.querySelector('.lt')?.remove();
document.querySelector('.rt')?.remove();
document.querySelector('.lb')?.remove();
document.querySelector('.rb')?.remove();
document.querySelector('.ilt')?.remove();
document.querySelector('.irt')?.remove();
document.querySelector('.ilb')?.remove();
document.querySelector('.irb')?.remove();
document.querySelector('.alert.alert-info.diff-notifier')?.remove();
document.querySelector('.button-up')?.remove();
if(document.querySelector('.choose-order'))
document.querySelector('.choose-order').parentElement.style='';
let table=document.querySelectorAll('.datatable');
Array.from(table).forEach(tb =>{
Array.from(tb.children).forEach(td => {td.style="";});
});
if(document.querySelector('.choose-order'))
document.querySelector('.choose-order').parentElement.style='';
const menu=document.querySelector('.menu-list.main-menu-list');
if(document.querySelector('a[href="/top"]')){
document.querySelector('a[href="/top"]')?.parentElement?.remove();
document.querySelector('a[href="/catalog"]')?.parentElement?.remove();
document.querySelector('a[href="/groups/my"]')?.parentElement?.remove();
document.querySelector('a[href="/ratings"]')?.parentElement?.remove();
document.querySelector('a[href="/edu/courses"]')?.parentElement?.remove();
document.querySelector('a[href="/apiHelp"]')?.parentElement?.remove();
document.querySelector('a[href="/calendar"]')?.parentElement?.remove();
document.querySelector('a[href="/help"]')?.parentElement?.remove();
document.querySelector('.menu-list.main-menu-list').querySelectorAll('*').forEach(el => el.className = '');
document.querySelector('.menu-list.main-menu-list').insertAdjacentHTML('beforeend', '<li class><a href="/problemset/status/?friends=on">记录</a></li>');
}
if(document.querySelector('.second-level-menu-list')){
Array.from(document.querySelectorAll('.second-level-menu-list')).forEach(div => {
//console.log(div);
document.querySelector('.menu-list.main-menu-list').insertAdjacentHTML('beforeend', '<li class><a>|</a></li>');
Array.from(div.children).forEach(li => {
//console.log(li);
let a=li.children[0];
if(a.text=="Problems")a.text="题目";
if(a.text=="Submit"||a.text=="Submit Code")a.text="提交";
if(a.text=="Status")a.text="状态";
if(a.text=="My Submissions")a.text="我的提交";
if(a.text=="Standings")a.text="排行榜";
if(a.text=="Custom test"||a.text=="Custom Invocation")a.text="自定义测试";
if(a.text=="Mashups")a.text="组合混搭";
if(a.text=="Gym")a.text="训练营";
if(a.text=="Main")a.text="主题库";
if(a.text=="Settings")a.text="设置";
if(a.text=="Lists")a.text="列表";
if(a.text=="Blog")a.text="博客";
if(a.text=="Teams")a.text="队伍";
if(a.text=="Submissions")a.text="记录";
if(a.text=="Contests"||a.text=="Contest")a.text="比赛";
if(a.text=="Problemsetting")a.text="题库";
if(a.text=="Room")a.text="房间";
if(a.text=="Common standings")a.text="总排行榜";
if(a.text=="Friends standings")a.text="好友排行榜";
if(a.text=="Registrants")a.text="参赛者";
if(a.text=="All registrants")a.text="所有参赛者";
if(a.text=="Registered friends")a.text="参赛的好友";
if(a.text=="acmsguru")a.text="今日排行榜";
if(li.className!="backLava")
menu.appendChild(li);
});
});
document.querySelector('.second-level-menu')?.remove();
if(window.location.pathname=="/problemset"){
document.querySelector('.menu-list.main-menu-list').insertAdjacentHTML('beforeend', '<li class><a>|</a></li>');
document.querySelector('.menu-list.main-menu-list').insertAdjacentHTML('beforeend', '<li class><a href="/better/randomproblem">随机跳题</a></li>');
}
}
if(document.getElementById('sidebar')){
let div=document.getElementById('sidebar');
div.style.position="sticky";
div.style.top="60px";
}
if(document.querySelector('.roundbox.menu-box.borderTopRound.borderBottomRound')){
let div=document.querySelector('.roundbox.menu-box.borderTopRound.borderBottomRound');
div.style.position="sticky";
div.style.top="0px";
div.style.zIndex="10";
}
document.getElementById('footer')?.remove();
document.getElementById('header').className="roundbox";
document.querySelector('.roundbox.sidebox.ContestVirtualFrame.borderTopRound')?.remove();
document.querySelector('.roundbox.sidebox.ContestCloneSidebarFrame.borderTopRound ')?.remove();
document.querySelector('.roundbox.highlight-blue.sidebox.borderTopRound ')?.remove();
[...document.querySelectorAll('.roundbox.sidebox.borderTopRound ')].filter(div =>div.innerHTML.includes('Languages')).forEach(div => div.remove());
[...document.querySelectorAll('.roundbox.sidebox.borderTopRound')].filter(div => div.innerHTML.includes("提交?")).forEach(div => div.remove());
[...document.querySelectorAll('.roundbox.sidebox.borderTopRound')].filter(div => div.innerHTML.includes("Submit?")).forEach(div => div.remove());
[...document.querySelectorAll('.roundbox.sidebox.borderTopRound')].filter(div => div.innerHTML.includes("上次未解决")).forEach(div => div.remove());
[...document.querySelectorAll('.roundbox.sidebox.borderTopRound')].filter(div => div.innerHTML.includes("Last unsolved")).forEach(div => div.remove());
if(/^\/contest\/[^\/]+\/problem\/[^\/]+$/.test(location.pathname)&&flag_problem_out_contest==false){
const match = window.location.pathname.match(/\/contest\/([^\/]+)\/problem\/([^\/]+)/);
flag_problem_out_contest=true;
if(match){
menu.insertAdjacentHTML('beforeend', '<li class><a>|</a></li>');
menu.insertAdjacentHTML('beforeend', '<li class><a better="false" href="/problemset/problem/'+match[1]+'/'+match[2]+'"/>退出比赛模式</a></li>');
}
}
return;
}
let flag_better_standing=false;
async function PageBetterStanding(){
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
if(flag_better_standing==true)return;
document.querySelector('.pagination')?.remove();
[...document.querySelectorAll('.top')].filter(div => div.innerHTML.includes('比赛名称') || div.innerHTML.includes('Name')).forEach(div => {
flag_better_standing=true;
(async function() {
const head=div.parentElement;
head.children[1].innerHTML="用户";
head.children[2].innerHTML="题目数量";
head.children[3].innerHTML="平均难度";
head.children[3].style.width="5em";
head.insertAdjacentHTML('beforeend','<th style="width: 5rm" class="top" draggable="true">状态</th>');
const table=head.parentElement;
//table.parentElement.parentElement.children[0].innerHTML="今日排行榜";
Array.from(table.children).forEach(tr => {
if(!tr.innerHTML.includes('用户')){
tr.remove();
}
});
const sec = Math.floor(new Date().setHours(0, 0, 0, 0) / 1000);
var cnt=0;
for (const u of friends) {
var res = await GetSubmissions(u, false);
var sum = GM_getValue("PageBetterStanding_"+u+"_sum");
var diff = GM_getValue("PageBetterStanding_"+u+"_diff");
if(!sum) sum=0;
if(!diff) diff=0;
cnt ++;
const tr = document.createElement("tr");
tr.innerHTML += "<td>"+cnt+"</td>";
tr.innerHTML += "<td><b>"+u+"</b></td>";
tr.innerHTML += "<td><b style='color: "+color(sum*200+800)+"'>"+sum+"</b></td>";
tr.innerHTML += "<td><b style='color: "+color(diff)+"'>"+Math.floor(diff)+"</b></td>";
tr.innerHTML += "<td><b style='color: orange'>缓存数据</b></td>";
table.appendChild(tr);
}
cnt=0;
for (const u of friends) {
cnt ++;
table.children[cnt].children[4].innerHTML="<b style='color: blue'>更新中</b>"
res = await GetSubmissions(u, true);
sum = 0;
diff = 0;
res.forEach(s => {
if (('rating' in s.problem ) && s.creationTimeSeconds >= sec) {
if(s.verdict == "OK"){
sum ++;
}
}
});
res.forEach(s => {
if (('rating' in s.problem )&& s.creationTimeSeconds >= sec) {
if(s.verdict == "OK"){
if(sum)diff += s.problem.rating / sum;
}
}
});
GM_setValue("PageBetterStanding_"+u+"_sum",sum);
GM_setValue("PageBetterStanding_"+u+"_diff",diff);
const tr = table.children[cnt];
tr.innerHTML = "";
tr.innerHTML += "<td>"+cnt+"</td>";
tr.innerHTML += "<td><b>"+u+"</b></td>";
tr.innerHTML += "<td><b style='color: "+color(sum*200+800)+"'>"+sum+"</b></td>";
tr.innerHTML += "<td><b style='color: "+color(diff)+"'>"+Math.floor(diff)+"</b></td>";
tr.innerHTML += "<td><b style='color: green'>已更新</b></td>";
await sleep(2200);
}
})();
});
return;
}
if(window.location.pathname=="/better/randomproblem"){
document.body.innerHTML="";
RandomProblem(2500,2800);
}
if(window.location.pathname=="/problemsets/acmsguru")PageBetterStanding();
const btn = document.createElement('button');
btn.textContent = '⬆';
btn.onclick = () => window.scrollTo({ top: 0, behavior: 'smooth' });
btn.style.cssText = 'position:fixed;bottom:20px;right:20px;padding:10px 50px;font-size:20px;cursor:pointer;z-index:9999';
document.body.appendChild(btn);
ProblemBetter();
StatusBetter();
NavBetter();
const observer = new MutationObserver(() => {
ProblemBetter();
StatusBetter();
NavBetter();
if(window.location.pathname=="/problemsets/acmsguru")PageBetterStanding();
});
observer.observe(document.body, {
childList: true,
subtree: true
});
async function watchUser(handle) {
const key = 'cf_' + handle;
const last = GM_getValue(key, 0);
const res = await fetch(`https://codeforces.com/api/user.status?handle=${handle}&from=1&count=5`);
const data = await res.json();
const subs = data.result;
for (const sub of subs) {
if (sub.id > last) {
GM_notification({
title: `${handle} 新提交`,
text: `${sub.problem.contestId}${sub.problem.index} - ${sub.verdict || 'PENDING'}`
});
}
}
if (subs.length) GM_setValue(key, subs[0].id);
}
})();