svdragster

Untitled

Aug 10th, 2025
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 17.73 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 in a given direction (if there's air and we have saplings)
  466. local function plantSapling(direction)
  467.  -- Check if we have saplings to plant
  468.  local saplingCount = getSaplingCount()
  469.  if saplingCount == 0 then
  470.    return true -- No saplings to plant, but that's okay
  471.   end
  472.  
  473.   -- Check if there's air where we want to plant
  474.  if not detectAir(direction) then
  475.    return true -- No air space, nothing to do
  476.  end
  477.  
  478.  -- Turn to face the planting direction
  479.  if direction == "left" then
  480.    turtle.turnLeft()
  481.  elseif direction == "right" then
  482.    turtle.turnRight()
  483.  end
  484.  
  485.  -- Select saplings and plant
  486.  turtle.select(SAPLING_SLOT)
  487.  local success = turtle.place()
  488.  
  489.  -- Return to original orientation
  490.  if direction == "left" then
  491.    turtle.turnRight()
  492.  elseif direction == "right" then
  493.    turtle.turnLeft()
  494.  end
  495.  
  496.  if success then
  497.    print("Planted sapling on " .. direction .. " side.")
  498.  end
  499.  
  500.  return true
  501. end
  502.  
  503. -- =============================================================================
  504. -- Main Program Logic
  505. -- =============================================================================
  506.  
  507. -- Function to perform one complete farming cycle
  508. local function farmingCycle()
  509.  local stepsFromChest = 0
  510.  
  511.  print("Starting farming cycle...")
  512.  
  513.  -- Step 1: Start on chest, manage inventory, check fuel
  514.  print("Managing inventory and checking fuel...")
  515.  manageInventory()
  516.  if not ensureFuel() then
  517.    print("ERROR: Not enough fuel to start farming cycle!")
  518.    return false
  519.  end
  520.  
  521.  -- Step 2: Move to cobblestone path
  522.  if not moveToPath() then
  523.    print("ERROR: Cannot reach cobblestone path!")
  524.    return false
  525.  end
  526.  stepsFromChest = 1
  527.  
  528.  -- Step 3: Main farming loop
  529.  while true do
  530.    -- Check fuel before operations
  531.    if not ensureFuel() then
  532.      print("Low fuel detected. Returning to chest early.")
  533.      break
  534.    end
  535.    
  536.    -- Check if inventory is getting full
  537.    if isInventoryFull() then
  538.      print("Inventory full. Returning to chest.")
  539.      break
  540.    end
  541.    
  542.    print("Farming at position " .. stepsFromChest .. " steps from chest.")
  543.    
  544.    -- Collect saplings from all directions
  545.    collectSaplings()
  546.    
  547.    -- Ensure fuel before tree operations
  548.    ensureFuel()
  549.    
  550.    -- Check and cut left tree, then plant sapling if needed
  551.    if not checkAndCutTree("left") then
  552.      print("Error cutting left tree. Continuing...")
  553.    end
  554.    plantSapling("left")
  555.    
  556.    -- Check and cut right tree, then plant sapling if needed
  557.    if not checkAndCutTree("right") then
  558.      print("Error cutting right tree. Continuing...")
  559.    end
  560.    plantSapling("right")
  561.    
  562.    -- Try to move forward
  563.    if not moveForwardSafely() then
  564.      print("Cannot move forward. Returning to chest.")
  565.      break
  566.    end
  567.    stepsFromChest = stepsFromChest + 1
  568.    
  569.    -- Check if we're still on cobblestone path
  570.     if not isOnCobblestone() then
  571.       print("Reached end of cobblestone path. Returning to chest.")
  572.       -- Step back onto the cobblestone
  573.       if turtle.back() then
  574.         stepsFromChest = stepsFromChest - 1
  575.       end
  576.       break
  577.     end
  578.   end
  579.  
  580.   -- Step 4: Return to chest
  581.   if not returnToChest(stepsFromChest) then
  582.     print("ERROR: Failed to return to chest!")
  583.     return false
  584.   end
  585.  
  586.   print("Farming cycle completed successfully.")
  587.   return true
  588. end
  589.  
  590. -- Main program function
  591. local function main()
  592.   print("=== Tree Farm v1.0 ===")
  593.   print("Automated tree farming system starting...")
  594.   print("")
  595.   print("Setup verification:")
  596.   print("- Turtle should be on top of a chest")
  597.   print("- Current fuel level: " .. turtle.getFuelLevel())
  598.   print("- Fuel in slot 1: " .. turtle.getItemCount(FUEL_SLOT) .. " items")
  599.   print("- Saplings in slot 2: " .. turtle.getItemCount(SAPLING_SLOT) .. " items")
  600.   print("- Cobblestone path should extend forward")
  601.   print("")
  602.  
  603.   -- Initial sapling check
  604.   if getSaplingCount() == 0 then
  605.     print("WARNING: No saplings found in slot 2!")
  606.     print("The turtle will still collect saplings but cannot plant any initially.")
  607.   end
  608.  
  609.   -- Proactive refueling at startup  
  610.   print("Ensuring fuel at startup...")
  611.   if not ensureFuel() then
  612.     print("ERROR: Cannot refuel at startup! Please add fuel to slot 1.")
  613.     return
  614.   end
  615.  
  616.   print("Starting continuous farming operation...")
  617.   print("Press Ctrl+T to stop the program.")
  618.   print("")
  619.  
  620.   local cycleCount = 0
  621.  
  622.   -- Main farming loop
  623.   while true do
  624.     cycleCount = cycleCount + 1
  625.     print("=== Cycle " .. cycleCount .. " ===")
  626.    
  627.     -- Ensure fuel at start of each cycle
  628.     if not ensureFuel() then
  629.       print("ERROR: Cannot refuel for cycle " .. cycleCount .. "! Stopping program.")
  630.       break
  631.     end
  632.    
  633.     -- Perform farming cycle
  634.     if not farmingCycle() then
  635.       print("ERROR: Farming cycle failed! Stopping program.")
  636.       break
  637.     end
  638.    
  639.     -- Wait on chest between cycles
  640.     print("Waiting " .. CHEST_WAIT_TIME .. " seconds before next cycle...")
  641.     os.sleep(CHEST_WAIT_TIME)
  642.   end
  643.  
  644.   print("Tree farming program ended.")
  645. end
  646.  
  647. -- Run the main program
  648. main()
Add Comment
Please, Sign In to add comment