diff --git a/turtle.lua b/turtle.lua index 3b7332a..04eb36e 100644 --- a/turtle.lua +++ b/turtle.lua @@ -15,7 +15,10 @@ local state = { target = nil, path = {}, lastStatusUpdate = 0, - stuckCounter = 0 + stuckCounter = 0, + visitedPositions = {}, -- Track where we've been + lastPosition = nil, + stuckInHoleCounter = 0 } -- Configuration @@ -505,7 +508,95 @@ local function returnHome() broadcastStatus() end --- Exploration algorithm +-- Helper functions for intelligent exploration +local function positionKey(pos) + if not pos then return nil end + return string.format("%d,%d,%d", pos.x, pos.y, pos.z) +end + +local function hasVisited(pos) + local key = positionKey(pos) + return state.visitedPositions[key] ~= nil +end + +local function markVisited(pos) + local key = positionKey(pos) + state.visitedPositions[key] = os.epoch("utc") +end + +local function isStuckInSamePosition() + if not state.lastPosition or not state.position then + return false + end + return state.lastPosition.x == state.position.x and + state.lastPosition.y == state.position.y and + state.lastPosition.z == state.position.z +end + +local function canMoveInDirection(direction) + if direction == "forward" then + local hasBlock = turtle.inspect() + return not hasBlock + elseif direction == "up" then + local hasBlock = turtle.inspectUp() + return not hasBlock + elseif direction == "down" then + local hasBlock = turtle.inspectDown() + return not hasBlock + end + return false +end + +local function isInHole() + -- Check if turtle is in a hole (blocks above preventing escape) + local aboveBlocked = turtle.inspectUp() + local forwardBlocked = turtle.inspect() + + -- If above is blocked and we can't move forward easily, we might be in a hole + return aboveBlocked and forwardBlocked +end + +local function tryClimbOut() + print("Attempting to climb out of hole...") + + -- Try to dig up and go up + for i = 1, 3 do + if canMoveInDirection("up") then + if smartUp() then + print("Climbed up 1 block") + state.stuckInHoleCounter = 0 + return true + end + else + smartDig("up") + sleep(0.1) + end + end + + -- Try all horizontal directions + for i = 1, 4 do + if canMoveInDirection("forward") then + if smartForward() then + print("Moved forward out of hole") + state.stuckInHoleCounter = 0 + return true + end + else + smartDig("forward") + sleep(0.1) + if smartForward() then + print("Dug and moved forward") + state.stuckInHoleCounter = 0 + return true + end + end + smartTurnRight() + end + + return false +end + +-- Exploration algorithm with intelligent navigation local function exploreStep() -- Check all directions for valuable ores for _, direction in ipairs({"forward", "up", "down"}) do