Maxwelljonez

MJZ MC LUA Modular Auto Turtle Wheat Farm

Aug 10th, 2023 (edited)
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 18.58 KB | Gaming | 0 0
  1. --{program="MJZ FarmBot",version="1.5"}
  2. ---------------------------------------
  3. -- 9.8.23   v1.0 initial
  4. -- 10.8.23  v1.1 improvements
  5. -- 10.8.23  v1.2 improvements on having multiple turtles and unique save files
  6. --          v1.3 added dropdown in bottom chest, added repeat loop function and timer
  7. -- 11.8.23  v1.4 General code improvements, torches calculation,
  8. -- 12.8.23  v1.5 Working now for even and uneven farm size, configurable timer
  9. --               More UX / UI improvements
  10. ---------------------------------------
  11. -- ToDo:
  12. -- announce available update, refuel from chest on top
  13.  
  14.  
  15. ---------------------------------------
  16. ---- DESCRIPTION ----------------------
  17. ---------------------------------------
  18. -- FarmBot: Modular Automated Turtle
  19. -- wheat farm (farming turtle)
  20. -- Details see information during
  21. -- program execution.
  22. -- Questions? Check on
  23. -- https://pastebin.com/P4Zcvj9B
  24. -- Please credit me if you use my
  25. -- program <3 <3 <3
  26.  
  27.  
  28. ---------------------------------------
  29. ---- PARAMETERS -----------------------
  30. ---------------------------------------
  31. local cVersion  ="1.5"
  32. local cPrgName  ="MJZ FarmBot"
  33. local debugging=false
  34. local slotFuel=16   -- where to put fuel
  35. local minFuel=300   -- the minimal amount of fuel required
  36. local sleepTime=400 -- the amount of time the turtle will wait until running another run
  37. -- Full name of crop as item and block and ripeness:
  38. local config = {
  39.     crop = {
  40.         block = "minecraft:wheat",
  41.         item = "minecraft:wheat_seeds",
  42.         ripe = 7 -- Default: 7 (crops have grow stages between 0 and 7)
  43.     },
  44. }
  45.  
  46.  --[[
  47.  /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
  48. Do not change anything below if you
  49. don't want the code to break!
  50.  /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
  51. ]]--
  52.  
  53. ---------------------------------------
  54. ---- VARIABLES ------------------------
  55. ---------------------------------------
  56. local width
  57. local length
  58. local time = os.time()
  59. local formattedTime = textutils.formatTime(time, true)
  60. local blnShowUsage=false
  61. local blnAskForParameters=true
  62. local blnAutoSetup=false
  63. local strSimpleCheck="Press enter to start: "
  64. local intCounter=0
  65. local maxCounter=0
  66. local fenceNeeded=0
  67. local torchesNeeded=0
  68. -- Dictionary of block names and its effects on the turtle:
  69. local BlockList = {}
  70. local computerID = os.getComputerID()
  71. local filename = "VarsFarmBot_" .. tostring(computerID)
  72. local skipConfig=false
  73. local sleepSeconds
  74. ---------------------------------------
  75. ---- tArgs ----------------------------
  76. ---------------------------------------
  77. local tArgs = {...}
  78. if #tArgs >= 1 then -- no error check
  79.   blnAskForParameters=false
  80.   if tArgs[1]=="help" then blnShowUsage=true end
  81.   if tArgs[1]=="setup" then blnAutoSetup=true end
  82.   if tArgs[1]=="set-up" then blnAutoSetup=true end
  83.   if tonumber(tArgs[1])~=nil then
  84.     maxCounter=tonumber(tArgs[1])
  85.   end
  86. end
  87.  
  88. -- Function to print debug information
  89. local function debug_print(txt, ...)
  90.     if debugging then
  91.         io.write(string.format(txt .. "\n", ...))
  92.     end
  93. end
  94. -- Add blocks to check for to BlockList dictionary:
  95. local function newBlock(blockName, blockFunction)
  96.     local temp = {
  97.         block = blockName,
  98.         fn = blockFunction
  99.     }
  100.     BlockList[blockName] = blockFunction
  101.     return temp
  102. end
  103. ---------------------------------------
  104. -- BASIC FUNCTIONS FOR TURTLE CONTROL -
  105. ---------------------------------------
  106. local function writeFile()
  107.     local handle = fs.open(filename, "w")
  108.     handle.write(tostring(length).."\n")
  109.     handle.write(tostring(width).."\n")
  110.     handle.write(tostring(fenceNeeded).."\n")
  111.     handle.write(tostring(torchesNeeded).."\n")
  112.     handle.write(tostring(minFuel).."\n")
  113.     handle.close()
  114. end
  115. local function readFile()
  116.     local handle = fs.open(filename, "r")
  117.     length = tonumber( handle.readLine() )
  118.     width = tonumber( handle.readLine() )
  119.     fenceNeeded = tonumber( handle.readLine() )
  120.     torchesNeeded = tonumber( handle.readLine() )
  121.     minFuel = tonumber( handle.readLine() )
  122.     handle.close()
  123. end
  124. local function askForInputText(textt)
  125.   local at=""  -- check prompting texts
  126.   if textt==nil then textt="Enter text:" end  -- ask for input
  127.   write(textt)
  128.   at=read()
  129.   return at
  130. end
  131. -- function for checking fuel
  132. local function checkFuel()
  133.   local tmp=turtle.getFuelLevel()
  134.   return tmp
  135. end
  136. -- Function for turtle behaviour
  137. local function ss(s) turtle.select(s) debug_print("Selecting Slot")  end
  138. local function ff() turtle.forward() debug_print("Moving Forward")  end
  139. local function bb() turtle.back() debug_print("moving backward") end
  140. local function up() turtle.up() debug_print("moving up") end
  141. local function dn() turtle.down() debug_print("moving down")  end
  142. local function tl() turtle.turnLeft() debug_print("turning left")  end
  143. local function tr() turtle.turnRight() debug_print("turning right")  end
  144. local function dd() turtle.digDown() debug_print("digging down")  end
  145. local function pu() turtle.placeUp() debug_print("placing up")  end
  146. local function pd() turtle.placeDown() debug_print("placing down")  end
  147. local function cd() turtle.detectDown() debug_print("detecting down")  end
  148. local function sk() turtle.suckDown() sleep(0.1) turtle.suckDown() debug_print("gathering items")  end
  149. local function Du(n) if n==nil then n=64 end turtle.dropUp(n) debug_print("dropping up") end
  150. local function Dd(n) if n==nil then n=64 end turtle.dropDown(n) debug_print("dropping down") end
  151. local function wt() write(". ") end
  152. local strSimpleCheck="Press enter to continue:"
  153. local success, data = turtle.inspectDown()
  154. local function dps()
  155.     for i=2,16 do
  156.         ss(i) Dd()
  157.     end
  158. end
  159. local function checkRefuel(minFuel, slotFuel)
  160.     if slotFuel==nil then slotFuel=16 end
  161.     if minFuel==nil then minFuel=1000 end
  162.     local tmpFuel=0 tmpFuel2=0
  163.     local tmpItems=65 --turtle.getItemCount(slotFuel)
  164.     local cSleep=5
  165.     -- step 1 check if more fuel is required
  166.     tmpFuel=turtle.getFuelLevel()
  167.     if fuelLevel == "unlimited" then
  168.         return true
  169.     end
  170.   tmpFuel2=tmpFuel-1 -- triggers print at least once
  171.   if tmpFuel<minFuel then
  172.     ss(slotFuel)
  173.     -- step 2 refuel loop
  174.     while tmpFuel<minFuel do
  175.       -- step 2.1 need to update fuel level?
  176.       if tmpFuel2~=tmpFuel then
  177.         -- fuel still too low and there have been items consumed
  178.         print("Need more fuel ("..tmpFuel.."/"..minFuel..") in slot "..slotFuel)
  179.       end
  180.       -- step 2.2 try to refuel
  181.       if tmpItems>0 then
  182.         -- try to refuel this items
  183.         turtle.refuel()
  184.       else
  185.         os.sleep(cSleep)      
  186.       end
  187.       -- step 2.3 update variables
  188.       tmpItems=turtle.getItemCount(slotFuel)
  189.       tmpFuel2=tmpFuel
  190.       tmpFuel=turtle.getFuelLevel()
  191.     end
  192.   end
  193.   -- step 3 either no need to refuel
  194.   --        or successfully refuelled
  195.   print("| Fuel level ok  ("..tmpFuel.."/"..minFuel..")") term.setCursorPos(39, 10) print ("|")
  196. end
  197. -- Tilling Seeding Harvesting
  198. local function isCropReadyToHarvest(block)
  199.     return block.state.age >= config.crop.ripe
  200. end
  201. -- Function to plant a crop
  202. local function plantCrop()
  203.     local currentItem = turtle.getItemDetail()
  204.  
  205.     if currentItem and currentItem.name == config.crop.item then
  206.         debug_print("Placing down crop!")
  207.         pd()
  208.        
  209.         sk()
  210.         return
  211.     end
  212.  
  213.     debug_print("Locating crop to replant...")
  214.     for i = 1, 16 do
  215.         turtle.select(i)
  216.         local newItem = turtle.getItemDetail()
  217.  
  218.         if newItem and newItem.name == config.crop.item then
  219.             debug_print("Placing down crop!")
  220.             pd()
  221.             sk()
  222.             return
  223.         end
  224.     end
  225.  
  226.     -- Failed to replant:
  227.     debug_print("Could not locate crop in inventory to replant... carrying on.")
  228. end
  229. -- Function to handle harvesting and replanting
  230. local function hr()
  231.     local success, data = turtle.inspectDown()
  232.  
  233.     if success and data.name == config.crop.block then
  234.         local block = data
  235.         debug_print("Crop found...")
  236.        
  237.         if isCropReadyToHarvest(block) then
  238.             debug_print("Ready to harvest!")
  239.             dd()
  240.             plantCrop()
  241.             sk()
  242.         else
  243.             debug_print("Still growing...")
  244.             sk()
  245.         end
  246.     else
  247.         debug_print("There isn't a crop under me: tilling.")
  248.         dd()
  249.         plantCrop()
  250.     end
  251. end
  252.  
  253. local function placeFence()
  254. pd() ff()
  255. end
  256.  
  257. local function placeFenceAndTorch()
  258. pd() up() ss(3) pd() ss(2) ff() dn()
  259. end
  260.  
  261. local function placeCorner()
  262. pd() up() ss(3) pd() ss(2) tr() ff() dn()
  263. end
  264.  
  265. local function placeTorchesAndFences(count)
  266.     placeCorner()
  267.     for i = count,1,-1  do
  268. if i % 3 == 0 and i > 1 and i <= count - 1 then
  269.             placeFenceAndTorch()
  270.             count = count - 1
  271.         else
  272.         placeFence()
  273.         end
  274.     end
  275. end
  276.  
  277. ---------------------------------------
  278. ---- set-up farm ----------------------
  279. ---------------------------------------
  280. -- Check if tutorial is needed
  281. if blnShowUsage then
  282. term.clear() term.setCursorPos(1,1)
  283.   print("+-------------------------------------+")
  284.   print("|"..cPrgName.." "..cVersion..",by MaxwellJoneZ      |")
  285.   print("+-------------------------------------+")
  286.   print("Usage:")
  287.   print("FarmBot [setup]")
  288.   print("   Will start auto setup")
  289.   print("   or:")
  290.   print("FarmBot [maxCounter]")
  291.   print("   0=will farm infinitely")
  292.   print("   x=will farm x rounds")
  293.   print("FarmBot [help]")
  294.   print("   Will show this message again")
  295.   return  
  296. end
  297. -- Check if autosetup false and if VarsFarmBot exists
  298. if blnAutoSetup==false then
  299.     if fs.exists(filename) then
  300.         if tonumber(tArgs[1])~=nil then
  301.             shouldExit = true
  302.         end
  303.         if not shouldExit then
  304.             term.clear() term.setCursorPos(1,1)
  305.             readFile()
  306.             print ("File Loaded")
  307.             print("+-------------------------------------+")
  308.             write("Farmsize: ") write("Length = ") write(length) write(" Width = ") print(width)
  309.             print ("Using Stored Variables")
  310.             textutils.slowPrint ("Is that ok? [y/n]")
  311.             local input = read()
  312.             if input=="y" then
  313.                 sleep(1)
  314.                 write ("Auto Setup ") print (blnAutoSetup)
  315.                 sleep(0.5)
  316.                 print (" Starting the Farm")
  317.             elseif input=="n" then blnAutoSetup=true
  318.                 print("No")
  319.                 write ("Auto Setup set to ") print (blnAutoSetup)
  320.                 sleep(1)
  321.             else
  322.                 print("Wrong answer. Please try again.")
  323.             return
  324.             end
  325.         end
  326.     else
  327.         term.clear() term.setCursorPos(1,1)
  328.         print("+-------------------------------------+")
  329.         print("|"..cPrgName.." "..cVersion..",by MaxwellJoneZ      |")
  330.         print("+-------------------------------------+")
  331.         textutils.slowPrint ("Invalid Arguments")
  332.         sleep(0.2)
  333.         print ("Please run the Setup or type ")
  334.         print("      FarmBot [help]")
  335.         print ("without the brackets for more info")
  336.         textutils.slowPrint ("............")
  337.     return
  338.     end
  339. end
  340. -- Check if autosetup true
  341. if blnAutoSetup then
  342.   write("Setting up farm...")
  343.   sleep(1)
  344. -- step 1 get size
  345.  term.clear() term.setCursorPos(1,1)
  346.  print("+-------------------------------------+")
  347.  print("|"..cPrgName.." "..cVersion..",by MaxwellJoneZ (1/3)|")
  348.  print("+-------------------------------------+")
  349.  print("Welcome to FarmBot for ComputerCraft")
  350.  print("Let's prepare the farm.")
  351.  textutils.slowPrint ("What's the length?")
  352.  print("Type the number and press enter")
  353.  length = read()
  354.  write("Ok.")
  355.  print("+-------------------------------------+")
  356.  textutils.slowPrint("What's the width?") write ("going to the right side)")
  357.  print("Type the number and press enter")
  358.  width = read()
  359.  print("Okay, let's prepare the farm")
  360.  fenceNeeded = ((length+2)*2+width*2)-1
  361.  local function calculateTorchAmount(sideLength)
  362.     return math.floor((sideLength - 1) / 3)
  363. end
  364. torchesNeeded=calculateTorchAmount(length)+calculateTorchAmount(width)+calculateTorchAmount(length)+calculateTorchAmount(width-1)+4
  365.  minFuel = (fenceNeeded*3+(length + width * 2)*4)
  366.  sleep(1)
  367.  
  368.  -- writing the variables to the file
  369.  writeFile()
  370.   print("+-------------------------------------+")
  371.   print("Farmsize: ") write("Length = ") print(length) write("Width = ") print(width)
  372.   write("Sqm = ") print(length*width)
  373.   for i=1,3 do
  374.    write(". ")
  375.    sleep(0.2)
  376.   end
  377. --  sleep(1)
  378. end
  379. -- step 2 Final check and Setup
  380. if blnAutoSetup then
  381.  repeat
  382.  term.clear() term.setCursorPos(1,1)
  383.   print("+-------------------------------------+")
  384.   print("|"..cPrgName.." "..cVersion..",by MaxwellJoneZ (2/3)|")
  385.   print("+-------------------------------------+")
  386.   print("| 1.Farm set-up: Place farming turtle |")
  387.   print("|   down (bottom left corner of farm) |")
  388.   print("|   It needs a hoe on the side!       |")
  389.   print("|                                     |")
  390.   print("| Materials needed for auto set-up:   |")
  391.   print("|   slot 2:  fences   ("..fenceNeeded..")")
  392.   term.setCursorPos(39,9) print("|")   term.setCursorPos(1,10)
  393.   print("|   slot 3:  torches  ("..torchesNeeded..")")
  394.   term.setCursorPos(39,10) print("|")   term.setCursorPos(1,11)
  395.   print("|   slot 4:  chest    (2)             |")
  396.   print("+-------------------------------------+")
  397.  
  398.   if blnAutoSetup then
  399.    if turtle.getItemCount(4)<2 or turtle.getItemCount(2)<fenceNeeded or turtle.getItemCount(3)<torchesNeeded then
  400.    -- inventory not ready for set-up
  401.      strSimpleCheck="Fill in slots 2-4 and press enter:"
  402.    else
  403.      strSimpleCheck="Press enter to start:"
  404.    end
  405.  else  
  406.    strSimpleCheck="Press enter to start:"
  407.  end
  408. if not blnAskForParameters and strSimpleCheck=="Press enter to start:" then break end
  409. until askForInputText(strSimpleCheck)=="" and strSimpleCheck=="Press enter to start:"
  410. end
  411.  
  412. term.clear() term.setCursorPos(1,1)
  413.  if blnAutoSetup then
  414. -- end of theorical Setup
  415.  print("Setup starting...")
  416.  print("Wait for the setup to happen and run")
  417.  print("FarmBot [maxCounter]")
  418.  print("Setting up the farm...")
  419.  sleep(1)
  420.  checkRefuel(minFuel,slotFuel)
  421. ----- Do the job
  422. ----- Place Chests
  423.  term.clear() term.setCursorPos(1,1)
  424.  repeat
  425.  print("+-------------------------------------+")
  426.  print("|                                     |")
  427.  print("|     I don't have a pick, can you    |")
  428.  print("|     Dig 1 Bloc Under the Turtle     |")
  429.  print("|                                     |")
  430.  print("|                                     |")
  431.  print("|                Please ;)            |")
  432.  print("|                                     |")
  433.  print("|                                     |")
  434.  print("|                                     |")
  435.  print("|                                     |")
  436.  print("+-------------------------------------+")
  437.  if turtle.detectDown()==true then end
  438.  until turtle.detectDown()==false
  439.  print("|            Thank you   <3           |")
  440.  print("|                                     |")
  441.  print("|                                     |")
  442.  print("|            Placing Chests           |")
  443.  print("|                                     |")
  444.  ss(4) write("|.    ") pd() write(".    ") up() write(".    ") pu() write(".    ") ss(2) write(".    ") tl() write(".    ") ff() write(".    ")
  445.  print("|                                     |")
  446.  print("|            Placing Fences           |")
  447.  
  448. -- Place Fences
  449. placeTorchesAndFences(length)
  450. placeTorchesAndFences(width)
  451. placeTorchesAndFences(length)
  452. placeTorchesAndFences(width-1)
  453.  
  454. -- Empty Useless Mats
  455. for i = 2, 4 do
  456.     ss(i)
  457.     Du()
  458.     wt()
  459. end
  460. tr() dn()
  461. print("|                                     |")
  462. print("|                                     |")
  463. print("|                                     |")
  464. print("|                Done !               |")
  465. print("|                                     |")
  466. print("|                                     |")
  467. print("|      Ready for Farming Program      |")
  468. print("|      You can now run the Farm       |")
  469. print("+-------------------------------------+")
  470.  return end
  471.  
  472. ---------------------------------------
  473. ---- main -----------------------------
  474. ---------------------------------------
  475.  
  476. repeat
  477.  print("+-------------------------------------+")
  478.  print("|"..cPrgName.." "..cVersion..",by MaxwellJoneZ (3/3)|")
  479.  print("+-------------------------------------+")
  480.  print("| 2. Running the farm:                |")
  481.  print("|   Farming turtle sits above chest   |")
  482.  print("|   (as after running set-up).        |")
  483.  print("|   Please empty the top chest and add|")
  484.  print("|   fuel into it.                     |")
  485.  print("|                                     |")
  486.  print("|Turtle inventory:                    |")
  487.  print("|   slot  1: seeds             (2+x)  |")
  488.  print("+-------------------------------------+")
  489.  
  490.   if turtle.getItemCount(1)<2 then
  491.   -- inventory not ready
  492.   strSimpleCheck="Provide seeds in slot 1 and press enter:"
  493. else  
  494.   strSimpleCheck="Press enter to start:"
  495.   end
  496.  if not blnAskForParameters and strSimpleCheck=="Press enter to start:" then break end
  497. until askForInputText(strSimpleCheck)=="" and strSimpleCheck=="Press enter to start:"
  498. ---------------------------------------
  499. ---- run  -----------------------------
  500. ---------------------------------------
  501. local repeatTimes = tonumber(tArgs[1])
  502.  print("|   Running the farm " ..repeatTimes.. " times           ")
  503. if repeatTimes == 0 then
  504.     repeatTimes = math.huge -- Repeat indefinitely
  505. elseif not repeatTimes then
  506.     repeatTimes = 1
  507. end
  508. for a = 1, repeatTimes do
  509. local function Waiting()
  510.     if a < repeatTimes then
  511.         for i = 1, sleepTime do
  512.             sleep(1)
  513.             term.setCursorPos(1, 12) -- Adjust the y-coordinate to match your desired position
  514.             local sleepSeconds = i
  515.             if sleepSeconds < 10 then
  516.                 sleepSeconds = "0" .. sleepSeconds
  517.             end
  518.             print("| Sleep  " .. sleepSeconds .." of " .. sleepTime .. "") term.setCursorPos(39, 12) print ("|")
  519.         end
  520.     end
  521. end
  522.     if debugging then
  523.         print("Debugging: enabled")
  524.     end
  525.     readFile()
  526.     term.clear() term.setCursorPos(1,1)
  527.      print("+-------------------------------------+")
  528.  print("|"..cPrgName.." "..cVersion..",by MaxwellJoneZ      |")
  529.  print("+-------------------------------------+")
  530.     print("|                                     |")
  531.     print("|                                     |")
  532.     print("| Run N°  "..a.. " of " ..repeatTimes.."") term.setCursorPos(39, 6) print ("|")
  533.     print("|                                     |")
  534.     print("|                                     |")
  535.     print("|                                     |")
  536.     checkRefuel(minFuel,slotFuel)
  537.     print("|                                     |")
  538.     up() ff() hr()
  539.     local n=0
  540.     for i=1,width-1 do
  541.         n=n+1
  542.         for i=1,length-1 do
  543.             ff() hr()
  544.         end
  545.         if(n%2==0)
  546.             then tl() ff() hr() tl()
  547.             else tr() ff() hr() tr()
  548.         end
  549.     end
  550.     for i=1,length-1 do
  551.         ff() hr()
  552.     end
  553.     -- then go back
  554.     if(width%2==0) then
  555.         tr()
  556.         for i=1,width-1 do
  557.             ff()
  558.         end
  559.         tr() bb() dn() dps() Waiting()
  560.         else
  561.         for i=1,length-1 do
  562.             bb()
  563.         end
  564.         tr()
  565.         for i=1,width-1 do
  566.             bb()
  567.         end
  568.         tl() bb() dn() dps() Waiting()
  569.     end
  570. end
Add Comment
Please, Sign In to add comment