Torn Combat Logger with Dropdown Menu Integration

Logs combat events and integrates into the dropdown menu of Torn PDA

当前为 2024-10-14 提交的版本,查看 最新版本

// ==UserScript==
// @name         Torn Combat Logger with Dropdown Menu Integration
// @namespace    http://torn.com/
// @version      1.6
// @description  Logs combat events and integrates into the dropdown menu of Torn PDA
// @author       Quanna_Parker
// @match        https://www.torn.com/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // Initialize an array to store combat logs
    let combatLogs = JSON.parse(localStorage.getItem("combatLogs")) || [];

    // Max number of logs before auto-cleanup
    const maxLogs = 100;

    // Function to log combat events with additional details
    function logCombat(eventDetails) {
        const logEntry = {
            time: new Date().toLocaleString(),
            attacker: eventDetails.attacker,
            damage: eventDetails.damage,
            result: eventDetails.result,
            attackType: eventDetails.attackType,
            yourHealthBefore: eventDetails.yourHealthBefore,
            yourHealthAfter: eventDetails.yourHealthAfter
        };

        // Add the new log to the logs array
        combatLogs.push(logEntry);

        // Auto-cleanup: Remove oldest log if exceeding maxLogs
        if (combatLogs.length > maxLogs) {
            combatLogs.shift();
        }

        // Save logs to local storage
        localStorage.setItem("combatLogs", JSON.stringify(combatLogs));
        console.log("Combat logged: ", logEntry);
    }

    // Function to monitor events for combat information
    function monitorCombatEvents() {
        document.addEventListener('DOMContentLoaded', function() {
            const eventSection = document.querySelector("#events");

            if (eventSection) {
                let events = eventSection.querySelectorAll(".event");

                events.forEach(event => {
                    if (event.textContent.includes("attacked")) {
                        // Parse event details (adjust this based on Torn's actual event structure)
                        let attacker = event.querySelector(".attacker")?.textContent || "Unknown";
                        let damage = event.querySelector(".damage")?.textContent || "0";
                        let result = event.querySelector(".result")?.textContent || "N/A";
                        let attackType = event.querySelector(".attack-type")?.textContent || "N/A";
                        let yourHealthBefore = event.querySelector(".health-before")?.textContent || "N/A";
                        let yourHealthAfter = event.querySelector(".health-after")?.textContent || "N/A";

                        logCombat({ attacker, damage, result, attackType, yourHealthBefore, yourHealthAfter });
                    }
                });
            }
        });
    }

    // Call the function to start monitoring
    monitorCombatEvents();

    // Function to create the log display pop-up with filtering and sorting
    function viewLogs() {
        // Create the pop-up container
        let logWindow = document.createElement('div');
        logWindow.style.position = 'fixed';
        logWindow.style.top = '50px';
        logWindow.style.right = '50px';
        logWindow.style.width = '400px';
        logWindow.style.height = '400px';
        logWindow.style.backgroundColor = 'white';
        logWindow.style.border = '1px solid black';
        logWindow.style.zIndex = 1000;
        logWindow.style.overflowY = 'scroll';
        logWindow.style.padding = '10px';
        logWindow.style.boxShadow = '0px 0px 10px rgba(0, 0, 0, 0.5)';
        logWindow.style.borderRadius = '10px';

        // Close button
        let closeButton = document.createElement('button');
        closeButton.innerHTML = 'Close';
        closeButton.style.float = 'right';
        closeButton.onclick = function() {
            document.body.removeChild(logWindow);
        };

        // Filter by attacker
        let filterLabel = document.createElement('label');
        filterLabel.innerHTML = "Filter by Attacker: ";
        let filterInput = document.createElement('input');
        filterInput.setAttribute("type", "text");

        // Sort options
        let sortLabel = document.createElement('label');
        sortLabel.innerHTML = "Sort by: ";
        let sortSelect = document.createElement('select');
        let sortByTime = new Option("Time", "time");
        let sortByDamage = new Option("Damage", "damage");
        sortSelect.add(sortByTime);
        sortSelect.add(sortByDamage);

        // Create the display logs function with filtering and sorting
        function displayLogs() {
            let sortedLogs = [...combatLogs];  // Clone the logs to sort
            const filterText = filterInput.value.toLowerCase();

            // Sort logs based on the selected option
            if (sortSelect.value === 'damage') {
                sortedLogs.sort((a, b) => parseInt(b.damage) - parseInt(a.damage));
            } else if (sortSelect.value === 'time') {
                sortedLogs.sort((a, b) => new Date(b.time) - new Date(a.time));
            }

            // Create the logs display
            let logsHTML = '<h3>Combat Logs</h3>';
            sortedLogs.forEach(log => {
                if (!filterText || log.attacker.toLowerCase().includes(filterText)) {
                    logsHTML += `<p><strong>Time:</strong> ${log.time}<br/>
                                 <strong>Attacker:</strong> ${log.attacker}<br/>
                                 <strong>Damage:</strong> ${log.damage}<br/>
                                 <strong>Result:</strong> ${log.result}<br/>
                                 <strong>Attack Type:</strong> ${log.attackType}<br/>
                                 <strong>Your Health (Before):</strong> ${log.yourHealthBefore}<br/>
                                 <strong>Your Health (After):</strong> ${log.yourHealthAfter}</p><hr/>`;
                }
            });
            logContent.innerHTML = logsHTML;
        }

        let logContent = document.createElement('div');
        filterInput.addEventListener('input', displayLogs);
        sortSelect.addEventListener('change', displayLogs);

        logWindow.appendChild(closeButton);
        logWindow.appendChild(filterLabel);
        logWindow.appendChild(filterInput);
        logWindow.appendChild(sortLabel);
        logWindow.appendChild(sortSelect);
        logWindow.appendChild(logContent);

        document.body.appendChild(logWindow);
        displayLogs();  // Initial display without filter or sorting
    }

    // Function to add the button to the Torn PDA dropdown menu
    function addCombatLogsButton() {
        const selectors = [
            ".dropdown", // Common dropdown
            ".menu",     // Common menu
            ".nav",      // Navigation menu
            "#menu",     // Specific ID
            "ul"         // Unordered list
        ];

        for (let selector of selectors) {
            const existingDropdown = document.querySelector(selector);
            if (existingDropdown) {
                const logsMenuItem = document.createElement('li'); // Create a new list item
                logsMenuItem.innerHTML = '<a href="#" id="combat-logs-menu">View Combat Logs</a>';
                existingDropdown.appendChild(logsMenuItem); // Append to the dropdown menu

                // Add click event to the new menu item
                logsMenuItem.onclick = function() {
                    viewLogs();
                };
                console.log('Combat Logs menu item added to dropdown.');
                return; // Exit after successfully adding
            }
        }
        console.error('Dropdown menu not found with any of the specified selectors.');
    }

    // Add button to the dropdown menu after the DOM is fully loaded
    window.onload = function() {
        addCombatLogsButton();
    };
})();