Territorial.io Auto-Join & Play (Focus-Triggered)

F7 arms the script. When armed, clicking a tab auto-starts the game. F6 toggles space-spam. Works on territorial.io & CroxyProxy.

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

// ==UserScript==
// @name         Territorial.io Auto-Join & Play (Focus-Triggered)
// @namespace    Violentmonkey Scripts
// @version      6.0
// @description  F7 arms the script. When armed, clicking a tab auto-starts the game. F6 toggles space-spam. Works on territorial.io & CroxyProxy.
// @author       Assistant
// @match        https://territorial.io/*
// @match        https://*.croxyproxy.com/*territorial.io*
// @match        https://*/*?__cpo=*
// @grant        none
// @run-at       document-end
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';

    // --- State Variables ---
    let isAutomationRunning = false;
    let isSpammingActive = false;
    let spaceSpamIntervalId = null;
    // We use sessionStorage so the "armed" state is forgotten when you close the browser.
    let isArmed = sessionStorage.getItem('territorialAutoStartArmed') === 'true';

    // Stop immediately if this isn't a territorial.io page.
    if (!isTerritorialPage()) return;

    // Initial log message based on armed state
    console.log(`[Auto-Play] Script ready. Auto-start is ${isArmed ? 'ARMED' : 'DISARMED'}. Press F7 to toggle. Press F6 to control spam.`);

    // --- Event Listeners ---

    // F6 and F7 key controls
    document.addEventListener('keydown', (event) => {
        if (event.key === 'F6') {
            event.preventDefault();
            toggleManualSequence();
        }
        if (event.key === 'F7') {
            event.preventDefault();
            toggleArmedState();
        }
    });

    // Listener for when the tab becomes visible
    document.addEventListener('visibilitychange', () => {
        // If the tab is now visible AND the script is armed AND nothing is already running...
        if (document.visibilityState === 'visible' && isArmed && !isAutomationRunning && !isSpammingActive) {
            console.log('[Auto-Play] Tab focused while armed. Starting automation automatically.');
            isAutomationRunning = true;
            startAutomation();
        }
    });

    // --- Control Functions ---

    function toggleManualSequence() {
        if (isSpammingActive) {
            stopSpaceSpam();
        } else if (!isAutomationRunning) {
            isAutomationRunning = true;
            startAutomation();
        } else {
            console.warn('[Auto-Play] Automation sequence is already running.');
        }
    }

    function toggleArmedState() {
        isArmed = !isArmed;
        sessionStorage.setItem('territorialAutoStartArmed', isArmed);
        console.log(`[Auto-Play] Auto-start on focus is now ${isArmed ? 'ARMED' : 'DISARMED'}.`);
        if (!isArmed) {
            console.log("Auto-start will not trigger when you switch to this tab.");
        }
    }

    function startAutomation() {
        waitForElementAndClick(findMultiplayerButton, () => {
            waitForElementAndClick(findReadyButton, () => {
                isAutomationRunning = false;
                startSpaceSpam();
            }, "'Ready' button", () => { isAutomationRunning = false; });
        }, "'Multiplayer' button", () => { isAutomationRunning = false; });
    }

    function startSpaceSpam() {
        if (isSpammingActive) return;
        isSpammingActive = true;
        console.log('[Auto-Play] Starting spacebar spam. Press F6 to stop.');
        spaceSpamIntervalId = setInterval(simulateSpacePress, 150);
    }

    function stopSpaceSpam() {
        if (!isSpammingActive) return;
        clearInterval(spaceSpamIntervalId);
        spaceSpamIntervalId = null;
        isSpammingActive = false;
        console.log('[Auto-Play] Spacebar spam stopped.');
    }

    function simulateSpacePress() {
        document.dispatchEvent(new KeyboardEvent('keydown', { 'key': ' ', 'code': 'Space', 'keyCode': 32, 'bubbles': true }));
    }

    // --- Helper Functions ---

    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 false;
    }

    const TIMEOUT_SECONDS = 15;
    const CHECK_INTERVAL_MS = 200;

    function waitForElementAndClick(findFunction, successCallback, description, timeoutCallback) {
        let attempts = 0;
        const maxAttempts = (TIMEOUT_SECONDS * 1000) / CHECK_INTERVAL_MS;
        console.log(`[Auto-Play] Searching for: ${description}`);
        const interval = setInterval(() => {
            if (attempts >= maxAttempts) {
                clearInterval(interval);
                console.error(`[Auto-Play] Timed out waiting for: ${description}`);
                if (timeoutCallback) timeoutCallback();
                return;
            }
            const element = findFunction();
            if (element) {
                clearInterval(interval);
                element.click();
                if (successCallback) successCallback();
            }
            attempts++;
        }, CHECK_INTERVAL_MS);
    }

    const findMultiplayerButton = () => Array.from(document.querySelectorAll('button')).find(btn => btn.innerText.includes('Multiplayer'));
    const findReadyButton = () => Array.from(document.querySelectorAll('button')).find(btn => btn.innerText.trim().startsWith('Ready'));
})();

QingJ © 2025

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