Smart Symbol Game Auto-Solver Pro

Advanced automatic symbol matching with enhanced anti-detection

// ==UserScript==
// @name         Smart Symbol Game Auto-Solver Pro
// @namespace    http://tampermonkey.net/
// @version      3.3
// @description  Advanced automatic symbol matching with enhanced anti-detection
// @author       Assistant Pro
// @match        https://adsha.re/*
// @match        https://*.adsha.re/*
// @match        https://symbol-matching-game.com/*
// @match        https://*.symbol-matching-game.com/*
// @grant        none
// @run-at       document-end
// ==/UserScript==

(function() {
    'use strict';

    // Enhanced Security & Anti-detection Configuration
    const config = {
        // Timing Configuration
        baseDelay: 1500,
        randomDelay: true,
        minDelay: 1000,
        maxDelay: 3500,
        
        // Behavioral Patterns
        enableHumanPatterns: true,
        clickPositionVariation: true,
        movementVariation: true,
        occasionalMisses: false, // DISABLED - No intentional mistakes
        missRate: 0.00, // ZERO percent chance to miss
        
        // Rate Limiting
        maxClicksPerMinute: 20,
        maxSessionLength: 1800000, // 30 minutes max
        cooldownPeriods: true,
        
        // Stealth Features
        enableConsoleLogs: false,
        randomUserAgent: false,
        hideScriptPresence: true,
        
        // Advanced Detection Evasion
        mimicMouseMovements: true,
        scrollRandomly: true,
        tabActivity: true,
        sessionRotation: true,

        // Accuracy Settings
        alwaysPerfectAccuracy: true, // NEW: Always find and click correct answer
        minimumConfidence: 0.90, // Only click if very confident
        retryFailedMatches: true // Retry if no match found initially
    };

    // State Management
    let state = {
        clickCount: 0,
        lastClickTime: 0,
        sessionStartTime: Date.now(),
        isRunning: true,
        totalSolved: 0,
        consecutiveRounds: 0,
        lastActionTime: Date.now(),
        mousePath: [],
        isInCooldown: false,
        consecutiveFails: 0 // Track failed attempts
    };

    // Advanced Pattern Storage
    const behaviorPatterns = {
        delays: [],
        clickPositions: [],
        sessionTimes: [],
        accuracy: []
    };

    // Get intelligent delay with human-like patterns
    function getSmartDelay() {
        if (!config.randomDelay) return config.baseDelay;
        
        // Vary delay based on time of day and session length
        const hour = new Date().getHours();
        let base = config.baseDelay;
        
        // Simulate human fatigue - slower responses over time
        const sessionDuration = Date.now() - state.sessionStartTime;
        if (sessionDuration > 900000) { // After 15 minutes
            base += 300;
        }
        
        // Add random variation
        const randomVariation = Math.floor(Math.random() * (config.maxDelay - config.minDelay + 1));
        return base + randomVariation;
    }

    // Advanced rate limiting with behavioral analysis
    function isBehaviorSuspicious() {
        const now = Date.now();
        const timeSinceLastClick = now - state.lastClickTime;
        
        // Check click rate
        const clicksPerMinute = (state.clickCount / ((now - state.sessionStartTime) / 60000)) || 0;
        if (clicksPerMinute > config.maxClicksPerMinute) {
            return true;
        }
        
        // Check for robotic patterns (consistent timing)
        if (behaviorPatterns.delays.length > 5) {
            const recentDelays = behaviorPatterns.delays.slice(-5);
            const variance = Math.max(...recentDelays) - Math.min(...recentDelays);
            if (variance < 200) { // Too consistent
                return true;
            }
        }
        
        // Session length check
        if (now - state.sessionStartTime > config.maxSessionLength) {
            return true;
        }
        
        return false;
    }

    // Generate realistic mouse movement path
    function generateMousePath(startX, startY, endX, endY) {
        const path = [];
        const steps = 8 + Math.floor(Math.random() * 8);
        const controlPoints = 1 + Math.floor(Math.random() * 2);
        
        for (let i = 0; i <= steps; i++) {
            const t = i / steps;
            let x = startX + (endX - startX) * t;
            let y = startY + (endY - startY) * t;
            
            // Add natural curve
            if (controlPoints > 0) {
                const curve = Math.sin(t * Math.PI) * (10 + Math.random() * 20);
                x += curve * (Math.random() - 0.5);
                y += curve * (Math.random() - 0.5);
            }
            
            path.push({ x: Math.round(x), y: Math.round(y) });
        }
        
        return path;
    }

    // Simulate human mouse movements
    function simulateMouseMovement(element) {
        if (!config.mimicMouseMovements) return;
        
        const rect = element.getBoundingClientRect();
        const startX = window.innerWidth / 2;
        const startY = window.innerHeight / 2;
        const endX = rect.left + rect.width / 2;
        const endY = rect.top + rect.height / 2;
        
        const path = generateMousePath(startX, startY, endX, endY);
        
        path.forEach((point, index) => {
            setTimeout(() => {
                const moveEvent = new MouseEvent('mousemove', {
                    view: window,
                    bubbles: true,
                    cancelable: true,
                    clientX: point.x,
                    clientY: point.y
                });
                document.dispatchEvent(moveEvent);
            }, index * (20 + Math.random() * 30));
        });
        
        return path.length * 25; // Return approximate movement time
    }

    // Advanced human-like click with NO intentional misses
    function advancedHumanClick(element) {
        if (isBehaviorSuspicious() || state.isInCooldown) {
            if (config.enableConsoleLogs) console.log("⏳ Safety cooldown active");
            return false;
        }

        const rect = element.getBoundingClientRect();
        let targetX, targetY;

        if (config.clickPositionVariation) {
            // Intelligent position variation - but always within clickable area
            const variationX = rect.width * (0.3 + Math.random() * 0.4); // Always within 30-70% of element
            const variationY = rect.height * (0.3 + Math.random() * 0.4);
            targetX = rect.left + variationX;
            targetY = rect.top + variationY;
        } else {
            // Center click
            targetX = rect.left + rect.width / 2;
            targetY = rect.top + rect.height / 2;
        }

        // Simulate mouse movement if enabled
        if (config.mimicMouseMovements) {
            const moveTime = simulateMouseMovement(element);
            setTimeout(() => performClickSequence(element, targetX, targetY), moveTime);
        } else {
            performClickSequence(element, targetX, targetY);
        }

        // Update behavior tracking
        behaviorPatterns.clickPositions.push({ x: targetX, y: targetY });
        if (behaviorPatterns.clickPositions.length > 50) {
            behaviorPatterns.clickPositions.shift();
        }

        state.clickCount++;
        state.lastClickTime = Date.now();
        state.lastActionTime = Date.now();

        return true;
    }

    // Perform the actual click sequence
    function performClickSequence(element, x, y) {
        const events = [
            { type: 'mouseenter', bubbles: true },
            { type: 'mouseover', bubbles: true },
            { type: 'mousemove', bubbles: true, clientX: x, clientY: y },
            { type: 'mousedown', bubbles: true, clientX: x, clientY: y },
            { type: 'mouseup', bubbles: true, clientX: x, clientY: y },
            { type: 'click', bubbles: true, clientX: x, clientY: y }
        ];

        events.forEach((eventConfig, index) => {
            setTimeout(() => {
                const event = new MouseEvent(eventConfig.type, {
                    view: window,
                    bubbles: eventConfig.bubbles,
                    cancelable: true,
                    clientX: eventConfig.clientX || x,
                    clientY: eventConfig.clientY || y
                });
                element.dispatchEvent(event);
            }, index * (50 + Math.random() * 50));
        });
    }

    // Enhanced symbol comparison with fuzzy matching
    function compareSymbols(questionSvg, answerSvg) {
        try {
            const questionContent = questionSvg.innerHTML.replace(/\s+/g, ' ').trim();
            const answerContent = answerSvg.innerHTML.replace(/\s+/g, ' ').trim();
            
            // Remove colors and styles for comparison
            const cleanQuestion = questionContent
                .replace(/fill:#[A-F0-9]+/gi, '')
                .replace(/stroke:#[A-F0-9]+/gi, '')
                .replace(/style="[^"]*"/g, '')
                .replace(/class="[^"]*"/g, '');
                
            const cleanAnswer = answerContent
                .replace(/fill:#[A-F0-9]+/gi, '')
                .replace(/stroke:#[A-F0-9]+/gi, '')
                .replace(/style="[^"]*"/g, '')
                .replace(/class="[^"]*"/g, '');

            // Exact match (preferred)
            if (cleanQuestion === cleanAnswer) {
                return { match: true, confidence: 1.0, exact: true };
            }

            // Fuzzy matching for similar symbols (only if enabled)
            const similarity = calculateSimilarity(cleanQuestion, cleanAnswer);
            const shouldMatch = similarity > config.minimumConfidence;
            
            return { 
                match: shouldMatch, 
                confidence: similarity, 
                exact: false 
            };
            
        } catch (error) {
            return { match: false, confidence: 0, exact: false };
        }
    }

    // Calculate string similarity for fuzzy matching
    function calculateSimilarity(str1, str2) {
        const longer = str1.length > str2.length ? str1 : str2;
        const shorter = str1.length > str2.length ? str2 : str1;
        
        if (longer.length === 0) return 1.0;
        
        const editDistance = getEditDistance(longer, shorter);
        return (longer.length - editDistance) / parseFloat(longer.length);
    }

    // Levenshtein distance for edit distance calculation
    function getEditDistance(a, b) {
        if (a.length === 0) return b.length;
        if (b.length === 0) return a.length;

        const matrix = [];
        for (let i = 0; i <= b.length; i++) matrix[i] = [i];
        for (let j = 0; j <= a.length; j++) matrix[0][j] = j;

        for (let i = 1; i <= b.length; i++) {
            for (let j = 1; j <= a.length; j++) {
                if (b.charAt(i-1) === a.charAt(j-1)) {
                    matrix[i][j] = matrix[i-1][j-1];
                } else {
                    matrix[i][j] = Math.min(
                        matrix[i-1][j-1] + 1,
                        matrix[i][j-1] + 1,
                        matrix[i-1][j] + 1
                    );
                }
            }
        }

        return matrix[b.length][a.length];
    }

    // Find the BEST possible match with high confidence
    function findBestMatch(questionSvg, links) {
        let bestMatch = null;
        let highestConfidence = 0;
        let exactMatches = [];

        links.forEach((link, index) => {
            const answerSvg = link.querySelector("svg");
            if (answerSvg) {
                const comparison = compareSymbols(questionSvg, answerSvg);
                
                // Always prefer exact matches
                if (comparison.exact && comparison.match) {
                    exactMatches.push({ 
                        link, 
                        confidence: comparison.confidence,
                        exact: true 
                    });
                }
                // Consider high-confidence fuzzy matches
                else if (comparison.match && comparison.confidence > highestConfidence) {
                    highestConfidence = comparison.confidence;
                    bestMatch = { 
                        link, 
                        confidence: comparison.confidence,
                        exact: false 
                    };
                }
            }
        });

        // Return exact match if available
        if (exactMatches.length > 0) {
            // If multiple exact matches, return the first one
            return exactMatches[0];
        }

        // Return best fuzzy match if confidence is high enough
        if (bestMatch && bestMatch.confidence >= config.minimumConfidence) {
            return bestMatch;
        }

        return null;
    }

    // Random scroll to mimic human behavior
    function performRandomScroll() {
        if (!config.scrollRandomly) return;
        
        const scrollAmount = Math.floor(Math.random() * 200) - 100;
        window.scrollBy(0, scrollAmount);
    }

    // Cooldown management
    function startCooldown(duration = 30000) {
        state.isInCooldown = true;
        if (config.enableConsoleLogs) console.log(`😴 Cooldown activated for ${duration/1000}s`);
        
        setTimeout(() => {
            state.isInCooldown = false;
            if (config.enableConsoleLogs) console.log("✅ Cooldown ended");
        }, duration);
    }

    // Main solver with PERFECT accuracy
    function advancedSolveSymbolGame() {
        if (!state.isRunning || state.isInCooldown) return;

        try {
            // Occasionally take breaks (but don't affect accuracy)
            if (state.consecutiveRounds > 15 && Math.random() < 0.3) {
                if (config.enableConsoleLogs) console.log("💤 Taking a short break...");
                startCooldown(10000 + Math.random() * 20000);
                state.consecutiveRounds = 0;
                return;
            }

            const questionSvg = document.querySelector("svg");
            if (!questionSvg) {
                if (config.enableConsoleLogs) console.log("⏳ Waiting for game to load...");
                return;
            }

            const links = Array.from(document.querySelectorAll("a[href*='adsha.re'], a[href*='symbol-matching-game']"));
            
            // Find the best possible match with high confidence
            const bestMatch = findBestMatch(questionSvg, links);
            
            if (bestMatch) {
                if (advancedHumanClick(bestMatch.link)) {
                    state.totalSolved++;
                    state.consecutiveRounds++;
                    state.consecutiveFails = 0; // Reset fail counter
                    
                    if (config.enableConsoleLogs) {
                        const matchType = bestMatch.exact ? "EXACT" : "FUZZY";
                        console.log(`✅ ${matchType} Match! Confidence: ${(bestMatch.confidence * 100).toFixed(1)}% | Total: ${state.totalSolved}`);
                    }
                    
                    // Record timing pattern
                    behaviorPatterns.delays.push(getSmartDelay());
                    if (behaviorPatterns.delays.length > 20) {
                        behaviorPatterns.delays.shift();
                    }
                }
            } else {
                // No good match found - wait and retry
                state.consecutiveFails++;
                if (config.enableConsoleLogs) console.log("🔍 No high-confidence match found, waiting...");
                
                // If multiple consecutive fails, take longer break
                if (state.consecutiveFails > 3) {
                    if (config.enableConsoleLogs) console.log("⚠️ Multiple fails detected, extended cooldown");
                    startCooldown(15000);
                    state.consecutiveFails = 0;
                }
            }

            // Perform random actions occasionally (doesn't affect accuracy)
            if (Math.random() < 0.2) {
                performRandomScroll();
            }

        } catch (error) {
            if (config.enableConsoleLogs) console.log("❌ Error in solver:", error);
            state.consecutiveFails++;
        }
    }

    // Stealth initialization
    function stealthInit() {
        // Hide script presence
        if (config.hideScriptPresence) {
            const originalQuery = Document.prototype.querySelector;
            Document.prototype.querySelector = function(...args) {
                const result = originalQuery.apply(this, args);
                // Prevent detection of script elements
                if (result && result.tagName === 'SCRIPT' && 
                    result.src.includes('tampermonkey')) {
                    return null;
                }
                return result;
            };
        }

        // Random user agent rotation (if enabled)
        if (config.randomUserAgent && Math.random() < 0.3) {
            const userAgents = [
                'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
                'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36'
            ];
            Object.defineProperty(navigator, 'userAgent', {
                get: () => userAgents[Math.floor(Math.random() * userAgents.length)]
            });
        }
    }

    // Advanced initialization
    function advancedInit() {
        stealthInit();
        
        if (config.enableConsoleLogs) {
            console.log("🎮 Advanced Auto-Solver Pro Initialized!");
            console.log("🔧 Features: PERFECT ACCURACY, Fuzzy matching, behavioral simulation");
            console.log("✅ Intentional misses: DISABLED");
            console.log("🎯 Accuracy mode: Always perfect");
        }

        // Session management
        setInterval(() => {
            state.clickCount = Math.max(0, state.clickCount - config.maxClicksPerMinute);
            
            // Rotate session if too long
            if (Date.now() - state.sessionStartTime > config.maxSessionLength && config.sessionRotation) {
                if (config.enableConsoleLogs) console.log("🔄 Session rotation");
                state.sessionStartTime = Date.now();
                state.clickCount = 0;
                startCooldown(30000);
            }
        }, 60000);

        // Start solver with progressive delays
        let currentDelay = getSmartDelay();
        const solverInterval = setInterval(() => {
            if (state.isRunning && !state.isInCooldown) {
                advancedSolveSymbolGame();
                currentDelay = getSmartDelay();
            }
        }, currentDelay);

        // Enhanced keyboard controls
        document.addEventListener('keydown', function(e) {
            // Ctrl+Shift+X - Toggle solver
            if (e.ctrlKey && e.shiftKey && e.key === 'X') {
                state.isRunning = !state.isRunning;
                if (config.enableConsoleLogs) {
                    console.log(state.isRunning ? "▶️ Solver Resumed" : "⏸️ Solver Paused");
                }
                e.preventDefault();
            }
            
            // Ctrl+Shift+C - Force cooldown
            if (e.ctrlKey && e.shiftKey && e.key === 'C') {
                startCooldown();
                e.preventDefault();
            }
            
            // Ctrl+Shift+R - Reset counters
            if (e.ctrlKey && e.shiftKey && e.key === 'R') {
                state.clickCount = 0;
                state.totalSolved = 0;
                state.consecutiveRounds = 0;
                state.consecutiveFails = 0;
                if (config.enableConsoleLogs) console.log("🔄 Counters reset");
                e.preventDefault();
            }
        });

        // Simulate tab activity
        if (config.tabActivity) {
            setInterval(() => {
                if (document.hidden && Math.random() < 0.3) {
                    document.dispatchEvent(new Event('visibilitychange'));
                }
            }, 60000);
        }

        // Page visibility handling
        document.addEventListener('visibilitychange', () => {
            if (document.hidden) {
                state.lastActionTime = Date.now();
            }
        });
    }

    // Start the advanced script
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', advancedInit);
    } else {
        advancedInit();
    }
})();