svdragster

Untitled

Aug 10th, 2025
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 18.99 KB | None | 0 0
  1. --[[
  2.   Automated Tree Farm Program for ComputerCraft Turtles
  3.  
  4.   Description:
  5.   This program creates an automated tree farming system where the turtle follows
  6.   a cobblestone path, harvests mature trees, plants saplings, and manages inventory
  7.   by depositing items into a chest at the starting position.
  8.  
  9.   Setup:
  10.   1. Place the turtle on top of a chest (starting position)
  11.   2. Put fuel (e.g., Coal, Charcoal) in Slot 1 of the turtle's inventory
  12.  3. Put saplings in Slot 2 (up to 32, excess will be deposited)
  13.  4. Create a straight cobblestone path in the direction the turtle faces
  14.  5. The turtle will follow this path, turning around when it reaches non-cobblestone
  15.  
  16.  Operation:
  17.  - Moves forward along cobblestone path
  18.  - Collects saplings from all 4 directions at each position
  19.  - Checks left and right sides for trees to harvest
  20.  - Plants saplings in empty spaces on left and right sides
  21.  - Returns to chest when reaching end of cobblestone path
  22.  - Deposits wood and excess saplings, then waits 5 seconds before repeating
  23.  
  24.  Usage:
  25.  Run the program without arguments: treefarm
  26.  The turtle will start the farming cycle automatically.
  27. --]]
  28.  
  29. -- =============================================================================
  30. -- Configuration
  31. -- =============================================================================
  32.  
  33. local FUEL_SLOT = 1
  34. local SAPLING_SLOT = 2
  35. local FIRST_STORAGE_SLOT = 3
  36. local LAST_STORAGE_SLOT = 16
  37.  
  38. -- Maximum saplings to keep (excess deposited in chest)
  39. local MAX_SAPLINGS = 32
  40.  
  41. -- How long to wait on chest between farming cycles
  42. local CHEST_WAIT_TIME = 5
  43.  
  44. -- Maximum height to climb when cutting trees (safety limit)
  45. local MAX_TREE_HEIGHT = 20
  46.  
  47. -- Minimum fuel level before attempting to refuel
  48. local MIN_FUEL_LEVEL = 80
  49.  
  50. -- =============================================================================
  51. -- Helper Functions
  52. -- =============================================================================
  53.  
  54. -- Function to check fuel and refuel if necessary
  55. local function ensureFuel()
  56.  local currentFuel = turtle.getFuelLevel()
  57.  if currentFuel == "unlimited" then
  58.    return true
  59.  end
  60.  
  61.  if currentFuel < MIN_FUEL_LEVEL then
  62.    print("Low on fuel (" .. currentFuel .. "). Refueling...")
  63.    turtle.select(FUEL_SLOT)
  64.    
  65.    -- Try to refuel 2-3 items for good fuel buffer
  66.    for i = 1, 3 do
  67.      if turtle.refuel(1) then
  68.        print("Refueled. Current level: " .. turtle.getFuelLevel())
  69.      else
  70.        if i == 1 then
  71.          print("ERROR: No fuel items in slot " .. FUEL_SLOT .. "!")
  72.          return false
  73.        end
  74.        break -- No more fuel items, but we got some
  75.      end
  76.    end
  77.  end
  78.  return true
  79. end
  80.  
  81. -- Function to manage inventory by depositing items into chest
  82. local function manageInventory()
  83.  print("Managing inventory...")
  84.  
  85.  -- Count current saplings
  86.  turtle.select(SAPLING_SLOT)
  87.  local saplingCount = turtle.getItemCount(SAPLING_SLOT)
  88.  
  89.  -- Deposit ALL items from storage slots (slots 3-16)
  90.  for i = FIRST_STORAGE_SLOT, LAST_STORAGE_SLOT do
  91.    turtle.select(i)
  92.    if turtle.getItemCount(i) > 0 then
  93.      turtle.dropDown() -- Drop everything into chest below
  94.    end
  95.  end
  96.  
  97.  -- Deposit excess saplings if we have more than MAX_SAPLINGS
  98.  if saplingCount > MAX_SAPLINGS then
  99.    turtle.select(SAPLING_SLOT)
  100.    local excessSaplings = saplingCount - MAX_SAPLINGS
  101.    turtle.dropDown(excessSaplings)
  102.    print("Deposited " .. excessSaplings .. " excess saplings.")
  103.  end
  104.  
  105.  -- Reselect sapling slot for consistent state
  106.  turtle.select(SAPLING_SLOT)
  107.  print("Inventory management complete.")
  108. end
  109.  
  110. -- Function to check if inventory is getting full
  111. local function isInventoryFull()
  112.  local emptySlots = 0
  113.  for i = FIRST_STORAGE_SLOT, LAST_STORAGE_SLOT do
  114.    if turtle.getItemCount(i) == 0 then
  115.      emptySlots = emptySlots + 1
  116.    end
  117.  end
  118.  -- Consider full if we have less than 3 empty slots (safety margin)
  119.  return emptySlots < 3
  120. end
  121.  
  122. -- Function to get current sapling count
  123. local function getSaplingCount()
  124.  turtle.select(SAPLING_SLOT)
  125.  return turtle.getItemCount(SAPLING_SLOT)
  126. end
  127.  
  128. -- Function to check if turtle is on cobblestone path
  129. local function isOnCobblestone()
  130.  local success, blockData = turtle.inspectDown()
  131.  if success then
  132.    return blockData.name == "minecraft:cobblestone"
  133.  end
  134.  return false
  135. end
  136.  
  137. -- Function to safely move forward with path verification
  138. local function moveForwardSafely()
  139.  if not ensureFuel() then
  140.    return false
  141.  end
  142.  
  143.  -- Clear any obstacles in front
  144.  while turtle.detect() do
  145.    if not turtle.dig() then
  146.      print("Cannot clear obstacle ahead!")
  147.      return false
  148.    end
  149.  end
  150.  
  151.  -- Move forward
  152.  if not turtle.forward() then
  153.    print("Cannot move forward!")
  154.    return false
  155.  end
  156.  
  157.  return true
  158. end
  159.  
  160. -- Function to return to chest (turn around and go back)
  161. local function returnToChest(stepsFromChest)
  162.  print("Returning to chest (" .. stepsFromChest .. " steps)...")
  163.  
  164.  -- Make sure we have fuel for the return trip
  165.  if not ensureFuel() then
  166.    print("ERROR: Cannot refuel for return trip!")
  167.    return false
  168.  end
  169.  
  170.  -- Turn around 180 degrees to face back toward chest
  171.  turtle.turnLeft()
  172.  turtle.turnLeft()
  173.  
  174.  -- Walk back to chest with progress tracking
  175.  for i = 1, stepsFromChest do
  176.    print("Returning... step " .. i .. "/" .. stepsFromChest)
  177.    
  178.    if not moveForwardSafely() then
  179.      print("ERROR: Cannot return to chest! Stopped at step " .. i)
  180.      print("Turtle position: " .. (stepsFromChest - i + 1) .. " steps from chest")
  181.      return false
  182.    end
  183.  end
  184.  
  185.  -- Turn around 180 degrees again to face original direction
  186.  print("Turning to face original direction...")
  187.  turtle.turnLeft()
  188.  turtle.turnLeft()
  189.  
  190.  print("Successfully returned to chest and oriented correctly.")
  191.  return true
  192. end
  193.  
  194. -- Function to move off chest to first cobblestone block
  195. local function moveToPath()
  196.  if not ensureFuel() then
  197.    return false
  198.  end
  199.  
  200.  print("Moving from chest to cobblestone path...")
  201.  if not moveForwardSafely() then
  202.    return false
  203.  end
  204.  
  205.  if not isOnCobblestone() then
  206.    print("WARNING: Not on cobblestone path! Check your setup.")
  207.    return false
  208.  end
  209.  
  210.  print("On cobblestone path.")
  211.  return true
  212. end
  213.  
  214. -- Function to collect saplings from all 6 directions (including up and down)
  215. local function collectSaplings()
  216.  local initialSaplings = getSaplingCount()
  217.  local collected = 0
  218.  
  219.  turtle.select(SAPLING_SLOT)
  220.  
  221.  -- Try to suck from current position (items on ground at same level)
  222.  if turtle.suck() then
  223.    collected = collected + 1
  224.  end
  225.  
  226.  -- Check above (saplings on leaf blocks or dropped from height)
  227.  if turtle.suckUp() then
  228.    collected = collected + 1
  229.  end
  230.  
  231.  -- Check below (saplings that fell directly underneath)
  232.  if turtle.suckDown() then
  233.    collected = collected + 1
  234.  end
  235.  
  236.  -- Check front
  237.  if turtle.suck() then
  238.    collected = collected + 1
  239.  end
  240.  
  241.  -- Check left
  242.  turtle.turnLeft()
  243.  if turtle.suck() then
  244.    collected = collected + 1
  245.  end
  246.  
  247.  -- Check back
  248.  turtle.turnLeft()
  249.  if turtle.suck() then
  250.    collected = collected + 1
  251.  end
  252.  
  253.  -- Check right
  254.  turtle.turnLeft()
  255.  if turtle.suck() then
  256.    collected = collected + 1
  257.  end
  258.  
  259.  -- Return to original orientation
  260.  turtle.turnLeft()
  261.  
  262.  if collected > 0 then
  263.    local finalSaplings = getSaplingCount()
  264.    local actuallyCollected = finalSaplings - initialSaplings
  265.    if actuallyCollected > 0 then
  266.      print("Collected " .. actuallyCollected .. " saplings.")
  267.    end
  268.  end
  269. end
  270.  
  271. -- Function to check if a block is a log (tree block)
  272. local function isLog(blockData)
  273.  if not blockData then
  274.    return false
  275.  end
  276.  return string.find(blockData.name, "log") ~= nil
  277. end
  278.  
  279. -- Function to detect tree in a given direction (left or right)
  280. local function detectTree(direction)
  281.  if direction == "left" then
  282.    turtle.turnLeft()
  283.  elseif direction == "right" then
  284.    turtle.turnRight()
  285.  end
  286.  
  287.  local success, blockData = turtle.inspect()
  288.  local hasTree = success and isLog(blockData)
  289.  
  290.  -- Return to original orientation
  291.  if direction == "left" then
  292.    turtle.turnRight()
  293.  elseif direction == "right" then
  294.    turtle.turnLeft()
  295.  end
  296.  
  297.  return hasTree
  298. end
  299.  
  300. -- Function to cut down a tree (turtle must be facing the tree base)
  301. local function cutTreeInDirection()
  302.  if not ensureFuel() then
  303.    return false
  304.  end
  305.  
  306.  print("Cutting tree...")
  307.  
  308.  -- Select a storage slot for tree cutting (not fuel or saplings)
  309.  turtle.select(FIRST_STORAGE_SLOT)
  310.  
  311.  -- Mine the base log
  312.  if not turtle.dig() then
  313.    print("Cannot mine tree base!")
  314.    return false
  315.  end
  316.  
  317.  -- Move to tree base position
  318.  if not turtle.forward() then
  319.    print("Cannot move to tree base!")
  320.    return false
  321.  end
  322.  
  323.  local height = 0
  324.  local maxRetries = 3
  325.  
  326.  -- Go up while there are logs above, mining as we go
  327.  while height < MAX_TREE_HEIGHT do
  328.    -- Check fuel before each major operation
  329.    if not ensureFuel() then
  330.      print("Low fuel during tree cutting! Descending...")
  331.      break
  332.    end
  333.    
  334.    -- Check if there's a log above us
  335.     local success, blockData = turtle.inspectUp()
  336.     if not (success and isLog(blockData)) then
  337.       break -- No more logs above
  338.     end
  339.    
  340.     -- Mine the log above with retries
  341.     local digRetries = 0
  342.     while not turtle.digUp() and digRetries < maxRetries do
  343.       digRetries = digRetries + 1
  344.       os.sleep(0.5) -- Wait for falling blocks
  345.     end
  346.    
  347.     if digRetries >= maxRetries then
  348.       print("Cannot mine log above after " .. maxRetries .. " attempts!")
  349.       break
  350.     end
  351.    
  352.     -- Try to move up with retries
  353.     local moveRetries = 0
  354.     while not turtle.up() and moveRetries < maxRetries do
  355.       moveRetries = moveRetries + 1
  356.       turtle.digUp() -- Clear any obstruction
  357.       os.sleep(0.5)
  358.     end
  359.    
  360.     if moveRetries >= maxRetries then
  361.       print("Cannot move up after " .. maxRetries .. " attempts!")
  362.       break
  363.     end
  364.    
  365.     height = height + 1
  366.    
  367.     -- Also mine any logs in front while we're going up
  368.    local frontDigAttempts = 0
  369.    while turtle.detect() and frontDigAttempts < 5 do
  370.      local frontSuccess, frontData = turtle.inspect()
  371.      if frontSuccess and isLog(frontData) then
  372.        turtle.dig()
  373.      else
  374.        break
  375.      end
  376.      frontDigAttempts = frontDigAttempts + 1
  377.    end
  378.  end
  379.  
  380.  -- Emergency failsafe: if we went too high, record it
  381.  if height >= MAX_TREE_HEIGHT then
  382.    print("WARNING: Reached maximum tree height limit!")
  383.  end
  384.  
  385.  -- Go all the way back down to ground level
  386.  print("Descending from height " .. height .. "...")
  387.  for i = 1, height do
  388.    local downRetries = 0
  389.    while not turtle.down() and downRetries < maxRetries do
  390.      downRetries = downRetries + 1
  391.      turtle.digDown() -- Clear any obstruction below
  392.      os.sleep(0.5)
  393.    end
  394.    
  395.    if downRetries >= maxRetries then
  396.      print("CRITICAL ERROR: Cannot descend! Stuck at height " .. (height - i + 1))
  397.      print("Manual intervention required!")
  398.      return false
  399.    end
  400.  end
  401.  
  402.  -- Move back to the path with retries
  403.  local backRetries = 0
  404.  while not turtle.back() and backRetries < maxRetries do
  405.    backRetries = backRetries + 1
  406.    turtle.dig() -- Clear any obstruction in the way
  407.    os.sleep(0.5)
  408.  end
  409.  
  410.  if backRetries >= maxRetries then
  411.    print("ERROR: Cannot return to path after " .. maxRetries .. " attempts!")
  412.    return false
  413.  end
  414.  
  415.  print("Tree cut successfully.")
  416.  return true
  417. end
  418.  
  419. -- Function to check and cut tree on left or right side
  420. local function checkAndCutTree(direction)
  421.  if not detectTree(direction) then
  422.    return true -- No tree, nothing to do
  423.  end
  424.  
  425.  -- Turn to face the tree
  426.  if direction == "left" then
  427.    turtle.turnLeft()
  428.  elseif direction == "right" then
  429.    turtle.turnRight()
  430.  end
  431.  
  432.  -- Cut the tree
  433.  local success = cutTreeInDirection()
  434.  
  435.  -- Return to original orientation
  436.  if direction == "left" then
  437.    turtle.turnRight()
  438.  elseif direction == "right" then
  439.    turtle.turnLeft()
  440.  end
  441.  
  442.  return success
  443. end
  444.  
  445. -- Function to check if there's air (empty space) in a given direction
  446. local function detectAir(direction)
  447.   if direction == "left" then
  448.     turtle.turnLeft()
  449.   elseif direction == "right" then
  450.     turtle.turnRight()
  451.   end
  452.  
  453.   local hasAir = not turtle.detect()
  454.  
  455.   -- Return to original orientation
  456.   if direction == "left" then
  457.     turtle.turnRight()
  458.   elseif direction == "right" then
  459.     turtle.turnLeft()
  460.   end
  461.  
  462.   return hasAir
  463. end
  464.  
  465. -- Function to plant sapling by moving to the spot, collecting items, and planting
  466. local function plantSapling(direction)
  467.   -- Ensure fuel for planting operations
  468.   if not ensureFuel() then
  469.     return false
  470.   end
  471.  
  472.   -- Check if we have saplings to plant
  473.   local saplingCount = getSaplingCount()
  474.   if saplingCount == 0 then
  475.     print("No saplings to plant on " .. direction .. " side.")
  476.     return true -- No saplings to plant, but that's okay
  477.  end
  478.  
  479.  -- Check if there's air where we want to plant
  480.   if not detectAir(direction) then
  481.     return true -- No air space, nothing to do
  482.   end
  483.  
  484.   print("Moving to " .. direction .. " side to plant and collect items...")
  485.  
  486.   -- Turn to face the planting direction
  487.   if direction == "left" then
  488.     turtle.turnLeft()
  489.   elseif direction == "right" then
  490.     turtle.turnRight()
  491.   end
  492.  
  493.   -- Move to the planting spot
  494.   if not turtle.forward() then
  495.     print("Cannot move to " .. direction .. " planting spot!")
  496.     -- Return to original orientation
  497.     if direction == "left" then
  498.       turtle.turnRight()
  499.     elseif direction == "right" then
  500.       turtle.turnLeft()
  501.     end
  502.     return false
  503.   end
  504.  
  505.   -- Collect items from all 6 directions while on the planting spot
  506.   collectSaplings()
  507.  
  508.   -- Move back to the path
  509.   if not turtle.back() then
  510.     print("ERROR: Cannot return to path from " .. direction .. " side!")
  511.     return false
  512.   end
  513.  
  514.   -- Now plant sapling forward (onto the spot where we just were)
  515.   turtle.select(SAPLING_SLOT)
  516.   local success = turtle.place()
  517.  
  518.   if success then
  519.     print("Planted sapling on " .. direction .. " side.")
  520.   end
  521.  
  522.   -- Return to original orientation (facing forward along path)
  523.   if direction == "left" then
  524.     turtle.turnRight()
  525.   elseif direction == "right" then
  526.     turtle.turnLeft()
  527.   end
  528.  
  529.   return true
  530. end
  531.  
  532. -- =============================================================================
  533. -- Main Program Logic
  534. -- =============================================================================
  535.  
  536. -- Function to perform one complete farming cycle
  537. local function farmingCycle()
  538.   local stepsFromChest = 0
  539.  
  540.   print("Starting farming cycle...")
  541.  
  542.   -- Step 1: Start on chest, manage inventory, check fuel
  543.   print("Managing inventory and checking fuel...")
  544.   manageInventory()
  545.   if not ensureFuel() then
  546.     print("ERROR: Not enough fuel to start farming cycle!")
  547.     return false
  548.   end
  549.  
  550.   -- Step 2: Move to cobblestone path
  551.   if not moveToPath() then
  552.     print("ERROR: Cannot reach cobblestone path!")
  553.     return false
  554.   end
  555.   stepsFromChest = 1
  556.  
  557.   -- Step 3: Main farming loop
  558.   while true do
  559.     -- Check fuel before operations
  560.     if not ensureFuel() then
  561.       print("Low fuel detected. Returning to chest early.")
  562.       break
  563.     end
  564.    
  565.     -- Check if inventory is getting full
  566.     if isInventoryFull() then
  567.       print("Inventory full. Returning to chest.")
  568.       break
  569.     end
  570.    
  571.     print("Farming at position " .. stepsFromChest .. " steps from chest.")
  572.    
  573.     -- Ensure fuel before tree operations
  574.     ensureFuel()
  575.    
  576.     -- Check and cut left tree, then plant sapling if needed
  577.     if not checkAndCutTree("left") then
  578.       print("Error cutting left tree. Continuing...")
  579.     end
  580.     plantSapling("left")
  581.    
  582.     -- Check and cut right tree, then plant sapling if needed
  583.     if not checkAndCutTree("right") then
  584.       print("Error cutting right tree. Continuing...")
  585.     end
  586.     plantSapling("right")
  587.    
  588.     -- Collect any remaining items on the path
  589.     collectSaplings()
  590.    
  591.     -- Try to move forward
  592.     if not moveForwardSafely() then
  593.       print("Cannot move forward. Returning to chest.")
  594.       break
  595.     end
  596.     stepsFromChest = stepsFromChest + 1
  597.    
  598.     -- Check if we're still on cobblestone path
  599.    if not isOnCobblestone() then
  600.      print("Reached end of cobblestone path. Returning to chest.")
  601.      -- Step back onto the cobblestone
  602.      if turtle.back() then
  603.        stepsFromChest = stepsFromChest - 1
  604.      end
  605.      break
  606.    end
  607.  end
  608.  
  609.  -- Step 4: Return to chest
  610.  if not returnToChest(stepsFromChest) then
  611.    print("ERROR: Failed to return to chest!")
  612.    return false
  613.  end
  614.  
  615.  print("Farming cycle completed successfully.")
  616.  return true
  617. end
  618.  
  619. -- Main program function
  620. local function main()
  621.  print("=== Tree Farm v1.0 ===")
  622.  print("Automated tree farming system starting...")
  623.  print("")
  624.  print("Setup verification:")
  625.  print("- Turtle should be on top of a chest")
  626.  print("- Current fuel level: " .. turtle.getFuelLevel())
  627.  print("- Fuel in slot 1: " .. turtle.getItemCount(FUEL_SLOT) .. " items")
  628.  print("- Saplings in slot 2: " .. turtle.getItemCount(SAPLING_SLOT) .. " items")
  629.  print("- Cobblestone path should extend forward")
  630.  print("")
  631.  
  632.  -- Initial sapling check
  633.  if getSaplingCount() == 0 then
  634.    print("WARNING: No saplings found in slot 2!")
  635.    print("The turtle will still collect saplings but cannot plant any initially.")
  636.  end
  637.  
  638.  -- Proactive refueling at startup  
  639.  print("Ensuring fuel at startup...")
  640.  if not ensureFuel() then
  641.    print("ERROR: Cannot refuel at startup! Please add fuel to slot 1.")
  642.    return
  643.  end
  644.  
  645.  print("Starting continuous farming operation...")
  646.  print("Press Ctrl+T to stop the program.")
  647.  print("")
  648.  
  649.  local cycleCount = 0
  650.  
  651.  -- Main farming loop
  652.  while true do
  653.    cycleCount = cycleCount + 1
  654.    print("=== Cycle " .. cycleCount .. " ===")
  655.    
  656.    -- Ensure fuel at start of each cycle
  657.    if not ensureFuel() then
  658.      print("ERROR: Cannot refuel for cycle " .. cycleCount .. "! Stopping program.")
  659.      break
  660.    end
  661.    
  662.    -- Check if we have saplings before starting farming cycle
  663.    if getSaplingCount() == 0 then
  664.      print("No saplings available. Waiting on chest for saplings to be added...")
  665.      print("Waiting " .. CHEST_WAIT_TIME .. " seconds before checking again...")
  666.      os.sleep(CHEST_WAIT_TIME)
  667.      cycleCount = cycleCount - 1  -- Don't count this as a real cycle
  668.     else
  669.       -- Perform farming cycle
  670.       if not farmingCycle() then
  671.         print("ERROR: Farming cycle failed! Stopping program.")
  672.         break
  673.       end
  674.      
  675.       -- Wait on chest between cycles
  676.       print("Waiting " .. CHEST_WAIT_TIME .. " seconds before next cycle...")
  677.       os.sleep(CHEST_WAIT_TIME)
  678.     end
  679.   end
  680.  
  681.   print("Tree farming program ended.")
  682. end
  683.  
  684. -- Run the main program
  685. main()
Add Comment
Please, Sign In to add comment