Torn Pickpocketing Helper

Combines Cyclist alerts and difficulty color-coding for the pickpocketing crime. All features are toggleable.

当前为 2025-06-23 提交的版本,查看 最新版本

// ==UserScript==
// @name         Torn Pickpocketing Helper
// @namespace    torn.pickpocketing.helper
// @version      2.1
// @description  Combines Cyclist alerts and difficulty color-coding for the pickpocketing crime. All features are toggleable.
// @author       Microbes & Korbrm (Merged & Fixed eaksquad)
// @match        https://www.torn.com/loader.php?sid=crimes*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=torn.com
// @grant        none
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';

    // --- Configuration ---
    const SETTINGS = {
        cyclistAlerts: {
            enabled: true,
            soundUrl: 'https://audio.jukehost.co.uk/gxd2HB9RibSHhr13OiW6ROCaaRbD8103',
            highlightColor: '#00ff00',
        },
        difficultyColors: {
            enabled: true,
            showCategoryText: true,
        }
    };

    // --- Data Definitions ---
    const markGroups = {
        "Safe": ["Drunk man", "Drunk woman", "Homeless person", "Junkie", "Elderly man", "Elderly woman"],
        "Moderately Unsafe": ["Classy lady", "Laborer", "Postal worker", "Young man", "Young woman", "Student"],
        "Unsafe": ["Rich kid", "Sex worker", "Thug"],
        "Risky": ["Jogger", "Businessman", "Businesswoman", "Gang member", "Mobster"],
        "Dangerous": ["Cyclist"],
        "Very Dangerous": ["Police officer"],
    };
    const categoryColorMap = { "Safe": "#37b24d", "Moderately Unsafe": "#74b816", "Unsafe": "#f59f00", "Risky": "#f76707", "Dangerous": "#f03e3e", "Very Dangerous": "#7048e8" };
    const skillTiers = {
        tier1: { "Safe": "#37b24d", "Moderately Unsafe": "#f76707", "Unsafe": "#f03e3e", "Risky": "#f03e3e", "Dangerous": "#f03e3e", "Very Dangerous": "#7048e8" },
        tier2: { "Safe": "#37b24d", "Moderately Unsafe": "#37b24d", "Unsafe": "#f76707", "Risky": "#f03e3e", "Dangerous": "#f03e3e", "Very Dangerous": "#7048e8" },
        tier3: { "Safe": "#37b24d", "Moderately Unsafe": "#37b24d", "Unsafe": "#37b24d", "Risky": "#f76707", "Dangerous": "#f03e3e", "Very Dangerous": "#7048e8" },
        tier4: { "Safe": "#37b24d", "Moderately Unsafe": "#37b24d", "Unsafe": "#37b24d", "Risky": "#37b24d", "Dangerous": "#f76707", "Very Dangerous": "#7048e8" },
        tier5: { "Safe": "#37b24d", "Moderately Unsafe": "#37b24d", "Unsafe": "#37b24d", "Risky": "#37b24d", "Dangerous": "#37b24d", "Very Dangerous": "#7048e8" },
    };

    // --- State Management ---
    let isCyclistAlertsEnabled = SETTINGS.cyclistAlerts.enabled;
    let isDifficultyColorsEnabled = SETTINGS.difficultyColors.enabled;
    let isCyclistCurrentlyAvailable = false;

    // --- Core Logic ---
    function processAllTargets(crimes, skill) {
        let activeTierColors;
        if (skill < 10) { activeTierColors = skillTiers.tier1; }
        else if (skill < 35) { activeTierColors = skillTiers.tier2; }
        else if (skill < 65) { activeTierColors = skillTiers.tier3; }
        else if (skill < 80) { activeTierColors = skillTiers.tier4; }
        else { activeTierColors = skillTiers.tier5; }

        // *** FIX 1: Use a more robust selector that doesn't rely on volatile class names. ***
        // This selector finds the container and then any direct child div, which is much more stable.
        const targetElements = document.querySelectorAll('.crimes-pickpocketing-container > div > div');

        targetElements.forEach(element => {
            // This selector is also fragile, let's find the title in a more robust way.
            // The title is usually the first div inside the main content area of the item.
            const titleElement = element.querySelector('div[class*="title_"]');
            if (!titleElement) return;

            // *** FIX 2: Clean the target name before using it for lookups. ***
            // This removes any "(Category)" text we might have added on a previous run.
            const targetName = titleElement.textContent.trim().split(' (')[0];

            // Reset styles to prevent issues on re-renders
            const parentContainer = titleElement.closest('div[class*="item-container_"]');
            if (!parentContainer) return;

            parentContainer.style.backgroundColor = '';
            parentContainer.style.borderLeft = '';
            titleElement.style.color = '';

            let category = '';
            for (const cat in markGroups) {
                if (markGroups[cat].includes(targetName)) {
                    category = cat;
                    break;
                }
            }

            if (!category) return;

            if (isDifficultyColorsEnabled) {
                titleElement.style.color = categoryColorMap[category];
                parentContainer.style.borderLeft = `3px solid ${activeTierColors[category]}`;
                if (SETTINGS.difficultyColors.showCategoryText && window.innerWidth > 400) {
                    if (!titleElement.textContent.includes('(')) {
                         titleElement.textContent = `${targetName} (${category})`;
                    }
                }
            }

            if (isCyclistAlertsEnabled && targetName === 'Cyclist' && isCyclistCurrentlyAvailable) {
                parentContainer.style.backgroundColor = SETTINGS.cyclistAlerts.highlightColor;
            }
        });
    }

    function initializeCrimeObserver() {
        interceptFetch("torn.com", "/page.php?sid=crimesData", (response) => {
            const crimes = response?.DB?.crimesByType;
            const skill = response?.DB?.pickpocketing?.skill;

            if (!crimes || typeof skill === 'undefined') return;

            isCyclistCurrentlyAvailable = crimes.some(c => c.title === "Cyclist" && c.available === true);

            if (isCyclistAlertsEnabled && isCyclistCurrentlyAvailable) {
                playAlertSound();
            }

            setTimeout(() => processAllTargets(crimes, skill), 150); // Slightly increased timeout for safety
        });
    }

    function setupInterface() {
        if (document.getElementById('pp-helper-controls')) return;
        const controlsContainer = `<div id="pp-helper-controls" style="margin-bottom: 10px; display: flex; gap: 10px; flex-wrap: wrap;"><a id="cyclist-toggle-btn" class="torn-btn"></a><a id="colors-toggle-btn" class="torn-btn"></a></div>`;
        $('.pickpocketing-root').prepend(controlsContainer);

        const cyclistBtn = $('#cyclist-toggle-btn');
        const colorsBtn = $('#colors-toggle-btn');

        function updateCyclistButton() { cyclistBtn.text(`Cyclist Alerts: ${isCyclistAlertsEnabled ? 'ON' : 'OFF'}`).css(isCyclistAlertsEnabled ? { 'background': '#4CAF50', 'color': 'white' } : { 'background': '', 'color': '' }); }
        function updateColorsButton() { colorsBtn.text(`Difficulty Colors: ${isDifficultyColorsEnabled ? 'ON' : 'OFF'}`).css(isDifficultyColorsEnabled ? { 'background': '#4CAF50', 'color': 'white' } : { 'background': '', 'color': '' }); }

        cyclistBtn.on('click', () => { isCyclistAlertsEnabled = !isCyclistAlertsEnabled; updateCyclistButton(); if (isCyclistAlertsEnabled && isCyclistCurrentlyAvailable) playAlertSound(); });
        colorsBtn.on('click', () => { isDifficultyColorsEnabled = !isDifficultyColorsEnabled; updateColorsButton(); document.querySelector('.crimes-pickpocketing-container').click(); });

        updateCyclistButton();
        updateColorsButton();
    }

    // --- Utility Functions ---
    function playAlertSound() { const audio = new Audio(SETTINGS.cyclistAlerts.soundUrl); audio.play().catch(error => console.error("[PPHelper] Audio failed:", error)); }
    function waitForElementToExist(selector) { return new Promise(resolve => { if (document.querySelector(selector)) return resolve(document.querySelector(selector)); const observer = new MutationObserver(() => { if (document.querySelector(selector)) { resolve(document.querySelector(selector)); observer.disconnect(); } }); observer.observe(document.body, { subtree: true, childList: true }); }); }
    function interceptFetch(url, q, callback) { const originalFetch = window.fetch; window.fetch = function(...args) { return originalFetch.apply(this, args).then(response => { if (response.url.includes(url) && response.url.includes(q)) { response.clone().json().then(json => callback(json)).catch(error => console.error("[PPHelper] Intercept failed:", error)); } return response; }); }; }

    // --- Script Entry Point ---
    waitForElementToExist('.pickpocketing-root').then(() => { console.log("[PPHelper] Initializing Pickpocketing Helper."); setupInterface(); });
    initializeCrimeObserver();
})();