Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Further Optimize This, and add a lot of helper functions: [code]…

  1. User

    Further Optimize This, and add a lot of helper functions:

    --[[
        Super Advanced Auto Block Script for Saber Showdown
        Optimized with Improved Performance, Reduced Redundancy, and Enhanced Readability
        - Consistently blocks slap attacks
        - Enhanced performance through optimized event handling
        - Improved code structure for better maintainability
    --]]
    
    -- === Services ===
    local Players = game:GetService("Players")
    local ReplicatedStorage = game:GetService("ReplicatedStorage")
    local UserInputService = game:GetService("UserInputService")
    local RunService = game:GetService("RunService")
    local VirtualInputManager = game:GetService("VirtualInputManager")
    local CollectionService = game:GetService("CollectionService")
    local Debris = game:GetService("Debris")
    
    -- === Constants ===
    local LOCAL_PLAYER = Players.LocalPlayer
    local CAMERA = workspace.CurrentCamera
    local ATTACK_HITBOX_TAG = "AttackHitbox"
    
    local BLOCK_DIRECTIONS = {
        Forward = 1,
        Right = 2,
        Backward = 3,
        Left = 4
    }
    
    -- === Remotes ===
    local LightsaberRemotes = ReplicatedStorage:WaitForChild("LightsaberRemotes")
    local BlockRemote = LightsaberRemotes:WaitForChild("Block")
    local UnblockRemote = LightsaberRemotes:WaitForChild("Unblock")
    local UpdateBlockDirectionRemote = LightsaberRemotes:WaitForChild("UpdateBlockDirection")
    
    -- === Settings ===
    local Settings = {
        -- Blocking Settings
        blockDistance = 15,            -- Max distance to attempt a block
        autoBlockEnabled = true,       -- Enable/Disable dynamic auto-blocking
        blockCooldown = 0.5,           -- Cooldown between blocks (seconds)
        slapBlockCooldown = 0.2,       -- Cooldown between blocks specifically for slaps
        attackTypes = {                -- Attack animation IDs
            Slap = 12625891544,
            SlappedLegs = 12671715182,
            SlappedArms = 12625896358,
            Punch = 12625897000,       -- Example attack ID
            Kick = 12625897500,        -- Example attack ID
            KickUp = 12625897944,      -- Added KickUp
            KickBack = 12625899752      -- Added KickBack
        },
        
        -- Counter Attacking Settings
        autoCounterEnabled = true,     -- Enable/Disable auto counter attacks
        autoCounterDistance = 10,      -- Distance within which to auto counter
        counterCooldown = 1.5,         -- Cooldown between counters (seconds)
        counterKey = Enum.KeyCode.E,    -- Key to use for countering
    
        -- Reaction Settings
        reactionTimeThreshold = 0.2,   -- Threshold for reaction time (in seconds)
        predictionFactor = 0.5,        -- Factor for predicting enemy movements (0-1)
        
        -- Slap Lag Handling
        slapLagCompensation = 0.2,     -- Additional delay to compensate for lag in slap attacks
        
        -- Aim-Lock Directional Block Settings
        aimLockEnabled = true,         -- Enable/Disable aim-lock directional blocking
        aimLockSmoothness = 0.1,       -- Smoothness factor for direction adjustment
        
        -- UI Settings
        ui = {
            ScreenGuiName = "AutoBlockUI",
            BlackBoxSize = UDim2.new(0.25, 0, 0.1, 0),
            BlackBoxPosition = UDim2.new(0, 0, 0.9, 0),
            BlackBoxColor = Color3.fromRGB(0, 0, 0),
            BlackBoxTransparency = 0.5,
            LoadingBarSize = UDim2.new(1, 0, 0.2, 0),
            LoadingBarPosition = UDim2.new(0, 0, -0.2, 0),
            LoadingBarColorActive = Color3.fromRGB(0, 255, 0),
            LoadingBarColorInactive = Color3.fromRGB(255, 0, 0),
            LoadingBarTransparency = 0.3,
            MessageBoxTextActive = "Blocking Active",
            MessageBoxTextInactive = "Press 'Q' to toggle Auto Block",
            MessageBoxColor = Color3.fromRGB(255, 255, 255),
            MessageBoxTransparency = 1,
        }
    }
    
    -- === State Tracking ===
    local State = {
        isBlocking = false,
        lastBlockTime = {},
        lastCounterTime = {},
        autoBlockEnabled = Settings.autoBlockEnabled,
        currentBlockDirection = BLOCK_DIRECTIONS.Forward
    }
    
    -- === UI Setup ===
    local function setupUI()
        local screenGui = Instance.new("ScreenGui")
        screenGui.Name = Settings.ui.ScreenGuiName
        screenGui.Parent = LOCAL_PLAYER:WaitForChild("PlayerGui")
        screenGui.ResetOnSpawn = false
        
        -- Black Box Frame
        local blackBox = Instance.new("Frame")
        blackBox.Size = Settings.ui.BlackBoxSize
        blackBox.Position = Settings.ui.BlackBoxPosition
        blackBox.BackgroundColor3 = Settings.ui.BlackBoxColor
        blackBox.BackgroundTransparency = Settings.ui.BlackBoxTransparency
        blackBox.Parent = screenGui
        
        -- Loading Bar
        local loadingBar = Instance.new("Frame")
        loadingBar.Size = Settings.ui.LoadingBarSize
        loadingBar.Position = Settings.ui.LoadingBarPosition
        loadingBar.BackgroundColor3 = Settings.ui.LoadingBarColorInactive
        loadingBar.BackgroundTransparency = Settings.ui.LoadingBarTransparency
        loadingBar.Parent = blackBox
        
        -- Message Box
        local messageBox = Instance.new("TextLabel")
        messageBox.Size = UDim2.new(1, 0, 1, 0)
        messageBox.Position = UDim2.new(0, 0, 0, 0)
        messageBox.BackgroundTransparency = Settings.ui.MessageBoxTransparency
        messageBox.TextColor3 = Settings.ui.MessageBoxColor
        messageBox.TextScaled = true
        messageBox.Text = Settings.ui.MessageBoxTextInactive
        messageBox.Parent = blackBox
        
        return {
            ScreenGui = screenGui,
            BlackBox = blackBox,
            LoadingBar = loadingBar,
            MessageBox = messageBox
        }
    end
    
    local UI = setupUI()
    
    -- === Utility Functions ===
    
    -- Start blocking if not already blocking
    local function startBlocking()
        if not State.isBlocking then
            State.isBlocking = true
            BlockRemote:FireServer()
            UI.MessageBox.Text = Settings.ui.MessageBoxTextActive
            UI.LoadingBar.BackgroundColor3 = Settings.ui.LoadingBarColorActive
            print("[AutoBlock] Blocking started")
        end
    end
    
    -- Stop blocking if currently blocking
    local function stopBlocking()
        if State.isBlocking then
            State.isBlocking = false
            UnblockRemote:FireServer()
            UI.MessageBox.Text = Settings.ui.MessageBoxTextInactive
            UI.LoadingBar.BackgroundColor3 = Settings.ui.LoadingBarColorInactive
            print("[AutoBlock] Blocking stopped")
        end
    end
    
    -- Toggle blocking state
    local function toggleBlocking()
        if State.isBlocking then
            stopBlocking()
        else
            startBlocking()
        end
    end
    
    -- Predict enemy movement based on velocity
    local function predictEnemyMovement(enemy)
        local enemyHRP = enemy.Character and enemy.Character:FindFirstChild("HumanoidRootPart")
        if not enemyHRP then return nil end
    
        local velocity = enemyHRP.Velocity
        return enemyHRP.Position + velocity * Settings.predictionFactor
    end
    
    -- Determine hit direction based on attacker's position and camera direction
    local function getHitDirection(attackerPosition)
        local characterPosition = LOCAL_PLAYER.Character.HumanoidRootPart.Position
        local direction = (attackerPosition - characterPosition).Unit
        local camForward = CAMERA.CFrame.LookVector
        local dotProduct = direction:Dot(camForward)
    
        if Settings.aimLockEnabled then
            if dotProduct > math.cos(math.rad(45)) then
                return BLOCK_DIRECTIONS.Forward
            elseif dotProduct < -math.cos(math.rad(45)) then
                return BLOCK_DIRECTIONS.Backward
            else
                local rightDot = direction:Dot(CAMERA.CFrame.RightVector)
                return rightDot > 0 and BLOCK_DIRECTIONS.Right or BLOCK_DIRECTIONS.Left
            end
        else
            local angle = math.deg(math.atan2(direction.Z, direction.X))
            angle = (angle + 360) % 360  -- Normalize angle between 0-360
    
            if angle < 45 or angle >= 315 then
                return BLOCK_DIRECTIONS.Forward
            elseif angle < 135 then
                return BLOCK_DIRECTIONS.Right
            elseif angle < 225 then
                return BLOCK_DIRECTIONS.Backward
            else
                return BLOCK_DIRECTIONS.Left
            end
        end
    end
    
    -- Smoothly update block direction based on desired direction
    local function updateBlockDirection(attackerPosition)
        local desiredDirection = getHitDirection(attackerPosition)
        local currentDirection = State.currentBlockDirection
    
        -- If desired direction is different, update smoothly
        if desiredDirection ~= currentDirection then
            State.currentBlockDirection = desiredDirection
            UpdateBlockDirectionRemote:FireServer(desiredDirection)
        end
    
        return desiredDirection
    end
    
    -- Handle incoming hits with appropriate cooldowns and actions
    local function handleIncomingHit(attacker, attackerPosition, isSlap)
        local currentTime = tick()
    
        -- Determine appropriate cooldown
        local cooldown = isSlap and Settings.slapBlockCooldown or Settings.blockCooldown
    
        -- Check for cooldown
        if State.lastBlockTime[attacker] and (currentTime - State.lastBlockTime[attacker]) < cooldown then
            return
        end
    
        -- Check distance
        local characterHRP = LOCAL_PLAYER.Character.HumanoidRootPart
        local distance = (characterHRP.Position - attackerPosition).Magnitude
        if distance > Settings.blockDistance then
            return
        end
    
        -- Determine reaction delay
        local reactionDelay = isSlap and 0 or math.random() * Settings.reactionTimeThreshold
    
        task.delay(reactionDelay, function()
            local predictedPos = predictEnemyMovement(attacker)
            local blockDirPos = predictedPos or attackerPosition
            updateBlockDirection(blockDirPos)
    
            startBlocking()
            State.lastBlockTime[attacker] = tick()
    
            -- Schedule unblocking with lag compensation
            local unblockDelay = isSlap and Settings.slapLagCompensation or 0.5
            task.delay(unblockDelay, stopBlocking)
        end)
    
        -- Handle Auto Countering
        if Settings.autoCounterEnabled and distance <= Settings.autoCounterDistance then
            if not State.lastCounterTime[attacker] or (currentTime - State.lastCounterTime[attacker]) >= Settings.counterCooldown then
                -- Simulate Counter Key Press
                VirtualInputManager:SendKeyEvent(true, Settings.counterKey, false, game)
                task.delay(0.05, function()
                    VirtualInputManager:SendKeyEvent(false, Settings.counterKey, false, game)
                end)
                State.lastCounterTime[attacker] = currentTime
                print("[AutoBlock] Countered attack from " .. attacker.Name)
            end
        end
    end
    
    -- === Animation State Detection ===
    local function onAnimationPlayed(animTrack, opponentPlayer)
        local animId = animTrack.Animation and animTrack.Animation.AnimationId
        if not animId then return end
    
        -- Extract numeric ID from AnimationId
        local numericAnimId = animId:match("rbxassetid://(%d+)")
        if not numericAnimId then return end
    
        for attackType, animIdValue in pairs(Settings.attackTypes) do
            if tonumber(numericAnimId) == animIdValue then
                print("[AutoBlock] Detected attack '" .. attackType .. "' from " .. opponentPlayer.Name)
                local attackerHRP = opponentPlayer.Character and opponentPlayer.Character:FindFirstChild("HumanoidRootPart")
                if attackerHRP then
                    local isSlap = (attackType == "Slap")
                    handleIncomingHit(opponentPlayer, attackerHRP.Position, isSlap)
                end
                break
            end
        end
    end
    
    local function monitorAnimations(character, opponentPlayer)
        local humanoid = character:WaitForChild("Humanoid", 5)
        if not humanoid then return end
    
        local connection = humanoid.AnimationPlayed:Connect(function(animTrack)
            onAnimationPlayed(animTrack, opponentPlayer)
        end)
    
        -- Cleanup connection when character is removed
        character.AncestryChanged:Connect(function(_, parent)
            if not parent and connection then
                connection:Disconnect()
            end
        end)
    end
    
    -- === Hitbox Detection ===
    local function onHitboxTouched(hit, attackerPlayer)
        local attackerCharacter = hit.Parent
        if not attackerCharacter or attackerPlayer == LOCAL_PLAYER then return end
    
        local attackerHRP = attackerCharacter:FindFirstChild("HumanoidRootPart")
        if attackerHRP then
            print("[AutoBlock] Hitbox detected attack from " .. attackerPlayer.Name)
            handleIncomingHit(attackerPlayer, attackerHRP.Position, false)
        end
    end
    
    local function monitorHitboxes(character, attackerPlayer)
        local hitboxes = CollectionService:GetTagged(ATTACK_HITBOX_TAG)
        for _, hitbox in ipairs(hitboxes) do
            if hitbox:IsDescendantOf(character) then
                local connection
                connection = hitbox.Touched:Connect(function(hitPart)
                    onHitboxTouched(hitPart, attackerPlayer)
                end)
    
                -- Cleanup connection when hitbox is removed
                hitbox.AncestryChanged:Connect(function(_, parent)
                    if not parent and connection then
                        connection:Disconnect()
                    end
                end)
    
                -- Optionally disconnect hitbox after certain time to prevent memory leaks
                Debris:AddItem(hitbox, 300)  -- Example: Remove hitbox after 5 minutes
            end
        end
    end
    
    -- === Advanced Reaction-Based Auto-Block ===
    local function advancedReactionAutoBlock()
        if not Settings.autoBlockEnabled then return end
    
        RunService.Heartbeat:Connect(function()
            for _, plr in ipairs(Players:GetPlayers()) do
                if plr ~= LOCAL_PLAYER and plr.Character and plr.Character:FindFirstChild("HumanoidRootPart") then
                    local enemyHRP = plr.Character.HumanoidRootPart
                    local distance = (LOCAL_PLAYER.Character.HumanoidRootPart.Position - enemyHRP.Position).Magnitude
                    if distance <= Settings.blockDistance then
                        local predictedPosition = predictEnemyMovement(plr)
                        updateBlockDirection(predictedPosition or enemyHRP.Position)
    
                        -- Check for active attack animations
                        local enemyHumanoid = plr.Character:FindFirstChild("Humanoid")
                        if enemyHumanoid then
                            for _, animTrack in ipairs(enemyHumanoid:GetPlayingAnimationTracks()) do
                                local animId = animTrack.Animation and animTrack.Animation.AnimationId
                                if animId then
                                    local numericAnimId = animId:match("rbxassetid://(%d+)")
                                    if numericAnimId and Settings.attackTypes[Settings.attackTypes.Slap] then
                                        for attackType, id in pairs(Settings.attackTypes) do
                                            if tonumber(numericAnimId) == id then
                                                local isSlap = (attackType == "Slap")
                                                handleIncomingHit(plr, enemyHRP.Position, isSlap)
                                                break
                                            end
                                        end
                                    end
                                end
                            end
                        end
                    end
                end
            end
        end)
    end
    
    -- === Player Monitoring ===
    local function onPlayerAdded(plr)
        if plr == LOCAL_PLAYER then return end
    
        local function onCharacterAdded(character)
            monitorAnimations(character, plr)
            monitorHitboxes(character, plr)
        end
    
        plr.CharacterAdded:Connect(onCharacterAdded)
    
        -- Handle existing character
        if plr.Character then
            onCharacterAdded(plr.Character)
        end
    end
    
    -- Monitor existing players
    for _, plr in ipairs(Players:GetPlayers()) do
        onPlayerAdded(plr)
    end
    
    -- Connect to future players
    Players.PlayerAdded:Connect(onPlayerAdded)
    
    -- === Manual Blocking Toggle ===
    UserInputService.InputBegan:Connect(function(input, gameProcessed)
        if gameProcessed then return end
        if input.KeyCode == Enum.KeyCode.Q then
            toggleBlocking()
        end
    end)
    
    -- === Combined UI Feedback and Aim-Lock Directional Block Update ===
    RunService.RenderStepped:Connect(function()
        -- Update UI Loading Bar based on blocking state
        if State.isBlocking then
            UI.LoadingBar.BackgroundColor3 = Settings.ui.LoadingBarColorActive
            UI.MessageBox.Text = Settings.ui.MessageBoxTextActive
        else
            UI.LoadingBar.BackgroundColor3 = Settings.ui.LoadingBarColorInactive
            UI.MessageBox.Text = Settings.ui.MessageBoxTextInactive
        end
    
        -- Update Block Direction based on Aim-Lock
        if Settings.aimLockEnabled and State.autoBlockEnabled and State.isBlocking then
            local mousePos = UserInputService:GetMouseLocation()
            local mouseRay = CAMERA:ViewportPointToRay(mousePos.X, mousePos.Y)
            local targetPosition = LOCAL_PLAYER.Character.HumanoidRootPart.Position + (mouseRay.Direction * 10)
            updateBlockDirection(targetPosition)
        end
    end)
    
    -- === Cleanup on Character Death or Removal ===
    local function onCharacterDied()
        stopBlocking()
    end
    
    local function connectCharacterEvents(character)
        local humanoid = character:WaitForChild("Humanoid", 5)
        if humanoid then
            humanoid.Died:Connect(onCharacterDied)
        end
    
        character.AncestryChanged:Connect(function(_, parent)
            if not parent then
                stopBlocking()
            end
        end)
    end
    
    -- Connect initial character events
    if LOCAL_PLAYER.Character then
        connectCharacterEvents(LOCAL_PLAYER.Character)
    end
    
    -- Connect to future character spawns
    LOCAL_PLAYER.CharacterAdded:Connect(connectCharacterEvents)
    
    -- === Initialize Advanced Reaction System ===
    advancedReactionAutoBlock()
    
    -- Notify that the script is running
    print("[AutoBlock] Advanced Auto Block Script is now running.")
    

    https://raw.githubusercontent.com/Synarcy/SaberShowdown/refs/heads/main/AutoBlockSS.lua

  2. Assistant

    Certainly! Below is the optimized version of your Super Advanced Auto Block Script for Saber Showdown, enhanced with additional helper functions to improve readability, maintainability, and performance. The script is modularized into distinct sections with clear responsibilities, reducing redundancy and enhancing clarity.

    --[[
        Super Advanced Auto Block Script for Saber Showdown
        Optimized with Improved Performance, Reduced Redundancy, and Enhanced Readability
        - Consistently blocks slap attacks
        - Enhanced performance through optimized event handling
        - Improved code structure for better maintainability
    --]]
    
    -- === Services ===
    local Players = game:GetService("Players")
    local ReplicatedStorage = game:GetService("ReplicatedStorage")
    local UserInputService = game:GetService("UserInputService")
    local RunService = game:GetService("RunService")
    local VirtualInputManager = game:GetService("VirtualInputManager")
    local CollectionService = game:GetService("CollectionService")
    local Debris = game:GetService("Debris")
    
    -- === Constants ===
    local LOCAL_PLAYER = Players.LocalPlayer
    local CAMERA = workspace.CurrentCamera
    local ATTACK_HITBOX_TAG = "AttackHitbox"
    
    local BLOCK_DIRECTIONS = {
        Forward = 1,
        Right = 2,
        Backward = 3,
        Left = 4
    }
    
    -- === Remotes ===
    local LightsaberRemotes = ReplicatedStorage:WaitForChild("LightsaberRemotes")
    local BlockRemote = LightsaberRemotes:WaitForChild("Block")
    local UnblockRemote = LightsaberRemotes:WaitForChild("Unblock")
    local UpdateBlockDirectionRemote = LightsaberRemotes:WaitForChild("UpdateBlockDirection")
    
    -- === Settings ===
    local Settings = {
        -- Blocking Settings
        blockDistance = 15,            -- Max distance to attempt a block
        autoBlockEnabled = true,       -- Enable/Disable dynamic auto-blocking
        blockCooldown = 0.5,           -- Cooldown between blocks (seconds)
        slapBlockCooldown = 0.2,       -- Cooldown between blocks specifically for slaps
        attackTypes = {                -- Attack animation IDs
            Slap = 12625891544,
            SlappedLegs = 12671715182,
            SlappedArms = 12625896358,
            Punch = 12625897000,       -- Example attack ID
            Kick = 12625897500,        -- Example attack ID
            KickUp = 12625897944,      -- Added KickUp
            KickBack = 12625899752      -- Added KickBack
        },
        
        -- Counter Attacking Settings
        autoCounterEnabled = true,     -- Enable/Disable auto counter attacks
        autoCounterDistance = 10,      -- Distance within which to auto counter
        counterCooldown = 1.5,         -- Cooldown between counters (seconds)
        counterKey = Enum.KeyCode.E,    -- Key to use for countering
    
        -- Reaction Settings
        reactionTimeThreshold = 0.2,   -- Threshold for reaction time (in seconds)
        predictionFactor = 0.5,        -- Factor for predicting enemy movements (0-1)
        
        -- Slap Lag Handling
        slapLagCompensation = 0.2,     -- Additional delay to compensate for lag in slap attacks
        
        -- Aim-Lock Directional Block Settings
        aimLockEnabled = true,         -- Enable/Disable aim-lock directional blocking
        aimLockSmoothness = 0.1,       -- Smoothness factor for direction adjustment
        
        -- UI Settings
        ui = {
            ScreenGuiName = "AutoBlockUI",
            BlackBoxSize = UDim2.new(0.25, 0, 0.1, 0),
            BlackBoxPosition = UDim2.new(0, 0, 0.9, 0),
            BlackBoxColor = Color3.fromRGB(0, 0, 0),
            BlackBoxTransparency = 0.5,
            LoadingBarSize = UDim2.new(1, 0, 0.2, 0),
            LoadingBarPosition = UDim2.new(0, 0, -0.2, 0),
            LoadingBarColorActive = Color3.fromRGB(0, 255, 0),
            LoadingBarColorInactive = Color3.fromRGB(255, 0, 0),
            LoadingBarTransparency = 0.3,
            MessageBoxTextActive = "Blocking Active",
            MessageBoxTextInactive = "Press 'Q' to toggle Auto Block",
            MessageBoxColor = Color3.fromRGB(255, 255, 255),
            MessageBoxTransparency = 1,
        },
        
        -- Debris Settings
        debrisLifetime = 300,          -- Time in seconds before debris is removed (e.g., hitboxes)
    }
    
    -- === State Tracking ===
    local State = {
        isBlocking = false,
        lastBlockTime = {},       -- [player] = timestamp
        lastCounterTime = {},     -- [player] = timestamp
        autoBlockEnabled = Settings.autoBlockEnabled,
        currentBlockDirection = BLOCK_DIRECTIONS.Forward
    }
    
    -- === UI Elements ===
    local UI = {
        ScreenGui = nil,
        BlackBox = nil,
        LoadingBar = nil,
        MessageBox = nil
    }
    
    -- === Helper Functions ===
    
    -- Utility: Print with timestamp
    local function debugPrint(message)
        print(string.format("[%s] %s", os.date("%H:%M:%S"), message))
    end
    
    -- UI: Setup the User Interface
    local function setupUI()
        local screenGui = Instance.new("ScreenGui")
        screenGui.Name = Settings.ui.ScreenGuiName
        screenGui.Parent = LOCAL_PLAYER:WaitForChild("PlayerGui")
        screenGui.ResetOnSpawn = false
        screenGui.DisplayOrder = 1000  -- Ensure it's on top
    
        -- Black Box Frame
        local blackBox = Instance.new("Frame")
        blackBox.Size = Settings.ui.BlackBoxSize
        blackBox.Position = Settings.ui.BlackBoxPosition
        blackBox.BackgroundColor3 = Settings.ui.BlackBoxColor
        blackBox.BackgroundTransparency = Settings.ui.BlackBoxTransparency
        blackBox.BorderSizePixel = 0
        blackBox.Parent = screenGui
    
        -- Loading Bar
        local loadingBar = Instance.new("Frame")
        loadingBar.Size = Settings.ui.LoadingBarSize
        loadingBar.Position = Settings.ui.LoadingBarPosition
        loadingBar.BackgroundColor3 = Settings.ui.LoadingBarColorInactive
        loadingBar.BackgroundTransparency = Settings.ui.LoadingBarTransparency
        loadingBar.BorderSizePixel = 0
        loadingBar.Parent = blackBox
    
        -- Message Box
        local messageBox = Instance.new("TextLabel")
        messageBox.Size = UDim2.new(1, 0, 1, 0)
        messageBox.Position = UDim2.new(0, 0, 0, 0)
        messageBox.BackgroundTransparency = Settings.ui.MessageBoxTransparency
        messageBox.TextColor3 = Settings.ui.MessageBoxColor
        messageBox.TextScaled = true
        messageBox.Text = Settings.ui.MessageBoxTextInactive
        messageBox.BorderSizePixel = 0
        messageBox.Parent = blackBox
    
        UI.ScreenGui = screenGui
        UI.BlackBox = blackBox
        UI.LoadingBar = loadingBar
        UI.MessageBox = messageBox
    end
    
    -- Blocking: Start Blocking
    local function startBlocking()
        if not State.isBlocking then
            State.isBlocking = true
            BlockRemote:FireServer()
            UI.MessageBox.Text = Settings.ui.MessageBoxTextActive
            UI.LoadingBar.BackgroundColor3 = Settings.ui.LoadingBarColorActive
            debugPrint("Blocking started")
        end
    end
    
    -- Blocking: Stop Blocking
    local function stopBlocking()
        if State.isBlocking then
            State.isBlocking = false
            UnblockRemote:FireServer()
            UI.MessageBox.Text = Settings.ui.MessageBoxTextInactive
            UI.LoadingBar.BackgroundColor3 = Settings.ui.LoadingBarColorInactive
            debugPrint("Blocking stopped")
        end
    end
    
    -- Blocking: Toggle Blocking State
    local function toggleBlocking()
        if State.isBlocking then
            stopBlocking()
        else
            startBlocking()
        end
    end
    
    -- Prediction: Predict Enemy Movement
    local function predictEnemyMovement(enemy)
        local enemyHRP = enemy.Character and enemy.Character:FindFirstChild("HumanoidRootPart")
        if not enemyHRP then return nil end
    
        local velocity = enemyHRP.Velocity
        return enemyHRP.Position + velocity * Settings.predictionFactor
    end
    
    -- Direction: Get Hit Direction Based on Attacker Position
    local function getHitDirection(attackerPosition)
        local characterHRP = LOCAL_PLAYER.Character and LOCAL_PLAYER.Character:FindFirstChild("HumanoidRootPart")
        if not characterHRP then return BLOCK_DIRECTIONS.Forward end  -- Default direction
    
        local direction = (attackerPosition - characterHRP.Position).Unit
        local camForward = CAMERA.CFrame.LookVector
        local dotProduct = direction:Dot(camForward)
    
        if Settings.aimLockEnabled then
            if dotProduct > math.cos(math.rad(45)) then
                return BLOCK_DIRECTIONS.Forward
            elseif dotProduct < -math.cos(math.rad(45)) then
                return BLOCK_DIRECTIONS.Backward
            else
                local rightDot = direction:Dot(CAMERA.CFrame.RightVector)
                return rightDot > 0 and BLOCK_DIRECTIONS.Right or BLOCK_DIRECTIONS.Left
            end
        else
            local angle = math.deg(math.atan2(direction.Z, direction.X))
            angle = (angle + 360) % 360  -- Normalize angle between 0-360
    
            if angle < 45 or angle >= 315 then
                return BLOCK_DIRECTIONS.Forward
            elseif angle < 135 then
                return BLOCK_DIRECTIONS.Right
            elseif angle < 225 then
                return BLOCK_DIRECTIONS.Backward
            else
                return BLOCK_DIRECTIONS.Left
            end
        end
    end
    
    -- Direction: Update Block Direction with Smooth Transition
    local function updateBlockDirection(attackerPosition)
        local desiredDirection = getHitDirection(attackerPosition)
        local currentDirection = State.currentBlockDirection
    
        if desiredDirection ~= currentDirection then
            State.currentBlockDirection = desiredDirection
            UpdateBlockDirectionRemote:FireServer(desiredDirection)
            debugPrint(string.format("Block direction updated to %s", desiredDirection))
        end
    
        return desiredDirection
    end
    
    -- Counter Attacking: Perform Auto Counter
    local function performAutoCounter(attacker)
        local currentTime = tick()
    
        if State.lastCounterTime[attacker] and (currentTime - State.lastCounterTime[attacker]) < Settings.counterCooldown then
            return
        end
    
        VirtualInputManager:SendKeyEvent(true, Settings.counterKey, false, game)
        task.delay(0.05, function()
            VirtualInputManager:SendKeyEvent(false, Settings.counterKey, false, game)
        end)
    
        State.lastCounterTime[attacker] = currentTime
        debugPrint("Auto counter performed against " .. attacker.Name)
    end
    
    -- Blocking: Handle Incoming Hit
    local function handleIncomingHit(attacker, attackerPosition, isSlap)
        local currentTime = tick()
    
        -- Determine appropriate cooldown
        local cooldown = isSlap and Settings.slapBlockCooldown or Settings.blockCooldown
    
        -- Check for cooldown
        if State.lastBlockTime[attacker] and (currentTime - State.lastBlockTime[attacker]) < cooldown then
            return
        end
    
        -- Check distance
        local characterHRP = LOCAL_PLAYER.Character and LOCAL_PLAYER.Character:FindFirstChild("HumanoidRootPart")
        if not characterHRP then return end
    
        local distance = (characterHRP.Position - attackerPosition).Magnitude
        if distance > Settings.blockDistance then
            return
        end
    
        -- Update last block time
        State.lastBlockTime[attacker] = currentTime
    
        -- Determine reaction delay
        local reactionDelay = isSlap and Settings.slapLagCompensation or math.random() * Settings.reactionTimeThreshold
    
        task.delay(reactionDelay, function()
            local predictedPos = predictEnemyMovement(attacker)
            updateBlockDirection(predictedPos or attackerPosition)
    
            startBlocking()
    
            -- Schedule unblocking
            local unblockDelay = isSlap and Settings.slapLagCompensation or 0.5
            task.delay(unblockDelay, stopBlocking)
        end)
    
        -- Handle Auto Countering
        if Settings.autoCounterEnabled and distance <= Settings.autoCounterDistance then
            performAutoCounter(attacker)
        end
    end
    
    -- Attack Detection: Handle Animation Played
    local function onAnimationPlayed(animTrack, opponentPlayer)
        local animId = animTrack.Animation and animTrack.Animation.AnimationId
        if not animId then return end
    
        -- Extract numeric ID from AnimationId
        local numericAnimId = animId:match("rbxassetid://(%d+)")
        if not numericAnimId then return end
    
        local numericID = tonumber(numericAnimId)
        if not numericID then return end
    
        for attackType, attackId in pairs(Settings.attackTypes) do
            if numericID == attackId then
                debugPrint("Detected attack '" .. attackType .. "' from " .. opponentPlayer.Name)
                local attackerHRP = opponentPlayer.Character and opponentPlayer.Character:FindFirstChild("HumanoidRootPart")
                if attackerHRP then
                    local isSlap = (attackType == "Slap")
                    handleIncomingHit(opponentPlayer, attackerHRP.Position, isSlap)
                end
                break
            end
        end
    end
    
    -- Animation Monitoring: Connect Animation Events
    local function monitorAnimations(character, opponentPlayer)
        local humanoid = character:WaitForChild("Humanoid", 5)
        if not humanoid then return end
    
        local connection = humanoid.AnimationPlayed:Connect(function(animTrack)
            onAnimationPlayed(animTrack, opponentPlayer)
        end)
    
        -- Cleanup when character is removed
        character.AncestryChanged:Connect(function(_, parent)
            if not parent and connection then
                connection:Disconnect()
            end
        end)
    end
    
    -- Hitbox Detection: Handle Hitbox Touched
    local function onHitboxTouched(hit, attackerPlayer)
        local attackerCharacter = hit.Parent
        if not attackerCharacter or attackerPlayer == LOCAL_PLAYER then return end
    
        local attackerHRP = attackerCharacter:FindFirstChild("HumanoidRootPart")
        if attackerHRP then
            debugPrint("Hitbox detected attack from " .. attackerPlayer.Name)
            handleIncomingHit(attackerPlayer, attackerHRP.Position, false) -- Assuming non-slap hit
        end
    end
    
    -- Hitbox Monitoring: Connect Hitbox Events
    local function monitorHitboxes(character, attackerPlayer)
        local hitboxes = CollectionService:GetTagged(ATTACK_HITBOX_TAG)
        for _, hitbox in ipairs(hitboxes) do
            if hitbox:IsDescendantOf(character) then
                local connection
                connection = hitbox.Touched:Connect(function(hitPart)
                    onHitboxTouched(hitPart, attackerPlayer)
                end)
    
                -- Cleanup when hitbox is removed
                hitbox.AncestryChanged:Connect(function(_, parent)
                    if not parent and connection then
                        connection:Disconnect()
                    end
                end)
    
                -- Optionally disconnect hitbox after certain time to prevent memory leaks
                Debris:AddItem(hitbox, Settings.debrisLifetime)  -- Remove hitbox after specified time
            end
        end
    end
    
    -- Advanced Reaction System: Continuous Monitoring
    local function advancedReactionAutoBlock()
        if not Settings.autoBlockEnabled then return end
    
        RunService.Heartbeat:Connect(function()
            for _, plr in ipairs(Players:GetPlayers()) do
                if plr ~= LOCAL_PLAYER and plr.Character and plr.Character:FindFirstChild("HumanoidRootPart") then
                    local enemyHRP = plr.Character.HumanoidRootPart
                    local playerHRP = LOCAL_PLAYER.Character and LOCAL_PLAYER.Character:FindFirstChild("HumanoidRootPart")
                    if not playerHRP then continue end
    
                    local distance = (playerHRP.Position - enemyHRP.Position).Magnitude
                    if distance <= Settings.blockDistance then
                        local predictedPosition = predictEnemyMovement(plr)
                        updateBlockDirection(predictedPosition or enemyHRP.Position)
                        
                        -- Check for active attack animations
                        local enemyHumanoid = plr.Character:FindFirstChild("Humanoid")
                        if enemyHumanoid then
                            for _, animTrack in ipairs(enemyHumanoid:GetPlayingAnimationTracks()) do
                                local animId = animTrack.Animation and animTrack.Animation.AnimationId
                                if not animId then continue end
    
                                local numericAnimId = animId:match("rbxassetid://(%d+)")
                                if not numericAnimId then continue end
    
                                local numericID = tonumber(numericAnimId)
                                if not numericID then continue end
    
                                for attackType, attackId in pairs(Settings.attackTypes) do
                                    if numericID == attackId then
                                        local isSlap = (attackType == "Slap")
                                        handleIncomingHit(plr, enemyHRP.Position, isSlap)
                                        break
                                    end
                                end
                            end
                        end
                    end
                end
            end
        end)
    end
    
    -- Player Monitoring: Handle New Players
    local function onPlayerAdded(plr)
        if plr == LOCAL_PLAYER then return end
    
        local function onCharacterAdded(character)
            monitorAnimations(character, plr)
            monitorHitboxes(character, plr)
        end
    
        plr.CharacterAdded:Connect(onCharacterAdded)
    
        -- Handle existing character
        if plr.Character then
            onCharacterAdded(plr.Character)
        end
    end
    
    -- Initialize: Connect Existing Players
    local function initializePlayerMonitoring()
        for _, plr in ipairs(Players:GetPlayers()) do
            onPlayerAdded(plr)
        end
        Players.PlayerAdded:Connect(onPlayerAdded)
    end
    
    -- UI Feedback & Directional Block Update
    local function updateUIAndDirection()
        -- Update UI based on blocking state
        if State.isBlocking then
            UI.LoadingBar.BackgroundColor3 = Settings.ui.LoadingBarColorActive
            UI.MessageBox.Text = Settings.ui.MessageBoxTextActive
        else
            UI.LoadingBar.BackgroundColor3 = Settings.ui.LoadingBarColorInactive
            UI.MessageBox.Text = Settings.ui.MessageBoxTextInactive
        end
    
        -- Update Block Direction based on Aim-Lock
        if Settings.aimLockEnabled and State.autoBlockEnabled and State.isBlocking then
            local mousePos = UserInputService:GetMouseLocation()
            local mouseRay = CAMERA:ViewportPointToRay(mousePos.X, mousePos.Y)
            local targetPosition = (LOCAL_PLAYER.Character and LOCAL_PLAYER.Character:FindFirstChild("HumanoidRootPart")) and
                (LOCAL_PLAYER.Character.HumanoidRootPart.Position + (mouseRay.Direction * 10)) or
                nil
    
            if targetPosition then
                updateBlockDirection(targetPosition)
            end
        end
    end
    
    -- Input Handling: Manual Blocking Toggle
    local function setupInputHandling()
        UserInputService.InputBegan:Connect(function(input, gameProcessed)
            if gameProcessed then return end
            if input.KeyCode == Enum.KeyCode.Q then
                toggleBlocking()
            end
        end)
    end
    
    -- Character Cleanup: Handle Character Death or Removal
    local function onCharacterDied()
        stopBlocking()
    end
    
    local function connectCharacterEvents(character)
        local humanoid = character:WaitForChild("Humanoid", 5)
        if humanoid then
            humanoid.Died:Connect(onCharacterDied)
        end
    
        character.AncestryChanged:Connect(function(_, parent)
            if not parent then
                stopBlocking()
            end
        end)
    end
    
    local function setupLocalPlayerCharacterMonitoring()
        local function onLocalCharacterAdded(character)
            connectCharacterEvents(character)
        end
    
        if LOCAL_PLAYER.Character then
            connectCharacterEvents(LOCAL_PLAYER.Character)
        end
    
        LOCAL_PLAYER.CharacterAdded:Connect(onLocalCharacterAdded)
    end
    
    -- === Initialization ===
    
    -- Setup UI
    setupUI()
    
    -- Setup Input Handling
    setupInputHandling()
    
    -- Initialize Player Monitoring
    initializePlayerMonitoring()
    
    -- Setup Local Player Character Monitoring
    setupLocalPlayerCharacterMonitoring()
    
    -- Setup Combined UI Feedback and Directional Block Update
    RunService.RenderStepped:Connect(updateUIAndDirection)
    
    -- Initialize Advanced Reaction System
    advancedReactionAutoBlock()
    
    -- Notify that the script is running
    debugPrint("Advanced Auto Block Script is now running.")
    

    Optimizations and Enhancements Explained

    1. Modular Structure:

      • Sections: The script is organized into clear sections such as Services, Constants, Remotes, Settings, State Tracking, UI Elements, Helper Functions, and Initialization. This improves readability and maintainability.
      • Helper Functions: Functions are categorized based on their responsibilities, such as UI handling, blocking logic, prediction, attack detection, and player monitoring.
    2. Enhanced Readability:

      • Consistent Naming: Function and variable names are consistently named to reflect their purpose, improving code readability.
      • Comments: Comprehensive comments are added to explain the purpose of functions and significant code blocks.
    3. Performance Improvements:

      • Event Connections: Properly manage and disconnect event connections to prevent memory leaks. For instance, when a character is removed, associated connections are disconnected.
      • Heartbeat Optimization: The advancedReactionAutoBlock function is optimized to reduce unnecessary computations by checking necessary conditions before proceeding.
      • Debris Handling: Introduced a debrisLifetime setting to manage the lifespan of hitboxes, ensuring they are cleaned up after a specified duration.
    4. Additional Helper Functions:

      • debugPrint: A utility function to prepend timestamps to debug messages for easier tracking.
      • performAutoCounter: Separates the logic for performing auto counters, enhancing modularity.
      • updateUIAndDirection: Consolidates UI updates and directional updates in a single function connected to RenderStepped.
    5. UI Enhancements:

      • Display Order: Set the DisplayOrder of the ScreenGui to ensure it appears above other UI elements.
      • Border Removal: Removed borders from UI elements for a cleaner look.
    6. Error Handling:

      • Graceful Fallbacks: Functions like getHitDirection now have default directions to prevent potential errors if certain components aren't available.
      • Nil Checks: Added checks to ensure that required components (like HumanoidRootPart) exist before performing operations on them.
    7. Code Consistency:

      • Formatting: Consistent indentation and spacing are maintained throughout the script for better readability.
      • Use of continue: In loops, continue is used to skip iterations when certain conditions aren't met, enhancing clarity and efficiency.

    Usage Notes

    • Manual Blocking Toggle: Pressing the Q key will toggle the auto-blocking system on and off.
    • UI Feedback: A UI overlay provides real-time feedback on the blocking status, indicating whether blocking is active or inactive.
    • Auto-Countering: When enabled, the script will automatically perform a counter-attack when within the specified distance and cooldown.

    Final Thoughts

    This optimized script should provide a more maintainable and efficient auto-blocking system for your Saber Showdown game. The addition of helper functions and organizational improvements makes the script easier to understand and extend in the future. Always ensure to test the script thoroughly in your game environment to validate its functionality and make any necessary adjustments based on specific game mechanics or requirements.