Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --[[
- Automated Tree Farm Program for ComputerCraft Turtles
- Description:
- This program creates an automated tree farming system where the turtle follows
- a cobblestone path, harvests mature trees, plants saplings, and manages inventory
- by depositing items into a chest at the starting position.
- Setup:
- 1. Place the turtle on top of a chest (starting position)
- 2. Put fuel (e.g., Coal, Charcoal) in Slot 1 of the turtle's inventory
- 3. Put saplings in Slot 2 (up to 32, excess will be deposited)
- 4. Create a straight cobblestone path in the direction the turtle faces
- 5. The turtle will follow this path, turning around when it reaches non-cobblestone
- Operation:
- - Moves forward along cobblestone path
- - Collects saplings from all 4 directions at each position
- - Checks left and right sides for trees to harvest
- - Plants saplings in empty spaces on left and right sides
- - Returns to chest when reaching end of cobblestone path
- - Deposits wood and excess saplings, then waits 5 seconds before repeating
- Usage:
- Run the program without arguments: treefarm
- The turtle will start the farming cycle automatically.
- --]]
- -- =============================================================================
- -- Configuration
- -- =============================================================================
- local FUEL_SLOT = 1
- local SAPLING_SLOT = 2
- local FIRST_STORAGE_SLOT = 3
- local LAST_STORAGE_SLOT = 16
- -- Maximum saplings to keep (excess deposited in chest)
- local MAX_SAPLINGS = 32
- -- How long to wait on chest between farming cycles
- local CHEST_WAIT_TIME = 5
- -- Maximum height to climb when cutting trees (safety limit)
- local MAX_TREE_HEIGHT = 20
- -- Minimum fuel level before attempting to refuel
- local MIN_FUEL_LEVEL = 80
- -- =============================================================================
- -- Helper Functions
- -- =============================================================================
- -- Function to check fuel and refuel if necessary
- local function ensureFuel()
- local currentFuel = turtle.getFuelLevel()
- if currentFuel == "unlimited" then
- return true
- end
- if currentFuel < MIN_FUEL_LEVEL then
- print("Low on fuel (" .. currentFuel .. "). Refueling...")
- turtle.select(FUEL_SLOT)
- -- Try to refuel 2-3 items for good fuel buffer
- for i = 1, 3 do
- if turtle.refuel(1) then
- print("Refueled. Current level: " .. turtle.getFuelLevel())
- else
- if i == 1 then
- print("ERROR: No fuel items in slot " .. FUEL_SLOT .. "!")
- return false
- end
- break -- No more fuel items, but we got some
- end
- end
- end
- return true
- end
- -- Function to manage inventory by depositing items into chest
- local function manageInventory()
- print("Managing inventory...")
- -- Count current saplings
- turtle.select(SAPLING_SLOT)
- local saplingCount = turtle.getItemCount(SAPLING_SLOT)
- -- Deposit ALL items from storage slots (slots 3-16)
- for i = FIRST_STORAGE_SLOT, LAST_STORAGE_SLOT do
- turtle.select(i)
- if turtle.getItemCount(i) > 0 then
- turtle.dropDown() -- Drop everything into chest below
- end
- end
- -- Deposit excess saplings if we have more than MAX_SAPLINGS
- if saplingCount > MAX_SAPLINGS then
- turtle.select(SAPLING_SLOT)
- local excessSaplings = saplingCount - MAX_SAPLINGS
- turtle.dropDown(excessSaplings)
- print("Deposited " .. excessSaplings .. " excess saplings.")
- end
- -- Reselect sapling slot for consistent state
- turtle.select(SAPLING_SLOT)
- print("Inventory management complete.")
- end
- -- Function to check if inventory is getting full
- local function isInventoryFull()
- local emptySlots = 0
- for i = FIRST_STORAGE_SLOT, LAST_STORAGE_SLOT do
- if turtle.getItemCount(i) == 0 then
- emptySlots = emptySlots + 1
- end
- end
- -- Consider full if we have less than 3 empty slots (safety margin)
- return emptySlots < 3
- end
- -- Function to get current sapling count
- local function getSaplingCount()
- turtle.select(SAPLING_SLOT)
- return turtle.getItemCount(SAPLING_SLOT)
- end
- -- Function to check if turtle is on cobblestone path
- local function isOnCobblestone()
- local success, blockData = turtle.inspectDown()
- if success then
- return blockData.name == "minecraft:cobblestone"
- end
- return false
- end
- -- Function to safely move forward with path verification
- local function moveForwardSafely()
- if not ensureFuel() then
- return false
- end
- -- Clear any obstacles in front
- while turtle.detect() do
- if not turtle.dig() then
- print("Cannot clear obstacle ahead!")
- return false
- end
- end
- -- Move forward
- if not turtle.forward() then
- print("Cannot move forward!")
- return false
- end
- return true
- end
- -- Function to return to chest (turn around and go back)
- local function returnToChest(stepsFromChest)
- print("Returning to chest (" .. stepsFromChest .. " steps)...")
- -- Make sure we have fuel for the return trip
- if not ensureFuel() then
- print("ERROR: Cannot refuel for return trip!")
- return false
- end
- -- Turn around 180 degrees to face back toward chest
- turtle.turnLeft()
- turtle.turnLeft()
- -- Walk back to chest with progress tracking
- for i = 1, stepsFromChest do
- print("Returning... step " .. i .. "/" .. stepsFromChest)
- if not moveForwardSafely() then
- print("ERROR: Cannot return to chest! Stopped at step " .. i)
- print("Turtle position: " .. (stepsFromChest - i + 1) .. " steps from chest")
- return false
- end
- end
- -- Turn around 180 degrees again to face original direction
- print("Turning to face original direction...")
- turtle.turnLeft()
- turtle.turnLeft()
- print("Successfully returned to chest and oriented correctly.")
- return true
- end
- -- Function to move off chest to first cobblestone block
- local function moveToPath()
- if not ensureFuel() then
- return false
- end
- print("Moving from chest to cobblestone path...")
- if not moveForwardSafely() then
- return false
- end
- if not isOnCobblestone() then
- print("WARNING: Not on cobblestone path! Check your setup.")
- return false
- end
- print("On cobblestone path.")
- return true
- end
- -- Function to collect saplings from all 6 directions (including up and down)
- local function collectSaplings()
- local initialSaplings = getSaplingCount()
- local collected = 0
- turtle.select(SAPLING_SLOT)
- -- Try to suck from current position (items on ground at same level)
- if turtle.suck() then
- collected = collected + 1
- end
- -- Check above (saplings on leaf blocks or dropped from height)
- if turtle.suckUp() then
- collected = collected + 1
- end
- -- Check below (saplings that fell directly underneath)
- if turtle.suckDown() then
- collected = collected + 1
- end
- -- Check front
- if turtle.suck() then
- collected = collected + 1
- end
- -- Check left
- turtle.turnLeft()
- if turtle.suck() then
- collected = collected + 1
- end
- -- Check back
- turtle.turnLeft()
- if turtle.suck() then
- collected = collected + 1
- end
- -- Check right
- turtle.turnLeft()
- if turtle.suck() then
- collected = collected + 1
- end
- -- Return to original orientation
- turtle.turnLeft()
- if collected > 0 then
- local finalSaplings = getSaplingCount()
- local actuallyCollected = finalSaplings - initialSaplings
- if actuallyCollected > 0 then
- print("Collected " .. actuallyCollected .. " saplings.")
- end
- end
- end
- -- Function to check if a block is a log (tree block)
- local function isLog(blockData)
- if not blockData then
- return false
- end
- return string.find(blockData.name, "log") ~= nil
- end
- -- Function to detect tree in a given direction (left or right)
- local function detectTree(direction)
- if direction == "left" then
- turtle.turnLeft()
- elseif direction == "right" then
- turtle.turnRight()
- end
- local success, blockData = turtle.inspect()
- local hasTree = success and isLog(blockData)
- -- Return to original orientation
- if direction == "left" then
- turtle.turnRight()
- elseif direction == "right" then
- turtle.turnLeft()
- end
- return hasTree
- end
- -- Function to cut down a tree (turtle must be facing the tree base)
- local function cutTreeInDirection()
- if not ensureFuel() then
- return false
- end
- print("Cutting tree...")
- -- Select a storage slot for tree cutting (not fuel or saplings)
- turtle.select(FIRST_STORAGE_SLOT)
- -- Mine the base log
- if not turtle.dig() then
- print("Cannot mine tree base!")
- return false
- end
- -- Move to tree base position
- if not turtle.forward() then
- print("Cannot move to tree base!")
- return false
- end
- local height = 0
- local maxRetries = 3
- -- Go up while there are logs above, mining as we go
- while height < MAX_TREE_HEIGHT do
- -- Check fuel before each major operation
- if not ensureFuel() then
- print("Low fuel during tree cutting! Descending...")
- break
- end
- -- Check if there's a log above us
- local success, blockData = turtle.inspectUp()
- if not (success and isLog(blockData)) then
- break -- No more logs above
- end
- -- Mine the log above with retries
- local digRetries = 0
- while not turtle.digUp() and digRetries < maxRetries do
- digRetries = digRetries + 1
- os.sleep(0.5) -- Wait for falling blocks
- end
- if digRetries >= maxRetries then
- print("Cannot mine log above after " .. maxRetries .. " attempts!")
- break
- end
- -- Try to move up with retries
- local moveRetries = 0
- while not turtle.up() and moveRetries < maxRetries do
- moveRetries = moveRetries + 1
- turtle.digUp() -- Clear any obstruction
- os.sleep(0.5)
- end
- if moveRetries >= maxRetries then
- print("Cannot move up after " .. maxRetries .. " attempts!")
- break
- end
- height = height + 1
- -- Also mine any logs in front while we're going up
- local frontDigAttempts = 0
- while turtle.detect() and frontDigAttempts < 5 do
- local frontSuccess, frontData = turtle.inspect()
- if frontSuccess and isLog(frontData) then
- turtle.dig()
- else
- break
- end
- frontDigAttempts = frontDigAttempts + 1
- end
- end
- -- Emergency failsafe: if we went too high, record it
- if height >= MAX_TREE_HEIGHT then
- print("WARNING: Reached maximum tree height limit!")
- end
- -- Go all the way back down to ground level
- print("Descending from height " .. height .. "...")
- for i = 1, height do
- local downRetries = 0
- while not turtle.down() and downRetries < maxRetries do
- downRetries = downRetries + 1
- turtle.digDown() -- Clear any obstruction below
- os.sleep(0.5)
- end
- if downRetries >= maxRetries then
- print("CRITICAL ERROR: Cannot descend! Stuck at height " .. (height - i + 1))
- print("Manual intervention required!")
- return false
- end
- end
- -- Move back to the path with retries
- local backRetries = 0
- while not turtle.back() and backRetries < maxRetries do
- backRetries = backRetries + 1
- turtle.dig() -- Clear any obstruction in the way
- os.sleep(0.5)
- end
- if backRetries >= maxRetries then
- print("ERROR: Cannot return to path after " .. maxRetries .. " attempts!")
- return false
- end
- print("Tree cut successfully.")
- return true
- end
- -- Function to check and cut tree on left or right side
- local function checkAndCutTree(direction)
- if not detectTree(direction) then
- return true -- No tree, nothing to do
- end
- -- Turn to face the tree
- if direction == "left" then
- turtle.turnLeft()
- elseif direction == "right" then
- turtle.turnRight()
- end
- -- Cut the tree
- local success = cutTreeInDirection()
- -- Return to original orientation
- if direction == "left" then
- turtle.turnRight()
- elseif direction == "right" then
- turtle.turnLeft()
- end
- return success
- end
- -- Function to check if there's air (empty space) in a given direction
- local function detectAir(direction)
- if direction == "left" then
- turtle.turnLeft()
- elseif direction == "right" then
- turtle.turnRight()
- end
- local hasAir = not turtle.detect()
- -- Return to original orientation
- if direction == "left" then
- turtle.turnRight()
- elseif direction == "right" then
- turtle.turnLeft()
- end
- return hasAir
- end
- -- Function to plant sapling by moving to the spot, collecting items, and planting
- local function plantSapling(direction)
- -- Ensure fuel for planting operations
- if not ensureFuel() then
- return false
- end
- -- Check if we have saplings to plant
- local saplingCount = getSaplingCount()
- if saplingCount == 0 then
- print("No saplings to plant on " .. direction .. " side.")
- return true -- No saplings to plant, but that's okay
- end
- -- Check if there's air where we want to plant
- if not detectAir(direction) then
- return true -- No air space, nothing to do
- end
- print("Moving to " .. direction .. " side to plant and collect items...")
- -- Turn to face the planting direction
- if direction == "left" then
- turtle.turnLeft()
- elseif direction == "right" then
- turtle.turnRight()
- end
- -- Move to the planting spot
- if not turtle.forward() then
- print("Cannot move to " .. direction .. " planting spot!")
- -- Return to original orientation
- if direction == "left" then
- turtle.turnRight()
- elseif direction == "right" then
- turtle.turnLeft()
- end
- return false
- end
- -- Collect items from all 6 directions while on the planting spot
- collectSaplings()
- -- Plant sapling below (since we're standing on the planting spot)
- turtle.select(SAPLING_SLOT)
- local success = turtle.placeDown()
- if success then
- print("Planted sapling on " .. direction .. " side.")
- end
- -- Move back to the path
- if not turtle.back() then
- print("ERROR: Cannot return to path from " .. direction .. " side!")
- return false
- end
- -- Return to original orientation (facing forward along path)
- if direction == "left" then
- turtle.turnRight()
- elseif direction == "right" then
- turtle.turnLeft()
- end
- return true
- end
- -- =============================================================================
- -- Main Program Logic
- -- =============================================================================
- -- Function to perform one complete farming cycle
- local function farmingCycle()
- local stepsFromChest = 0
- print("Starting farming cycle...")
- -- Step 1: Start on chest, manage inventory, check fuel
- print("Managing inventory and checking fuel...")
- manageInventory()
- if not ensureFuel() then
- print("ERROR: Not enough fuel to start farming cycle!")
- return false
- end
- -- Step 2: Move to cobblestone path
- if not moveToPath() then
- print("ERROR: Cannot reach cobblestone path!")
- return false
- end
- stepsFromChest = 1
- -- Step 3: Main farming loop
- while true do
- -- Check fuel before operations
- if not ensureFuel() then
- print("Low fuel detected. Returning to chest early.")
- break
- end
- -- Check if inventory is getting full
- if isInventoryFull() then
- print("Inventory full. Returning to chest.")
- break
- end
- print("Farming at position " .. stepsFromChest .. " steps from chest.")
- -- Ensure fuel before tree operations
- ensureFuel()
- -- Check and cut left tree, then plant sapling if needed
- if not checkAndCutTree("left") then
- print("Error cutting left tree. Continuing...")
- end
- plantSapling("left")
- -- Check and cut right tree, then plant sapling if needed
- if not checkAndCutTree("right") then
- print("Error cutting right tree. Continuing...")
- end
- plantSapling("right")
- -- Collect any remaining items on the path
- collectSaplings()
- -- Try to move forward
- if not moveForwardSafely() then
- print("Cannot move forward. Returning to chest.")
- break
- end
- stepsFromChest = stepsFromChest + 1
- -- Check if we're still on cobblestone path
- if not isOnCobblestone() then
- print("Reached end of cobblestone path. Returning to chest.")
- -- Step back onto the cobblestone
- if turtle.back() then
- stepsFromChest = stepsFromChest - 1
- end
- break
- end
- end
- -- Step 4: Return to chest
- if not returnToChest(stepsFromChest) then
- print("ERROR: Failed to return to chest!")
- return false
- end
- print("Farming cycle completed successfully.")
- return true
- end
- -- Main program function
- local function main()
- print("=== Tree Farm v1.0 ===")
- print("Automated tree farming system starting...")
- print("")
- print("Setup verification:")
- print("- Turtle should be on top of a chest")
- print("- Current fuel level: " .. turtle.getFuelLevel())
- print("- Fuel in slot 1: " .. turtle.getItemCount(FUEL_SLOT) .. " items")
- print("- Saplings in slot 2: " .. turtle.getItemCount(SAPLING_SLOT) .. " items")
- print("- Cobblestone path should extend forward")
- print("")
- -- Initial sapling check
- if getSaplingCount() == 0 then
- print("WARNING: No saplings found in slot 2!")
- print("The turtle will still collect saplings but cannot plant any initially.")
- end
- -- Proactive refueling at startup
- print("Ensuring fuel at startup...")
- if not ensureFuel() then
- print("ERROR: Cannot refuel at startup! Please add fuel to slot 1.")
- return
- end
- print("Starting continuous farming operation...")
- print("Press Ctrl+T to stop the program.")
- print("")
- local cycleCount = 0
- -- Main farming loop
- while true do
- cycleCount = cycleCount + 1
- print("=== Cycle " .. cycleCount .. " ===")
- -- Ensure fuel at start of each cycle
- if not ensureFuel() then
- print("ERROR: Cannot refuel for cycle " .. cycleCount .. "! Stopping program.")
- break
- end
- -- Check if we have saplings before starting farming cycle
- if getSaplingCount() == 0 then
- print("No saplings available. Waiting on chest for saplings to be added...")
- print("Waiting " .. CHEST_WAIT_TIME .. " seconds before checking again...")
- os.sleep(CHEST_WAIT_TIME)
- cycleCount = cycleCount - 1 -- Don't count this as a real cycle
- else
- -- Perform farming cycle
- if not farmingCycle() then
- print("ERROR: Farming cycle failed! Stopping program.")
- break
- end
- -- Wait on chest between cycles
- print("Waiting " .. CHEST_WAIT_TIME .. " seconds before next cycle...")
- os.sleep(CHEST_WAIT_TIME)
- end
- end
- print("Tree farming program ended.")
- end
- -- Run the main program
- main()
Add Comment
Please, Sign In to add comment