-- Services local Players = game:GetService("Players") local Workspace = game:GetService("Workspace") local TweenService = game:GetService("TweenService") local RunService = game:GetService("RunService") -- PlaceId check local TARGET_PLACE_ID = 7871169780 if game.PlaceId ~= TARGET_PLACE_ID then warn(string.format("[Minesweeper Script] Wrong PlaceId (%s). Expected %s.", tostring(game.PlaceId), tostring(TARGET_PLACE_ID))) return end local player = Players.LocalPlayer or Players.PlayerAdded:Wait() -- Determine GUI parent local guiParent if type(gethui) == "function" then guiParent = gethui() else local success = pcall(function() return game:GetService("CoreGui").Name end) if success then guiParent = game:GetService("CoreGui") else guiParent = player:WaitForChild("PlayerGui") end end -- Create ScreenGui local screenGui = Instance.new("ScreenGui") screenGui.Name = "Gui_" .. math.random(10000, 99999) screenGui.ResetOnSpawn = false screenGui.DisplayOrder = 2147483647 screenGui.IgnoreGuiInset = true screenGui.ZIndexBehavior = Enum.ZIndexBehavior.Global screenGui.Parent = guiParent -- Main draggable frame (fixed 200x100) local mainFrame = Instance.new("Frame") mainFrame.Parent = screenGui mainFrame.BackgroundColor3 = Color3.fromRGB(45, 45, 45) mainFrame.Size = UDim2.new(0, 200, 0, 100) mainFrame.Position = UDim2.new(0.3, 0, 0.5, -50) mainFrame.Active = true mainFrame.BorderSizePixel = 0 local status = Instance.new("TextLabel") status.Parent = mainFrame status.BackgroundColor3 = Color3.fromRGB(60, 60, 60) status.Size = UDim2.new(0, 200, 0, 30) status.Position = UDim2.new(0, 0, 0, -30) status.Text = "Status: Offline" status.TextColor3 = Color3.fromRGB(255, 0, 0) status.TextScaled = true status.BorderSizePixel = 0 local function createButton(name, text, x, y, width, height, textColor) local btn = Instance.new("TextButton") btn.Name = name btn.Parent = mainFrame btn.Text = text btn.Size = UDim2.new(0, width, 0, height) btn.Position = UDim2.new(0, x, 0, y) btn.BackgroundColor3 = Color3.fromRGB(60, 60, 60) btn.TextColor3 = textColor or Color3.fromRGB(255, 255, 255) btn.TextScaled = true btn.AutoButtonColor = true btn.BorderSizePixel = 0 return btn end local toggleBtn = createButton("ToggleBtn", "START", 8, 8, 88, 26, Color3.fromRGB(0, 255, 0)) local fastBtn = createButton("FastBtn", "AUTO TOUCH: OFF", 104, 8, 88, 26, Color3.fromRGB(0, 255, 255)) local antiLagBtn = createButton("AntiLagBtn", "ANTI-LAG: OFF", 8, 38, 88, 26, Color3.fromRGB(255, 255, 255)) local flagWarningLabel = Instance.new("TextLabel") flagWarningLabel.Name = "FlagWarningLabel" flagWarningLabel.Parent = mainFrame flagWarningLabel.Text = "Flag skins can cause bugs." flagWarningLabel.Size = UDim2.new(0, 88, 0, 26) flagWarningLabel.Position = UDim2.new(0, 104, 0, 38) flagWarningLabel.BackgroundColor3 = Color3.fromRGB(52, 52, 52) flagWarningLabel.TextColor3 = Color3.fromRGB(255, 220, 100) flagWarningLabel.TextScaled = true flagWarningLabel.TextWrapped = true flagWarningLabel.Font = Enum.Font.SourceSansBold flagWarningLabel.BorderSizePixel = 0 local destroyBtn = createButton("DestroyBtn", "Destroy UI", 8, 68, 184, 24, Color3.fromRGB(255, 100, 100)) -- Drag (PC + Mobile) do local dragging = false local dragStart, startPos mainFrame.InputBegan:Connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Touch then dragging = true dragStart = input.Position startPos = mainFrame.Position input.Changed:Connect(function() if input.UserInputState == Enum.UserInputState.End then dragging = false end end) end end) mainFrame.InputChanged:Connect(function(input) if not dragging then return end if input.UserInputType == Enum.UserInputType.MouseMovement or input.UserInputType == Enum.UserInputType.Touch then local delta = input.Position - dragStart mainFrame.Position = UDim2.new( startPos.X.Scale, startPos.X.Offset + delta.X, startPos.Y.Scale, startPos.Y.Offset + delta.Y ) end end) end ------------------------------------------------------------------------------- -- CONFIG ------------------------------------------------------------------------------- local BATCH_SIZE = 30 -- số ô chạm song song mỗi vòng local TOTAL_MINES_DEFAULT = 100 -- tổng số mìn của bàn local LAST_TILE_DEDUCTION = true -- tự suy ra các ô còn lại khi đã biết hết phần còn lại (dựa trên tổng số mìn) local GLOBAL_MINES_ENABLED = true -- dùng ràng buộc "tổng số mìn" (tự tắt nếu dữ liệu mâu thuẫn) local MINE_MARKER_THRESHOLD = 90 -- đủ số mìn này thì dựng tia "Here" local AUTO_TOUCH_RANGE = 60 local ANTI_LAG_DISTANCE = 60 local SOLVER_CONTEXT_PADDING = 8 local FLAG_REFRESH_INTERVAL = 0.5 local VISUALS_IN_WORKSPACE = true local VISUAL_HARD_RANGE = 250 -- khi Anti-Lag OFF vẫn không vẽ highlight xa hơn mức này (giảm lag mobile) local LOOP_INTERVAL = 0.12 local FORCE_SOLVE_INTERVAL = 2 -- ép giải lại tối thiểu mỗi 2s dù trạng thái không đổi local MAX_COMPONENT_CELLS = 26 -- cụm biên lớn hơn mức này dùng suy luận tập hợp thay vì liệt kê local MAX_ENUM_NODES = 40000 -- trần số nút backtracking mỗi cụm local BULK_CHANGE_THRESHOLD = 150 -- số part thêm/xoá cùng lúc coi là "ván mới" local FLAG_CELL = 6 -- kích thước ô lưới băm vị trí cờ ------------------------------------------------------------------------------- -- STATE ------------------------------------------------------------------------------- local isScanning = false local isAutoTouching = false local isAntiLagOn = false local solverGeneration = 0 local autoTouchGeneration = 0 local cachedParts = {} local cachedSet = {} local neighborMap = {} local numberTiles = {} local knownMines = {} local knownSafe = {} local probabilityMap = {} local currentBestGuess = nil local connections = {} local trackedVisuals = {} local checkedNoNumber = {} -- [part] = {n = lần thử, t = thời điểm thử gần nhất} local flagGrid = {} local lastUnknown = {} local lastSig = nil local lastSolveTime = 0 local lastSoftReset = 0 local conflicts = 0 local actionCooldown = setmetatable({}, { __mode = "k" }) local addedQueue = {} local removedSinceFlush = 0 local flushScheduled = false local herePillarPart = nil local hereBillboardGui = nil local hereTargetPart = nil local hereHeight = 8 local hereRenderConn = nil local fiftyFiftyAlertActive = false local activeAlertLabel = nil local activeAlertTween = nil local alertToken = 0 local visualsFolder = Instance.new("Folder") visualsFolder.Name = "TopEspVisuals_" .. tostring(screenGui.Name) if VISUALS_IN_WORKSPACE then pcall(function() visualsFolder.Parent = Workspace end) end if not visualsFolder.Parent then visualsFolder.Parent = guiParent end ------------------------------------------------------------------------------- -- 50/50 NOTIFICATION ------------------------------------------------------------------------------- local function clearFiftyFiftyAlert() alertToken = alertToken + 1 fiftyFiftyAlertActive = false if activeAlertTween then pcall(function() activeAlertTween:Cancel() end) activeAlertTween = nil end if activeAlertLabel then pcall(function() activeAlertLabel:Destroy() end) activeAlertLabel = nil end end local function triggerFiftyFiftyAlert() if fiftyFiftyAlertActive then return end fiftyFiftyAlertActive = true alertToken = alertToken + 1 local currentToken = alertToken local lbl = Instance.new("TextLabel") lbl.Name = "FiftyFiftyAlert" lbl.AnchorPoint = Vector2.new(0.5, 0.5) lbl.Position = UDim2.new(0.5, 0, 0.75, 0) lbl.Size = UDim2.new(0, 420, 0, 22) lbl.BackgroundTransparency = 1 lbl.Text = "Open other boxes to reduce the chances of having to guess." lbl.TextColor3 = Color3.fromRGB(255, 255, 255) lbl.TextSize = 14 lbl.Font = Enum.Font.GothamMedium lbl.TextWrapped = false lbl.TextScaled = false lbl.TextXAlignment = Enum.TextXAlignment.Center lbl.TextYAlignment = Enum.TextYAlignment.Center lbl.Parent = screenGui activeAlertLabel = lbl task.delay(3, function() if currentToken ~= alertToken or not lbl or not lbl.Parent then return end local tween = TweenService:Create(lbl, TweenInfo.new(0.85, Enum.EasingStyle.Quad, Enum.EasingDirection.In), { Position = UDim2.new(0.5, 0, 1.08, 0), TextTransparency = 1 }) activeAlertTween = tween tween.Completed:Connect(function() if currentToken == alertToken then if activeAlertLabel == lbl then activeAlertLabel = nil end activeAlertTween = nil fiftyFiftyAlertActive = false pcall(function() lbl:Destroy() end) end end) tween:Play() end) end ------------------------------------------------------------------------------- -- HELPERS ------------------------------------------------------------------------------- local function getTileRoot() local flagObj = Workspace:FindFirstChild("Flag") if not flagObj then return nil end return flagObj:FindFirstChild("Parts") end local function getCharPos() local char = player.Character local root = char and (char:FindFirstChild("HumanoidRootPart") or char:FindFirstChild("Head")) return root and root.Position or nil end local function isWithinDistance(part, charPos, maxDist) if not charPos or not part then return true end return (part.Position - charPos).Magnitude <= maxDist end local function isWithinActiveRange(part, charPos, extraPadding) if not isAntiLagOn then return true end if not charPos or not part then return true end return (part.Position - charPos).Magnitude <= ANTI_LAG_DISTANCE + (extraPadding or 0) end local function sortByProximity(list, charPos) if not charPos or #list <= 1 then return end table.sort(list, function(a, b) return (a.Position - charPos).Magnitude < (b.Position - charPos).Magnitude end) end local function countKnownMines() local count = 0 for part, isMine in pairs(knownMines) do if isMine and part and part.Parent then count = count + 1 end end return count end local function countKnownSafeUnrevealed() local count = 0 for part, isSafe in pairs(knownSafe) do if isSafe and part and part.Parent then count = count + 1 end end return count end local function isColorMatch(c1, r, g, b) return math.abs(c1.R - r) < 0.05 and math.abs(c1.G - g) < 0.05 and math.abs(c1.B - b) < 0.05 end -- Ô rác: RGB(255,255,125) local function isExcluded(part) if not part:IsA("BasePart") then return true end return isColorMatch(part.Color, 1.000, 1.000, 0.490) end -- Ô số: RGB(230,230,113) local function isNumberColor(part) if not part or not part:IsA("BasePart") then return false end return isColorMatch(part.Color, 0.902, 0.902, 0.443) end -- Ô chưa mở: chỉ dựa trên màu (không phụ thuộc cache số) để phát hiện ván reset local function isUnrevealed(part) if not part or not part.Parent or not part:IsA("BasePart") then return false end local c = part.Color if isColorMatch(c, 1.000, 1.000, 0.490) then return false end return isColorMatch(c, 0.804, 0.557, 0.392) or isColorMatch(c, 0.706, 0.490, 0.345) end -- FIX: bản gốc có thể lặp vô hạn ở đây (FindFirstChildWhichIsA không nhận tham số thứ 3) local function getNumber(part) if not part or not part:IsA("BasePart") or isExcluded(part) then return nil end for _, d in ipairs(part:GetDescendants()) do if d:IsA("TextLabel") and d.Visible then local num = tonumber(string.match(d.Text, "%d+")) if num and num >= 1 and num <= 8 then return num end end end return nil end local function isTileCandidate(part) if not part or not part:IsA("BasePart") then return false end if isExcluded(part) then return false end if isNumberColor(part) or isUnrevealed(part) then return true end if part.Name == "Part" and part.Parent and string.find(string.lower(part.Parent.Name), "part") then return true end if part:FindFirstChildWhichIsA("TextLabel", true) then return getNumber(part) ~= nil end return false end local function countUnrevealedNeighbors(part) local neighbors = neighborMap[part] if not neighbors then return 0 end local c = 0 for _, n in ipairs(neighbors) do if isUnrevealed(n) and not knownMines[n] and not knownSafe[n] then c = c + 1 end end return c end local function countRevealedNumberNeighbors(part) local neighbors = neighborMap[part] if not neighbors then return 0 end local c = 0 for _, n in ipairs(neighbors) do if n.Parent and numberTiles[n] then c = c + 1 end end return c end local function onCooldown(part, secs) local t = actionCooldown[part] return t ~= nil and (os.clock() - t) < secs end local function stamp(part) actionCooldown[part] = os.clock() end ------------------------------------------------------------------------------- -- FLAG CACHE (lưới băm không gian -> hasFlag O(1)) ------------------------------------------------------------------------------- local function addFlagPos(pos) local k = math.floor(pos.X / FLAG_CELL) .. ":" .. math.floor(pos.Z / FLAG_CELL) local b = flagGrid[k] if not b then b = {}; flagGrid[k] = b end b[#b + 1] = pos end local function refreshFlagCache() flagGrid = {} local flagFolder = Workspace:FindFirstChild("Flag") or Workspace:FindFirstChild("Flags") if flagFolder then for _, desc in ipairs(flagFolder:GetDescendants()) do if desc:IsA("BasePart") and not cachedSet[desc] then addFlagPos(desc.Position) end end end for _, obj in ipairs(Workspace:GetChildren()) do if obj:IsA("Model") and string.find(string.lower(obj.Name), "flag") then local primary = obj.PrimaryPart or obj:FindFirstChildWhichIsA("BasePart") if primary then addFlagPos(primary.Position) end end end end local function hasFlag(part) if not part or not part.Parent then return false end local pPos = part.Position local sx = part.Size.X * 0.55 local sz = part.Size.Z * 0.55 local cx = math.floor(pPos.X / FLAG_CELL) local cz = math.floor(pPos.Z / FLAG_CELL) for ix = cx - 1, cx + 1 do for iz = cz - 1, cz + 1 do local b = flagGrid[ix .. ":" .. iz] if b then for _, f in ipairs(b) do local dy = f.Y - pPos.Y if math.abs(f.X - pPos.X) < sx and math.abs(f.Z - pPos.Z) < sz and dy > 0.3 and dy < 6 then return true end end end end end return false end local function clickTile(part) if not part or not part.Parent then return end local cd = part:FindFirstChildOfClass("ClickDetector") or part:FindFirstChildWhichIsA("ClickDetector", true) if cd and typeof(fireclickdetector) == "function" then fireclickdetector(cd, 0) end end ------------------------------------------------------------------------------- -- TOUCH TRIGGER ------------------------------------------------------------------------------- local function triggerTileTouch(targetTile) if not targetTile or not targetTile.Parent then return end local char = player.Character if not char then return end local limb = char:FindFirstChild("RightFoot") or char:FindFirstChild("Right Leg") or char:FindFirstChild("LeftFoot") or char:FindFirstChild("Left Leg") or char:FindFirstChild("HumanoidRootPart") if not limb then return end if typeof(firetouchinterest) == "function" then firetouchinterest(limb, targetTile, 0) task.wait(0.015) firetouchinterest(limb, targetTile, 1) else local probe = Instance.new("Part") probe.Name = "LegProbe" probe.Size = limb.Size probe.CanCollide = false probe.CanQuery = false probe.CanTouch = true probe.Massless = true probe.Transparency = 1 probe.CFrame = targetTile.CFrame probe.Parent = char task.wait(0.02) pcall(function() probe:Destroy() end) end end ------------------------------------------------------------------------------- -- "HERE" 3D FLAT RAY + BILLBOARD (>= MINE_MARKER_THRESHOLD) ------------------------------------------------------------------------------- local function stopHereFacingLoop() if hereRenderConn then hereRenderConn:Disconnect() hereRenderConn = nil end end local function applyHereFacingCFrame() if not herePillarPart or not herePillarPart.Parent or not hereTargetPart or not hereTargetPart.Parent then return end local baseTopY = hereTargetPart.Position.Y + (hereTargetPart.Size.Y * 0.5) local centerPos = Vector3.new(hereTargetPart.Position.X, baseTopY + (hereHeight * 0.5), hereTargetPart.Position.Z) local cam = Workspace.CurrentCamera local lookTarget = cam and Vector3.new(cam.CFrame.Position.X, centerPos.Y, cam.CFrame.Position.Z) if lookTarget and (lookTarget - centerPos).Magnitude > 0.01 then herePillarPart.CFrame = CFrame.lookAt(centerPos, lookTarget) else herePillarPart.CFrame = CFrame.new(centerPos) end end local function startHereFacingLoop() if hereRenderConn then return end hereRenderConn = RunService.RenderStepped:Connect(function() if not isScanning or not herePillarPart or not herePillarPart.Parent then stopHereFacingLoop() return end applyHereFacingCFrame() end) end local function clearHerePillar() stopHereFacingLoop() hereTargetPart = nil if hereBillboardGui then pcall(function() hereBillboardGui:Destroy() end) hereBillboardGui = nil end if herePillarPart then pcall(function() herePillarPart:Destroy() end) herePillarPart = nil end end local function findNearestUnrevealedTile(charPos) local nearestPart, shortestDist = nil, math.huge for _, part in ipairs(lastUnknown) do if part.Parent and isUnrevealed(part) and not knownMines[part] and not knownSafe[part] and isWithinActiveRange(part, charPos, 0) and not hasFlag(part) then local dist = charPos and (part.Position - charPos).Magnitude or 0 if dist < shortestDist then shortestDist = dist nearestPart = part end end end return nearestPart end local function updateHerePillar(charPos, foundMinesCount) if not isScanning or foundMinesCount < MINE_MARKER_THRESHOLD then clearHerePillar() return end local target = findNearestUnrevealedTile(charPos) if not target then clearHerePillar() return end hereTargetPart = target local flatWidth = math.max(0.45, math.min(target.Size.X, target.Size.Z) * 0.35) local flatThickness = 0.06 if not herePillarPart or not herePillarPart.Parent then local p = Instance.new("Part") p.Name = "HereFlatRay" p.Anchored = true p.CanCollide = false p.CanTouch = false p.CanQuery = false p.CastShadow = false p.Massless = true p.Material = Enum.Material.Neon p.Color = Color3.fromRGB(255, 255, 255) p.Transparency = 0.25 p.Size = Vector3.new(flatWidth, hereHeight, flatThickness) p.Parent = visualsFolder herePillarPart = p else herePillarPart.Size = Vector3.new(flatWidth, hereHeight, flatThickness) end applyHereFacingCFrame() startHereFacingLoop() if not hereBillboardGui or not hereBillboardGui.Parent then local bb = Instance.new("BillboardGui") bb.Name = "HereBillboard" bb.Adornee = herePillarPart bb.AlwaysOnTop = true bb.Size = UDim2.new(0, 76, 0, 26) bb.StudsOffset = Vector3.new(0, (hereHeight * 0.5) + 1.2, 0) bb.Parent = guiParent local lbl = Instance.new("TextLabel") lbl.Name = "HereLabel" lbl.Size = UDim2.new(1, 0, 1, 0) lbl.BackgroundTransparency = 1 lbl.Text = "Here" lbl.TextColor3 = Color3.fromRGB(255, 255, 255) lbl.TextStrokeColor3 = Color3.fromRGB(0, 0, 0) lbl.TextStrokeTransparency = 0.35 lbl.TextScaled = true lbl.Font = Enum.Font.GothamBold lbl.Parent = bb hereBillboardGui = bb else hereBillboardGui.Adornee = herePillarPart end end ------------------------------------------------------------------------------- -- TOP-FACE VISUALS (ESP) ------------------------------------------------------------------------------- local function clearVisuals(part) if not part then return end local entry = trackedVisuals[part] if entry then if entry.box then pcall(function() entry.box:Destroy() end) end if entry.topFill then pcall(function() entry.topFill:Destroy() end) end trackedVisuals[part] = nil end end local function clearAllVisuals() for part, entry in pairs(trackedVisuals) do if entry then if entry.box then pcall(function() entry.box:Destroy() end) end if entry.topFill then pcall(function() entry.topFill:Destroy() end) end end trackedVisuals[part] = nil end end local function withinVisualRange(part, charPos) if not charPos or not part then return true end local limit = isAntiLagOn and ANTI_LAG_DISTANCE or VISUAL_HARD_RANGE return (part.Position - charPos).Magnitude <= limit end local function createHighlight(part, color, name) if not part or not part:IsA("BasePart") or not part.Parent then return end local charPos = getCharPos() if not withinVisualRange(part, charPos) then clearVisuals(part) return end local existing = trackedVisuals[part] if name == "Guess_Highlight" and existing and (existing.tag == "Safe_Highlight" or existing.tag == "Mine_Highlight") then return end if existing and existing.tag == name and existing.topFill and existing.topFill.Parent then return end clearVisuals(part) local capThickness = 0.06 local topFill = Instance.new("Part") topFill.Name = name .. "_TopCap" topFill.Anchored = true topFill.CanCollide = false topFill.CanTouch = false topFill.CanQuery = false topFill.CastShadow = false topFill.Massless = true topFill.Material = Enum.Material.SmoothPlastic topFill.Color = color topFill.Transparency = 0.45 topFill.Size = Vector3.new( math.max(0.1, part.Size.X * 0.96), capThickness, math.max(0.1, part.Size.Z * 0.96) ) topFill.CFrame = part.CFrame * CFrame.new(0, (part.Size.Y * 0.5) + (capThickness * 0.5) + 0.02, 0) topFill.Parent = visualsFolder local box = Instance.new("SelectionBox") box.Name = name .. "_Border" box.Adornee = topFill box.Color3 = color box.LineThickness = 0.04 box.Transparency = 0.05 box.SurfaceTransparency = 1 box.Parent = visualsFolder trackedVisuals[part] = { tag = name, box = box, topFill = topFill } end local function syncVisualsRange(charPos) for part, _ in pairs(trackedVisuals) do if not part.Parent or isExcluded(part) or numberTiles[part] or not isUnrevealed(part) then clearVisuals(part) elseif not withinVisualRange(part, charPos) then clearVisuals(part) end end for part, isMine in pairs(knownMines) do if isMine and part.Parent and isUnrevealed(part) and withinVisualRange(part, charPos) then createHighlight(part, Color3.new(1, 0, 0), "Mine_Highlight") end end for part, isSafe in pairs(knownSafe) do if isSafe and part.Parent and isUnrevealed(part) and withinVisualRange(part, charPos) then createHighlight(part, Color3.new(0, 1, 0), "Safe_Highlight") end end if currentBestGuess and currentBestGuess.Parent and isUnrevealed(currentBestGuess) and not knownMines[currentBestGuess] and not knownSafe[currentBestGuess] and withinVisualRange(currentBestGuess, charPos) then createHighlight(currentBestGuess, Color3.fromRGB(255, 255, 0), "Guess_Highlight") end end ------------------------------------------------------------------------------- -- NEIGHBOR CACHING ------------------------------------------------------------------------------- local function buildNeighborMapBulk(parts) local maxDim = 1 for _, p in ipairs(parts) do local d = math.max(p.Size.X, p.Size.Z) if d > maxDim then maxDim = d end end local cellSize = math.max(4, maxDim * 2) local buckets = {} for _, p in ipairs(parts) do local key = math.floor(p.Position.X / cellSize) .. ":" .. math.floor(p.Position.Z / cellSize) local b = buckets[key] if not b then b = {}; buckets[key] = b end b[#b + 1] = p end for _, center in ipairs(parts) do local cx = math.floor(center.Position.X / cellSize) local cz = math.floor(center.Position.Z / cellSize) local radius = center.Size.X * 1.85 local neighbors = {} for ix = cx - 1, cx + 1 do for iz = cz - 1, cz + 1 do local b = buckets[ix .. ":" .. iz] if b then for _, p in ipairs(b) do if p ~= center and math.abs(p.Position.Y - center.Position.Y) < 1.5 and (p.Position - center.Position).Magnitude < radius then neighbors[#neighbors + 1] = p end end end end end neighborMap[center] = neighbors end end local function cacheNeighbors(centerPart, forceRefresh) if not forceRefresh and neighborMap[centerPart] then return end local neighbors = {} local partsInBox = Workspace:GetPartBoundsInBox(centerPart.CFrame, centerPart.Size * 2.5) for _, p in ipairs(partsInBox) do if p ~= centerPart and isTileCandidate(p) then if math.abs(p.Position.Y - centerPart.Position.Y) < 1.5 and (p.Position - centerPart.Position).Magnitude < (centerPart.Size.X * 1.85) then neighbors[#neighbors + 1] = p end end end neighborMap[centerPart] = neighbors end local function rescanBoard() cachedParts = {} cachedSet = {} neighborMap = {} local tileRoot = getTileRoot() if not tileRoot then return end local candidates = {} for _, obj in ipairs(tileRoot:GetDescendants()) do if isTileCandidate(obj) then candidates[#candidates + 1] = obj cachedSet[obj] = true end end cachedParts = candidates buildNeighborMapBulk(candidates) end ------------------------------------------------------------------------------- -- RESET HELPERS ------------------------------------------------------------------------------- -- Reset "mềm": chỉ xoá suy luận (giữ số đã đọc) local function softResetKnowledge() clearAllVisuals() clearFiftyFiftyAlert() clearHerePillar() knownMines = {} knownSafe = {} probabilityMap = {} currentBestGuess = nil lastSig = nil lastSoftReset = os.clock() end -- Reset "cứng": ván mới -> xoá cả số đã đọc local function hardResetKnowledge() softResetKnowledge() numberTiles = {} checkedNoNumber = {} lastUnknown = {} end ------------------------------------------------------------------------------- -- SOLVER ------------------------------------------------------------------------------- local function markMine(p) if not p or not p.Parent or knownMines[p] then return false end if knownSafe[p] then conflicts = conflicts + 1 -- suy luận mâu thuẫn -> dữ liệu có thể cũ return false end knownMines[p] = true createHighlight(p, Color3.new(1, 0, 0), "Mine_Highlight") return true end local function markSafe(p) if not p or not p.Parent or knownSafe[p] then return false end if knownMines[p] then conflicts = conflicts + 1 return false end knownSafe[p] = true createHighlight(p, Color3.new(0, 1, 0), "Safe_Highlight") return true end -- Thu thập ràng buộc: mỗi ô số -> {cells = ô chưa rõ, need = số mìn còn thiếu} local function collectConstraints(charPos) local cons = {} for centerPart, targetNum in pairs(numberTiles) do if not centerPart.Parent then numberTiles[centerPart] = nil elseif isWithinActiveRange(centerPart, charPos, SOLVER_CONTEXT_PADDING) then local neighbors = neighborMap[centerPart] if neighbors then local cells, need = {}, targetNum for _, n in ipairs(neighbors) do if knownMines[n] then need = need - 1 elseif knownSafe[n] then -- an toàn: bỏ khỏi tập elseif isUnrevealed(n) then cells[#cells + 1] = n end end if #cells > 0 then cons[#cons + 1] = { part = centerPart, cells = cells, need = need } end end end end return cons end -- Lan truyền: luật cơ bản (need=0 / need=số ô) + luật hiệu tập con, lặp đến khi hết tiến triển local function propagate(cons) for _ = 1, 10 do local progressed = false local index = {} for _, c in ipairs(cons) do if not c.dead then local need = c.need local cells, set = {}, {} for _, p in ipairs(c.cells) do if knownMines[p] then need = need - 1 elseif not knownSafe[p] then cells[#cells + 1] = p set[p] = true end end c.cells, c.need, c.set = cells, need, set if #cells == 0 then c.dead = true elseif need < 0 or need > #cells then c.dead = true conflicts = conflicts + 1 elseif need == 0 then for _, p in ipairs(cells) do if markSafe(p) then progressed = true end end c.dead = true elseif need == #cells then for _, p in ipairs(cells) do if markMine(p) then progressed = true end end c.dead = true else for _, p in ipairs(cells) do local l = index[p] if not l then l = {}; index[p] = l end l[#l + 1] = c end end end end -- Subset rule: A ⊂ B => (B \ A) chứa đúng (needB - needA) mìn for _, A in ipairs(cons) do if not A.dead and A.set then local list = index[A.cells[1]] if list then for _, B in ipairs(list) do if B ~= A and not B.dead and B.set and #B.cells > #A.cells then local sub = true for _, p in ipairs(A.cells) do if not B.set[p] then sub = false; break end end if sub then local diff = {} for _, p in ipairs(B.cells) do if not A.set[p] then diff[#diff + 1] = p end end local dn = B.need - A.need if dn == 0 then for _, p in ipairs(diff) do if markSafe(p) then progressed = true end end elseif dn == #diff then for _, p in ipairs(diff) do if markMine(p) then progressed = true end end end end end end end end end if not progressed then break end end end -- Chia ràng buộc thành các cụm liên thông (độc lập nhau) local function buildComponents(cons) local cellCons = {} for ci, c in ipairs(cons) do for _, p in ipairs(c.cells) do local l = cellCons[p] if not l then l = {}; cellCons[p] = l end l[#l + 1] = ci end end local visitedCon, comps = {}, {} for ci = 1, #cons do if not visitedCon[ci] then visitedCon[ci] = true local stack = { ci } local conList, cellList, cellSeen = {}, {}, {} while #stack > 0 do local cur = table.remove(stack) conList[#conList + 1] = cons[cur] for _, p in ipairs(cons[cur].cells) do if not cellSeen[p] then cellSeen[p] = true cellList[#cellList + 1] = p for _, cj in ipairs(cellCons[p]) do if not visitedCon[cj] then visitedCon[cj] = true stack[#stack + 1] = cj end end end end end comps[#comps + 1] = { cons = conList, cells = cellList } end end return comps end -- Liệt kê chính xác mọi cấu hình mìn hợp lệ của một cụm (backtracking có cắt tỉa) -- Trả về: countByK[k] = số nghiệm có k mìn; cellByK[k][i] = số nghiệm đó có mìn ở ô i local function enumerateComponent(comp) local cells = comp.cells local n = #cells local cellIndex = {} for i, c in ipairs(cells) do cellIndex[c] = i end local cellCons = {} for i = 1, n do cellCons[i] = {} end local conCells, conNeed, conAssigned, conUnassigned = {}, {}, {}, {} for ci, c in ipairs(comp.cons) do local idxs = {} for _, p in ipairs(c.cells) do local ix = cellIndex[p] idxs[#idxs + 1] = ix table.insert(cellCons[ix], ci) end conCells[ci] = idxs conNeed[ci] = c.need conAssigned[ci] = 0 conUnassigned[ci] = #idxs end -- Thứ tự BFS để các ràng buộc được "đóng" sớm -> cắt tỉa mạnh local order, seen, queue, qi = {}, { [1] = true }, { 1 }, 1 while qi <= #queue do local u = queue[qi] qi = qi + 1 order[#order + 1] = u for _, ci in ipairs(cellCons[u]) do for _, v in ipairs(conCells[ci]) do if not seen[v] then seen[v] = true queue[#queue + 1] = v end end end end if #order ~= n then return nil end local assign = {} for i = 1, n do assign[i] = 0 end local countByK, cellByK = {}, {} local nodes, aborted, mines = 0, false, 0 local function rec(pos) if aborted then return end nodes = nodes + 1 if nodes > MAX_ENUM_NODES then aborted = true return end if pos > n then countByK[mines] = (countByK[mines] or 0) + 1 local arr = cellByK[mines] if not arr then arr = {} for i = 1, n do arr[i] = 0 end cellByK[mines] = arr end for i = 1, n do if assign[i] == 1 then arr[i] = arr[i] + 1 end end return end local u = order[pos] local cl = cellCons[u] for v = 0, 1 do local ok = true for _, ci in ipairs(cl) do local a = conAssigned[ci] + v local un = conUnassigned[ci] - 1 if a > conNeed[ci] or a + un < conNeed[ci] then ok = false break end end if ok then assign[u] = v for _, ci in ipairs(cl) do conAssigned[ci] = conAssigned[ci] + v conUnassigned[ci] = conUnassigned[ci] - 1 end mines = mines + v rec(pos + 1) mines = mines - v for _, ci in ipairs(cl) do conAssigned[ci] = conAssigned[ci] - v conUnassigned[ci] = conUnassigned[ci] + 1 end assign[u] = 0 end end end rec(1) if aborted then return nil end return { countByK = countByK, cellByK = cellByK, n = n } end local function clamp(x, lo, hi) if x < lo then return lo end if x > hi then return hi end return x end -- Phân tích biên: xác suất từng ô + ô chắc chắn mìn/an toàn. -- R = số mìn còn lại, O = số ô chưa rõ nằm ngoài biên, useGlobal = dùng ràng buộc tổng số mìn. local function analyzeFrontier(cons, R, O, useGlobal) local comps = buildComponents(cons) local res = { probs = {}, mines = {}, safes = {}, frontier = {}, rho = nil, outsideSafe = false, outsideMine = false, conflict = false, } local sumMin, sumMax, totalFrontier = 0, 0, 0 for _, comp in ipairs(comps) do for _, p in ipairs(comp.cells) do res.frontier[p] = true end totalFrontier = totalFrontier + #comp.cells if #comp.cells <= MAX_COMPONENT_CELLS then comp.enum = enumerateComponent(comp) end if comp.enum then local kmin, kmax = math.huge, -1 for k in pairs(comp.enum.countByK) do if k < kmin then kmin = k end if k > kmax then kmax = k end end if kmax < 0 then res.conflict = true -- cụm vô nghiệm => số liệu không nhất quán comp.enum = nil comp.kmin, comp.kmax = 0, #comp.cells else comp.kmin, comp.kmax = kmin, kmax end else comp.kmin, comp.kmax = 0, #comp.cells end -- Xác suất heuristic cho cụm quá lớn if not comp.enum then comp.heur = {} local e = 0 for _, c in ipairs(comp.cons) do local pr = c.need / #c.cells for _, p in ipairs(c.cells) do if not comp.heur[p] or pr > comp.heur[p] then comp.heur[p] = pr end end end for _, p in ipairs(comp.cells) do e = e + (comp.heur[p] or 0.5) end comp.heurE = e end sumMin = sumMin + comp.kmin sumMax = sumMax + comp.kmax end local globalOk = useGlobal and R >= 0 and sumMin <= R and (sumMax + O) >= R local useDensity = globalOk and O > 0 local function allowed(comp, k) if not globalOk then return true end return (k + (sumMin - comp.kmin) <= R) and (k + (sumMax - comp.kmax) + O >= R) end -- Mật độ mìn ngoài biên (rho) hội tụ lặp: rho = (R - E[mìn biên]) / O local rho = 0.5 if useDensity then rho = clamp(R / (O + math.max(1, totalFrontier)), 0.001, 0.999) end local r = 1 for _ = 1, 3 do r = useDensity and (rho / (1 - rho)) or 1 local sumE = 0 for _, comp in ipairs(comps) do if comp.enum then local wsum, ksum = 0, 0 for k, cnt in pairs(comp.enum.countByK) do if allowed(comp, k) then local w = cnt * (r ^ k) wsum = wsum + w ksum = ksum + w * k end end comp.E = wsum > 0 and (ksum / wsum) or 0 else comp.E = comp.heurE end sumE = sumE + comp.E end if useDensity then rho = clamp((R - sumE) / O, 0.001, 0.999) end end r = useDensity and (rho / (1 - rho)) or 1 -- Xác suất cuối + ô chắc chắn for _, comp in ipairs(comps) do if comp.enum then local n = comp.enum.n local cellW, mineSol = {}, {} for i = 1, n do cellW[i] = 0; mineSol[i] = 0 end local wsum, totalSol = 0, 0 for k, cnt in pairs(comp.enum.countByK) do if allowed(comp, k) then local rk = r ^ k wsum = wsum + cnt * rk totalSol = totalSol + cnt local arr = comp.enum.cellByK[k] for i = 1, n do cellW[i] = cellW[i] + arr[i] * rk mineSol[i] = mineSol[i] + arr[i] end end end if wsum > 0 and totalSol > 0 then for i, p in ipairs(comp.cells) do res.probs[p] = cellW[i] / wsum if mineSol[i] == 0 then res.safes[#res.safes + 1] = p elseif mineSol[i] == totalSol then res.mines[#res.mines + 1] = p end end else res.conflict = true for _, p in ipairs(comp.cells) do res.probs[p] = 0.5 end end else for _, p in ipairs(comp.cells) do res.probs[p] = comp.heur[p] or 0.5 end end end if globalOk and O > 0 then res.rho = rho if sumMin >= R then res.outsideSafe = true end if sumMax + O <= R then res.outsideMine = true end elseif useGlobal and not globalOk and #comps > 0 then res.globalInconsistent = true end return res end local function gatherUnknown(charPos) local list = {} for _, p in ipairs(cachedParts) do if p.Parent and isUnrevealed(p) and not knownMines[p] and not knownSafe[p] and isWithinActiveRange(p, charPos, 0) then list[#list + 1] = p end end return list end local function applyAnalysis(res, unknown) local progressed = false for _, p in ipairs(res.safes) do if markSafe(p) then progressed = true end end for _, p in ipairs(res.mines) do if markMine(p) then progressed = true end end if res.outsideSafe then for _, p in ipairs(unknown) do if not res.frontier[p] and markSafe(p) then progressed = true end end elseif res.outsideMine then for _, p in ipairs(unknown) do if not res.frontier[p] and markMine(p) then progressed = true end end end return progressed end -- Chọn ô đoán tốt nhất (xác suất thấp nhất, hoà thì ưu tiên ô nhiều thông tin / gần người chơi) local function pickGuess(res, unknown, charPos, R) local endgame = R <= 2 local list = {} for p, prob in pairs(res.probs) do if p.Parent and isUnrevealed(p) and not knownMines[p] and not knownSafe[p] and isWithinActiveRange(p, charPos, 0) then local info = countUnrevealedNeighbors(p) * 0.6 + countRevealedNumberNeighbors(p) * 0.3 if endgame then info = info * 2 end local dist = charPos and (p.Position - charPos).Magnitude or 0 list[#list + 1] = { part = p, prob = prob, score = prob * 1000 - info + dist * 0.005 } end end -- Ô ngoài biên: chỉ thêm ứng viên gần người chơi nhất local outsideProb = res.rho if not outsideProb then outsideProb = (R > 0 and #unknown > 0) and clamp(R / #unknown, 0.001, 0.999) or 0.5 end local nearest, nd = nil, math.huge for _, p in ipairs(unknown) do if not res.frontier[p] and not hasFlag(p) then local d = charPos and (p.Position - charPos).Magnitude or 0 if d < nd then nd = d; nearest = p end end end if nearest then list[#list + 1] = { part = nearest, prob = outsideProb, score = outsideProb * 1000 + nd * 0.005 } end if #list == 0 then return nil, 1 end table.sort(list, function(a, b) return a.score < b.score end) local chosen for i = 1, math.min(#list, 6) do if not hasFlag(list[i].part) then chosen = list[i]; break end end chosen = chosen or list[1] -- Phát hiện 50/50: tốt nhất vẫn ~50% và có >= 2 ô ~50% local fifty = 0 for _, e in ipairs(list) do if math.abs(e.prob - 0.5) < 0.03 then fifty = fifty + 1 end end if chosen.prob >= 0.45 and fifty >= 2 then triggerFiftyFiftyAlert() end return chosen.part, chosen.prob end -- Suy luận ô còn lại: khi mọi ô khác đã được xác định (mìn / an toàn), -- các ô chưa rõ còn sót lại được quyết định hoàn toàn bởi tổng số mìn. -- R = TOTAL - số mìn đã biết, U = số ô chưa mở và chưa xác định -- R == 0 -> toàn bộ U an toàn; R == U -> toàn bộ U là mìn -- Chỉ chạy khi Anti-Lag OFF (cần nhìn thấy cả bàn). local function deduceLastTiles(charPos) if not LAST_TILE_DEDUCTION or not GLOBAL_MINES_ENABLED or isAntiLagOn then return false end local unknown = gatherUnknown(charPos) local U = #unknown local R = TOTAL_MINES_DEFAULT - countKnownMines() if U == 0 or R < 0 or R > U then return false end -- dữ liệu không nhất quán -> bỏ qua local progressed = false if R == 0 then for _, p in ipairs(unknown) do if markSafe(p) then progressed = true end end elseif R == U then for _, p in ipairs(unknown) do if markMine(p) then progressed = true end end end return progressed end local function solveBoard(charPos) conflicts = 0 local useGlobal = GLOBAL_MINES_ENABLED and not isAntiLagOn local analysis, unknown for _ = 1, 3 do local cons = collectConstraints(charPos) propagate(cons) local alive = {} for _, c in ipairs(cons) do if not c.dead and #c.cells > 0 then alive[#alive + 1] = c end end unknown = gatherUnknown(charPos) local frontierProbe = {} for _, c in ipairs(alive) do for _, p in ipairs(c.cells) do frontierProbe[p] = true end end local O = 0 for _, p in ipairs(unknown) do if not frontierProbe[p] then O = O + 1 end end local R = TOTAL_MINES_DEFAULT - countKnownMines() analysis = analyzeFrontier(alive, R, O, useGlobal) if analysis.conflict then conflicts = conflicts + 1 end local progressed = applyAnalysis(analysis, unknown) if deduceLastTiles(charPos) then progressed = true end if not progressed then break end end probabilityMap = analysis and analysis.probs or {} lastUnknown = gatherUnknown(charPos) -- Có nước an toàn trong tầm? local hasSafe = false for part, isSafe in pairs(knownSafe) do if isSafe and part.Parent and isUnrevealed(part) and isWithinActiveRange(part, charPos, 0) then hasSafe = true break end end if currentBestGuess and ( not currentBestGuess.Parent or knownSafe[currentBestGuess] or knownMines[currentBestGuess] or hasSafe or not isWithinActiveRange(currentBestGuess, charPos, 0) ) then local e = trackedVisuals[currentBestGuess] if e and e.tag == "Guess_Highlight" then clearVisuals(currentBestGuess) end currentBestGuess = nil end if not hasSafe and analysis then local R = TOTAL_MINES_DEFAULT - countKnownMines() local best = pickGuess(analysis, lastUnknown, charPos, R) if best and best ~= currentBestGuess then if currentBestGuess then local e = trackedVisuals[currentBestGuess] if e and e.tag == "Guess_Highlight" then clearVisuals(currentBestGuess) end end currentBestGuess = best createHighlight(best, Color3.fromRGB(255, 255, 0), "Guess_Highlight") end end end ------------------------------------------------------------------------------- -- MAIN SOLVER LOOP ------------------------------------------------------------------------------- local lastFlagRefresh = 0 local lastStatusText = "" local function solverTick() local charPos = getCharPos() local now = os.clock() if now - lastFlagRefresh >= FLAG_REFRESH_INTERVAL then lastFlagRefresh = now refreshFlagCache() end local unrevCount, numCount, staleNumbers = 0, 0, 0 local writeIndex = 1 for readIndex = 1, #cachedParts do local part = cachedParts[readIndex] if part and part.Parent then cachedParts[writeIndex] = part writeIndex = writeIndex + 1 if isAntiLagOn and not isWithinActiveRange(part, charPos, SOLVER_CONTEXT_PADDING) then clearVisuals(part) else if not neighborMap[part] then cacheNeighbors(part, false) end if isExcluded(part) then if numberTiles[part] or knownSafe[part] or knownMines[part] then numberTiles[part] = nil; knownSafe[part] = nil; knownMines[part] = nil clearVisuals(part) end elseif isUnrevealed(part) then unrevCount = unrevCount + 1 if numberTiles[part] then -- ô số quay lại trạng thái chưa mở => ván được reset numberTiles[part] = nil checkedNoNumber[part] = nil staleNumbers = staleNumbers + 1 end else if knownSafe[part] then knownSafe[part] = nil clearVisuals(part) end if numberTiles[part] then numCount = numCount + 1 else local rec = checkedNoNumber[part] if not rec or (rec.n < 4 and now - rec.t > 0.4) then local num = getNumber(part) if num then numberTiles[part] = num checkedNoNumber[part] = nil numCount = numCount + 1 clearVisuals(part) else checkedNoNumber[part] = { n = (rec and rec.n or 0) + 1, t = now } end end end end end else if part then clearVisuals(part) neighborMap[part] = nil numberTiles[part] = nil knownMines[part] = nil knownSafe[part] = nil checkedNoNumber[part] = nil cachedSet[part] = nil end end end for i = writeIndex, #cachedParts do cachedParts[i] = nil end if staleNumbers >= 3 then hardResetKnowledge() return end local minesCount = countKnownMines() local safeCount = countKnownSafeUnrevealed() local bx = isAntiLagOn and charPos and math.floor(charPos.X / 6) or 0 local bz = isAntiLagOn and charPos and math.floor(charPos.Z / 6) or 0 local sig = string.format("%d|%d|%d|%d|%d|%d|%s", unrevCount, numCount, minesCount, safeCount, bx, bz, tostring(isAntiLagOn)) local solved = false if sig ~= lastSig or now - lastSolveTime >= FORCE_SOLVE_INTERVAL then solveBoard(charPos) lastSig = sig lastSolveTime = now solved = true -- Mâu thuẫn -> dữ liệu suy luận có thể cũ, reset mềm (có cooldown tránh nhấp nháy) if conflicts > 0 and now - lastSoftReset > 1.5 then softResetKnowledge() return end end if solved or isAntiLagOn then syncVisualsRange(charPos) end updateHerePillar(charPos, countKnownMines()) local text = string.format("%s %d/%d | safe %d", isAutoTouching and "Auto(60)" or "Scan", countKnownMines(), TOTAL_MINES_DEFAULT, countKnownSafeUnrevealed()) if text ~= lastStatusText then lastStatusText = text status.Text = text end end local function startSolverLoop() solverGeneration = solverGeneration + 1 local myGeneration = solverGeneration task.spawn(function() local lastErr = nil while isScanning and myGeneration == solverGeneration do local ok, err = pcall(solverTick) if not ok and err ~= lastErr then lastErr = err warn("[Minesweeper Script] solver error: " .. tostring(err)) end task.wait(LOOP_INTERVAL) end clearHerePillar() end) end ------------------------------------------------------------------------------- -- BOARD CHANGE HANDLING (gộp sự kiện thêm/xoá part) ------------------------------------------------------------------------------- local function flushBoardChanges() flushScheduled = false if not isScanning then addedQueue = {} removedSinceFlush = 0 return end local q = addedQueue local removed = removedSinceFlush addedQueue = {} removedSinceFlush = 0 if #q + removed >= BULK_CHANGE_THRESHOLD then -- Khả năng cao là ván mới: quét lại bàn và xoá toàn bộ tri thức cũ hardResetKnowledge() rescanBoard() return end local touched = {} for _, part in ipairs(q) do if part.Parent then touched[part] = true end end for part in pairs(touched) do cacheNeighbors(part, true) for _, nb in ipairs(neighborMap[part] or {}) do cacheNeighbors(nb, true) end end lastSig = nil -- buộc giải lại end local function scheduleFlush() if flushScheduled then return end flushScheduled = true task.delay(0.15, flushBoardChanges) end local function onDescendantAdded(descendant) if isScanning and isTileCandidate(descendant) then if not cachedSet[descendant] then cachedSet[descendant] = true cachedParts[#cachedParts + 1] = descendant end addedQueue[#addedQueue + 1] = descendant scheduleFlush() end end local function onDescendantRemoving(descendant) if isScanning and cachedSet[descendant] then removedSinceFlush = removedSinceFlush + 1 scheduleFlush() end end ------------------------------------------------------------------------------- -- UI CONNECTIONS ------------------------------------------------------------------------------- toggleBtn.MouseButton1Click:Connect(function() if isScanning then isScanning = false isAutoTouching = false solverGeneration = solverGeneration + 1 autoTouchGeneration = autoTouchGeneration + 1 toggleBtn.Text = "START" toggleBtn.TextColor3 = Color3.fromRGB(0, 255, 0) fastBtn.Text = "AUTO TOUCH: OFF" fastBtn.TextColor3 = Color3.fromRGB(0, 255, 255) status.Text = "Status: Offline" status.TextColor3 = Color3.fromRGB(255, 0, 0) for _, conn in pairs(connections) do conn:Disconnect() end connections = {} hardResetKnowledge() cachedParts = {}; cachedSet = {}; neighborMap = {} addedQueue = {}; removedSinceFlush = 0 else local tileRoot = getTileRoot() if not tileRoot then warn("[Minesweeper Script] Không tìm thấy workspace.Flag.Parts") status.Text = "Status: Flag.Parts Not Found" status.TextColor3 = Color3.fromRGB(255, 170, 0) return end isScanning = true toggleBtn.Text = "STOP" toggleBtn.TextColor3 = Color3.fromRGB(255, 0, 0) status.Text = "Status: Scanning..." status.TextColor3 = Color3.fromRGB(0, 255, 0) lastStatusText = "" hardResetKnowledge() rescanBoard() refreshFlagCache() table.insert(connections, tileRoot.DescendantAdded:Connect(onDescendantAdded)) table.insert(connections, tileRoot.DescendantRemoving:Connect(onDescendantRemoving)) startSolverLoop() end end) fastBtn.MouseButton1Click:Connect(function() if not isScanning then return end isAutoTouching = not isAutoTouching lastStatusText = "" if isAutoTouching then fastBtn.Text = "AUTO TOUCH: ON" fastBtn.TextColor3 = Color3.fromRGB(0, 255, 0) autoTouchGeneration = autoTouchGeneration + 1 local myGeneration = autoTouchGeneration task.spawn(function() local lastErr = nil while isAutoTouching and isScanning and myGeneration == autoTouchGeneration do local ok, err = pcall(function() local charPos = getCharPos() if not charPos then task.wait(0.1) return end refreshFlagCache() local didWork = false -- 1. Gỡ cờ đặt nhầm trên ô an toàn (gần nhất trước) local misplaced = {} for part in pairs(knownSafe) do if part.Parent and isUnrevealed(part) and hasFlag(part) and not onCooldown(part, 0.7) and isWithinDistance(part, charPos, AUTO_TOUCH_RANGE) then misplaced[#misplaced + 1] = part end end sortByProximity(misplaced, charPos) for _, part in ipairs(misplaced) do if not isAutoTouching or not isScanning then break end local latest = getCharPos() if latest and isWithinDistance(part, latest, AUTO_TOUCH_RANGE) then clickTile(part) stamp(part) didWork = true task.wait(0.02) end end -- 2. Cắm cờ lên mìn đã chắc chắn local toFlag = {} for part in pairs(knownMines) do if part.Parent and isUnrevealed(part) and not hasFlag(part) and not onCooldown(part, 0.7) and isWithinDistance(part, charPos, AUTO_TOUCH_RANGE) then toFlag[#toFlag + 1] = part end end sortByProximity(toFlag, charPos) for _, part in ipairs(toFlag) do if not isAutoTouching or not isScanning then break end local latest = getCharPos() if latest and isWithinDistance(part, latest, AUTO_TOUCH_RANGE) then clickTile(part) stamp(part) didWork = true task.wait(0.02) end end -- 3. Mở ô an toàn (theo lô song song) local toReveal = {} for part in pairs(knownSafe) do if part.Parent and isUnrevealed(part) and not hasFlag(part) and not onCooldown(part, 0.35) and isWithinDistance(part, charPos, AUTO_TOUCH_RANGE) then toReveal[#toReveal + 1] = part end end sortByProximity(toReveal, charPos) if #toReveal > 0 then for i = 1, math.min(#toReveal, BATCH_SIZE) do local part = toReveal[i] stamp(part) task.spawn(function() if isAutoTouching and isScanning then local latest = getCharPos() if latest and isWithinDistance(part, latest, AUTO_TOUCH_RANGE) then triggerTileTouch(part) end end end) end didWork = true task.wait(0.05) end if not didWork then task.wait(0.08) end end) if not ok and err ~= lastErr then lastErr = err warn("[Minesweeper Script] auto-touch error: " .. tostring(err)) task.wait(0.2) end end if myGeneration == autoTouchGeneration then isAutoTouching = false if fastBtn and fastBtn.Parent then fastBtn.Text = "AUTO TOUCH: OFF" fastBtn.TextColor3 = Color3.fromRGB(0, 255, 255) end end end) else autoTouchGeneration = autoTouchGeneration + 1 fastBtn.Text = "AUTO TOUCH: OFF" fastBtn.TextColor3 = Color3.fromRGB(0, 255, 255) end end) antiLagBtn.MouseButton1Click:Connect(function() isAntiLagOn = not isAntiLagOn if isAntiLagOn then antiLagBtn.Text = "ANTI-LAG: ON" antiLagBtn.TextColor3 = Color3.fromRGB(0, 255, 0) else antiLagBtn.Text = "ANTI-LAG: OFF" antiLagBtn.TextColor3 = Color3.fromRGB(255, 255, 255) end lastSig = nil -- buộc giải lại với phạm vi mới if isScanning then local charPos = getCharPos() syncVisualsRange(charPos) updateHerePillar(charPos, countKnownMines()) end end) destroyBtn.MouseButton1Click:Connect(function() isScanning = false isAutoTouching = false isAntiLagOn = false solverGeneration = solverGeneration + 1 autoTouchGeneration = autoTouchGeneration + 1 for _, conn in pairs(connections) do conn:Disconnect() end connections = {} clearAllVisuals() clearFiftyFiftyAlert() clearHerePillar() pcall(function() visualsFolder:Destroy() end) screenGui:Destroy() end)