TriX Executor for Territorial.io

TriX is a powerful, command-driven script executor designed to enhance your territorial.io experience. It features a modular interface with a command prompt for quick automation and a dedicated JavaScript Executor for running your own custom code. ⚠️ The JS Executor is a powerful tool; never run code from untrusted sources. Take control of your game with TriX.

目前為 2025-07-02 提交的版本,檢視 最新版本

// ==UserScript==
// @name         TriX Executor for Territorial.io
// @namespace    Violentmonkey Scripts
// @version      36.0.0
// @description  TriX is a powerful, command-driven script executor designed to enhance your territorial.io experience. It features a modular interface with a command prompt for quick automation and a dedicated JavaScript Executor for running your own custom code. ⚠️ The JS Executor is a powerful tool; never run code from untrusted sources. Take control of your game with TriX.
// @author       Painsel & Assistant
// @match        https://*/*
// @grant        none
// @run-at       document-end
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';

    // --- Configuration & State ---
    const tabId = sessionStorage.getItem('trixTabId') || Math.floor(10000 + Math.random() * 90000);
    sessionStorage.setItem('trixTabId', tabId);
    let isMaster = false;

    const baseNames = ['Strategist','Ironclad','Vanguard','Tactician','Swiftstrike','Commander','Sentinel','Echo','Shadow','Apex','Overwatch','Pioneer','Horizon','Maverick','Pathfinder','Siege','Rampart','Nexus','Warden','Beacon','Vengeance','Fury','Razor','Annihilator','Slayer','Berserker','Havoc','Destroyer','Venom','Overlord','Executioner','Dominator','Reaper','Conqueror','Thunder','Juggernaut','Warlord','Avalanche','Brutal','Phantom','Specter','Cipher','Rogue','Enigma','Obscure','Whisper','Nomad','Drifter','Wanderer','Cryptic','Illusionist','Abyss','Void','Stalker','Wraith','Shade','Mirage','Eclipse','Pixel','Ninja','Quasar','Goblin','Sparky','Unicorn','GummyBear','Captain','Phoenix','Fuzzy','Whiz','Zoom','Giggle','Panda','Retro','Waffle','Disco','Cosmic','Jellyfish','BubbleGum','Player','Gamer','Pro','Warrior','Legend','Elite','Ace','Ruler','Master','Chief','Hunter','Zealot','Crusader','Guardian','Knight','Baron','Duke','King','Queen','Aegis','Alpha','Amazon','Ambush','Android','Apollo','Arcane','Archer','Arctic','Argon','Argus','Ares','Armada','Arrow','Artillery','Asgard','Ash','Assassin','Asteroid','Astra','Atlas','Atom','Aurora','Avatar','Avenger','Axiom','Azrael','Azure','Ballista','Bandit','Banshee','Barbarian','Barrage','Basilisk','Bastion','Battalion','Bear','Behemoth','Biscuit','Blackout','Blade','Blaster','Blaze','Blitz','Blizzard','Blockade','Bolt','Bomber','Boop','Borealis','Breaker','Brigade','Bullet','Button','Cabal','Cadet','Caliber','Canyon','Cascade','Cataclysm','Catalyst','Catapult','Cavalry','Centurion','Cerberus','Chaos','Charger','Chimera','Cinder','Citadel','Cleric','Cliff','Cobra'];
    
    if (!isTerritorialPage()) return;


    // --- UI CREATION AND MANAGEMENT ---

    function createExecutorUI() {
        if (document.getElementById('trix-frame')) return;
        const frame = document.createElement('div'); frame.id = 'trix-frame';
        Object.assign(frame.style, { position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', background: '#111', border: '1px solid #444', borderRadius: '6px', zIndex: '100000', boxShadow: '0 0 15px rgba(0,0,0,0.5)', padding: '8px', cursor: 'move', animation: 'trix-fade-in 0.3s ease-out' });
        const executor = document.createElement('div'); executor.id = 'trix-executor';
        Object.assign(executor.style, { width: '600px', backgroundColor: '#1e1e1e', display: 'flex', flexDirection: 'column', fontFamily: 'Consolas, "Courier New", monospace', cursor: 'default' });
        const header = document.createElement('div'); header.id = 'trix-header';
        Object.assign(header.style, { backgroundColor: '#111', color: 'white', padding: '8px', borderTopLeftRadius: '5px', borderTopRightRadius: '5px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' });
        header.innerHTML = `<div><img src="https://i.postimg.cc/pVhYV8kL/image.png" style="height: 20px; margin-right: 10px; vertical-align: middle;"> TriX <span style="font-size: 0.7em; color: #888;">by Painsel</span></div>`;
        const headerControls = document.createElement('div'); Object.assign(headerControls.style, { display: 'flex', alignItems: 'center', gap: '8px' });
        const tabCounter = document.createElement('span'); tabCounter.id = "trix-tab-counter"; tabCounter.title = "Active territorial.io tabs"; Object.assign(tabCounter.style, { color: '#ccc', fontSize: '12px', marginRight: '8px', background: '#252526', padding: '3px 6px', borderRadius: '4px' }); tabCounter.textContent = "Tabs: 1";
        const toggleButton = document.createElement('button'); toggleButton.innerHTML = "−"; Object.assign(toggleButton.style, { background: '#555', border: 'none', color: 'white', borderRadius: '4px', cursor: 'pointer', width: '22px', height: '22px', fontSize: '16px', lineHeight: '1', padding: '0' });
        const fileMenuContainer = document.createElement('div'); fileMenuContainer.className = 'trix-menu-container';
        const fileButton = document.createElement('button'); fileButton.className = 'trix-menu-button'; fileButton.textContent = 'File';
        const fileDropdown = document.createElement('div'); fileDropdown.className = 'trix-dropdown-content';
        fileDropdown.innerHTML = `<a href="#" id="trix-inject-btn">Inject</a><a href="#" id="trix-open-btn">Open...</a><a href="#" id="trix-save-btn">Save As...</a>`;
        fileMenuContainer.appendChild(fileButton); fileMenuContainer.appendChild(fileDropdown);
        fileButton.addEventListener('click', (e) => { e.stopPropagation(); fileDropdown.style.display = fileDropdown.style.display === 'block' ? 'none' : 'block'; });
        document.addEventListener('click', () => { fileDropdown.style.display = 'none'; });
        headerControls.appendChild(tabCounter); headerControls.appendChild(toggleButton); headerControls.appendChild(fileMenuContainer); header.appendChild(headerControls);
        const body = document.createElement('div'); body.id = 'trix-body'; Object.assign(body.style, { display: 'flex', overflow: 'hidden', height: '420px', transition: 'height 0.3s ease-out' });
        const sidebar = document.createElement('div'); Object.assign(sidebar.style, { width: '160px', backgroundColor: '#252526', padding: '10px 0', borderRight: '1px solid #444', display: 'flex', flexDirection: 'column' });
        sidebar.innerHTML = `
            <div id="trix-user-info" style="padding: 0 15px 10px; border-bottom: 1px solid #444;">
                <h4 style="margin: 0 0 5px; color: white;">User Info</h4>
                <span style="font-size: 12px; color: #ccc;">ID: <span id="trix-user-id">${tabId}</span></span>
            </div>
            <div style="flex-grow: 1; margin-top: 10px;">
                <button class="trix-nav-button active" data-page="cmd">Command Prompt</button>
                <button class="trix-nav-button" id="trix-executor-nav-btn" data-page="executor" disabled>Script Executor</button>
                <button class="trix-nav-button" id="trix-server-log-nav-btn" data-page="serverlog" disabled>Server Logs</button>
                <button class="trix-nav-button" data-page="changelog">Changelog</button>
            </div>`;
        const content = document.createElement('div'); Object.assign(content.style, { flexGrow: '1', display: 'flex', flexDirection: 'column' });
        const cmdPage = document.createElement('div'); cmdPage.id = 'trix-page-cmd'; cmdPage.className = 'trix-page'; Object.assign(cmdPage.style, { display: 'flex', flexDirection: 'column', height: '100%' });
        cmdPage.innerHTML = `<div id="trix-history" style="flex-grow: 1; padding: 10px; overflow-y: auto; font-size: 13px;"></div><div style="display: flex; border-top: 1px solid #444; align-items: center;"><input type="text" id="trix-cmd-input" placeholder="Type a command..." style="flex-grow: 1; background: #333; border: none; color: white; padding: 8px; outline: none;"><button id="trix-send-btn" style="background: #0e639c; color: white; border: none; padding: 0 15px; cursor: pointer; align-self: stretch;">Send</button></div>`;
        const executorPage = document.createElement('div'); executorPage.id = 'trix-page-executor'; executorPage.className = 'trix-page'; Object.assign(executorPage.style, { display: 'none', flexDirection: 'column', height: '100%', padding: '10px' });
        executorPage.innerHTML = `<div style="margin-bottom: 5px; color: #ffeb3b;">⚠️ Use 'trix.require.TAB_ID("URL")' in F12 console for targeted remote execution.</div><textarea id="trix-script-input" placeholder="-- Use the F12 console for trix.require --\n\n// Local execution still works\nreturn { success: true };" style="flex-grow: 1; background: #111; color: #e0e0e0; border: 1px solid #444; resize: none; width: 100%; box-sizing: border-box; font-family: inherit;"></textarea><div style="display: flex; gap: 10px; margin-top: 10px;"><button id="trix-execute-script-btn" style="background: #c62828; color: white; border: none; padding: 10px; cursor: pointer; flex-grow: 1;">Execute on this tab</button><button id="trix-clear-script-btn" style="background: #555; color: white; border: none; padding: 10px; cursor: pointer;">Clear</button></div>`;
        const changelogPage = document.createElement('div'); changelogPage.id = 'trix-page-changelog'; changelogPage.className = 'trix-page'; Object.assign(changelogPage.style, { display: 'none', padding: '15px', overflowY: 'auto', color: '#ccc', fontSize: '13px' });
        const serverLogPage = document.createElement('div'); serverLogPage.id = 'trix-page-serverlog'; serverLogPage.className = 'trix-page'; Object.assign(serverLogPage.style, { display: 'none', padding: '15px', overflowY: 'auto', color: '#ccc', fontSize: '13px' });
        serverLogPage.innerHTML = `<h3 style="color: white; margin-top: 0;">Simulated Server Logs</h3><div id="trix-server-log-content"></div>`;
        content.appendChild(cmdPage); content.appendChild(executorPage); content.appendChild(changelogPage); content.appendChild(serverLogPage);
        body.appendChild(sidebar); body.appendChild(content);
        executor.appendChild(header); executor.appendChild(body);
        frame.appendChild(executor); document.body.appendChild(frame);
        addGlobalStyles(); makeDraggable(frame); setupCommandPrompt(); setupSidebarNavigation(); populateChangelog(changelogPage); setupExecutorInjection(); logToHistory("Welcome to TriX Executor. Type /help for commands.");
        toggleButton.onclick = () => { const isMinimized = body.style.display === 'none'; body.style.display = isMinimized ? 'flex' : 'none'; frame.style.padding = isMinimized ? '8px' : '0'; toggleButton.innerHTML = isMinimized ? '−' : '+'; };
    }

    function createVisibleTabId() {
        if (document.getElementById('trix-visible-id')) return;
        const idLabel = document.createElement('div');
        idLabel.id = 'trix-visible-id';
        Object.assign(idLabel.style, {
            position: 'fixed', top: '10px', right: '10px', zIndex: '99999', background: 'rgba(0,0,0,0.7)',
            color: '#ccc', padding: '3px 8px', borderRadius: '4px', fontFamily: 'sans-serif', fontSize: '12px'
        });
        idLabel.textContent = `ID: ${tabId}`;
        document.body.appendChild(idLabel);
    }
    
    // --- SCRIPT EXECUTOR & FILE MENU ---
    function setupExecutorInjection() {
        document.getElementById('trix-inject-btn').addEventListener("click", e => {
            e.preventDefault(); const injectButton = e.target;
            injectButton.innerHTML = 'Injecting...'; injectButton.style.pointerEvents = 'none'; logToHistory("Injecting JavaScript Runtime...");
            setTimeout(() => {
                logToHistory("Injection successful. JS Executor is now online.", "success");
                document.getElementById("trix-executor-nav-btn").disabled = false;
                document.getElementById("trix-server-log-nav-btn").disabled = false;
                injectButton.innerHTML = 'Injected ✔'; injectButton.style.color = '#4caf50';
                document.getElementById("trix-execute-script-btn").addEventListener("click", () => executeLocalScript());
                document.getElementById("trix-clear-script-btn").addEventListener("click", () => { document.getElementById("trix-script-input").value = ""; });
                // Expose the targeted require function to the F12 console
                window.trix = {
                    require: new Proxy({}, {
                        get(target, prop) {
                            const targetTabId = String(prop);
                            return async (url) => {
                                logToHistory(`Sent require command for tab ${targetTabId}`);
                                sendCommandToAgents('execute-remote-script', [url], targetTabId);
                            };
                        }
                    })
                };
                logToHistory("`trix.require.ID('URL')` is now available in the F12 console.", "success");
            }, 1000);
        });
        document.getElementById('trix-save-btn').addEventListener("click", e => { e.preventDefault(); saveScriptToFile(); });
        document.getElementById('trix-open-btn').addEventListener("click", e => { e.preventDefault(); openScriptFromFile(); });
    }
    
    // --- COMMAND & EXECUTION LOGIC ---
    function executeLocalScript() {
        const scriptText = document.getElementById("trix-script-input").value;
        if ("" === scriptText.trim()) return logToHistory("Script input is empty.", "error");
        logToHistory("Executing local script...");
        try {
            window.trixHandle = new Function(scriptText)();
            logToHistory("Script attached. Use 'trixHandle' in F12 console to manage.", "success");
            logToServerPanel("[200 OK] Local script attached to window.trixHandle.", "success");
        } catch (e) {
            logToServerPanel(`[500 ERROR] ${e.message}`, "error");
            console.error("Local Script Error:", e);
        }
    }
    async function executeRemoteScript(url) {
        logToHistory(`Received require for: ${url}`);
        try {
            const response = await fetch(url);
            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            const code = await response.text();
            new Function(code)();
            logToServerPanel(`[200 OK] Remote script from ${url} executed.`, "success");
        } catch (e) {
            logToServerPanel(`[500 ERROR] Failed to fetch/execute ${url}: ${e.message}`, 'error');
            console.error(e);
        }
    }

    // --- CROSS-TAB COMMUNICATION & ROLE MANAGEMENT ---
    function sendCommandToAgents(command, args = [], targetId = null) { const payload = { cmd: command, args, targetId, commandId: Date.now() }; localStorage.setItem('trix-command', JSON.stringify(payload)); }
    function setupStorageListener() {
        window.addEventListener('storage', e => {
            if (e.key === 'trix-master-heartbeat' && e.newValue) {
                if (isMaster) { isMaster = false; const frame = document.getElementById('trix-frame'); if (frame) frame.style.display = 'none'; }
            }
            if (e.key === 'trix-command' && e.newValue) {
                const payload = JSON.parse(e.newValue);
                if (!payload.targetId || payload.targetId == tabId) { // If it's for me or for everyone
                    executeReceivedCommand(payload);
                }
            }
        });
    }
    function setupTabCounter() {
        setInterval(() => { const heartbeats = JSON.parse(localStorage.getItem('trix-agent-heartbeats') || '{}'); heartbeats[tabId] = Date.now(); localStorage.setItem('trix-agent-heartbeats', JSON.stringify(heartbeats)); }, 2000);
        window.addEventListener('beforeunload', () => { const heartbeats = JSON.parse(localStorage.getItem('trix-agent-heartbeats') || '{}'); delete heartbeats[tabId]; localStorage.setItem('trix-agent-heartbeats', JSON.stringify(heartbeats)); });
        if (isMaster) {
            setInterval(() => { localStorage.setItem('trix-master-heartbeat', Date.now()); }, 2000);
            setInterval(() => {
                const heartbeats = JSON.parse(localStorage.getItem('trix-agent-heartbeats') || '{}');
                let activeCount = 0;
                for (const id in heartbeats) { if (Date.now() - heartbeats[id] < 5000) activeCount++; else delete heartbeats[id]; }
                localStorage.setItem('trix-agent-heartbeats', JSON.stringify(heartbeats));
                const counterEl = document.getElementById('trix-tab-counter');
                if(counterEl) counterEl.textContent = `Tabs: ${activeCount}`;
            }, 1000);
            window.addEventListener('beforeunload', () => { localStorage.removeItem('trix-master-heartbeat'); });
        }
    }
    function executeReceivedCommand(payload) { logToHistory(`Executing command: ${payload.cmd}`); switch (payload.cmd) { case 'execute-remote-script': executeRemoteScript(payload.args[0]); break; /* Other commands can go here */ } }
    
    // --- GENERIC HELPERS & UTILITIES ---
    function addGlobalStyles(){const style=document.createElement("style");style.textContent=`@keyframes trix-fade-in{from{opacity:0;transform:translate(-50%,-50%) scale(.95)}to{opacity:1;transform:translate(-50%,-50%) scale(1)}}#trix-executor-nav-btn:disabled,#trix-server-log-nav-btn:disabled{color:#666;cursor:not-allowed}.trix-nav-button{background:0 0;border:none;color:#ccc;display:block;width:100%;text-align:left;padding:10px 15px;cursor:pointer;font-family:inherit;font-size:14px}.trix-nav-button:hover:not(:disabled){background:#333}.trix-nav-button.active{background:#0e639c;color:#fff}#trix-history .trix-log,#trix-server-log-content .trix-log{margin-bottom:5px}#trix-history .trix-error,#trix-server-log-content .trix-error{color:#f44336}#trix-history .trix-success,#trix-server-log-content .trix-success{color:#4caf50}.trix-menu-container{position:relative;display:inline-block;}.trix-menu-button{background:#555;color:white;border:none;padding:4px 10px;border-radius:4px;cursor:pointer;font-family:inherit;}.trix-dropdown-content{display:none;position:absolute;right:0;background-color:#2a2d2e;min-width:120px;box-shadow:0 8px 16px 0 rgba(0,0,0,0.2);z-index:1;border:1px solid #444;border-radius:4px;}.trix-dropdown-content a{color:#ccc;padding:8px 12px;text-decoration:none;display:block;font-size:13px;}.trix-dropdown-content a:hover{background-color:#333;}.trix-menu-button:focus + .trix-dropdown-content, .trix-menu-container:hover .trix-dropdown-content{display:block;}.trix-menu-container:hover .trix-menu-button{background-color:#666;}`,document.head.appendChild(style)}
    function populateChangelog(container){container.innerHTML=`<h3 style="color:white;margin-top:0">Changelog</h3><h4>v36.0.0 - Targeted Require</h4><ul><li>Added visible Tab ID to each game tab.</li><li>Implemented console command 'trix.require.TAB_ID("URL")' for targeted remote script execution.</li><li>Removed "Targets" input and simplified UI to a single executor page.</li></ul><h4>v32.0.6 - Command System Fix</h4><ul><li>Fixed a critical bug where the Master tab would not execute its own commands.</li></ul>`}
    function logToHistory(message, type = "log") { if(!isMaster) return; const history = document.getElementById("trix-history"); if (!history) return; const entry = document.createElement("div"); entry.className = `trix-${type}`; entry.textContent = message; history.appendChild(entry); history.scrollTop = history.scrollHeight; }
    function setupCommandPrompt(){const input=document.getElementById("trix-cmd-input"),sendBtn=document.getElementById("trix-send-btn"),handler=()=>{input.value.trim()&&(handleCommand(input.value),input.value="")};input.addEventListener("keydown",(e=>{if("Enter"===e.key)handler()})),sendBtn.addEventListener("click",handler)}
    function setupSidebarNavigation(){document.querySelectorAll(".trix-nav-button").forEach(button=>{button.addEventListener("click",()=>{if(button.disabled)return;document.querySelectorAll(".trix-nav-button").forEach(btn=>btn.classList.remove("active")),button.classList.add("active");const pageId=`trix-page-${button.dataset.page}`;document.querySelectorAll(".trix-page").forEach(page=>{page.style.display=page.id===pageId?(page.id.includes("cmd")||page.id.includes("executor")?"flex":"block"):"none"})})})}
    function logToServerPanel(message,type="log"){if(!isMaster)return;const logContent=document.getElementById("trix-server-log-content");if(!logContent)return;const entry=document.createElement("div");entry.className=`trix-${type}`;const timestamp=(new Date).toLocaleTimeString();entry.innerHTML=`<span style="color: #888;">[${timestamp}]</span> ${message}`,logContent.appendChild(entry),logContent.scrollTop=logContent.scrollHeight}
    function saveScriptToFile(){const scriptText=document.getElementById("trix-script-input").value;if(""===scriptText.trim())return logToHistory("Cannot save an empty script.","error");const blob=new Blob([scriptText],{type:"text/plain;charset=utf-8"}),now=new Date,pad=num=>num.toString().padStart(2,"0"),timestamp=`${now.getFullYear()}-${pad(now.getMonth()+1)}-${pad(now.getDate())}_${pad(now.getHours())}-${pad(now.getMinutes())}-${pad(now.getSeconds())}`,filename=`trix_script_${timestamp}.txt`,link=document.createElement("a");link.href=URL.createObjectURL(blob),link.download=filename,document.body.appendChild(link),link.click(),document.body.removeChild(link),URL.revokeObjectURL(link.href),logToHistory(`Script saved as ${filename}`,"success")}
    function openScriptFromFile(){const input=document.createElement("input");input.type="file",input.accept=".txt,.js,.script",input.onchange=e=>{const file=e.target.files[0];if(!file)return;const reader=new FileReader;reader.onload=event=>{document.getElementById("trix-script-input").value=event.target.result,logToHistory(`Loaded script: ${file.name}`,"success")},reader.readAsText(file)},input.click()}
    function makeDraggable(element){let isDragging=!1,offsetX,offsetY;const handle=element;handle.onmousedown=e=>{if(e.target!==handle&&!e.target.closest("#trix-header"))return;e.preventDefault(),isDragging=!0,offsetX=e.clientX-element.offsetLeft,offsetY=e.clientY-element.offsetTop,document.onmousemove=e=>{isDragging&&(element.style.left=`${e.clientX-offsetX}px`,element.style.top=`${e.clientY-offsetY}px`)},document.onmouseup=()=>{isDragging=!1,document.onmousemove=document.onmouseup=null}}}
    function isTerritorialPage() { const href = window.location.href; if (href.includes("territorial.io")) return true; if (href.includes("?__cpo=")) { try { return atob(new URLSearchParams(window.location.search).get("__cpo")).includes("territorial.io"); } catch (e) { return false; } } return document.title.toLowerCase().includes("territorial.io"); }
    function waitForElement(findFunction, description, timeout = 15000) { return new Promise((resolve, reject) => { let attempts = 0, maxAttempts = timeout / 200; const interval = setInterval(() => { if (attempts++ >= maxAttempts) { clearInterval(interval); reject(new Error(`Timed out: ${description}`)); } const element = findFunction(); if (element) { clearInterval(interval); resolve(element); } }, 200); }); }
    const findUsernameInput = () => document.getElementById("input0");
    function initialize() { waitForElement(findUsernameInput, "Game UI to load", 5000).then(() => { createVisibleTabId(); isMasterTab() ? becomeMaster() : becomeAgent(); }).catch(() => {}); }
    function isMasterTab() { const heartbeat = localStorage.getItem("trix-master-heartbeat"); return !heartbeat || (Date.now() - heartbeat > 4000); }
    function becomeAgent() { console.log("[TriX] Master detected. Initializing as Agent."); setupStorageListener(); setupTabCounter(); }
    function becomeMaster() { console.log("[TriX] No master detected. Initializing as Master."); isMaster = true; createExecutorUI(); setupStorageListener(); setupTabCounter(); }
    initialize();
})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址