--[[ WARNING: Heads up! This script has not been verified by ScriptBlox. Use at your own risk! ]] --[[ BearAI.client.lua ----------------- A fair-play "player brain" for YOUR OWN copy of a Bear-style survival game. WHERE IT GOES: StarterPlayer > StarterPlayerScripts (make it a LocalScript) TOGGLE: press CONFIG.ToggleKey (default P) or click the status box in the corner. TIP: turn Workspace.StreamingEnabled OFF so the AI can see the whole map. DELTA COMPATIBILITY NOTES: - ProximityPrompt interaction uses fireproximityprompt (Delta) as the primary method, then falls back to InputHoldBegin/End, then to a manual wait. - Pathfinding falls back to direct Humanoid:MoveTo if PathfindingService is blocked, but still tries ring points around unreachable goals when the service works but reports NoPath. - Character is fully loaded before the AI starts. ]] if not game:IsLoaded() then game.Loaded:Wait() end local Players = game:GetService("Players") local Workspace = game:GetService("Workspace") local PathfindingService = game:GetService("PathfindingService") local CollectionService = game:GetService("CollectionService") local UserInputService = game:GetService("UserInputService") local player = Players.LocalPlayer --============================================================================== -- CONFIG --============================================================================== local CONFIG = { StartEnabled = true, ToggleKey = Enum.KeyCode.P, ShowHud = true, ShowPath = true, IsActive = nil, SetSprint = nil, BearNames = { "Bear" }, BearTag = "Bear", BearTeamNames = { "Bear" }, IsBear = nil, PuzzleNames = {}, PuzzleTag = "Puzzle", HideSpotTag = "HideSpot", ExitTag = "Exit", PriorityWords = { "key", "fuse", "battery", "gear", "pick", "take", "grab", "collect", "code", "lever", "button", "switch", "generator", "power", "fix", "repair", "unlock", "insert", "place" }, ExitWords = { "exit", "escape", "finish", "leave" }, HideWords = { "hide", "hiding", "locker", "closet", "wardrobe" }, IgnoreWords = { "shop", "buy", "purchase", "robux", "gamepass", "skin", "vip", "settings", "spectate", "redeem" }, SightDistance = 90, HearDistance = 38, MemorySeconds = 7, AssumedBearSpeed = 18, PanicDistance = 16, DangerSeconds = 2.6, DangerHoldSeconds = 1.2, ObjectiveClearance = 30, SafetyMarginSeconds = 1.5, FleeCommitSeconds = 0.9, HideMaxApproach = 40, HideMaxSeconds = 18, HideClearSeconds = 3.5, RetryCooldown = 5, MaxAttempts = 4, CustomSolvers = {}, IsSolved = nil, } --============================================================================== -- STATE --============================================================================== local character, humanoid, root local enabled = CONFIG.StartEnabled local plan, planToken = nil, 0 local memory = { done = {}, attempts = {}, cool = {} } local threat = { level = "safe", dist = math.huge, ttc = math.huge, los = false } local lastSeenPos, lastSeenTime, lastSeenBear, lastDangerTime = nil, 0, nil, -100 local tracks, warned = {}, {} local sprinting = false local prompts, tools, bears, namedPuzzles, teamBears = {}, {}, {}, {}, {} local classCache = setmetatable({}, { __mode = "k" }) local AGENT = { AgentRadius = 2, AgentHeight = 5, AgentCanJump = true, WaypointSpacing = 4 } local function alive() return humanoid ~= nil and root ~= nil and humanoid.Health > 0 and root.Parent ~= nil end local function isCurrent(token) return enabled and token == planToken and alive() end local function warnOnce(key, message) if warned[key] then return end warned[key] = true warn("[BearAI] " .. message) end local function setSprint(on) if sprinting == on then return end sprinting = on if CONFIG.SetSprint then pcall(CONFIG.SetSprint, on) end end --============================================================================== -- HELPERS --============================================================================== local function lower(s) return string.lower(tostring(s or "")) end local function hasWord(text, list) text = lower(text) for _, word in ipairs(list) do if string.find(text, lower(word), 1, true) then return true end end return false end local function flat(v) return Vector3.new(v.X, 0, v.Z) end local function positionOf(inst) if not inst then return nil end if inst:IsA("BasePart") then return inst.Position end if inst:IsA("Attachment") then return inst.WorldPosition end if inst:IsA("Model") then return inst:GetPivot().Position end if inst:IsA("ProximityPrompt") then return positionOf(inst.Parent) end return nil end local function taggedUp(inst, tag) local cur = inst while cur and cur ~= Workspace do if CollectionService:HasTag(cur, tag) then return true end cur = cur.Parent end return false end local function textOf(prompt) local parts = { prompt.ActionText, prompt.ObjectText } local cur = prompt.Parent for _ = 1, 4 do if not cur or cur == Workspace then break end table.insert(parts, cur.Name) cur = cur.Parent end return table.concat(parts, " ") end local function insideCharacter(inst) local cur = inst.Parent while cur and cur ~= Workspace do if cur:IsA("Model") and cur:FindFirstChildOfClass("Humanoid") then return true end cur = cur.Parent end return false end local rayParams = RaycastParams.new() rayParams.FilterType = Enum.RaycastFilterType.Exclude rayParams.RespectCanCollide = true rayParams.IgnoreWater = true local function ignoreList() local list = { character } if lastSeenBear and lastSeenBear.Parent then table.insert(list, lastSeenBear) end return list end local function castRay(from, to, ignore) rayParams.FilterDescendantsInstances = ignore or ignoreList() return Workspace:Raycast(from, to - from, rayParams) end local function clearLine(from, to, ignore) return castRay(from, to, ignore) == nil end --============================================================================== -- WORLD REGISTRY --============================================================================== local function isBearModel(model) if model == character then return false end if CollectionService:HasTag(model, CONFIG.BearTag) then return true end if CONFIG.IsBear then local ok, res = pcall(CONFIG.IsBear, model) if ok and res then return true end end if Players:GetPlayerFromCharacter(model) then return false end local lname = lower(model.Name) for _, name in ipairs(CONFIG.BearNames) do if lname == lower(name) then return true end end return string.find(lname, "bear", 1, true) ~= nil and model:FindFirstChildOfClass("Humanoid") ~= nil end local hasNamedPuzzles = #CONFIG.PuzzleNames > 0 local puzzleNameSet = {} for _, name in ipairs(CONFIG.PuzzleNames) do puzzleNameSet[lower(name)] = true end local function register(inst) if inst:IsA("ProximityPrompt") then prompts[inst] = true elseif inst:IsA("Tool") then tools[inst] = true elseif inst:IsA("Model") then if hasNamedPuzzles and puzzleNameSet[lower(inst.Name)] then namedPuzzles[inst] = true end task.defer(function() if inst.Parent and isBearModel(inst) then bears[inst] = true end end) elseif hasNamedPuzzles and inst:IsA("BasePart") and puzzleNameSet[lower(inst.Name)] then namedPuzzles[inst] = true end end local function unregister(inst) prompts[inst] = nil tools[inst] = nil bears[inst] = nil namedPuzzles[inst] = nil end local function refreshPlayerBears() for model in pairs(teamBears) do bears[model] = nil end teamBears = {} for _, other in ipairs(Players:GetPlayers()) do local char = other.Character if other ~= player and char then local isBear = isBearModel(char) if not isBear and other.Team then local teamName = lower(other.Team.Name) for _, name in ipairs(CONFIG.BearTeamNames) do if teamName == lower(name) then isBear = true end end end if isBear then bears[char] = true teamBears[char] = true end end end end local function resetMemory() memory.done, memory.attempts, memory.cool = {}, {}, {} tracks, warned = {}, {} lastSeenPos, lastSeenTime, lastSeenBear, lastDangerTime = nil, 0, nil, -100 threat = { level = "safe", dist = math.huge, ttc = math.huge, los = false } end --============================================================================== -- PERCEPTION --============================================================================== local function bearRootOf(bear) return bear:FindFirstChild("HumanoidRootPart") or bear.PrimaryPart or bear:FindFirstChildWhichIsA("BasePart", true) end local function knownBearPos() if threat.pos then return threat.pos end if lastSeenPos and os.clock() - lastSeenTime <= CONFIG.MemorySeconds then return lastSeenPos end return nil end local function perceive() local now = os.clock() local myPos = root.Position local best = { level = "safe", dist = math.huge, ttc = math.huge, los = false } for bear in pairs(bears) do local br = bear.Parent and bearRootOf(bear) if br then local bpos = br.Position local vel = Vector3.new(0, 0, 0) local track = tracks[bear] if track then local dt = now - track.t if dt >= 0.05 then vel = track.vel:Lerp((bpos - track.pos) / dt, 0.5) track.pos, track.t, track.vel = bpos, now, vel else vel = track.vel end else tracks[bear] = { pos = bpos, t = now, vel = vel } end local flatVel = flat(vel) local toMe = myPos - bpos local dist = toMe.Magnitude local closing = dist > 0.1 and flatVel:Dot(toMe / dist) or 0 local ttc = dist / math.max(flatVel.Magnitude, CONFIG.AssumedBearSpeed) local sees = dist <= CONFIG.SightDistance and clearLine(bpos + Vector3.new(0, 2, 0), myPos + Vector3.new(0, 1.5, 0), { character, bear }) local heard = dist <= CONFIG.HearDistance if sees or heard then lastSeenPos, lastSeenTime, lastSeenBear = bpos, now, bear local level = "alert" if dist <= CONFIG.PanicDistance or (sees and ttc <= CONFIG.DangerSeconds) or ((not sees) and closing > 4 and ttc <= CONFIG.DangerSeconds * 0.6) then level = "danger" end local better = best.level == "safe" or (level == "danger" and best.level == "alert") or (level == best.level and ttc < best.ttc) if better then best = { level = level, dist = dist, ttc = ttc, los = sees, pos = bpos, bear = bear } end end end end if best.level == "danger" then lastDangerTime = now elseif best.level == "alert" and now - lastDangerTime < CONFIG.DangerHoldSeconds then best.level = "danger" end threat = best end local function safeToPursue(pos) local b = knownBearPos() if not b then return true end local bearDist = (pos - b).Magnitude if bearDist < CONFIG.ObjectiveClearance then return false end local myDist = (pos - root.Position).Magnitude local tBear = bearDist / CONFIG.AssumedBearSpeed local tMe = myDist / math.max(humanoid.WalkSpeed, 1) return tBear > tMe + CONFIG.SafetyMarginSeconds end --============================================================================== -- ESCAPE TACTICS --============================================================================== local function openness(point) local free = 0 for i = 0, 7 do local a = i * math.pi / 4 local from = point + Vector3.new(0, 2, 0) local to = from + Vector3.new(math.cos(a) * 12, 0, math.sin(a) * 12) if not castRay(from, to) then free = free + 1 end end return free end local function pickFleePoint(sneak) local origin = root.Position local backwards = -flat(root.CFrame.LookVector) local bpos = knownBearPos() or (origin + backwards * -20) local toBear = flat(bpos - origin) local toBearDir = toBear.Magnitude > 0.1 and toBear.Unit or backwards local mySpeed = math.max(humanoid.WalkSpeed, 1) local bearSpeed = CONFIG.AssumedBearSpeed local radii = sneak and { 8, 14, 20 } or { 16, 26, 38 } local eye = Vector3.new(0, 2, 0) local best, bestScore for i = 0, 15 do local a = i / 16 * math.pi * 2 local dir = Vector3.new(math.cos(a), 0, math.sin(a)) local toward = math.max(0, dir:Dot(toBearDir)) for _, r in ipairs(radii) do local probe = origin + dir * r local hit = castRay(probe + Vector3.new(0, 25, 0), probe + Vector3.new(0, -35, 0)) if hit and math.abs(hit.Position.Y - origin.Y) < 14 then local cand = hit.Position local wallBetween = castRay(origin + eye, cand + eye) ~= nil local margin = math.clamp((cand - bpos).Magnitude / bearSpeed - (cand - origin).Magnitude / mySpeed, -4, 6) local hidden = not clearLine(bpos + eye, cand + eye) local score = margin * 10 + (hidden and 25 or 0) + (wallBetween and -25 or 15) + openness(cand) * 4 - toward * 30 if not best or score > bestScore then best, bestScore = cand, score end end end end return best end local function fleeStillGood(p) local b = knownBearPos() if not b or not p.dest then return true end local myD = (p.dest - root.Position).Magnitude if myD < 6 then return false end local bearT = (p.dest - b).Magnitude / CONFIG.AssumedBearSpeed local meT = myD / math.max(humanoid.WalkSpeed, 1) return bearT - meT > 0.8 end --============================================================================== -- MOVEMENT --============================================================================== local pathFolder, pathOwner = nil, nil local function clearPath(token) if pathFolder and (token == nil or pathOwner == token) then pathFolder:ClearAllChildren() end end local function drawPath(waypoints, token) if not CONFIG.ShowPath then return end if not pathFolder then pathFolder = Instance.new("Folder") pathFolder.Name = "BearAI_Path" pathFolder.Parent = Workspace end pathOwner = token pathFolder:ClearAllChildren() for _, wp in ipairs(waypoints) do local dot = Instance.new("Part") dot.Shape = Enum.PartType.Ball dot.Size = Vector3.new(0.7, 0.7, 0.7) dot.Position = wp.Position + Vector3.new(0, 0.5, 0) dot.Anchored = true dot.CanCollide = false dot.CanQuery = false dot.CanTouch = false dot.Material = Enum.Material.Neon dot.Color = wp.Action == Enum.PathWaypointAction.Jump and Color3.fromRGB(255, 200, 0) or Color3.fromRGB(0, 200, 255) dot.Parent = pathFolder end end local function ringPoints(center, radius) local points = {} for i = 0, 7 do local a = i * math.pi / 4 local probe = center + Vector3.new(math.cos(a) * radius, 0, math.sin(a) * radius) local hit = castRay(probe + Vector3.new(0, 8, 0), probe + Vector3.new(0, -24, 0)) if hit then table.insert(points, hit.Position) end end local me = root.Position table.sort(points, function(p, q) return (p - me).Magnitude < (q - me).Magnitude end) return points end local function followOnce(goal, target, token, opts) local path = PathfindingService:CreatePath(AGENT) local ok = pcall(function() path:ComputeAsync(root.Position, goal) end) if not isCurrent(token) then return "cancelled" end -- FIX: distinguish "service broken" (direct fallback) from "no path to goal" (try ring points) if not ok then return "direct" end if path.Status ~= Enum.PathStatus.Success then return "nopath" end local waypoints = path:GetWaypoints() drawPath(waypoints, token) local blockedAt = nil local blockedConn = path.Blocked:Connect(function(index) blockedAt = index end) local result = "arrived" for i = 2, #waypoints do local wp = waypoints[i] if wp.Action == Enum.PathWaypointAction.Jump then humanoid.Jump = true end humanoid:MoveTo(wp.Position) local lastDist, lastProgress, jumped = math.huge, os.clock(), false local closeEnough = false while true do if not isCurrent(token) then result = "cancelled"; break end local pos = root.Position if opts.stopWithin and (pos - target).Magnitude <= opts.stopWithin then closeEnough = true; break end if blockedAt and blockedAt >= i then result = "replan"; break end local d = (flat(pos) - flat(wp.Position)).Magnitude if d <= 2.5 then break end local now = os.clock() if d < lastDist - 0.4 then lastDist, lastProgress = d, now end if now - lastProgress > 1.4 then if jumped then result = "stuck"; break end jumped = true lastProgress = now humanoid.Jump = true humanoid:MoveTo(wp.Position) end task.wait(0.05) end if closeEnough or result ~= "arrived" then break end end blockedConn:Disconnect() clearPath(token) return result end local function goTo(target, token, opts) opts = opts or {} local deadline = os.clock() + (opts.maxTime or 25) local goals, gi, tries = { target }, 1, 0 while isCurrent(token) and os.clock() < deadline and tries < 14 do tries = tries + 1 if opts.stopWithin and (root.Position - target).Magnitude <= opts.stopWithin then return "arrived" end local r = followOnce(goals[gi], target, token, opts) if r == "arrived" or r == "cancelled" then return r end if r == "direct" then humanoid:MoveTo(goals[gi]) local start = os.clock() while isCurrent(token) and os.clock() - start < (opts.maxTime or 25) do if opts.stopWithin and (root.Position - target).Magnitude <= opts.stopWithin then return "arrived" end if (flat(root.Position) - flat(goals[gi])).Magnitude <= 2.5 then return "arrived" end task.wait(0.1) end if not isCurrent(token) then return "cancelled" end return "failed" end if r == "nopath" then if #goals == 1 then for _, p in ipairs(ringPoints(target, 4)) do table.insert(goals, p) end end gi = gi + 1 if gi > #goals then return "nopath" end end task.wait(0.05) end if not isCurrent(token) then return "cancelled" end return "failed" end --============================================================================== -- INTERACTION --============================================================================== local function inventoryCount() local n = 0 local backpack = player:FindFirstChildOfClass("Backpack") if backpack then for _, item in ipairs(backpack:GetChildren()) do if item:IsA("Tool") then n = n + 1 end end end for _, item in ipairs(character:GetChildren()) do if item:IsA("Tool") then n = n + 1 end end return n end local function uiSignature() local gui = player:FindFirstChildOfClass("PlayerGui") if not gui then return "" end local names = {} for _, g in ipairs(gui:GetChildren()) do if g:IsA("ScreenGui") and g.Enabled and g.Name ~= "BearAI_HUD" then local visible = 0 for _, child in ipairs(g:GetChildren()) do if child:IsA("GuiObject") and child.Visible then visible = visible + 1 end end table.insert(names, g.Name .. ":" .. visible) end end table.sort(names) return table.concat(names, ",") end local function snapshot(prompt) return { enabled = prompt.Enabled, action = prompt.ActionText, object = prompt.ObjectText, items = inventoryCount(), } end local function promptChanged(prompt, before) if not prompt:IsDescendantOf(Workspace) then return true end return prompt.Enabled ~= before.enabled or prompt.ActionText ~= before.action or prompt.ObjectText ~= before.object or inventoryCount() ~= before.items end -- Delta-compatible prompt interaction local function holdPrompt(prompt, token) if not isCurrent(token) then return false end -- 1. fireproximityprompt (Delta) if fireproximityprompt then local ok = pcall(fireproximityprompt, prompt) if ok then task.wait(0.1) return isCurrent(token) end end -- 2. Native InputHoldBegin/End local ok = pcall(function() prompt:InputHoldBegin() end) if ok then local started, needed = os.clock(), prompt.HoldDuration + 0.2 while os.clock() - started < needed and isCurrent(token) do task.wait(0.05) end pcall(function() prompt:InputHoldEnd() end) return isCurrent(token) end -- 3. Manual wait (some executors block InputHoldBegin) if isCurrent(token) then task.wait(prompt.HoldDuration + 0.2) pcall(function() prompt:InputHoldEnd() end) return isCurrent(token) end return false end local function equipMatchingTool(prompt, attempts) local list = {} local backpack = player:FindFirstChildOfClass("Backpack") if backpack then for _, item in ipairs(backpack:GetChildren()) do if item:IsA("Tool") then table.insert(list, item) end end end for _, item in ipairs(character:GetChildren()) do if item:IsA("Tool") then table.insert(list, item) end end if #list == 0 then return end local text = lower(textOf(prompt)) for _, tool in ipairs(list) do if #tool.Name > 0 and string.find(text, lower(tool.Name), 1, true) then humanoid:EquipTool(tool) return end end if attempts >= 2 then humanoid:EquipTool(list[(attempts - 2) % #list + 1]) end end local function usePrompt(obj, token, attempts) local prompt = obj.prompt local pos = positionOf(prompt.Parent) or obj.pos local within = math.max(math.clamp(prompt.MaxActivationDistance * 0.55, 2.5, 7) / attempts, 2) local res = goTo(pos, token, { stopWithin = within, maxTime = 30 }) if res ~= "arrived" then return res end equipMatchingTool(prompt, attempts) local before, uiBefore = snapshot(prompt), uiSignature() if not holdPrompt(prompt, token) then return "cancelled" end local started = os.clock() while isCurrent(token) and os.clock() - started < 1.2 do if promptChanged(prompt, before) then return "done" end task.wait(0.1) end if not isCurrent(token) then return "cancelled" end if uiSignature() ~= uiBefore then return "ui" end return "nochange" end --============================================================================== -- OBJECTIVES --============================================================================== local function classify(prompt) local c = classCache[prompt] if c then return c.kind, c.bonus end local text = textOf(prompt) local kind = "task" if insideCharacter(prompt) or hasWord(text, CONFIG.IgnoreWords) then kind = "ignore" elseif taggedUp(prompt, CONFIG.HideSpotTag) or hasWord(text, CONFIG.HideWords) then kind = "hide" elseif hasWord(text, CONFIG.ExitWords) then kind = "exit" end local bonus = hasWord(text, CONFIG.PriorityWords) and 1 or 0 classCache[prompt] = { kind = kind, bonus = bonus } return kind, bonus end local function isLooseTool(tool) return tool:IsDescendantOf(Workspace) and not insideCharacter(tool) end local function isSolved(inst) if inst:GetAttribute("Solved") == true or inst:GetAttribute("Completed") == true or inst:GetAttribute("Done") == true then return true end if CONFIG.IsSolved then local ok, res = pcall(CONFIG.IsSolved, inst) return ok and res == true end return false end local function chooseObjective() local now = os.clock() local me = root.Position local tasks, exits = {}, {} local explicit, scoped = {}, false for _, inst in ipairs(CollectionService:GetTagged(CONFIG.PuzzleTag)) do if inst:IsDescendantOf(Workspace) then explicit[inst] = true end end for inst in pairs(namedPuzzles) do if inst:IsDescendantOf(Workspace) then explicit[inst] = true end end local function add(list, obj) if memory.done[obj.key] or (memory.attempts[obj.key] or 0) >= CONFIG.MaxAttempts then return end table.insert(list, obj) end for inst in pairs(explicit) do scoped = true local pos = positionOf(inst) if pos and not isSolved(inst) then add(tasks, { key = inst, inst = inst, prompt = inst:FindFirstChildWhichIsA("ProximityPrompt", true), pos = pos, bonus = 1, }) end end -- FIX: check IsDescendantOf before .Enabled (safer for destroyed prompts) for prompt in pairs(prompts) do if prompt:IsDescendantOf(Workspace) and prompt.Enabled then local kind, bonus = classify(prompt) local pos = positionOf(prompt.Parent) if pos then if kind == "task" and not scoped then add(tasks, { key = prompt, inst = prompt.Parent, prompt = prompt, pos = pos, bonus = bonus }) elseif kind == "exit" then add(exits, { key = prompt, inst = prompt.Parent, prompt = prompt, pos = pos, bonus = 0, exit = true }) end end end end for tool in pairs(tools) do if isLooseTool(tool) then local handle = tool:FindFirstChild("Handle") if handle then add(tasks, { key = tool, inst = tool, pos = handle.Position, bonus = 2, pickup = true }) end end end for _, part in ipairs(CollectionService:GetTagged(CONFIG.ExitTag)) do local pos = part:IsDescendantOf(Workspace) and positionOf(part) if pos then add(exits, { key = part, inst = part, pos = pos, bonus = 0, exit = true, touch = true }) end end local function pick(list) local best, bestScore for _, obj in ipairs(list) do if (memory.cool[obj.key] or 0) <= now and safeToPursue(obj.pos) then local score = obj.bonus * 25 - (obj.pos - me).Magnitude if plan and plan.obj and plan.obj.key == obj.key and not plan.finished then score = score + 30 end if not bestScore or score > bestScore then best, bestScore = obj, score end end end return best end local best = pick(tasks) if best then return best end if #tasks > 0 then return nil end return pick(exits) end local function bestHideSpot() local now = os.clock() local b = knownBearPos() local me = root.Position local best, bestDist for prompt in pairs(prompts) do -- FIX: check IsDescendantOf first if prompt:IsDescendantOf(Workspace) and prompt.Enabled and (memory.cool[prompt] or 0) <= now and classify(prompt) == "hide" then local pos = positionOf(prompt.Parent) if pos then local myDist = (pos - me).Magnitude if myDist <= CONFIG.HideMaxApproach and (not b or (pos - b).Magnitude > myDist * 1.3 + 8) then if not bestDist or myDist < bestDist then best, bestDist = prompt, myDist end end end end end return best end --============================================================================== -- BEHAVIOURS --============================================================================== local function findSolver(obj) local cur = obj.inst while cur and cur ~= Workspace do local solver = CONFIG.CustomSolvers[cur.Name] if solver then return solver end cur = cur.Parent end return nil end local function makeContext(obj, token) local ctx = { player = player, character = character, humanoid = humanoid, root = root, instance = obj.inst, prompt = obj.prompt, position = obj.pos, } function ctx.alive() return isCurrent(token) end function ctx.walkTo(pos, within) return goTo(pos, token, { stopWithin = within or 4, maxTime = 30 }) end function ctx.pressPrompt(p) p = p or obj.prompt if not p then return false end return holdPrompt(p, token) end return ctx end local function runPickup(obj, token, attempts) local tool = obj.inst local handle = tool:FindFirstChild("Handle") if not handle then memory.attempts[tool] = CONFIG.MaxAttempts return end local before = inventoryCount() local res = goTo(handle.Position, token, { stopWithin = 2.5, maxTime = 25 }) if res == "cancelled" then return end if res == "arrived" then humanoid:MoveTo(handle.Position) local started = os.clock() while isCurrent(token) and os.clock() - started < 1.5 do if inventoryCount() ~= before or not tool:IsDescendantOf(Workspace) then memory.done[tool] = true return end task.wait(0.1) end end if isCurrent(token) then memory.attempts[tool] = attempts memory.cool[tool] = os.clock() + CONFIG.RetryCooldown * attempts end end local function runObjective(p, token) local obj = p.obj local attempts = (memory.attempts[obj.key] or 0) + 1 if obj.touch then goTo(obj.pos, token, { stopWithin = 3, maxTime = 30 }) if isCurrent(token) then task.wait(1) end return end if obj.pickup then runPickup(obj, token, attempts) return end local solver = findSolver(obj) if solver then local ok, result = pcall(solver, makeContext(obj, token)) if not isCurrent(token) then return end if ok and result then memory.done[obj.key] = true else if not ok then warn("[BearAI] solver for '" .. obj.inst.Name .. "' errored: " .. tostring(result)) end memory.attempts[obj.key] = attempts memory.cool[obj.key] = os.clock() + CONFIG.RetryCooldown * attempts end return end if not obj.prompt then warnOnce(obj.key, "'" .. obj.inst.Name .. "' has no ProximityPrompt and no CustomSolver yet, so the AI can't finish it.") memory.attempts[obj.key] = CONFIG.MaxAttempts return end local result = usePrompt(obj, token, attempts) if result == "done" then memory.done[obj.key] = true elseif result == "ui" then warnOnce(obj.key, "'" .. obj.inst.Name .. "' opened a UI (probably a minigame puzzle). Add a CustomSolver named '" .. obj.inst.Name .. "' to finish it.") memory.attempts[obj.key] = CONFIG.MaxAttempts elseif result ~= "cancelled" then memory.attempts[obj.key] = attempts memory.cool[obj.key] = os.clock() + CONFIG.RetryCooldown * attempts end end local function runHide(p, token) local prompt = p.target local pos = positionOf(prompt.Parent) if not pos or goTo(pos, token, { stopWithin = 4, maxTime = 8 }) ~= "arrived" then memory.cool[prompt] = os.clock() + 6 return end holdPrompt(prompt, token) local started, calmSince = os.clock(), nil while isCurrent(token) and os.clock() - started < CONFIG.HideMaxSeconds do if threat.level == "safe" then calmSince = calmSince or os.clock() if os.clock() - calmSince >= CONFIG.HideClearSeconds then break end else calmSince = nil end task.wait(0.2) end if isCurrent(token) and prompt.Enabled then holdPrompt(prompt, token) end memory.cool[prompt] = os.clock() + 4 end local function runPlan(p, token) if p.kind == "Flee" then setSprint(p.mode == "run") goTo(p.dest, token, { maxTime = 3.5 }) elseif p.kind == "Hide" then setSprint(true) runHide(p, token) setSprint(false) elseif p.kind == "Objective" then setSprint(false) runObjective(p, token) end end --============================================================================== -- THE BRAIN --============================================================================== local function decide() local now = os.clock() if plan and not plan.finished and (plan.kind == "Hide" or plan.kind == "Flee") and now < (plan.commitUntil or 0) then return plan end if threat.level == "danger" then if plan and not plan.finished and plan.kind == "Flee" and plan.mode == "run" and fleeStillGood(plan) then return plan end local spot = bestHideSpot() if spot then return { kind = "Hide", target = spot, commitUntil = now + CONFIG.HideMaxSeconds + 4 } end local dest = pickFleePoint(false) if dest then return { kind = "Flee", mode = "run", dest = dest, commitUntil = now + CONFIG.FleeCommitSeconds } end return nil end local obj = chooseObjective() if obj then return { kind = "Objective", target = obj.key, obj = obj } end if threat.level == "alert" and threat.los then if plan and not plan.finished and plan.kind == "Flee" and plan.mode == "sneak" and fleeStillGood(plan) then return plan end local dest = pickFleePoint(true) if dest then return { kind = "Flee", mode = "sneak", dest = dest, commitUntil = now + 0.6 } end end return nil end local function setPlan(newPlan) planToken = planToken + 1 local token = planToken if plan then plan.finished = true end plan = newPlan if not newPlan then setSprint(false) if alive() then humanoid:MoveTo(root.Position) end return end task.spawn(function() local ok, err = pcall(runPlan, newPlan, token) if not ok then warn("[BearAI] " .. tostring(err)) end if planToken == token then newPlan.finished = true plan = nil end end) end local function think() perceive() local want = decide() if want == plan then return end if want == nil and plan == nil then setSprint(false) return end if want and plan and not plan.finished and want.kind == plan.kind and want.target ~= nil and want.target == plan.target then return end setPlan(want) end local function setEnabled(on) enabled = on planToken = planToken + 1 if plan then plan.finished = true end plan = nil setSprint(false) clearPath(nil) if alive() then humanoid:MoveTo(root.Position) end end local function activeNow() if not enabled or not alive() then return false end if CONFIG.IsActive then local ok, res = pcall(CONFIG.IsActive) return ok and res == true end return true end --============================================================================== -- STATUS BOX --============================================================================== local hud local function buildHud() if not CONFIG.ShowHud then return end local gui = Instance.new("ScreenGui") gui.Name = "BearAI_HUD" gui.ResetOnSpawn = false hud = Instance.new("TextButton") hud.Size = UDim2.fromOffset(300, 84) hud.Position = UDim2.fromOffset(12, 60) hud.BackgroundColor3 = Color3.fromRGB(18, 18, 24) hud.BackgroundTransparency = 0.25 hud.AutoButtonColor = false hud.TextColor3 = Color3.new(1, 1, 1) hud.Font = Enum.Font.GothamMedium hud.TextSize = 14 hud.TextXAlignment = Enum.TextXAlignment.Left hud.TextYAlignment = Enum.TextYAlignment.Top hud.TextWrapped = true hud.Text = "" local pad = Instance.new("UIPadding") pad.PaddingLeft = UDim.new(0, 10) pad.PaddingTop = UDim.new(0, 8) pad.Parent = hud local corner = Instance.new("UICorner") corner.CornerRadius = UDim.new(0, 8) corner.Parent = hud hud.MouseButton1Click:Connect(function() setEnabled(not enabled) end) hud.Parent = gui gui.Parent = player:WaitForChild("PlayerGui") end local function updateHud() if not hud then return end if not enabled then hud.Text = "Bear AI: OFF\n(" .. CONFIG.ToggleKey.Name .. " or click to turn on)" return end local doneCount = 0 for _ in pairs(memory.done) do doneCount = doneCount + 1 end local doing = "idle" if plan then doing = plan.kind if plan.obj then doing = doing .. ": " .. plan.obj.inst.Name elseif plan.mode then doing = doing .. " (" .. plan.mode .. ")" end end local bearText = threat.level if threat.dist < math.huge then bearText = bearText .. string.format(" (%.0f studs)", threat.dist) end hud.Text = string.format("Bear AI: ON (%s toggles)\nDoing: %s\nBear: %s\nTasks done: %d", CONFIG.ToggleKey.Name, doing, bearText, doneCount) end --============================================================================== -- START UP --============================================================================== local function bindCharacter(char) -- FIX: guard against double-binding the same character if char == character then return end local hum = char:WaitForChild("Humanoid") local hrp = char:WaitForChild("HumanoidRootPart") character, humanoid, root = char, hum, hrp resetMemory() planToken = planToken + 1 plan = nil setSprint(false) hum.Died:Connect(function() planToken = planToken + 1 plan = nil setSprint(false) end) end -- Ensure character is fully loaded before the AI starts task.spawn(function() while not player.Character do task.wait(0.5) end bindCharacter(player.Character) end) player.CharacterAdded:Connect(bindCharacter) buildHud() for _, inst in ipairs(Workspace:GetDescendants()) do register(inst) end Workspace.DescendantAdded:Connect(register) Workspace.DescendantRemoving:Connect(unregister) for _, inst in ipairs(CollectionService:GetTagged(CONFIG.BearTag)) do if inst:IsA("Model") then bears[inst] = true end end CollectionService:GetInstanceAddedSignal(CONFIG.BearTag):Connect(function(inst) if inst:IsA("Model") then bears[inst] = true end end) task.spawn(function() while true do refreshPlayerBears() task.wait(1) end end) UserInputService.InputBegan:Connect(function(input, processed) if not processed and input.KeyCode == CONFIG.ToggleKey then setEnabled(not enabled) end end) task.spawn(function() while true do task.wait(0.15) if activeNow() then local ok, err = pcall(think) if not ok then warn("[BearAI] " .. tostring(err)) end elseif plan then setPlan(nil) end updateHud() end end)