rdalkire

farm081

Jun 29th, 2014
338
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. --[[ com.ape42.turtle.Farm 0.8.1
  2.   For computercraft 1.63
  3.   Farms X rows, trying to alternate
  4.      crops according to the reference
  5.      slots, which are the first
  6.      contiguous slots that have seeds.
  7.      If it doesn't have enough seed to
  8.      alternate,  it will leave a gap.
  9.      There are two globals constants -
  10.      to sleep GROW_WAIT minutes, and
  11.      repeat MAX_REPEATS or until out
  12.      of fuel.
  13.   @author R David Alkire, IGN ian_xw
  14.      
  15. TODO/WIP:
  16. - Make it so the 'running' column is
  17.     farmland.  Turn robot around and
  18.     till backwards.
  19. - Give more explicit usage instructions
  20.     and include a readme
  21. - Add melon/pumpkin slots, handling.
  22. - Allow the turtle to start at right
  23.     corner, depending which way is
  24.     open.
  25. - Create a routine for automated field
  26.     creation, given flat grassy area,
  27.     a bucket and a source of water.
  28.  
  29. This work is licensed under the
  30.  Creative Commons Attribution 4.0
  31.  International License. To view a copy
  32.  of this license, visit
  33.  http://creativecommons.org/licenses/by/4.0/
  34.  or send a letter to Creative Commons,
  35.  444 Castro Street, Suite 900, Mountain
  36.  View, California, 94041, USA.
  37. ]]
  38.  
  39. -- The wait time between beginning of
  40. -- each harvest, in minutes.
  41. GROW_WAIT = 40
  42.  
  43. -- The number of times to farm the
  44. -- field, baring other constraints
  45. MAX_REPEATS = 3
  46.  
  47. -- Initial slots indicate what items
  48. -- the user deems plantable.
  49. local plntblCnt = 1
  50.  
  51. -- Initializes the Plantable Count.
  52. -- Called before any work is done, this
  53. -- finds the last populated inventory
  54. -- slot.  That and the ones below
  55. -- will be used as reference.
  56. -- @return plntblCnt
  57. local function initPlntblCnt()
  58.   local indx = 0
  59.   local isPlntbl = true
  60.   while isPlntbl and indx < 16 do
  61.     indx = indx + 1
  62.     turtle.select(indx)
  63.     isPlntbl= turtle.getItemCount()> 0
  64.   end
  65.   plntblCnt = indx - 1
  66.   return plntblCnt
  67. end
  68.  
  69. -- For the non - reference slots,
  70. -- find one that matches the
  71. -- currently selected and match that.
  72. -- Or return false.
  73. local function selectNonRefSlot()
  74.  
  75.   local s = plntblCnt + 1
  76.   local seedy = false
  77.   while s < 16 and seedy == false do
  78.     seedy = turtle.compareTo( s )
  79.     if seedy then
  80.       turtle.select(s)
  81.     end
  82.     s = s + 1
  83.   end --while
  84.   return seedy
  85. end
  86.  
  87. -- Decides what to plant based the
  88. --  reference slots (plntblCnt)
  89. -- @param rowIndex the current row
  90. -- @block block # within the row,
  91. --  starting with 1.
  92. -- @param prevRow an array of crop
  93. --  types for previous row
  94. local function sow( rowIndex, block,
  95.     prevRow )
  96.   local seedy = false
  97.  
  98.   -- Alternate among the plantables:
  99.   -- loop through reference slots.
  100.   local i = 0
  101.   local refSlt = 0
  102.   while i < plntblCnt and seedy == false do
  103.     --use what was for a given reference slot
  104.     refSlt = ( (rowIndex + i )% plntblCnt) + 1
  105.    
  106.     turtle.select(refSlt)
  107.     if turtle.getItemCount(refSlt) > 1 then
  108.       seedy = true
  109.     else
  110.       seedy = selectNonRefSlot()
  111.     end
  112.     i = i + 1
  113.   end
  114.  
  115.   if seedy then
  116.     if prevRow[block]== refSlt then
  117.       prevRow[block] = 0
  118.     else
  119.       prevRow[block] = refSlt
  120.       turtle.place()
  121.     end -- if matches
  122.   else
  123.     print("Apparently, out of seeds")
  124.   end -- if seedy
  125.  
  126.   return seedy
  127. end
  128.  
  129. -- Harvests a row: Digs (hoes) and
  130. -- moves forward the length or until
  131. -- the way is blocked
  132. -- @param lth the expected length of
  133. --  the row or 0 if not yet determined
  134. -- @param firstRow
  135. -- @return how long the row was, or
  136. --  0 if there was an unexpected stop
  137. --  due to fuel outage after first row.
  138. local function reapRow( lth, firstRow )
  139.   -- print( "Reaping a row ")
  140.  
  141. -- Loop until length is reached or
  142. -- the way is blocked
  143.   local keepGoing = true
  144.   local placeR = 1
  145.  
  146.   if firstRow then
  147.     local fuel = turtle.getFuelLevel()
  148.     local maxLth = fuel/2 - 1
  149.     if lth > maxLth then
  150.       lth = maxLth
  151.       print(string.format("First row. "
  152.           .."fuel %d, max length %d",
  153.           fuel, lth))
  154.     end
  155.   end
  156.   while keepGoing do
  157.    
  158.     turtle.dig() -- reaps
  159.     keepGoing = turtle.forward()
  160.  
  161.     -- sees if it can keepGoing
  162.     if keepGoing then
  163.       placeR = placeR + 1
  164.       if placeR >= lth and lth > 0 then
  165.         keepGoing = false
  166.       end
  167.       -- prevents infinite loop
  168.       if placeR > 1023 then
  169.         keepGoing = false
  170.       end
  171.     else
  172.       if firstRow == false then
  173.         print("Stopped unexpectedly")
  174.         placeR = 0
  175.         print("placeR="..placeR)
  176.       end
  177.     end
  178.    
  179.   end -- while loop
  180.  
  181.   lth = placeR
  182.   return lth
  183. end
  184.  
  185. -- Backs up, tilling & planting
  186. -- @param lnth row length
  187. -- @param indx which row
  188. -- @param prevRow array of crop plantings
  189. --  for the previous row
  190. -- @return true if successful.  False
  191. --  means seeds ran out, or there was
  192. --  a blockage.
  193. local function sowRow(lnth, indx, prevRow)
  194.   -- print( "Sowing a row." )
  195.   local block = 1
  196.   local seedy = true
  197.  
  198.   -- while it has length & seeds
  199.   while block < lnth do
  200.    
  201.     turtle.back()
  202.     turtle.dig()
  203.  
  204.     -- if there are still seeds
  205.     if seedy then
  206.       seedy = sow(indx, block, prevRow)
  207.     end
  208.     block = block + 1
  209.   end
  210.  
  211.   -- return if there's seeds still.
  212.   return seedy
  213.  
  214. end
  215.  
  216. -- Determines whether there's enough
  217. -- fuel to: move to another row,
  218. -- reap it, sow it, and return to
  219. -- base
  220. -- @param rowIndex, rowLength
  221. local function isFuelOKForNextRow(
  222.     rowIndex, rowLength)
  223.  
  224.   local fuelNeed = 1 + rowIndex
  225.       + ( rowLength * 2 )
  226.  
  227.   local fuelLevel = turtle.getFuelLevel()
  228.  
  229.   local isEnough= fuelLevel >= fuelNeed
  230.   if isEnough ~= true then
  231.     print("Not enough fuel for next "
  232.         .."row and return trip.")
  233.     print( string.format(
  234.         "fuelNeed %d, rowIndex %d, "
  235.         .."rowLength %d", fuelNeed,
  236.         rowIndex, rowLength ) )
  237.        
  238.     print( string.format( "fuelLevel %d",
  239.         fuelLevel ) )
  240.    
  241.   end
  242.  
  243.   return isEnough
  244.  
  245. end
  246.  
  247. -- Checks fuel, and if good, moves to
  248. --    next row, reaps and sows.
  249. -- @param rowLength, isFirst, prevRow,
  250. --    rowIndex.
  251. --    prevRow is array of ints, each
  252. --    a reference item slot, from, you
  253. --    guessed it: the previous row.
  254. -- @return isFuelOK, rowLength, isSeedy,
  255. --    isBlocked.  isSeedy means there
  256. --    are still seeds to be planted.
  257. --    isBlocked means it was blocked
  258. --    when moving from one row to the
  259. --    next, which is meant to be a
  260. --    normal scene.
  261. local function moveOnAndDoOne( rowLength,
  262.     isFirst, prevRow, rowIndex )
  263.  
  264.   local isFuelOK = true
  265.   local isSeedy = true
  266.   local isBlocked = false
  267.  
  268.   -- After the first row
  269.   if isFirst == false then
  270.  
  271.     isFuelOK = isFuelOKForNextRow(
  272.         rowIndex, rowLength )
  273.    
  274.     if isFuelOK then
  275.       -- Move to the next row
  276.       turtle.turnRight()
  277.       isBlocked=turtle.forward()==false
  278.       turtle.turnLeft()
  279.     end
  280.    
  281.   end -- if after first
  282.  
  283.   if isFuelOK and isSeedy and
  284.       not isBlocked then
  285.      
  286.     rowLength= reapRow( rowLength, isFirst )
  287.     if isFirst then
  288.       -- initializes previous array
  289.       for i = 1, rowLength do
  290.         prevRow[i] = 0
  291.       end
  292.     end
  293.    
  294.     if rowLength > 0 then
  295.       isSeedy=sowRow( rowLength, rowIndex, prevRow)
  296.     end
  297.    
  298.   end -- if fuel OK
  299.  
  300.   return isFuelOK, rowLength, isSeedy,
  301.       isBlocked
  302.  
  303. end
  304.  
  305. -- Harvests and plants the rows
  306. -- @param width/ rows number of
  307. --  expected plantable rows
  308. -- @return number of rows planted.
  309. --  If stopped unexpectedly this will
  310. --  be 0.
  311. local function reapAndSow( rows )
  312.   -- print("beginning reapAndSow()")
  313.   -- Find out how many slots are for
  314.   -- reference.
  315.   local plntbl = initPlntblCnt()
  316.  
  317.   print("The first "..plntbl..
  318.     " slots \nare deemed plantable")
  319.  
  320.   local prevRow = {}
  321.   print("rows = ".. rows)
  322.   local rowLength = rows
  323.   local rowIndex = 0
  324.   local isSeedy = true
  325.   local isFuelOK = true
  326.   local isFirst = true
  327.   local isBlocked = false
  328.  
  329.   while (rowIndex< rows) and isSeedy
  330.       and isFuelOK and not isBlocked do
  331.    
  332.     -- print( "rowIndex ".. rowIndex )
  333.    
  334.     -- If there was an unexpected
  335.     -- stop in previous row, then
  336.     -- rowLength will be its initial
  337.     -- value, 0
  338.     if rowLength<= 0 and isFirst== false then  
  339.       -- Stops loop
  340.       isSeedy = false
  341.     else
  342.      
  343.       isFuelOK, rowLength, isSeedy,
  344.           isBlocked =
  345.           moveOnAndDoOne( rowLength,
  346.           isFirst, prevRow, rowIndex )
  347.      
  348.       --[[ TODO clean out when ready
  349.       print( string.format(
  350.           "in farm(), after "
  351.           .."moveOnAndDoOne( rowLength %d, "
  352.           .."isFirst %s, rowIndex %d)",
  353.           rowLength, tostring(isFirst),
  354.           rowIndex ) )
  355.      
  356.       print( string.format(
  357.           "Which returned isFuelOK %s, "
  358.           .."rowLength %d, isSeedy %s",
  359.           tostring( isFuelOK ), rowLength,
  360.           tostring(isSeedy) ) )
  361.       ]]
  362.      
  363.     end -- if rowLength > 0 & not first
  364.    
  365.     isFirst = false
  366.     rowIndex = rowIndex + 1
  367.    
  368.   end -- while rows & isSeedy
  369.  
  370.   -- The number of rows traversed
  371.   -- or 0 if unexpected problem
  372.   local rtrnVal = 0
  373.   if rowLength > 0 then
  374.     -- If fuel was too low, it did not
  375.     -- move to next row, so therefore
  376.     -- its row is one less than otherwise
  377.     if isFuelOK and not isBlocked then
  378.       rtrnVal = rowIndex
  379.     else
  380.       rtrnVal = rowIndex - 1
  381.     end
  382.   else
  383.     rtrnVal = 0
  384.   end
  385.  
  386.   return rtrnVal
  387.  
  388. end
  389.  
  390. -- Returns to the start and drops all
  391. -- inventory except one of each
  392. -- reference item. (It's assumed there
  393. -- are hoppers & a chest.)
  394. -- @param rows how many rows are
  395. --  planted.
  396. -- @return true if successful. False
  397. --  means there was blockage or fuel
  398. --  outage.
  399. local function returnAndStore(rows)
  400.  
  401.   turtle.turnLeft()
  402.   local canGo = true
  403.   local forwards = (rows - 1)
  404.  
  405.   print( string.format(
  406.         "returnAndStore(rows): "
  407.         .."rows %d, forwards %d",
  408.         rows, forwards ))
  409.  
  410.   local stp = 1
  411.   while (stp <= forwards) and canGo do
  412.     canGo = turtle.forward()
  413.     stp = stp + 1
  414.   end
  415.  
  416.   turtle.turnLeft()
  417.  
  418.   if canGo then
  419.     for i = 16, 1, -1 do
  420.       turtle.select(i)
  421.       if i > plntblCnt then
  422.         turtle.drop()
  423.       else
  424.         turtle.drop(
  425.             turtle.getItemCount(i)- 1)
  426.       end
  427.     end
  428.   else
  429.     print("couldn't store")
  430.   end --canGo
  431.   turtle.turnLeft()
  432.   turtle.turnLeft()
  433.   return canGo
  434. end
  435.  
  436. -- This prints a message about the fuel
  437. -- situation.
  438. -- @param n is how many plantings have
  439. --  been completed so far
  440. -- @param fuelStart
  441. -- @param widthFromUsr is how wide the
  442. --  farm should have been according to
  443. --  the user.
  444. local function printFuelMsg(n, fuelStart,
  445.     widthFromUsr)
  446.  
  447.   local fuelLevel = turtle.getFuelLevel()
  448.  
  449.   print("after harvest: "..(n)
  450.     .." of ".. MAX_REPEATS)
  451.    
  452.   print("fuelLevel ".. fuelLevel)
  453.   local fuelPerTurn = (fuelStart-fuelLevel)
  454.   print( "fuelPerTurn ".. fuelPerTurn )
  455.  
  456.   local fltTurns = fuelLevel/fuelPerTurn
  457.   local floorTrns = math.floor( fltTurns )
  458.   local frction = fltTurns - floorTrns
  459.   local rowsPart = frction * widthFromUsr
  460.  
  461.   print( string.format(
  462.       "There would be enough fuel "
  463.       .."for %d more turns "
  464.       .."plus %d rows.",
  465.       floorTrns, rowsPart ))
  466.      
  467.   if fuelLevel< fuelPerTurn and n < MAX_REPEATS then
  468.     local fuelNeeded = (1 - frction) * fuelPerTurn
  469.     local coals = math.ceil(fuelNeeded/80);
  470.    
  471.     print( string.format(
  472.         "To finish the next harvest "
  473.         .."as well or better than this one, "
  474.         .."%d more fuel units are "
  475.         .."needed.  That's %d pieces "
  476.         .."of coal at least.  "
  477.         .."Slot #9 please", fuelNeeded,
  478.         coals ) )
  479.        
  480.   end
  481.  
  482. end
  483.  
  484. -- Farms the field repeatedly up to
  485. -- MAX_REPEATS, or the fuel runs out,
  486. -- or there's some unexpected stop.
  487. -- @param widthFromUsr is the width
  488. --  of the square farm, according to
  489. --  user.  If 0, this will estimate
  490. --  the maximum width according to
  491. --  fuel.
  492. local function farm( widthFromUsr )
  493.  
  494.     --[[ Start ]]
  495.     -- three times, if enough fuel
  496.     local n = 1
  497.     local okSoFar = true
  498.     while n<= MAX_REPEATS and okSoFar do
  499.       local startTime = os.clock();
  500.       turtle.select(9)
  501.       turtle.refuel()
  502.       local fuelStart = turtle.getFuelLevel()
  503.       print("fuel at start = ".. fuelStart)
  504.      
  505.       local maxLnth = math.floor(
  506.           math.sqrt(2* fuelStart)/ 2)
  507.      
  508.       print("Estimated max field "
  509.           .. "side \nfor full cycle: "
  510.           .. maxLnth)
  511.      
  512.       if widthFromUsr == 0 then
  513.         widthFromUsr = maxLnth
  514.       end
  515.      
  516.       local rowsDone = reapAndSow( widthFromUsr )
  517.       okSoFar = returnAndStore(rowsDone)
  518.       if rowsDone > 0 then
  519.         if okSoFar then
  520.        
  521.           printFuelMsg(n, fuelStart, widthFromUsr )
  522.          
  523.           local endTime = os.clock()
  524.           local duration = endTime - startTime
  525.           local waitTime = ( GROW_WAIT*60)-duration
  526.           local nextTime = endTime+ waitTime
  527.           if (n < MAX_REPEATS) and okSoFar then
  528.             os.sleep(waitTime)
  529.           end
  530.         end --okSofar
  531.       else
  532.         okSoFar = false
  533.       end
  534.       n = n + 1
  535.     end -- of MAX_REPEATS loop
  536.    
  537.     if okSoFar == false then
  538.       print("Stopped.")
  539.     end
  540.  
  541. end
  542.  
  543. local function main( tArgs )
  544.   local widthFromUsr = 0
  545.  
  546.   --[[ If user supplies a good number,
  547.   this uses it as row count.  If user
  548.   supplied a bad argument, it indicates.
  549.   ]]
  550.   local argCount = table.getn(tArgs)
  551.   local badArg = false
  552.   local badArgMsg = "Argument OK"
  553.   if argCount > 0 then
  554.     widthFromUsr = tArgs[1]
  555.     if tonumber(widthFromUsr)==nil then
  556.       badArg = true
  557.       badArgMsg = "Argument not a number"
  558.     else
  559.       widthFromUsr = tonumber(widthFromUsr)
  560.     end
  561.    
  562.   else
  563.     badArg = true
  564.     badArgMsg = "Supply width of farm."
  565.   end
  566.    
  567.   if badArg then
  568.     print( badArgMsg )
  569.     print("Put at least 1 of something" )
  570.     print(" plantable in first few slots.")
  571.   else
  572.     farm( widthFromUsr )
  573.   end
  574.  
  575. end
  576.  
  577. local tArgs = {...}
  578. main(tArgs)
Advertisement
Add Comment
Please, Sign In to add comment