Dark Spawner Script
HomeGamesTrendingExecutors
Dark Spawner Script

The best community driven platform for finding the latest Roblox scripts. Create, share, and discover amazing scripts.

Scripts
715+
Games
452+
Votes cast
8,357+

Quick Links

  • How to Use
  • Games
  • Trending Scripts
  • Executors
  • FAQs

Community

Links coming soon.

Contact

  • [email protected]
  • Report a script

© 2026 Dark Spawner Script. All rights reserved.

About UsPrivacy PolicyDisclaimer
Home›Games›CRAZY 8 Ball

CRAZY 8 Ball Script 8 Ball Hub: Aimbot, Impossible Shots

CRAZY 8 Ball•5 hours ago
0 views
CRAZY 8 Ball Script 8 Ball Hub: Aimbot, Impossible Shots
No Key
  • Working
  • updated 5 hours ago
  • No key
  • tested on Delta, Xeno
T

Team Darkspawner

Hub: 8 Ball Hub

Play Game Game Link

Description

Use this 8 Ball Hub for CRAZY 8 Ball Roblox!! Now you can get features like Impossible Shots, Aimbot, Multi Ball Pots, Self Learning AI and Shot Guide Lines, and More!! The Aimbot tab holds the main controls, including Place cue ball automatically, Call the 8 ball pocket, Position play and Move the cue with the mouse. The Break power slider sits at 1, its maximum, and a Replan now (R) button works out the shot again. The menu notes that Enable aimbot starts disabled with RightShift as its hotkey, while the other tabs cover Impossible shots, Evolutionary AI, Multi ball, Precision and Lines. No key on this one, so paste the loadstring and go!!

Features

  • +Aimbot
  • +Shot Guide Lines
  • +Impossible Shots
  • +Bank Shots
  • +Double Bank Shots
  • +Kick Shots
  • +Combo Shots
  • +Multi Ball Pots
  • +Auto Perfect Shot
  • +Auto Place Cue Ball
  • +Auto Call 8 Ball Pocket
  • +Position Play
  • +Spin Control
  • +Self Learning AI
  • +Humanize Mode
CRAZY 8 Ball

CRAZY 8 Ball

Explore more scripts for this game (1)

Script

Raw Download
local Players = game:GetService("Players")
local RS = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local UIS = game:GetService("UserInputService")

local lp = Players.LocalPlayer
local Shared = RS:WaitForChild("Shared")
local Net = RS:WaitForChild("Net")
local Config = require(Shared:WaitForChild("Config"))
local Placement = require(Shared:WaitForChild("Placement"))
local Physics = Shared:WaitForChild("Physics")
local TablePhys = require(Physics:WaitForChild("Table"))
local Ball = require(Physics:WaitForChild("Ball"))
local Simulation = require(Physics:WaitForChild("Simulation"))
local Aim = require(Physics:WaitForChild("Aim"))
local CueMod = require(Physics:WaitForChild("Cue"))
local ShotFinder = require(Shared:WaitForChild("Bots"):WaitForChild("ShotFinder"))
local ShotJudge = require(Shared:WaitForChild("Rules"):WaitForChild("ShotJudge"))
local CuePlacement = require(Shared:WaitForChild("Rules"):WaitForChild("CuePlacement"))
local cv = workspace:WaitForChild("ClientVisuals")

local G = getgenv()
for _, k in ipairs({ "BOLA8HUB", "BOLA8", "BOLA8_LINEAS" }) do
    local old = G[k]
    if old then
        pcall(old.destroy or old.stop or function() end)
        G[k] = nil
    end
end

local S = {
    enabled = false,
    action = "Auto",
    strategy = "Normal",

    autoPlace = true,
    autoPocket = true,
    usePosition = true,
    positionWeight = 1.0,
    mouseAim = true,
    breakPower = 1.0,

    allowBank = true,
    allowDouble = true,
    allowKick = true,
    allowCombo = true,
    brute = true,
    bruteStep = 0.5,
    budget = 4.0,
    maxCut = 80,
    maxPower = 1.0,

    robustChecks = 2,
    robustEps = 0.10,
    strict = false,
    powerVariants = 5,
    useSpin = false,
    spinAmount = 0.5,

    multiStep = 2.0,
    multiMin = 2,
    multiSpin = true,

    aiMult = 2,
    aiSpin = true,
    aiGoal = "Balanced",
    learn = true,

    humanize = false,
    delayMin = 0.6,
    delayMax = 1.6,
    angleNoise = 0.0,
    powerNoise = 0.0,
    missChance = 0.0,

    showPlan = true,
    showAim = false,
    thickness = Config.Guideline.LineWidthStuds or 0.08,
    planColor = Color3.fromRGB(80, 255, 120),
    aimColor = Color3.fromRGB(255, 255, 255),
    notify = true,
}

local KEYS = { toggle = "RightShift", replan = "R", lines = "T" }
local function keyName(v) return (tostring(v):match("([%w_]+)$")) or tostring(v) end

local H = { S = S, running = true, busy = false, plans = {}, done = {}, retries = {}, conns = {}, stats = { shots = 0 } }
G.BOLA8HUB = H

local Finder = Config.Bots.Finder
local finderOrig = {}
for _, k in ipairs({ "MaxCutDegrees", "MaxPower", "CandidatesTried" }) do finderOrig[k] = Finder[k] end
local function applyFinder()
    pcall(function()
        Finder.MaxCutDegrees = S.maxCut
        Finder.MaxPower = S.maxPower
        Finder.CandidatesTried = (S.strategy == "Impossible" or S.strategy == "Multi-ball" or S.strategy == "Evolutionary AI") and 24 or 12
    end)
end
applyFinder()

local radius = Config.Balls.RadiusInches
local diameter = 2 * radius
local fixedStep = Config.Physics.FixedStep
local MP = Config.Multiplayer
local GEO = TablePhys.build({ pocketsOpen = true })
local halfL, halfW = GEO.halfLength, GEO.halfWidth
local ELEV = Config.Cue.CueElevationDegrees
local WebUI

local function log(msg) print("[8Ball Hub] " .. tostring(msg)) end
local function note(title, text)
    if not S.notify or not WebUI then return end
    pcall(function() WebUI:Notify({ Title = title, Content = text, Duration = 3 }) end)
end

local function wrap(a)
    while a > math.pi do a -= 2 * math.pi end
    while a < -math.pi do a += 2 * math.pi end
    return a
end
local function dist(ax, ay, bx, by)
    local dx, dy = bx - ax, by - ay
    return math.sqrt(dx * dx + dy * dy)
end
local function unit(ax, ay, bx, by)
    local dx, dy = bx - ax, by - ay
    local m = math.sqrt(dx * dx + dy * dy)
    if m < 1e-9 then return 0, 0 end
    return dx / m, dy / m
end
local function gauss()
    return math.sqrt(-2 * math.log(math.max(1e-9, math.random()))) * math.cos(2 * math.pi * math.random())
end

local function unpackBalls(s)
    local t = {}
    if type(s.balls[1]) == "table" then return s.balls end
    for i = 1, #s.balls, 4 do
        table.insert(t, {
            id = (i - 1) / 4, x = s.balls[i], y = s.balls[i + 1],
            z = s.balls[i + 2] or 0, pocketed = s.balls[i + 3] == 1,
        })
    end
    return t
end
local function findBall(balls, id)
    for _, b in ipairs(balls) do if b.id == id then return b end end
    return nil
end
local function groupOf(id)
    local ok, g = pcall(ShotJudge.group, id)
    return ok and g or nil
end

local HttpService = game:GetService("HttpService")
local MEM_FILE = "ball8_memory.json"
local Mem = { version = 1, breaks = {}, kinds = {}, shots = 0 }
local memDirty, memLastSave = false, 0

local function memLoad()
    local ok, data = pcall(function() return HttpService:JSONDecode(readfile(MEM_FILE)) end)
    if ok and type(data) == "table" then
        Mem.breaks = type(data.breaks) == "table" and data.breaks or {}
        Mem.kinds = type(data.kinds) == "table" and data.kinds or {}
        Mem.shots = tonumber(data.shots) or 0
        return true
    end
    return false
end
local function memSave(force)
    if not memDirty then return end
    if not force and os.clock() - memLastSave < 5 then return end
    local ok = pcall(function() writefile(MEM_FILE, HttpService:JSONEncode(Mem)) end)
    if ok then memDirty, memLastSave = false, os.clock() end
end
local function memClear()
    Mem.breaks, Mem.kinds, Mem.shots = {}, {}, 0
    memDirty = true
    memSave(true)
end
memLoad()

local function kindBonus(kind)
    if not S.learn then return 0 end
    local k = Mem.kinds[kind]
    if not k or k.n < 3 then return 0 end
    local r = (k.ok + 2) / (k.n + 3)
    return (r - 0.67) * 600
end

local function recordBreak(y, off, pow, spin, score, real)
    local list = Mem.breaks
    for _, e in ipairs(list) do
        if math.abs(e.y - y) < 0.6 and math.abs(e.off - off) < 0.006 and math.abs(e.pow - pow) < 0.03 then
            e.trials += 1
            e.pots += real
            e.score = math.max(e.score or 0, score or 0)
            return
        end
    end
    table.insert(list, {
        y = y, off = off, pow = pow, sx = spin and spin.x or 0, sy = spin and spin.y or 0,
        score = score or 0, trials = 1, pots = real,
    })
    table.sort(list, function(a, b)
        local ra, rb = a.pots / a.trials, b.pots / b.trials
        if ra ~= rb then return ra > rb end
        return (a.score or 0) > (b.score or 0)
    end)
    while #list > 40 do table.remove(list) end
end

local function memBreakSeeds(y)
    local out = {}
    for _, e in ipairs(Mem.breaks) do
        if math.abs(e.y - y) < 1.5 then table.insert(out, e) end
        if #out >= 6 then break end
    end
    return out
end
local function memBestBreakY()
    local e = Mem.breaks[1]
    return e and e.y or nil
end

local snaps = {}
local checkOutcome
H.conns[#H.conns + 1] = Net.TableState.OnClientEvent:Connect(function(s)
    if type(s) == "table" and s.id then
        snaps[s.id] = s
        if H.pending then pcall(checkOutcome, s) end
    end
end)

local function mySeat()
    for _, s in pairs(snaps) do
        if s.seats then
            for _, seat in ipairs(s.seats) do
                if seat.userId == lp.UserId then return s, seat.team end
            end
        end
    end
    return nil, nil
end

checkOutcome = function(s)
    local p = H.pending
    if not p then return end
    if os.clock() - p.t > 60 then H.pending = nil return end
    if s.id ~= p.tableId or not s.shot then return end
    local sh = s.shot
    if sh.shooter ~= lp.UserId or sh.turnId ~= p.turnId then return end
    H.pending = nil
    if not S.learn then return end

    local startB = sh.start and unpackBalls({ balls = sh.start }) or {}
    local finB = sh.final and unpackBalls({ balls = sh.final }) or {}
    local was = {}
    for _, b in ipairs(startB) do if b.pocketed then was[b.id] = true end end
    local actualSet, realPots = {}, 0
    for _, b in ipairs(finB) do
        if b.pocketed and not was[b.id] then
            actualSet[b.id] = true
            if b.id ~= 0 then realPots += 1 end
        end
    end
    local success = not actualSet[0]
    for _, id in ipairs(p.pred or {}) do
        if not actualSet[id] then success = false end
    end

    local k = Mem.kinds[p.kind] or { n = 0, ok = 0 }
    k.n += 1
    if success then k.ok += 1 end
    Mem.kinds[p.kind] = k
    Mem.shots += 1
    if p.isBreak and p.y then
        recordBreak(p.y, p.off or 0, p.power, p.spin, p.score, realPots)
    end
    memDirty = true
    memSave()
    note("Learning", string.format("%s: %s (potted %d). Reliability %s: %d/%d",
        p.kind, success and "matched the prediction" or "did NOT match the prediction", realPots, p.kind, k.ok, k.n))
end

local function currentAim(tableId)
    local guide = cv:FindFirstChild("Guideline")
    if not guide then return nil end
    local pl = Placement.forTable(tableId)
    if not pl then return nil end
    for _, name in ipairs({ "Path", "LeftEdge", "RightEdge" }) do
        local strip = guide:FindFirstChild(name)
        if strip and strip.Transparency < 1 then
            local lv = strip.CFrame.LookVector
            if math.abs(lv.X) > 1e-4 or math.abs(lv.Z) > 1e-4 then
                return (Placement.aimAngle(pl, lv.X, lv.Z) + math.pi) % (2 * math.pi)
            end
        end
    end
    return nil
end

local degPerPixel = math.rad(Config.Input.AimDegreesPerPixel or 0.18)
local function rotateTo(tableId, target)
    local cur = currentAim(tableId)
    if not cur then return false end
    local sign = 1
    for _ = 1, 3 do
        local err = wrap(target - cur)
        if math.abs(err) < 0.003 then return true end
        local m = lp:GetMouse()
        local vp = workspace.CurrentCamera.ViewportSize
        pcall(mousemoverel, vp.X / 2 - m.X, vp.Y / 2 - m.Y)
        task.wait(0.04)
        pcall(mouse1press)
        task.wait(0.03)
        pcall(mousemoverel, -sign * err / degPerPixel, 0)
        task.wait(0.10)
        pcall(mouse1release)
        task.wait(0.10)
        local after = currentAim(tableId)
        if not after then return false end
        local observed = wrap(after - cur)
        if observed * err < 0 and math.abs(observed) > 0.01 then sign = -sign end
        cur = after
    end
    return math.abs(wrap(target - cur)) < 0.02
end

local function clampSpinVec(sx, sy)
    local ok, a, b = pcall(CueMod.clampSpin, sx, sy)
    if ok and a then return { x = a, y = b } end
    return { x = sx, y = sy }
end

local function nearestPocketDist(x, y)
    local best = 1e9
    for _, p in ipairs(GEO.pockets) do
        local d = dist(x, y, p.x, p.y)
        if d < best then best = d end
    end
    return best
end

local function simulateFull(st, cand, spin, opts)
    local mult = (opts and opts.mult) or 1
    local track = opts and opts.track
    local dt = fixedStep * mult
    local simBalls, cueObj = {}, nil
    for _, b in ipairs(st.balls) do
        if b.id == 0 or not b.pocketed then
            local nb = Ball.new(b.id, b.x, b.y)
            table.insert(simBalls, nb)
            if b.id == 0 then cueObj = nb end
        end
    end
    if not cueObj then return nil end
    local ok, simState = pcall(Simulation.newState, st.geometry, simBalls)
    if not ok or not simState then return nil end
    local ok2 = pcall(Simulation.strike, simState, {
        angle = cand.angle, power = cand.power,
        spin = spin or { x = 0, y = 0 }, elevation = ELEV,
    })
    if not ok2 then return nil end

    local events, firstHit = {}, nil
    local minDist, hitSet, nHit = {}, {}, 0
    for stepIdx = 1, math.floor(8 / dt) do
        pcall(Simulation.step, simState, dt, events)
        for _, e in ipairs(events) do
            if e.type == "ballHit" then
                if not firstHit and (e.ball == 0 or e.other == 0) then
                    firstHit = (e.ball == 0) and e.other or e.ball
                end
                if track and not hitSet[e.ball .. ":" .. e.other] then
                    hitSet[e.ball .. ":" .. e.other] = true
                    nHit += 1
                end
            end
        end
        if track and stepIdx % 4 == 0 then
            for _, b in ipairs(simBalls) do
                if b.id ~= 0 and not b.pocketed then
                    local d = nearestPocketDist(b.x, b.y)
                    if d < (minDist[b.id] or 1e9) then minDist[b.id] = d end
                end
            end
        end
        local moving = false
        for _, b in ipairs(simBalls) do
            if Ball.isMoving(b) then moving = true break end
        end
        if not moving then break end
        table.clear(events)
    end

    local res = {
        scratch = cueObj.pocketed == true, cueX = cueObj.x, cueY = cueObj.y,
        firstHit = firstHit, pocketedIds = {}, pocketOf = {}, balls = {},
        minDist = minDist, nHit = nHit,
    }
    for _, b in ipairs(simBalls) do
        table.insert(res.balls, { id = b.id, x = b.x, y = b.y, z = 0, pocketed = b.pocketed == true })
        if b.pocketed and b.id ~= 0 then
            table.insert(res.pocketedIds, b.id)
            local pk = b.pocket
            res.pocketOf[b.id] = (type(pk) == "table") and pk.id or pk
        end
    end
    return res
end

local function openingNear(x, y, margin)
    for _, p in ipairs(GEO.pockets) do
        if dist(x, y, p.x, p.y) < p.radius + margin then return true end
    end
    return false
end

local function nextShotValue(st, res, team)
    local nst = { geometry = GEO, balls = res.balls, groups = st.groups, team = team, phase = {} }
    local ok, cands = pcall(ShotFinder.candidates, nst, res.cueX, res.cueY)
    if not ok or not cands then return 0, 0 end
    return math.min(#cands, 4), (cands[1] and cands[1].score or 0)
end

local function evaluateShot(st, cand, res)
    if not res or res.scratch or res.firstHit == nil then return nil end
    local group = st.groups and st.groups[st.team]
    local okL, legal = pcall(ShotJudge.legalTarget, st.balls, group, res.firstHit)
    if okL and legal == false then return nil end

    local okS, _, elig = pcall(ShotFinder.status, st)
    local eightLegal = okS and elig == true
    local good, bad, win = 0, 0, false
    for _, id in ipairs(res.pocketedIds) do
        if id == 8 then
            if not eightLegal then return nil end
            local pk = res.pocketOf[8]
            if st.called and pk and pk ~= st.called then return nil end
            win = true
        else
            local g = groupOf(id)
            if group == nil or g == group then good += 1 else bad += 1 end
        end
    end
    if not cand.safe and good == 0 and not win then return nil end

    local extra = st.extra or (st.multi and 450 or 25)
    local score = 1000 + (win and 2000 or 0) + extra * math.max(0, good - 1) - 120 * bad
    if cand.ball and not win then
        for _, id in ipairs(res.pocketedIds) do
            if id == cand.ball then score += 40 break end
        end
    end

    if S.usePosition and not win then
        local n, best = nextShotValue(st, res, st.team)
        local pw = S.positionWeight * (st.posMul or 1)
        score += pw * (n * 45 + math.min(best * 8000, 120))
        local edge = math.min(halfL - math.abs(res.cueX), halfW - math.abs(res.cueY))
        if edge < 3 then score -= 40 * pw end
        if openingNear(res.cueX, res.cueY, 5) then score -= 60 * pw end
        for _, b in ipairs(res.balls) do
            if b.id ~= 0 and not b.pocketed and dist(b.x, b.y, res.cueX, res.cueY) < diameter * 1.15 then
                score -= 50 * pw
                break
            end
        end
    end
    return score, { good = good, bad = bad, win = win }
end

local function pathClear(st, ax, ay, bx, by, i1, i2)
    for _, o in ipairs(st.balls) do
        if not o.pocketed and o.id ~= 0 and o.id ~= i1 and o.id ~= i2 then
            if ShotFinder.segmentDistance(o.x, o.y, ax, ay, bx, by) < diameter - 1e-6 then return false end
        end
    end
    return true
end

local function inside(x, y)
    return math.abs(x) < halfL - radius and math.abs(y) < halfW - radius
end

local RAILS = {
    { axis = "y", c = halfW - radius }, { axis = "y", c = -(halfW - radius) },
    { axis = "x", c = halfL - radius }, { axis = "x", c = -(halfL - radius) },
}
local function reflect(px, py, r)
    if r.axis == "y" then return px, 2 * r.c - py end
    return 2 * r.c - px, py
end
local function railHit(ax, ay, ux, uy, r)
    local t
    if r.axis == "y" then
        if math.abs(uy) < 1e-9 then return nil end
        t = (r.c - ay) / uy
    else
        if math.abs(ux) < 1e-9 then return nil end
        t = (r.c - ax) / ux
    end
    if t <= 0 then return nil end
    return ax + ux * t, ay + uy * t, t
end

local function cutBetween(cx, cy, gx, gy, ux, uy)
    local dx, dy = unit(cx, cy, gx, gy)
    return math.acos(math.clamp(dx * ux + dy * uy, -1, 1))
end

local function genBanks(st, cue, ids, depth)
    local out = {}
    local seqs = {}
    for _, r in ipairs(RAILS) do table.insert(seqs, { r }) end
    if depth >= 2 then
        for _, r1 in ipairs(RAILS) do
            for _, r2 in ipairs(RAILS) do
                if r1 ~= r2 and not (r1.axis == r2.axis and r1.c == -r2.c and false) then
                    table.insert(seqs, { r1, r2 })
                end
            end
        end
    end
    for _, id in ipairs(ids) do
        local b = findBall(st.balls, id)
        if b and not b.pocketed then
            for _, p in ipairs(GEO.pockets) do
                for _, seq in ipairs(seqs) do
                    if #seq == depth then
                        local px, py = p.x, p.y
                        for i = #seq, 1, -1 do px, py = reflect(px, py, seq[i]) end
                        local ux, uy = unit(b.x, b.y, px, py)
                        local gx, gy = b.x - ux * diameter, b.y - uy * diameter
                        if inside(gx, gy) then
                            local hx, hy = railHit(b.x, b.y, ux, uy, seq[1])
                            local legOk = hx ~= nil and math.abs(hx) <= halfL and math.abs(hy) <= halfW
                            if legOk and pathClear(st, b.x, b.y, hx, hy, id) and pathClear(st, cue.x, cue.y, gx, gy, id) then
                                local cut = cutBetween(cue.x, cue.y, gx, gy, ux, uy)
                                if cut <= math.rad(85) then
                                    local total = dist(b.x, b.y, px, py) + dist(cue.x, cue.y, gx, gy)
                                    table.insert(out, {
                                        angle = math.atan2(gy - cue.y, gx - cue.x), ball = id, pocket = p.id,
                                        kind = (#seq == 1) and "BANK" or "2 BANKS",
                                        prio = math.cos(cut) / (1 + total / 120) / (#seq),
                                    })
                                end
                            end
                        end
                    end
                end
            end
        end
    end
    table.sort(out, function(a, b) return a.prio > b.prio end)
    return out
end

local function genKicks(st, cue, ids)
    local out = {}
    for _, id in ipairs(ids) do
        local b = findBall(st.balls, id)
        if b and not b.pocketed then
            for _, p in ipairs(GEO.pockets) do
                local ux, uy = unit(b.x, b.y, p.x, p.y)
                local gx, gy = b.x - ux * diameter, b.y - uy * diameter
                if inside(gx, gy) and pathClear(st, b.x, b.y, p.x, p.y, id) then
                    for _, r in ipairs(RAILS) do
                        local mx, my = reflect(gx, gy, r)
                        local dx, dy = unit(cue.x, cue.y, mx, my)
                        local hx, hy = railHit(cue.x, cue.y, dx, dy, r)
                        if hx and math.abs(hx) < halfL and math.abs(hy) < halfW
                            and pathClear(st, cue.x, cue.y, hx, hy, id) and pathClear(st, hx, hy, gx, gy, id) then
                            local cut = cutBetween(hx, hy, gx, gy, ux, uy)
                            if cut <= math.rad(70) then
                                local total = dist(cue.x, cue.y, hx, hy) + dist(hx, hy, gx, gy) + dist(b.x, b.y, p.x, p.y)
                                table.insert(out, {
                                    angle = math.atan2(my - cue.y, mx - cue.x), ball = id, pocket = p.id,
                                    kind = "KICK", prio = math.cos(cut) / (1 + total / 100) * 0.8,
                                })
                            end
                        end
                    end
                end
            end
        end
    end
    table.sort(out, function(a, b) return a.prio > b.prio end)
    return out
end

local function genCombos(st, cue, ids)
    local out = {}
    for _, aBall in ipairs(st.balls) do
        if aBall.id ~= 0 and not aBall.pocketed then
            for _, tid in ipairs(ids) do
                local t = findBall(st.balls, tid)
                if t and not t.pocketed and t.id ~= aBall.id then
                    for _, p in ipairs(GEO.pockets) do
                        local ux, uy = unit(t.x, t.y, p.x, p.y)
                        local gtx, gty = t.x - ux * diameter, t.y - uy * diameter
                        if inside(gtx, gty) and pathClear(st, t.x, t.y, p.x, p.y, t.id, aBall.id) then
                            local ax, ay = unit(aBall.x, aBall.y, gtx, gty)
                            local gax, gay = aBall.x - ax * diameter, aBall.y - ay * diameter
                            if inside(gax, gay)
                                and pathClear(st, aBall.x, aBall.y, gtx, gty, aBall.id, t.id)
                                and pathClear(st, cue.x, cue.y, gax, gay, aBall.id) then
                                local cut1 = cutBetween(cue.x, cue.y, gax, gay, ax, ay)
                                local cut2 = math.acos(math.clamp(ax * ux + ay * uy, -1, 1))
                                if cut1 <= math.rad(70) and cut2 <= math.rad(60) then
                                    local total = dist(cue.x, cue.y, gax, gay) + dist(aBall.x, aBall.y, gtx, gty) + dist(t.x, t.y, p.x, p.y)
                                    table.insert(out, {
                                        angle = math.atan2(gay - cue.y, gax - cue.x), ball = t.id, pocket = p.id,
                                        kind = "COMBO", prio = math.cos(cut1) * math.cos(cut2) / (1 + total / 90) * 0.7,
                                    })
                                end
                            end
                        end
                    end
                end
            end
        end
    end
    table.sort(out, function(a, b) return a.prio > b.prio end)
    return out
end

local function genBrute(st, cue, ids, tEnd)
    local out, best = {}, {}
    local legalSet = {}
    for _, id in ipairs(ids) do legalSet[id] = true end
    local step = math.max(0.1, S.bruteStep)
    local deg = 0
    local n = 0
    while deg < 360 do
        local a = math.rad(deg)
        local ok, tr = pcall(Aim.trace, st, { angle = a, power = 0.7, spin = { x = 0, y = 0 }, elevation = ELEV }, 1)
        if ok and tr and tr.contact == "ball" and tr.objectId and legalSet[tr.objectId] then
            local ob = findBall(st.balls, tr.objectId)
            if ob and (tr.objectDirX ~= 0 or tr.objectDirY ~= 0) then
                for _, p in ipairs(GEO.pockets) do
                    local vx, vy = p.x - ob.x, p.y - ob.y
                    local fwd = vx * tr.objectDirX + vy * tr.objectDirY
                    if fwd > 0 then
                        local lat = math.abs(vx * tr.objectDirY - vy * tr.objectDirX)
                        local window = p.radius * 0.85
                        if lat < window and pathClear(st, ob.x, ob.y, p.x, p.y, ob.id) then
                            local key = ob.id .. ":" .. p.id
                            if not best[key] or lat < best[key].lat then
                                best[key] = {
                                    lat = lat, angle = a, ball = ob.id, pocket = p.id, kind = "BRUTE FORCE",
                                    prio = (1 - lat / window) / (1 + fwd / 80) * 0.6,
                                }
                            end
                        end
                    end
                end
            end
        end
        deg += step
        n += 1
        if n % 40 == 0 then
            task.wait()
            if os.clock() > tEnd then break end
        end
    end
    for _, c in pairs(best) do table.insert(out, c) end
    table.sort(out, function(a, b) return a.prio > b.prio end)
    return out
end

local LADDER = { 0.7, 0.5, 0.9, 0.35, 1.0 }

local function spinFor(kx, ky)
    return clampSpinVec(kx * S.spinAmount * (Config.Cue.MaxSpinOffset or 1), ky * S.spinAmount * (Config.Cue.MaxSpinOffset or 1))
end

local function robustCount(st, c, spin)
    local n = S.robustChecks
    if n <= 0 then return 0, 0 end
    local e = math.rad(S.robustEps)
    local tests = { { -e, 1 }, { e, 1 }, { 0, 0.97 }, { 0, 1.03 }, { -2 * e, 1 }, { 2 * e, 1 } }
    local ok = 0
    for i = 1, math.min(n, #tests) do
        local da, pf = tests[i][1], tests[i][2]
        local t = { angle = c.angle + da, power = math.clamp(c.power * pf, Config.Input.MinPowerToShoot, 1), ball = c.ball, safe = c.safe }
        if evaluateShot(st, c, simulateFull(st, t, spin)) then ok += 1 end
        task.wait()
    end
    return ok, math.min(n, #tests)
end

local function safePlay(st, cue, tEnd)
    local ids = ShotFinder.ownIds(st)
    table.sort(ids, function(a, b)
        local ba, bb = findBall(st.balls, a), findBall(st.balls, b)
        return dist(cue.x, cue.y, ba.x, ba.y) < dist(cue.x, cue.y, bb.x, bb.y)
    end)
    local best, bestScore
    local opp = st.team and (3 - st.team) or nil
    for i = 1, math.min(5, #ids) do
        local b = findBall(st.balls, ids[i])
        if b and pathClear(st, cue.x, cue.y, b.x, b.y, b.id) then
            local ang = math.atan2(b.y - cue.y, b.x - cue.x)
            for _, pw in ipairs({ 0.12, 0.2, 0.3 }) do
                local c = { angle = ang, power = math.max(Config.Input.MinPowerToShoot, pw), ball = b.id, safe = true }
                local res = simulateFull(st, c)
                local sc = evaluateShot(st, c, res)
                if not sc and res and not res.scratch and res.firstHit then
                    local okL, legal = pcall(ShotJudge.legalTarget, st.balls, st.groups and st.groups[st.team], res.firstHit)
                    local ate8 = false
                    for _, id in ipairs(res.pocketedIds) do if id == 8 then ate8 = true end end
                    if (not okL or legal ~= false) and not ate8 then sc = 500 end
                end
                if sc then
                    if opp and st.groups and #st.groups > 0 then
                        local nst = { geometry = GEO, balls = res.balls, groups = st.groups, team = opp, phase = {} }
                        local okC, cands = pcall(ShotFinder.candidates, nst, res.cueX, res.cueY)
                        if okC and cands then sc -= #cands * 70 end
                    end
                    if not bestScore or sc > bestScore then
                        bestScore = sc
                        best = { angle = c.angle, power = c.power, ball = b.id, pocket = nil, kind = "SAFE", safe = true, score = sc }
                    end
                end
                task.wait()
            end
        end
        if os.clock() > tEnd + 1.5 then break end
    end
    if best then return best end
    local okF, safe = pcall(ShotFinder.safePlan, st, cue.x, cue.y)
    if okF and safe then
        return { angle = safe.angle, power = safe.power, ball = safe.ball, kind = "SAFE", safe = true, score = 0 }
    end
    return nil
end

local function spinVariants()
    return { spinFor(0, 0.6), spinFor(0, -0.6), spinFor(0.6, 0), spinFor(-0.6, 0) }
end

local function genSweepLoose(st, cue, ids, tEnd, stepDeg)
    local out, legalSet = {}, {}
    for _, id in ipairs(ids) do legalSet[id] = true end
    local deg, n = 0, 0
    while deg < 360 do
        local a = math.rad(deg)
        local ok, tr = pcall(Aim.trace, st, { angle = a, power = 0.7, spin = { x = 0, y = 0 }, elevation = ELEV }, 1)
        if ok and tr and tr.contact == "ball" and tr.objectId and legalSet[tr.objectId] then
            local ob = findBall(st.balls, tr.objectId)
            if ob then
                local bestLat = 1e9
                for _, p in ipairs(GEO.pockets) do
                    local vx, vy = p.x - ob.x, p.y - ob.y
                    local fwd = vx * tr.objectDirX + vy * tr.objectDirY
                    if fwd > 0 then bestLat = math.min(bestLat, math.abs(vx * tr.objectDirY - vy * tr.objectDirX)) end
                end
                table.insert(out, { angle = a, ball = tr.objectId, kind = "MULTI", prio = 1 / (1 + bestLat / 4) })
            end
        end
        deg += stepDeg
        n += 1
        if n % 40 == 0 then
            task.wait()
            if os.clock() > tEnd then break end
        end
    end
    table.sort(out, function(a, b) return a.prio > b.prio end)
    return out
end

local function multiEval(st, c, spin)
    local res = simulateFull(st, c, spin)
    local sc, info = evaluateShot(st, c, res)
    return sc, info, res
end

local function planMulti(st, cue, ids, tEnd)
    local seeds = {}
    local function add(list, maxN)
        for i = 1, math.min(maxN, #list) do table.insert(seeds, list[i]) end
    end
    for _, c in ipairs(ShotFinder.pots(st, 8, cue.x, cue.y)) do
        table.insert(seeds, { angle = c.angle, ball = c.ball, pocket = c.pocket, calPower = c.power, prio = 2 + (c.score or 0) })
    end
    add(genBanks(st, cue, ids, 1), 8)
    add(genCombos(st, cue, ids), 8)
    add(genKicks(st, cue, ids), 8)
    local step = math.max(0.5, S.multiStep)
    add(genSweepLoose(st, cue, ids, tEnd, step), 40)
    table.sort(seeds, function(a, b) return a.prio > b.prio end)

    local top = {}
    local function push(p)
        table.insert(top, p)
        table.sort(top, function(a, b) return a.score > b.score end)
        while #top > 4 do table.remove(top) end
    end
    local seedEnd = os.clock() + math.max(0, tEnd - os.clock()) * 0.6
    for _, sd in ipairs(seeds) do
        if os.clock() > seedEnd then break end
        local powers = sd.calPower and { sd.calPower, S.maxPower } or { 0.8, 0.6, 1.0 }
        for _, pw in ipairs(powers) do
            local c = { angle = sd.angle, power = math.clamp(pw, Config.Input.MinPowerToShoot, S.maxPower), ball = sd.ball }
            local sc, info, res = multiEval(st, c)
            if sc then
                push({ angle = c.angle, power = c.power, ball = sd.ball, pocket = sd.pocket, score = sc,
                    count = info.good + (info.win and 1 or 0), pred = res.pocketedIds })
            end
            task.wait()
        end
    end
    if #top == 0 then return nil end

    local best
    for i = 1, math.min(3, #top) do
        local cur = top[i]
        for _ = 1, 3 do
            local nbrs = {}
            for _, da in ipairs({ 0.5, -0.5, 0.2, -0.2, 0.08, -0.08 }) do
                table.insert(nbrs, { da = math.rad(da), pf = 1, spin = cur.spin })
            end
            for _, pf in ipairs({ 0.94, 1.06 }) do table.insert(nbrs, { da = 0, pf = pf, spin = cur.spin }) end
            if S.multiSpin then
                for _, sp in ipairs(spinVariants()) do table.insert(nbrs, { da = 0, pf = 1, spin = sp }) end
            end
            local improved = false
            for _, nb in ipairs(nbrs) do
                if os.clock() > tEnd then break end
                local c = { angle = cur.angle + nb.da, power = math.clamp(cur.power * nb.pf, Config.Input.MinPowerToShoot, S.maxPower), ball = cur.ball }
                local sc, info, res = multiEval(st, c, nb.spin)
                if sc and sc > cur.score then
                    cur = { angle = c.angle, power = c.power, ball = cur.ball, pocket = cur.pocket, score = sc,
                        count = info.good + (info.win and 1 or 0), spin = nb.spin, pred = res.pocketedIds }
                    improved = true
                end
                task.wait()
            end
            if not improved or os.clock() > tEnd then break end
        end
        if not best or cur.score > best.score then best = cur end
    end
    best = best or top[1]
    best.kind = "MULTI"
    return best
end

local function planBreak(st, cue, apex, tEnd)
    local base = math.atan2(apex.y - cue.y, apex.x - cue.x)
    local best
    local spins = { false }
    if S.multiSpin then for _, sp in ipairs(spinVariants()) do table.insert(spins, sp) end end
    for _, pw in ipairs({ math.min(1, S.maxPower), 0.92, 0.84 }) do
        for _, off in ipairs({ 0, 0.5, -0.5, 1, -1, 1.6, -1.6, 2.6, -2.6, 4, -4 }) do
            for _, sp in ipairs(spins) do
                if os.clock() > tEnd then break end
                local c = { angle = base + math.rad(off), power = math.clamp(pw, Config.Input.MinPowerToShoot, 1), safe = true }
                local sc, info, res = multiEval(st, c, sp or nil)
                if sc and (not best or sc > best.score) then
                    best = { angle = c.angle, power = c.power, score = sc, kind = "BREAK", spin = sp or nil,
                        count = info and info.good or 0, pred = res.pocketedIds }
                end
                task.wait()
            end
        end
    end
    return best
end

local function planAI(st, cue, ids, tEnd, isBreak)
    local legalSet = {}
    for _, id in ipairs(ids) do legalSet[id] = true end
    local spinMax = Config.Cue.MaxSpinOffset or 1
    local mult = math.clamp(math.floor(S.aiMult), 1, 3)
    local minP = Config.Input.MinPowerToShoot
    local t0 = os.clock()
    local span = math.max(0.3, tEnd - t0)

    local function ev(a, m)
        local power = math.clamp(a.pow, minP, S.maxPower)
        local spin
        if S.aiSpin and (math.abs(a.sx) + math.abs(a.sy)) > 0.02 then
            spin = clampSpinVec(a.sx * spinMax, a.sy * spinMax)
        end
        local c = { angle = a.ang, power = power }
        local res = simulateFull(st, c, spin, { mult = m, track = true })
        if not res then return -5000, nil, nil, spin, power end
        local sc, info = evaluateShot(st, c, res)
        if sc then return sc, res, info, spin, power end
        local f = -1000
        if res.scratch then f -= 400 end
        if res.firstHit == nil then f -= 500 end
        local prox = 0
        for id, d in pairs(res.minDist or {}) do
            if legalSet[id] then prox += math.max(0, 1 - d / 18) end
        end
        f += 130 * prox + 6 * math.min(res.nHit or 0, 12)
        return f, res, nil, spin, power
    end

    local pop = {}
    local function addInd(a, m)
        local f, res, info, spin, power = ev(a, m)
        local ind = { ang = a.ang, pow = a.pow, sx = a.sx, sy = a.sy, fit = f, valid = info ~= nil, info = info, spin = spin, power = power }
        table.insert(pop, ind)
        return ind
    end
    local function rs() return S.aiSpin and (math.random() * 2 - 1) * 0.5 or 0 end

    local seeds = {}
    if isBreak then
        local apex = findBall(st.balls, 1)
        if apex then
            local base = math.atan2(apex.y - cue.y, apex.x - cue.x)
            if S.learn then
                for _, e in ipairs(memBreakSeeds(cue.y)) do
                    table.insert(seeds, {
                        ang = base + e.off, pow = e.pow,
                        sx = (spinMax ~= 0) and (e.sx / spinMax) or 0, sy = (spinMax ~= 0) and (e.sy / spinMax) or 0,
                    })
                end
            end
            for _, off in ipairs({ 0, 1, -1, 2.5, -2.5 }) do
                for _, pw in ipairs({ 1.0, 0.9 }) do
                    table.insert(seeds, { ang = base + math.rad(off), pow = pw, sx = 0, sy = 0 })
                end
            end
        end
    else
        for _, c in ipairs(ShotFinder.pots(st, 5, cue.x, cue.y)) do
            table.insert(seeds, { ang = c.angle, pow = c.power, sx = 0, sy = 0 })
            table.insert(seeds, { ang = c.angle, pow = math.min(1, c.power * 1.15), sx = 0, sy = 0 })
        end
        for _, list in ipairs({ genBanks(st, cue, ids, 1), genCombos(st, cue, ids), genKicks(st, cue, ids) }) do
            for i = 1, math.min(4, #list) do
                table.insert(seeds, { ang = list[i].angle, pow = 0.75, sx = 0, sy = 0 })
            end
        end
    end
    local stage1End = t0 + span * 0.45
    for _, a in ipairs(seeds) do
        if os.clock() > stage1End then break end
        addInd(a, mult)
        task.wait()
    end
    local N = isBreak and 40 or 36
    local order = {}
    for i = 0, N - 1 do table.insert(order, i) end
    for i = #order, 2, -1 do
        local j = math.random(i)
        order[i], order[j] = order[j], order[i]
    end
    for _, i in ipairs(order) do
        if os.clock() > stage1End then break end
        addInd({ ang = (i + math.random()) / N * 2 * math.pi, pow = 0.4 + 0.6 * math.random(), sx = rs(), sy = rs() }, mult)
        task.wait()
    end
    if #pop == 0 then return nil end
    table.sort(pop, function(a, b) return a.fit > b.fit end)

    local islands = {}
    for _, ind in ipairs(pop) do
        local distinct = true
        for _, isl in ipairs(islands) do
            if math.abs(wrap(ind.ang - isl.ind.ang)) < math.rad(4) and math.abs(ind.pow - isl.ind.pow) < 0.2 then
                distinct = false
                break
            end
        end
        if distinct then
            table.insert(islands, { ind = ind, sig = { ang = 0.05, pow = 0.10, s = 0.20 } })
            if #islands >= 3 then break end
        end
    end
    local stage2End = tEnd - span * 0.15
    local gen = 0
    while os.clock() < stage2End and #islands > 0 do
        gen += 1
        for _, isl in ipairs(islands) do
            if os.clock() > stage2End then break end
            local bestChild
            for _ = 1, 3 do
                local p = isl.ind
                local a = {
                    ang = p.ang + gauss() * isl.sig.ang,
                    pow = math.clamp(p.pow + gauss() * isl.sig.pow, 0.1, 1),
                    sx = S.aiSpin and math.clamp(p.sx + gauss() * isl.sig.s, -1, 1) or 0,
                    sy = S.aiSpin and math.clamp(p.sy + gauss() * isl.sig.s, -1, 1) or 0,
                }
                local child = addInd(a, mult)
                if not bestChild or child.fit > bestChild.fit then bestChild = child end
                task.wait()
            end
            if bestChild and bestChild.fit > isl.ind.fit then
                isl.ind = bestChild
                isl.sig.ang = math.min(0.2, isl.sig.ang * 1.2)
                isl.sig.pow = math.min(0.25, isl.sig.pow * 1.2)
                isl.sig.s = math.min(0.4, isl.sig.s * 1.2)
            else
                isl.sig.ang = math.max(0.0004, isl.sig.ang * 0.82)
                isl.sig.pow = math.max(0.004, isl.sig.pow * 0.82)
                isl.sig.s = math.max(0.02, isl.sig.s * 0.82)
            end
        end
    end

    table.sort(pop, function(a, b) return a.fit > b.fit end)
    local finalists, seen = {}, {}
    for _, ind in ipairs(pop) do
        if ind.valid then
            local k = string.format("%.4f:%.3f", ind.ang % (2 * math.pi), ind.pow)
            if not seen[k] then
                seen[k] = true
                table.insert(finalists, ind)
                if #finalists >= 5 then break end
            end
        end
    end
    local verified = {}
    for _, ind in ipairs(finalists) do
        local f, res, info, spin, power = ev(ind, 1)
        if info then
            table.insert(verified, {
                angle = ind.ang, power = power, spin = spin, ball = res.firstHit, pocket = nil,
                score = f, count = info.good + (info.win and 1 or 0), kind = isBreak and "BREAK AI" or "AI",
                pred = res.pocketedIds,
            })
        end
        task.wait()
    end
    if #verified == 0 then return nil end
    table.sort(verified, function(a, b) return a.score > b.score end)

    if S.robustChecks > 0 and not isBreak then
        for i = 1, math.min(2, #verified) do
            local p = verified[i]
            local ok, n = robustCount(st, { angle = p.angle, power = p.power, ball = p.ball }, p.spin)
            p.score += 90 * ok - 160 * (n - ok)
            p.robust = n > 0 and (ok / n) or 1
        end
        table.sort(verified, function(a, b) return a.score > b.score end)
    end
    H.stats.aiEvals = #pop
    return verified[1]
end

local function planShot(snap, team, budgetOverride)
    local balls = unpackBalls(snap)
    local cue = findBall(balls, 0)
    if not cue then return nil end
    local st = { geometry = GEO, balls = balls, groups = snap.groups, team = team, phase = {}, called = snap.calledPocket }

    local strat = S.strategy
    st.multi = (strat == "Multi-ball")
    local isAI = (strat == "Evolutionary AI")
    if isAI then
        st.extra = ({ ["More balls"] = 450, ["Balanced"] = 150, ["Position"] = 25 })[S.aiGoal] or 150
        st.posMul = (S.aiGoal == "Position") and 1.8 or 1
    end
    local heavy = (strat == "Impossible" or strat == "Multi-ball" or isAI)
    local budget = budgetOverride or (heavy and S.budget or math.min(S.budget, 2.0))
    local tEnd = os.clock() + budget

    if snap.breakShot then
        local apex = findBall(balls, 1)
        if apex then
            if isAI then
                local pa = planAI(st, cue, ShotFinder.ownIds(st), tEnd, true)
                if pa then return pa end
            end
            if st.multi then
                local pb = planBreak(st, cue, apex, tEnd)
                if pb then return pb end
            end
            return { angle = math.atan2(apex.y - cue.y, apex.x - cue.x), power = S.breakPower, kind = "BREAK", score = 0 }
        end
    end

    local ids = ShotFinder.ownIds(st)

    if strat == "Safe" then
        return safePlay(st, cue, tEnd)
    end

    if isAI then
        local m = planAI(st, cue, ids, tEnd, false)
        if m then return m end
        strat = "Aggressive"
        st.extra, st.posMul = nil, nil
        tEnd = os.clock() + 2.0
    end

    if st.multi then
        local m = planMulti(st, cue, ids, tEnd)
        if m and m.count >= S.multiMin then return m end
        strat = "Aggressive"
        st.multi = false
        tEnd = os.clock() + 2.0
    end

    local pool = {}
    local function consider(c, powers, maxSucc, calibrated)
        local succ = 0
        local bestForCand
        for _, pw in ipairs(powers) do
            if os.clock() > tEnd then break end
            local cc = { angle = c.angle, power = math.clamp(pw, Config.Input.MinPowerToShoot, S.maxPower), ball = c.ball }
            local res = simulateFull(st, cc)
            local sc = evaluateShot(st, cc, res)
            if sc then
                succ += 1
                local plan = {
                    angle = cc.angle, power = cc.power, ball = c.ball, pocket = c.pocket,
                    kind = c.kind or "DIRECT", score = sc, res = res, pred = res.pocketedIds,
                }
                if not bestForCand or sc > bestForCand.score then bestForCand = plan end
                if succ >= maxSucc then break end
            end
            task.wait()
        end
        if bestForCand then table.insert(pool, bestForCand) end
    end

    local function directs()
        local pots = ShotFinder.pots(st, 8, cue.x, cue.y)
        for _, cand in ipairs(pots) do
            if st.called and cand.ball == 8 and cand.pocket ~= st.called then continue end
            local b = cand.power
            local pv = {
                b, math.min(S.maxPower, b * 1.08), math.max(Config.Input.MinPowerToShoot, b * 0.88),
                math.max(Config.Input.MinPowerToShoot, b * 0.75), math.min(S.maxPower, b * 1.25),
            }
            local list = {}
            for i = 1, math.min(S.powerVariants, #pv) do list[i] = pv[i] end
            consider({ angle = cand.angle, ball = cand.ball, pocket = cand.pocket, kind = "DIRECT" }, list, 3)
            if os.clock() > tEnd then break end
        end
    end

    local function runGen(list, maxN)
        for i = 1, math.min(maxN, #list) do
            local c = list[i]
            if st.called and c.ball == 8 and c.pocket ~= st.called then continue end
            consider(c, LADDER, 2)
            if os.clock() > tEnd then break end
        end
    end

    directs()
    local wantMore = (strat ~= "Normal") or (#pool == 0)
    if wantMore then
        if S.allowBank then runGen(genBanks(st, cue, ids, 1), 8) end
        if S.allowCombo then runGen(genCombos(st, cue, ids), 6) end
        if S.allowKick then runGen(genKicks(st, cue, ids), 6) end
        if strat == "Impossible" then
            if S.allowDouble then runGen(genBanks(st, cue, ids, 2), 8) end
            if S.brute then runGen(genBrute(st, cue, ids, tEnd), 12) end
        end
    end

    if #pool == 0 then
        return safePlay(st, cue, tEnd)
    end

    for _, p in ipairs(pool) do p.score += kindBonus(p.kind) end
    table.sort(pool, function(a, b) return a.score > b.score end)

    if S.robustChecks > 0 then
        local survivors = {}
        for i = 1, math.min(3, #pool) do
            local p = pool[i]
            local ok, n = robustCount(st, p, p.spin)
            p.robust = n > 0 and (ok / n) or 1
            p.score += 90 * ok - 160 * (n - ok)
            if not S.strict or ok == n then table.insert(survivors, p) end
        end
        if #survivors > 0 then pool = survivors end
        table.sort(pool, function(a, b) return a.score > b.score end)
    end

    local best = pool[1]

    if S.useSpin and best and not best.safe then
        local variants = { spinFor(0, 0.6), spinFor(0, -0.6), spinFor(0.6, 0), spinFor(-0.6, 0) }
        for _, sp in ipairs(variants) do
            local c = { angle = best.angle, power = best.power, ball = best.ball }
            local sc = evaluateShot(st, c, simulateFull(st, c, sp))
            if sc and sc > best.score + 15 then
                best.score, best.spin = sc, sp
            end
            task.wait()
        end
    end
    return best
end

local function choosePlacement(snap, team)
    local balls = unpackBalls(snap)
    local function movedBalls(x, y)
        local t = {}
        for _, b in ipairs(balls) do
            if b.id == 0 then
                table.insert(t, { id = 0, x = x, y = y, z = 0, pocketed = false })
            else
                table.insert(t, { id = b.id, x = b.x, y = b.y, z = b.z or 0, pocketed = b.pocketed })
            end
        end
        return t
    end

    if snap.breakShot then
        local x = MP.BreakLineX
        local isAI = S.strategy == "Evolutionary AI"
        local ys = (S.strategy == "Multi-ball") and { 0, 3, -3, 6, -6, 9, -9 }
            or (isAI and { 0, 4, -4, 8, -8 } or { 0 })
        if isAI and S.learn then
            local my = memBestBreakY()
            if my then
                local dup = false
                for _, y in ipairs(ys) do if math.abs(y - my) < 0.5 then dup = true end end
                if not dup then table.insert(ys, 1, my) end
            end
        end
        local bPlan, by, bs
        local function tryY(y, budget)
            if not CuePlacement.valid({ geometry = GEO, balls = balls }, x, y, true, 0) then return end
            local fake = {
                id = snap.id, epoch = snap.epoch, turnId = snap.turnId, groups = snap.groups,
                breakShot = true, balls = movedBalls(x, y),
            }
            local plan = planShot(fake, team, budget)
            local sc = plan and plan.score or 0
            if not bs or sc > bs then bs, bPlan, by = sc, plan, y end
        end
        if isAI then
            for _, y in ipairs(ys) do tryY(y, math.max(0.6, S.budget * 0.5 / #ys)) end
            if by then tryY(by, math.max(1.0, S.budget * 0.5)) end
        else
            for _, y in ipairs(ys) do tryY(y, math.max(0.8, S.budget / #ys)) end
        end
        if bPlan then return x, by, bPlan end
        return nil
    end

    local scored, count = {}, 0
    local x = -halfL + 3
    while x <= halfL - 3 do
        local y = -halfW + 3
        while y <= halfW - 3 do
            local st = { geometry = GEO, balls = balls, groups = snap.groups, team = team, phase = {} }
            if CuePlacement.valid(st, x, y, false, 0) then
                local nst = { geometry = GEO, balls = movedBalls(x, y), groups = snap.groups, team = team, phase = {} }
                local ok, cands = pcall(ShotFinder.candidates, nst, x, y)
                if ok and cands and #cands > 0 then
                    local sum = 0
                    for i = 1, math.min(3, #cands) do sum += cands[i].score end
                    table.insert(scored, { x = x, y = y, q = sum })
                end
            end
            y += 3
        end
        x += 3
        count += 1
        if count % 4 == 0 then task.wait() end
    end
    table.sort(scored, function(a, b) return a.q > b.q end)

    local bestPlan, bx, by, bs
    for i = 1, math.min(4, #scored) do
        local p = scored[i]
        local fake = {
            id = snap.id, epoch = snap.epoch, turnId = snap.turnId, groups = snap.groups,
            breakShot = false, calledPocket = snap.calledPocket, balls = movedBalls(p.x, p.y),
        }
        local plan = planShot(fake, team, math.min(S.budget, 1.2))
        if plan then
            local sc = (plan.score or 0) + (plan.safe and -2000 or 0)
            if not bs or sc > bs then bs, bestPlan, bx, by = sc, plan, p.x, p.y end
        end
        task.wait()
    end
    if bestPlan then return bx, by, bestPlan end
    if scored[1] then return scored[1].x, scored[1].y, nil end
    return nil
end

H.planShot = planShot
H.choosePlacement = choosePlacement

local function fire(snap, shot, cueX, cueY)
    local balls = unpackBalls(snap)
    local cue = findBall(balls, 0)
    Net.ShotFired:FireServer({
        epoch = snap.epoch, turnId = snap.turnId, tableId = snap.id,
        angle = shot.angle, power = math.clamp(shot.power, Config.Input.MinPowerToShoot, 1),
        spin = shot.spin or { x = 0, y = 0 }, elevation = ELEV,
        cueX = cueX or (cue and cue.x), cueY = cueY or (cue and cue.y),
    })
end
local function placeCue(snap, x, y)
    Net.MatchAction:FireServer({
        kind = "Place", tableId = snap.id, epoch = snap.epoch, turnId = snap.turnId, x = x, y = y, seq = 1,
    })
end
local function callPocket(snap, pocket)
    Net.MatchAction:FireServer({
        kind = "Pocket", tableId = snap.id, epoch = snap.epoch, turnId = snap.turnId, pocket = pocket,
    })
end

local function humanizeShot(shot)
    local s = { angle = shot.angle, power = shot.power, spin = shot.spin }
    if S.angleNoise > 0 then s.angle += math.rad(gauss() * S.angleNoise) end
    if S.powerNoise > 0 then s.power = math.clamp(s.power * (1 + gauss() * S.powerNoise / 100), Config.Input.MinPowerToShoot, 1) end
    if S.missChance > 0 and math.random() * 100 < S.missChance then
        s.angle += math.rad((math.random() < 0.5 and -1 or 1) * (1.2 + math.random() * 1.5))
    end
    return s
end

local function execute(snap, team, entry)
    local phase = snap.phase
    if S.humanize then task.wait(S.delayMin + math.random() * math.max(0, S.delayMax - S.delayMin)) end

    if phase == "PocketChoice" then
        if S.autoPocket and entry.pocket then
            callPocket(snap, entry.pocket)
            note("Pocket", "Called for the 8: " .. tostring(entry.pocket))
        end
        return
    end

    local plan = entry.plan
    if not plan then
        note("No shot", "No valid shot found")
        return
    end

    local cx, cy
    if phase == "Placement" then
        if not S.autoPlace or not entry.px then return end
        placeCue(snap, entry.px, entry.py)
        cx, cy = entry.px, entry.py
        task.wait(0.35)
    end

    local shot = humanizeShot(plan)
    if phase ~= "Placement" and S.mouseAim then
        pcall(function() rotateTo(snap.id, shot.angle) end)
        task.wait(0.10)
    end

    if S.action == "Auto" then
        fire(snap, shot, cx, cy)
        H.stats.shots += 1
        if S.learn then
            local pend = {
                t = os.clock(), tableId = snap.id, turnId = snap.turnId, kind = plan.kind, pred = plan.pred,
                isBreak = snap.breakShot == true, power = shot.power, spin = shot.spin, score = plan.score,
            }
            if pend.isBreak and cy then
                local balls = unpackBalls(snap)
                local apex = findBall(balls, 1)
                if apex then
                    pend.y = cy
                    pend.off = wrap(shot.angle - math.atan2(apex.y - cy, apex.x - cx))
                end
            end
            H.pending = pend
        end
        local title = plan.count and (plan.kind .. " x" .. plan.count) or plan.kind
        note(title, string.format("ball %s pocket %s power %.2f", tostring(plan.ball), tostring(plan.pocket), shot.power))
        log(string.format("%s ball=%s pocket=%s ang=%.4f pow=%.3f", plan.kind, tostring(plan.ball), tostring(plan.pocket), shot.angle, shot.power))
    end
end

local function turnKey(snap)
    return table.concat({ snap.id, snap.epoch or 0, snap.turnId or 0, snap.phase }, ":")
end

local function computeEntry(snap, team)
    local entry = { status = "computing", t = os.clock() }
    local phase = snap.phase
    if phase == "Placement" then
        local px, py, plan = choosePlacement(snap, team)
        entry.px, entry.py, entry.plan = px, py, plan
    elseif phase == "PocketChoice" then
        local plan = planShot({ id = snap.id, epoch = snap.epoch, turnId = snap.turnId, balls = snap.balls, groups = snap.groups }, team)
        if plan and plan.ball == 8 and plan.pocket then
            entry.pocket = plan.pocket
        else
            local ok, p = pcall(ShotFinder.eightPocket, GEO, unpackBalls(snap))
            if ok then entry.pocket = p end
        end
        entry.plan = plan
    else
        entry.plan = planShot(snap, team)
    end
    entry.status = "ready"
    return entry
end

local function pruneCache()
    local n = 0
    for _ in pairs(H.plans) do n += 1 end
    if n > 10 then
        local oldestK, oldestT
        for k, e in pairs(H.plans) do
            if not oldestT or (e.t or 0) < oldestT then oldestK, oldestT = k, e.t or 0 end
        end
        if oldestK then H.plans[oldestK] = nil end
    end
end

H.conns[#H.conns + 1] = Net.ShotRejected.OnClientEvent:Connect(function(reason)
    log("Shot rejected: " .. tostring(reason))
    local k = H.lastKey
    if k then
        H.retries[k] = (H.retries[k] or 0) + 1
        if H.retries[k] <= 2 then H.done[k] = nil end
    end
end)

function H.replan()
    local snap = mySeat()
    if snap then
        H.plans[turnKey(snap)] = nil
        H.done[turnKey(snap)] = nil
    end
end

task.spawn(function()
    while H.running do
        task.wait(0.15)
        if H.busy then continue end
        local snap, team = mySeat()
        if not snap or snap.shooter ~= lp.UserId then continue end
        local phase = snap.phase
        local actionable = phase == "Aiming" or phase == "PocketChoice" or (phase == "Placement" and snap.ballInHand == true)
        if not actionable then continue end

        local key = turnKey(snap)
        local entry = H.plans[key]
        if not entry then
            if S.enabled or S.showPlan then
                H.busy = true
                H.plans[key] = { status = "computing", t = os.clock() }
                pruneCache()
                task.spawn(function()
                    local ok, res = pcall(computeEntry, snap, team)
                    if ok then
                        H.plans[key] = res
                    else
                        H.plans[key] = { status = "ready", t = os.clock() }
                        log("Error while computing: " .. tostring(res))
                    end
                    H.busy = false
                end)
            end
        elseif entry.status == "ready" and S.enabled and S.action ~= "Suggest only" and not H.done[key] then
            H.done[key] = true
            H.lastKey = key
            H.busy = true
            task.spawn(function()
                local ok, err = pcall(execute, snap, team, entry)
                if not ok then log("Error while executing: " .. tostring(err)) end
                H.busy = false
            end)
        end
    end
end)

local folder = Instance.new("Folder")
folder.Name = "Ball8HubLines"
folder.Parent = workspace

local function mkPart(name)
    local p = Instance.new("Part")
    p.Name = name
    p.Anchored, p.CanCollide, p.CanQuery, p.CanTouch, p.CastShadow = true, false, false, false, false
    p.Material = Enum.Material.Neon
    p.Transparency = 1
    p.Size = Vector3.new(0.1, 0.1, 0.1)
    p.Parent = folder
    return p
end
local P = {
    planCue = mkPart("PlanCue"), planObj = mkPart("PlanObject"), planBounce = mkPart("PlanBounce"),
    planPocket = mkPart("PlanPocket"), planGhost = mkPart("PlanGhost"),
    aimCue = mkPart("AimCue"), aimObj = mkPart("AimObject"), aimBounce = mkPart("AimBounce"), aimGhost = mkPart("AimGhost"),
}
local heightInches = Config.Guideline.HeightAboveClothInches or 0.5

local function hideGroup(prefix)
    for k, p in pairs(P) do
        if string.sub(k, 1, #prefix) == prefix then p.Transparency = 1 end
    end
end
local function setLine(part, pl, ax, ay, bx, by, color, alpha)
    local x1, y1, z1 = Placement.toWorld(pl, ax, ay, heightInches)
    local x2, y2, z2 = Placement.toWorld(pl, bx, by, heightInches)
    local a, b = Vector3.new(x1, y1, z1), Vector3.new(x2, y2, z2)
    local len = (b - a).Magnitude
    if len < 0.02 then part.Transparency = 1 return end
    part.Color = color
    part.Size = Vector3.new(S.thickness, S.thickness, len)
    part.CFrame = CFrame.lookAt((a + b) / 2, b)
    part.Transparency = alpha or 0.1
end
local function setDot(part, pl, x, y, color, scale)
    local wx, wy, wz = Placement.toWorld(pl, x, y, heightInches)
    part.Color = color
    local sz = S.thickness * (scale or 3)
    part.Size = Vector3.new(sz, sz, sz)
    part.CFrame = CFrame.new(wx, wy, wz)
    part.Transparency = 0.1
end

local function drawTrace(prefix, st, pl, angle, color, pocket)
    local tr = Aim.trace(st, { angle = angle, power = 0.5, spin = { x = 0, y = 0 }, elevation = ELEV }, 1)
    if tr.contact == "none" then hideGroup(prefix) return end
    local cueLine, objLine, bounce, ghost = P[prefix .. "Cue"], P[prefix .. "Obj"], P[prefix .. "Bounce"], P[prefix .. "Ghost"]
    setLine(cueLine, pl, tr.startX, tr.startY, tr.ghostX, tr.ghostY, color, 0.1)
    setDot(ghost, pl, tr.ghostX, tr.ghostY, Color3.fromRGB(255, 80, 80))
    local lines = Aim.fullLines(st, tr)
    if tr.contact == "ball" and tr.objectId then
        local obj = findBall(st.balls, tr.objectId)
        if obj and lines.object then
            setLine(objLine, pl, obj.x, obj.y, obj.x + tr.objectDirX * lines.object, obj.y + tr.objectDirY * lines.object, Color3.fromRGB(255, 170, 0), 0.1)
        else
            objLine.Transparency = 1
        end
    else
        objLine.Transparency = 1
    end
    if lines.cue and (tr.cueDirX ~= 0 or tr.cueDirY ~= 0) then
        setLine(bounce, pl, tr.ghostX, tr.ghostY, tr.ghostX + tr.cueDirX * lines.cue, tr.ghostY + tr.cueDirY * lines.cue, Color3.fromRGB(0, 220, 255), 0.15)
    else
        bounce.Transparency = 1
    end
end

H.conns[#H.conns + 1] = RunService.RenderStepped:Connect(function()
    if not H.running then return end
    local snap, team = mySeat()
    if not snap or (not S.showPlan and not S.showAim) then hideGroup("plan") hideGroup("aim") return end
    local pl = Placement.forTable(snap.id)
    if not pl then hideGroup("plan") hideGroup("aim") return end
    local st = { geometry = GEO, balls = unpackBalls(snap) }

    if S.showAim and snap.phase == "Aiming" then
        local a = currentAim(snap.id)
        if a then pcall(drawTrace, "aim", st, pl, a, S.aimColor) else hideGroup("aim") end
    else
        hideGroup("aim")
    end

    local entry = H.plans[turnKey(snap)]
    if S.showPlan and snap.shooter == lp.UserId and snap.phase == "Aiming" and entry and entry.plan and entry.plan.angle then
        pcall(drawTrace, "plan", st, pl, entry.plan.angle, S.planColor)
        if entry.plan.pocket then
            for _, pk in ipairs(GEO.pockets) do
                if pk.id == entry.plan.pocket then setDot(P.planPocket, pl, pk.x, pk.y, S.planColor, 6) end
            end
        else
            P.planPocket.Transparency = 1
        end
    else
        hideGroup("plan")
        P.planPocket.Transparency = 1
    end
end)

H.conns[#H.conns + 1] = UIS.InputBegan:Connect(function(io, gp)
    if gp then return end
    local n = io.KeyCode.Name
    if n == KEYS.toggle then
        S.enabled = not S.enabled
        note("Aimbot", S.enabled and "ENABLED" or "DISABLED")
        if H.setToggle then pcall(H.setToggle, S.enabled) end
    elseif n == KEYS.replan then
        H.replan()
        note("Replanning", "Recomputing the shot")
    elseif n == KEYS.lines then
        S.showPlan = not S.showPlan
    end
end)

function H.destroy()
    H.running = false
    memDirty = true
    memSave(true)
    for _, c in ipairs(H.conns) do pcall(function() c:Disconnect() end) end
    pcall(function() folder:Destroy() end)
    for k, v in pairs(finderOrig) do pcall(function() Finder[k] = v end) end
    if H.window then pcall(function() H.window:Destroy() end) end
    log("Hub unloaded.")
end

local function loadWindUI()
    local ok, res = pcall(function()
        return loadstring(game:HttpGet("https://raw.githubusercontent.com/Footagesus/WindUI/main/dist/main.lua"))()
    end)
    if ok and res then return res end
    log("Could not load WindUI: " .. tostring(res))
    return nil
end

WebUI = loadWindUI()
if not WebUI then
    return "Hub loaded WITHOUT UI (WindUI unavailable)"
end

local Window = WebUI:CreateWindow({
    Title = "8 Ball Hub",
    Folder = "bola8hub",
    NewElements = true,
    HideSearchBar = false,
    OpenButton = {
        Title = "8 Ball Hub",
        CornerRadius = UDim.new(1, 0),
        StrokeThickness = 3,
        Enabled = true,
        Draggable = true,
        OnlyMobile = false,
        Color = ColorSequence.new(Color3.fromHex("#30FF6A"), Color3.fromHex("#e7ff2f")),
    },
    Topbar = { Height = 44, ButtonsType = "Mac" },
})
H.window = Window
pcall(function() Window:Tag({ Title = "v" .. tostring(WebUI.Version), Icon = "github", Color = Color3.fromHex("#1c1c1c") }) end)

local function val(o) return type(o) == "table" and (o.Title or o[1]) or o end
local Green, Blue, Yellow, Purple, Red, Grey =
    Color3.fromHex("#10C550"), Color3.fromHex("#257AF7"), Color3.fromHex("#ECA201"),
    Color3.fromHex("#7775F2"), Color3.fromHex("#EF4F1D"), Color3.fromHex("#83889E")

do
    local T = Window:Tab({ Title = "Aimbot", Icon = "crosshair", IconColor = Green, IconShape = "Square" })
    T:Section({ Title = "Main control" })
    local tg = T:Toggle({
        Flag = "enabled", Title = "Enable aimbot", Desc = "Hotkey: RightShift. Starts disabled.",
        Default = false, Callback = function(v) S.enabled = v end,
    })
    H.setToggle = function(v) pcall(function() tg:Set(v) end) end
    T:Space()
    T:Dropdown({
        Flag = "action", Title = "Action", Desc = "Auto = aims and shoots. Aim only = moves the cue. Suggest only = lines only.",
        Values = { "Auto", "Aim only", "Suggest only" }, Value = "Auto",
        Callback = function(o) S.action = val(o) end,
    })
    T:Space()
    T:Dropdown({
        Flag = "strategy", Title = "Strategy",
        Desc = "Normal: direct shots and, if none, others. Aggressive: tries everything. Impossible: searches for any shot. Multi-ball: pots as many as it can in one hit. Safe: defensive.",
        Values = { "Normal", "Aggressive", "Impossible", "Multi-ball", "Evolutionary AI", "Safe" }, Value = "Normal",
        Callback = function(o) S.strategy = val(o) applyFinder() end,
    })
    T:Space()
    T:Toggle({ Flag = "autoPlace", Title = "Place cue ball automatically", Desc = "Ball in hand: picks the best position.", Default = true, Callback = function(v) S.autoPlace = v end })
    T:Toggle({ Flag = "autoPocket", Title = "Call the 8-ball pocket", Default = true, Callback = function(v) S.autoPocket = v end })
    T:Toggle({ Flag = "usePosition", Title = "Position play", Desc = "Prefers the shot that leaves the cue ball well placed for the next one.", Default = true, Callback = function(v) S.usePosition = v end })
    T:Toggle({ Flag = "mouseAim", Title = "Move the cue with the mouse", Desc = "See the cue move as if you were aiming yourself.", Default = true, Callback = function(v) S.mouseAim = v end })
    T:Slider({ Flag = "breakPower", Title = "Break power", Step = 0.05, Value = { Min = 0.5, Max = 1, Default = 1 }, Callback = function(v) S.breakPower = v end })
    T:Space()
    T:Button({ Title = "Replan now (R)", Justify = "Center", Icon = "", Callback = function() H.replan() note("Replanning", "Recomputing the shot") end })
end

do
    local T = Window:Tab({ Title = "Impossible shots", Icon = "zap", IconColor = Yellow, IconShape = "Square" })
    T:Section({ Title = "Allowed shot types" })
    T:Toggle({ Flag = "allowBank", Title = "Bank shots", Desc = "The object ball bounces off a rail into the pocket.", Default = true, Callback = function(v) S.allowBank = v end })
    T:Toggle({ Flag = "allowDouble", Title = "Double bank", Desc = "Only in the Impossible strategy.", Default = true, Callback = function(v) S.allowDouble = v end })
    T:Toggle({ Flag = "allowKick", Title = "Kick (cue ball hits a rail first)", Default = true, Callback = function(v) S.allowKick = v end })
    T:Toggle({ Flag = "allowCombo", Title = "Combos", Desc = "The cue ball hits a ball that pushes another into the pocket.", Default = true, Callback = function(v) S.allowCombo = v end })
    T:Toggle({ Flag = "brute", Title = "Fine angle sweep", Desc = "Impossible only. Finds very thin cuts the normal finder discards.", Default = true, Callback = function(v) S.brute = v end })
    T:Space()
    T:Section({ Title = "Finder limits" })
    T:Slider({ Flag = "bruteStep", Title = "Sweep resolution (degrees)", Step = 0.05, Value = { Min = 0.1, Max = 2, Default = 0.5 }, Callback = function(v) S.bruteStep = v end })
    T:Slider({ Flag = "budget", Title = "Max computation time (s)", Step = 0.5, Value = { Min = 1, Max = 12, Default = 4 }, Callback = function(v) S.budget = v end })
    T:Slider({ Flag = "maxCut", Title = "Max cut (degrees)", Desc = "Higher = thinner shots.", Step = 1, Value = { Min = 30, Max = 88, Default = 80 }, Callback = function(v) S.maxCut = v applyFinder() end })
    T:Slider({ Flag = "maxPower", Title = "Max power", Desc = "The game's finder caps it at 0.85; you can raise it here.", Step = 0.05, Value = { Min = 0.5, Max = 1, Default = 1 }, Callback = function(v) S.maxPower = v applyFinder() end })
end

do
    local T = Window:Tab({ Title = "Evolutionary AI", Icon = "brain", IconColor = Blue, IconShape = "Square" })
    T:Section({ Title = "Free search (no formulas)" })
    T:Paragraph({
        Title = "What it is",
        Desc = "Pick the 'Evolutionary AI' strategy in Aimbot. Instead of ghost-ball formulas, it tests hundreds of actions (angle across all 360 degrees, power and spin) in the game's real physics and evolves the best ones. This discovers plays no formula would give: aiming at a rail so the cue ball bounces and spreads the pack, hitting hard to open the group, etc. On the break it also chooses where to place the cue ball.",
    })
    T:Dropdown({
        Flag = "aiGoal", Title = "Goal", Desc = "More balls = prioritizes potting several. Position = prioritizes leaving the cue ball well placed.",
        Values = { "More balls", "Balanced", "Position" }, Value = "Balanced",
        Callback = function(o) S.aiGoal = val(o) end,
    })
    T:Space()
    T:Slider({ Flag = "aiMult", Title = "Exploration speed", Desc = "1 = exact but slow. 2-3 = tests more actions per second; the final result is always verified with exact physics.", Step = 1, Value = { Min = 1, Max = 3, Default = 2 }, Callback = function(v) S.aiMult = v end })
    T:Toggle({ Flag = "aiSpin", Title = "Allow spin", Desc = "The AI can give the cue ball spin to control the bounce.", Default = true, Callback = function(v) S.aiSpin = v end })
    T:Paragraph({ Title = "Time", Desc = "Uses the 'Max computation time' from the Impossible shots tab. More time = more actions tested = better plays (4-8 s is a good range)." })
    T:Space()
    T:Section({ Title = "Memory (saved learning)" })
    T:Paragraph({
        Title = "What it stores",
        Desc = "Stores in ball8_memory.json: (1) the best break plays with how many balls they ACTUALLY potted, reused as a starting point; (2) the real reliability of each shot type (what the simulation predicted vs what happened on the server), which adjusts how much it trusts each one. It does not store individual shots: the table almost never repeats.",
    })
    T:Toggle({ Flag = "learn", Title = "Learn and use memory", Default = true, Callback = function(v) S.learn = v end })
    T:Space()
    T:Button({
        Title = "View statistics", Justify = "Center", Icon = "",
        Callback = function()
            local lines = {}
            for kind, k in pairs(Mem.kinds) do
                table.insert(lines, string.format("%s %d/%d", kind, k.ok, k.n))
            end
            table.sort(lines)
            local b = Mem.breaks[1]
            local bt = b and string.format(" | best break: %.1f in, %.1f balls avg (%d attempts)", b.y, b.pots / b.trials, b.trials) or ""
            note("Memory", string.format("%d shots. %s%s", Mem.shots, #lines > 0 and table.concat(lines, ", ") or "no data", bt))
        end,
    })
    T:Space()
    T:Button({ Title = "Save memory now", Justify = "Center", Icon = "", Callback = function() memDirty = true memSave(true) note("Memory", "Saved") end })
    T:Space()
    T:Button({ Title = "Clear memory", Color = Color3.fromHex("#ff4830"), Justify = "Center", Icon = "trash", Callback = function() memClear() note("Memory", "Cleared") end })
end

do
    local T = Window:Tab({ Title = "Multi-ball", Icon = "layers", IconColor = Red, IconShape = "Square" })
    T:Section({ Title = "Pot several balls in a single shot" })
    T:Paragraph({
        Title = "How it works",
        Desc = "Pick the 'Multi-ball' strategy in the Aimbot tab. It searches for the angle, power and spin with which the game's simulation pots the most of your balls at once (bounces, combos and spread). On the break it also optimizes the angle and the cue ball position.",
    })
    T:Slider({ Flag = "multiStep", Title = "Sweep resolution (degrees)", Desc = "Lower = searches more angles but takes longer.", Step = 0.5, Value = { Min = 0.5, Max = 5, Default = 2 }, Callback = function(v) S.multiStep = v end })
    T:Slider({ Flag = "multiMin", Title = "Minimum balls to pick it", Desc = "If no shot pots at least this many, it plays the best normal shot.", Step = 1, Value = { Min = 1, Max = 6, Default = 2 }, Callback = function(v) S.multiMin = v end })
    T:Toggle({ Flag = "multiSpin", Title = "Try spin", Desc = "Tests top/bottom/left/right spin when refining the shot.", Default = true, Callback = function(v) S.multiSpin = v end })
end

do
    local T = Window:Tab({ Title = "Precision", Icon = "sliders-horizontal", IconColor = Blue, IconShape = "Square" })
    T:Section({ Title = "Precision control" })
    T:Slider({ Flag = "robustChecks", Title = "Tolerance tests", Desc = "Each one re-simulates the shot with a small error. 0 = off.", Step = 1, Value = { Min = 0, Max = 6, Default = 2 }, Callback = function(v) S.robustChecks = v end })
    T:Slider({ Flag = "robustEps", Title = "Angle error to tolerate (degrees)", Step = 0.01, Value = { Min = 0.02, Max = 0.5, Default = 0.1 }, Callback = function(v) S.robustEps = v end })
    T:Toggle({ Flag = "strict", Title = "Strict mode", Desc = "Discards shots that don't pass ALL tests (if any do).", Default = false, Callback = function(v) S.strict = v end })
    T:Slider({ Flag = "powerVariants", Title = "Powers tested per shot", Step = 1, Value = { Min = 1, Max = 5, Default = 5 }, Callback = function(v) S.powerVariants = v end })
    T:Slider({ Flag = "positionWeight", Title = "Position play weight", Step = 0.1, Value = { Min = 0, Max = 2.5, Default = 1 }, Callback = function(v) S.positionWeight = v end })
    T:Space()
    T:Section({ Title = "Spin" })
    T:Toggle({ Flag = "useSpin", Title = "Use spin for position", Desc = "Tests top/bottom/left/right spin and keeps whichever improves position.", Default = false, Callback = function(v) S.useSpin = v end })
    T:Slider({ Flag = "spinAmount", Title = "Spin amount", Step = 0.05, Value = { Min = 0.1, Max = 1, Default = 0.5 }, Callback = function(v) S.spinAmount = v end })
    T:Space()
    T:Section({ Title = "Humanize (look like a real player)" })
    T:Toggle({ Flag = "humanize", Title = "Random delay before acting", Default = false, Callback = function(v) S.humanize = v end })
    T:Slider({ Flag = "delayMin", Title = "Minimum delay (s)", Step = 0.1, Value = { Min = 0, Max = 6, Default = 0.6 }, Callback = function(v) S.delayMin = v end })
    T:Slider({ Flag = "delayMax", Title = "Maximum delay (s)", Step = 0.1, Value = { Min = 0, Max = 8, Default = 1.6 }, Callback = function(v) S.delayMax = v end })
    T:Slider({ Flag = "angleNoise", Title = "Angle noise (degrees)", Step = 0.01, Value = { Min = 0, Max = 2, Default = 0 }, Callback = function(v) S.angleNoise = v end })
    T:Slider({ Flag = "powerNoise", Title = "Power noise (%)", Step = 0.5, Value = { Min = 0, Max = 15, Default = 0 }, Callback = function(v) S.powerNoise = v end })
    T:Slider({ Flag = "missChance", Title = "Intentional miss (%)", Step = 1, Value = { Min = 0, Max = 50, Default = 0 }, Callback = function(v) S.missChance = v end })
end

do
    local T = Window:Tab({ Title = "Lines", Icon = "eye", IconColor = Purple, IconShape = "Square" })
    T:Section({ Title = "Table guides" })
    T:Toggle({ Flag = "showPlan", Title = "Show suggested shot (T)", Desc = "Cue ball -> contact, object ball, bounce and pocket.", Default = true, Callback = function(v) S.showPlan = v end })
    T:Toggle({ Flag = "showAim", Title = "Show my current aim", Desc = "What would happen if you shot where the cue points right now.", Default = false, Callback = function(v) S.showAim = v end })
    T:Slider({ Flag = "thickness", Title = "Thickness", Step = 0.01, Value = { Min = 0.03, Max = 0.3, Default = S.thickness }, Callback = function(v) S.thickness = v end })
    T:Colorpicker({ Flag = "planColor", Title = "Suggested shot color", Default = S.planColor, Callback = function(c) S.planColor = c end })
    T:Colorpicker({ Flag = "aimColor", Title = "My aim color", Default = S.aimColor, Callback = function(c) S.aimColor = c end })
    T:Toggle({ Flag = "notify", Title = "Notifications", Default = true, Callback = function(v) S.notify = v end })
end

do
    local T = Window:Tab({ Title = "Settings", Icon = "settings", IconColor = Grey, IconShape = "Square" })
    T:Section({ Title = "Hotkeys" })
    T:Keybind({ Flag = "keyToggle", Title = "Toggle aimbot", Value = "RightShift", Callback = function(v) KEYS.toggle = keyName(v) end })
    T:Keybind({ Flag = "keyReplan", Title = "Replan", Value = "R", Callback = function(v) KEYS.replan = keyName(v) end })
    T:Keybind({ Flag = "keyLines", Title = "Show / hide lines", Value = "T", Callback = function(v) KEYS.lines = keyName(v) end })
    T:Keybind({ Flag = "keyUi", Title = "Open / close this window", Value = "RightAlt", Callback = function(v) pcall(function() Window:SetToggleKey(Enum.KeyCode[keyName(v)]) end) end })
    T:Space()
    T:Section({ Title = "Configuration" })

    local ConfigManager = Window.ConfigManager
    local cfgName = "default"
    T:Input({ Title = "Configuration name", Icon = "file-cog", Value = "default", Callback = function(v) cfgName = v end })
    T:Space()
    T:Button({
        Title = "Save configuration", Justify = "Center", Icon = "",
        Callback = function()
            local ok, err = pcall(function()
                Window.CurrentConfig = ConfigManager:Config(cfgName)
                Window.CurrentConfig:Save()
            end)
            note("Config", ok and ("Saved: " .. cfgName) or ("Error: " .. tostring(err)))
        end,
    })
    T:Space()
    T:Button({
        Title = "Load configuration", Justify = "Center", Icon = "",
        Callback = function()
            local ok, err = pcall(function()
                Window.CurrentConfig = ConfigManager:CreateConfig(cfgName)
                Window.CurrentConfig:Load()
            end)
            note("Config", ok and ("Loaded: " .. cfgName) or ("Error: " .. tostring(err)))
        end,
    })
    T:Space()
    T:Button({ Title = "Unload hub (removes everything)", Color = Color3.fromHex("#ff4830"), Justify = "Center", Icon = "shredder", Callback = function() H.destroy() end })
end

log("Hub loaded. Open the UI with the green button. Aimbot DISABLED by default.")
return "8Ball Hub loaded"

Similar Scripts

Da Hood Script 117 Hub: Camlock, Auto Kill

No Key • 5 hours ago

Slap Battles Script FriedPotato Hub: Slap Aura, Reach

Key System • 5 hours ago

Ant Evolution Script Spiritual Gaming: Auto Evolve, Orbs

Key System • 5 hours ago

Jujutsu Farm Script Starlink: Auto Farm, Auto Roll

No Key • 5 hours ago

Steal A Dumpling Script Spiritual Gaming: Auto Steal, Sell

Key System • 5 hours ago