svdragster

Untitled

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