跳到正文

剪贴板

剪贴板 h5z2xsxl

原文
剪贴板信息

剪贴板信息

收录
更新
JavaScript
// ==UserScript==
// @name         daimayuan 比赛排行榜增强功能
// @namespace    http://oj.daimayuan.top/
// @version      2.0
// @description  在比赛排行榜中添加多维度排名功能,并高亮显示通过题目的用户
// @author       deepseek R1
// @match        http://oj.daimayuan.top/contest/*/standings
// @grant        GM_addStyle
// @grant        GM_xmlhttpRequest
// ==/UserScript==

(function() {
    'use strict';

    // 添加自定义样式
    GM_addStyle(`
        /* 排名模式切换按钮 */
        .ranking-mode-controls {
            margin: 10px 0;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 4px;
            display: flex;
            gap: 8px;
        }

        .ranking-mode-btn {
            padding: 6px 12px;
            background: #e9ecef;
            border: 1px solid #ced4da;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s;
        }

        .ranking-mode-btn:hover {
            background: #dee2e6;
        }

        .ranking-mode-btn.active {
            background: #3a86ff;
            color: white;
            border-color: #3a86ff;
        }

        /* 进度条样式 */
        .problem-status-header {
            margin: 10px 0;
            padding: 10px;
            background: #e3f2fd;
            border-radius: 6px;
            font-weight: bold;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .progress-container {
            flex-grow: 1;
            height: 10px;
            background: #e0e0e0;
            border-radius: 5px;
            margin: 0 10px;
            overflow: hidden;
        }

        .progress-bar {
            height: 100%;
            background: #4caf50;
            border-radius: 5px;
            transition: width 0.3s;
        }

        .status-text {
            min-width: 180px;
            text-align: right;
        }

        /* 通过状态标记 */
        .accepted-cell {
            background-color: #e8f5e9 !important;
            position: relative;
        }

        .accepted-cell::after {
            content: "✓";
            position: absolute;
            top: 2px;
            right: 4px;
            font-size: 12px;
            font-weight: bold;
            color: #2e7d32;
        }

        /* 表头布局优化 */
        .problem-header-container {
            display: flex;
            flex-direction: column;
            min-height: 50px;
            padding: 3px 0;
        }

        .problem-header-link {
            display: block;
            margin-bottom: 4px;
        }

        .accepted-count {
            font-size: 0.75em;
            color: #2e7d32;
            background: #e8f5e9;
            padding: 2px 6px;
            border-radius: 10px;
            white-space: nowrap;
            margin-top: 2px;
        }
    `);

    // 全局变量
    let contestId;
    let standingsTable;
    let userStandings = [];
    let currentUsername;

    // 获取通过指定题目的用户名单
    function getAcceptedUsers(problemId) {
        return new Promise((resolve, reject) => {
            const baseUrl = `http://oj.daimayuan.top/contest/${contestId}/problem/${problemId}/statistics`;
            const acceptedUsers = new Set();
            const seenSubmissions = new Set();
            let page = 1;
            let hasNewData = true;

            const fetchPage = () => {
                if (!hasNewData) {
                    resolve(Array.from(acceptedUsers));
                    return;
                }

                const url = `${baseUrl}?page=${page}`;
                GM_xmlhttpRequest({
                    method: "GET",
                    url: url,
                    onload: function(response) {
                        try {
                            // 使用DOMParser解析HTML
                            const parser = new DOMParser();
                            const doc = parser.parseFromString(response.responseText, 'text/html');

                            // 选择所有包含提交记录的表格行
                            const rows = doc.querySelectorAll('.table-responsive table tbody tr');
                            if (rows.length === 0) {
                                resolve(Array.from(acceptedUsers));
                                return;
                            }

                            let pageHasNew = false;
                            for (const row of rows) {
                                // 提取提交ID
                                const idCell = row.querySelector('td:first-child a');
                                if (!idCell) continue;
                                const submissionId = idCell.textContent.trim().substring(1);

                                // 检查是否是新提交
                                if (!seenSubmissions.has(submissionId)) {
                                    seenSubmissions.add(submissionId);
                                    pageHasNew = true;

                                    // 提取用户名
                                    const userCell = row.querySelectorAll('td')[2];
                                    const username = userCell.querySelector('.uoj-username')?.textContent.trim();
                                    if (username) {
                                        acceptedUsers.add(username);
                                    }
                                }
                            }

                            // 如果整页都是已见过的提交,说明已达到最后一页
                            if (!pageHasNew) {
                                resolve(Array.from(acceptedUsers));
                                return;
                            }

                            page++;
                            fetchPage();
                        } catch (error) {
                            reject(error);
                        }
                    },
                    onerror: function(error) {
                        reject(error);
                    }
                });
            };

            fetchPage();
        });
    }

    // 等待排行榜表格加载完成
    function waitForStandingsTable() {
        return new Promise((resolve) => {
            const check = () => {
                const table = document.querySelector('#standings .table-responsive table');
                if (table) {
                    resolve(table);
                } else {
                    setTimeout(check, 100);
                }
            };
            check();
        });
    }

    // 创建状态显示条
    function createStatusHeader(totalProblems) {
        const header = document.createElement('div');
        header.className = 'problem-status-header';
        header.innerHTML = `
            <div>题目状态加载中</div>
            <div class="progress-container">
                <div class="progress-bar" style="width: 0%"></div>
            </div>
            <div class="status-text">0/${totalProblems} (0%)</div>
        `;
        return header;
    }

    // 更新状态显示条
    function updateStatusHeader(header, completed, totalProblems) {
        const percent = Math.round((completed/totalProblems)*100);
        header.querySelector('.progress-bar').style.width = `${percent}%`;
        header.querySelector('.status-text').textContent =
            `${completed}/${totalProblems} (${percent}%)`;

        if (completed === totalProblems) {
            header.innerHTML = `
                <div>题目状态加载完成!</div>
                <div class="status-text">${totalProblems}个题目已处理</div>
            `;
            header.style.backgroundColor = '#c8e6c9';
            header.style.color = '#2e7d32';
            header.style.transition = 'all 0.5s ease';

            setTimeout(() => {
                header.style.opacity = '0.7';
                setTimeout(() => {
                    header.style.height = '0';
                    header.style.padding = '0';
                    header.style.margin = '0';
                    header.style.overflow = 'hidden';
                    setTimeout(() => {
                        header.remove();
                    }, 500);
                }, 2000);
            }, 3000);
        }
    }

    // 处理单个题目
    async function processProblem(problem, table, statusHeader, totalProblems) {
        try {
            const headerCell = problem.headerCell;

            // 保存原始内容
            const originalLink = headerCell.querySelector('a').cloneNode(true);

            // 创建新的内容结构
            const headerContainer = document.createElement('div');
            headerContainer.className = 'problem-header-container';
            headerContainer.innerHTML = `
                <div class="problem-header-link"></div>
                <div class="accepted-count">加载中<span class="loading-spinner"></span></div>
            `;

            headerContainer.querySelector('.problem-header-link').appendChild(originalLink);
            headerCell.innerHTML = '';
            headerCell.appendChild(headerContainer);

            // 获取通过名单
            const acceptedUsers = await getAcceptedUsers(problem.id);
            const acceptedSet = new Set(acceptedUsers);

            // 处理表格数据
            const rows = table.querySelectorAll('tbody tr');
            let acceptedCount = 0;

            for (const row of rows) {
                const cells = row.querySelectorAll('td');
                if (cells.length < problem.index + 1) continue;

                // 获取用户名(第二列)
                const usernameCell = cells[1];
                const usernameLink = usernameCell.querySelector('.uoj-username');
                if (!usernameLink) continue;

                const username = usernameLink.textContent.trim();

                // 保存当前用户信息
                if (!currentUsername && usernameCell.querySelector('sup')) {
                    currentUsername = username;
                }

                if (acceptedSet.has(username)) {
                    // 标记通过的单元格
                    const problemCell = cells[problem.index];
                    problemCell.classList.add('accepted-cell');
                    acceptedCount++;
                }
            }

            // 更新通过人数统计
            const countElement = headerContainer.querySelector('.accepted-count');
            if (countElement) {
                countElement.innerHTML = `通过: ${acceptedCount}人`;
            }

            return true;
        } catch (error) {
            console.error(`处理题目 ${problem.id} 失败:`, error);
            const countElement = problem.headerCell.querySelector('.accepted-count');
            if (countElement) {
                countElement.innerHTML = '加载失败';
                countElement.style.color = '#d32f2f';
            }
            return false;
        }
    }

    // 收集用户数据
    function collectUserData(table) {
        const rows = table.querySelectorAll('tbody tr');
        userStandings = [];

        rows.forEach(row => {
            const cells = row.querySelectorAll('td');
            const rank = parseInt(cells[0].textContent);
            const username = cells[1].querySelector('.uoj-username')?.textContent.trim();
            const totalScore = parseInt(cells[2].children[0].textContent);

            // 计算通过的题目数
            let solvedCount = 0;
            for (let i = 3; i < cells.length; i++) {
                if (cells[i].classList.contains('accepted-cell')) {
                    solvedCount++;
                }
            }

            // 保存用户数据
            userStandings.push({
                row: row,
                originalRank: rank,
                username: username,
                totalScore: totalScore,
                solvedCount: solvedCount
            });
        });
    }

    // 添加排名模式切换控件
    function addRankingModeControls() {
        const controlsDiv = document.createElement('div');
        controlsDiv.className = 'ranking-mode-controls';
        controlsDiv.innerHTML = `
            <button class="ranking-mode-btn active" data-mode="default">默认排名</button>
            <button class="ranking-mode-btn" data-mode="score">只按分数排</button>
            <button class="ranking-mode-btn" data-mode="solved">按补题数排</button>
        `;

        // 插入到排行榜表格前面
        const standingsDiv = document.querySelector('#standings');
        standingsDiv.parentNode.insertBefore(controlsDiv, standingsDiv);

        // 添加事件监听
        controlsDiv.addEventListener('click', (e) => {
            if (e.target.tagName === 'BUTTON') {
                // 更新按钮状态
                controlsDiv.querySelectorAll('.ranking-mode-btn').forEach(btn => {
                    btn.classList.remove('active');
                });
                e.target.classList.add('active');

                // 切换排名模式
                switchRankingMode(e.target.dataset.mode);
            }
        });
    }

    // 切换排名模式
    function switchRankingMode(mode) {
        const tbody = standingsTable.querySelector('tbody');

        if (mode === 'default') {
            // 恢复默认排名
            userStandings.sort((a, b) => a.originalRank - b.originalRank);
            userStandings.forEach(user => {
                user.row.cells[0].textContent = user.originalRank;
                tbody.appendChild(user.row);
            });
            return;
        }

        // 获取当前用户数据
        const currentUser = userStandings.find(user => user.username === currentUsername);
        if (!currentUser) return;

        if (mode === 'score') {
            // 按分数排名
            const higherScoreCount = userStandings.filter(
                user => user.totalScore > currentUser.totalScore
            ).length;

            // 计算当前用户排名
            const currentUserRank = higherScoreCount + 1;

            // 更新所有用户的排名
            userStandings.forEach(user => {
                const higherCount = userStandings.filter(
                    u => u.totalScore > user.totalScore
                ).length;
                user.row.cells[0].textContent = higherCount + 1;
            });

            // 按分数排序
            userStandings.sort((a, b) => {
                return b.totalScore - a.totalScore;
            });
        }
        else if (mode === 'solved') {
            // 按补题数排名
            const higherSolvedCount = userStandings.filter(
                user => user.solvedCount > currentUser.solvedCount
            ).length;

            // 计算当前用户排名
            const currentUserRank = higherSolvedCount + 1;

            // 更新所有用户的排名
            userStandings.forEach(user => {
                const higherCount = userStandings.filter(
                    u => u.solvedCount > user.solvedCount
                ).length;
                user.row.cells[0].textContent = higherCount + 1;
            });

            // 按补题数排序
            userStandings.sort((a, b) => {
                if (b.solvedCount !== a.solvedCount) return b.solvedCount - a.solvedCount;
                if (b.totalScore !== a.totalScore) return b.totalScore - a.totalScore;
                return a.originalRank - b.originalRank;
            });
        }

        // 重新插入行
        tbody.innerHTML = '';
        userStandings.forEach(user => {
            tbody.appendChild(user.row);
        });

        // 确保当前用户高亮
        const currentUserRow = userStandings.find(user => user.username === currentUsername)?.row;
    }

    // 主函数
    async function main() {
        try {
            // 从URL中获取比赛ID
            const pathParts = window.location.pathname.split('/');
            contestId = pathParts[2]; // 例如:/contest/356/standings -> 356

            // 等待排行榜表格加载
            standingsTable = await waitForStandingsTable();

            // 获取所有题目
            const headers = standingsTable.querySelectorAll('thead th');
            const problems = [];

            for (let i = 0; i < headers.length; i++) {
                const header = headers[i];
                const link = header.querySelector('a');
                if (link && link.href) {
                    const match = link.href.match(/\/problem\/(\d+)/);
                    if (match) {
                        problems.push({
                            id: match[1],
                            headerCell: header,
                            index: i
                        });
                    }
                }
            }

            if (problems.length === 0) {
                console.log('未找到任何题目');
                return;
            }

            // 创建状态显示条
            const statusHeader = createStatusHeader(problems.length);
            standingsTable.parentNode.insertBefore(statusHeader, standingsTable);

            // 依次处理每个题目
            let completedCount = 0;
            for (const problem of problems) {
                const success = await processProblem(problem, standingsTable, statusHeader, problems.length);
                if (success) completedCount++;
                updateStatusHeader(statusHeader, completedCount, problems.length);
            }

            // 收集用户数据
            collectUserData(standingsTable);

            // 添加排名模式切换控件
            addRankingModeControls();

            console.log(`所有题目处理完成,共${problems.length}个题目`);

        } catch (error) {
            console.error('脚本执行出错:', error);
        }
    }

    // 页面加载完成后执行主函数
    window.addEventListener('load', function() {
        setTimeout(main, 1500); // 延迟1.5秒确保页面完全加载
    });
})();