View difference between Paste ID: MM0GNMek and 8k0aNbVG
SHOW: | | - or go back to the newest paste.
1-
--[[ com.ape42.turtle.Farm 0.7.1
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 
5+
     slots, which are the first
6
     contiguous slots that have seeds.
7-
     If it doesn't have enough seed to 
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-
Feature Changes by version:
15+
TODO/WIP:
16-
     0.1.0: Reaps one row.
16+
- Make it so the 'running' column is
17-
     0.2.0: Reaps & sows X rows, then
17+
    farmland.  Turn robot around and 
18-
      retrieves the harvest.
18+
    till backwards.
19-
     0.2.1: You now get a whole row of 
19+
20-
      a given plantable,if there are 
20+
    and include a readme
21-
      enough seeds.
21+
22-
     0.2.2: Better stoppage for out-of
22+
23-
      -fuel or if blocked.
23+
24-
     0.3.1: Sleeps and runs twice more
24+
25-
     0.4.1: Tries to plant each row,
25+
26-
      alternating crops if possible
26+
27-
    0.5.0: After first harvest, it
27+
28-
      finds fuel required per harvest.
28+
29-
      If there isn't enough for the
29+
30-
      next one it stops.
30+
31-
    0.5.1: if it has to stop, it
31+
32-
      shouldn't bother to sleep, so now
32+
33-
      it doesn't.
33+
34-
    0.6.1: No functional changes, but
34+
35-
      beginning to refactor
35+
36-
    0.7.1: Improved fuel-use. Now at
36+
37-
      the end of each row it sees if
37+
38-
      there's enough fuel to do another
38+
39-
      row and make it back to base. If
39+
-- The wait time between beginning of
40-
      not it goes back to the start 
40+
41-
      right away.
41+
42-
      Added auto-refueling:  Slot 9.
42+
43
-- The number of times to farm the
44-
TODO:
44+
45-
- Estimate max field size plantable
45+
46-
    for two harvests, given the fuel.
46+
47-
- After run - Estimate how many more
47+
48-
    runs & rows it'll be able to do
48+
49-
    with current fuel level.
49+
50-
- Change param meaning so that the 
50+
51-
  result is N rows, N blocks long
51+
52
-- Called before any work is done, this
53
-- finds the last populated inventory
54-
- Allow use of blockers instead of row
54+
55-
    parameter.
55+
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-
-- The wait time between beginning of 
73+
74
 
75
  local s = plntblCnt + 1
76
  local seedy = false
77-
-- The number of times to farm the 
77+
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-
local function sow( rowIndex, block, 
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-
local function reapRow( lth )
169+
170-
  print( "Reaping a row ")
170+
171
    else
172
      if firstRow == false then
173
        print("Stopped unexpectedly")
174
        placeR = 0
175
        print("placeR="..placeR)
176
      end
177-
-- lth 0 just means that really
177+
178-
-- the length is not yet determined
178+
179-
  local firstRow = lth == 0
179+
180
 
181
  lth = placeR
182-
    lth = fuel/2 - 1
182+
183-
    print(string.format("First row. "
183+
184-
        .."fuel %d, max length %d", 
184+
185-
        fuel, lth))
185+
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-
--  means seeds or fuel ran out, or
222+
223-
--  there was a blockage.
223+
224
  local fuelNeed = 1 + rowIndex
225-
        print( "Sowing a row." )
225+
226
 
227
  local fuelLevel = turtle.getFuelLevel()
228
 
229
  local isEnough= fuelLevel >= fuelNeed
230-
  while block < lnth and seedy do
230+
231
    print("Not enough fuel for next "
232-
    seedy = turtle.back()
232+
233
    print( string.format(
234
        "fuelNeed %d, rowIndex %d, "
235
        .."rowLength %d", fuelNeed,
236
        rowIndex, rowLength ) )
237
       
238
    print( string.format( "fuelLevel %d",
239-
        print("sowRow(): seedy== false" )
239+
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-
-- reap it, sow it, and return to 
251+
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-
  local fuelNeed = 1 + rowIndex 
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-
    print( string.format( 
266+
  local isBlocked = false
267
  
268-
        .."rowLength %d", fuelNeed, 
268+
269
  if isFirst == false then
270
 
271-
    print( string.format( "fuelLevel %d", 
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-
-- @param rowLength, isFirst, prevRow, 
282+
283
  if isFuelOK and isSeedy and 
284
      not isBlocked then
285
      
286
    rowLength= reapRow( rowLength, isFirst )
287-
-- @return isFuelOK, rowLength, isSeedy
287+
288-
local function moveOnAndDoOne( rowLength, 
288+
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-
    isFuelOK = isFuelOKForNextRow(rowIndex, 
296+
297-
        rowLength)
297+
298
  end -- if fuel OK
299
300
  return isFuelOK, rowLength, isSeedy,
301
      isBlocked
302-
      turtle.forward()
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 isFuelOK then
309+
--  If stopped unexpectedly this will
310-
    rowLength= reapRow( rowLength )
310+
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-
      -- if stopped, zeroes-out.
320+
321-
      rowLength= isSeedy and rowLength or 0
321+
322-
    end -- if rowLength
322+
  local rowLength = rows
323
  local rowIndex = 0
324
  local isSeedy = true
325
  local isFuelOK = true
326-
  return isFuelOK, rowLength, isSeedy
326+
327
  local isBlocked = false
328
 
329
  while (rowIndex< rows) and isSeedy
330
      and isFuelOK and not isBlocked do
331-
-- @param rows number of plantable rows
331+
332-
-- @return number of rows planted. 
332+
    -- print( "rowIndex ".. rowIndex )
333-
--  If stopped unexpectedly this will 
333+
334
    -- If there was an unexpected
335
    -- stop in previous row, then
336-
  print("beginning reapAndSow()")
336+
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-
  local rowLength = 0
346+
          isFirst, prevRow, rowIndex )
347
     
348
      --[[ TODO clean out when ready
349
      print( string.format(
350
          "in farm(), after "
351
          .."moveOnAndDoOne( rowLength %d, "
352-
  while (rowIndex< rows) and isSeedy 
352+
353-
      and isFuelOK do
353+
          rowLength, tostring(isFirst),
354-
    print( "rowIndex ".. rowIndex )
354+
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-
      isFuelOK, rowLength, isSeedy = 
365+
366-
          moveOnAndDoOne(rowLength, 
366+
367-
              isFirst, prevRow, 
367+
368-
              rowIndex )
368+
369
 
370-
      print( string.format(  
370+
  -- The number of rows traversed
371
  -- or 0 if unexpected problem
372-
          .."moveOnAndDoOne( rowLength %d, " 
372+
373
  if rowLength > 0 then
374-
          rowLength, tostring(isFirst), 
374+
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-
          tostring( isFuelOK ), rowLength, 
380+
      rtrnVal = rowIndex - 1
381
    end
382
  else
383
    rtrnVal = 0
384
  end
385
 
386
  return rtrnVal
387
 
388
end
389
 
390-
  -- The number of rows traversed 
390+
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-
    rtrnVal = isFuelOK and rowIndex or rowIndex - 1
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-
-- inventory except one of each 
407+
        .."rows %d, forwards %d", 
408
        rows, forwards ))
409
  
410-
-- @param rows how many rows are 
410+
411
  while (stp <= forwards) and canGo do
412-
-- @return true if successful. False 
412+
413-
--  means there was blockage or fuel 
413+
414
  end
415
 
416-
  print( "Returning to the start.")
416+
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-
        "returnAndStore(rows) "
441+
-- @param widthFromUsr is how wide the
442-
        .."couldn't store.  rows %d, "
442+
--  farm should have been according to
443-
        .."forwards %d", rows, forwards ))
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-
-- @param rowCntFromUsr is the number
453+
  local fuelPerTurn = (fuelStart-fuelLevel)
454-
-- of rows to farm, according to user
454+
  print( "fuelPerTurn ".. fuelPerTurn )
455-
local function farm( rowCntFromUsr )
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-
      print("fuelStart = ".. fuelStart)
466+
467-
      local rowsDone = reapAndSow( rowCntFromUsr )
467+
  if fuelLevel< fuelPerTurn and n < MAX_REPEATS then
468
    local fuelNeeded = (1 - frction) * fuelPerTurn
469-
      if rowsDone == rowCntFromUsr then
469+
    local coals = math.ceil(fuelNeeded/80);
470
    
471
    print( string.format(
472-
          local fuelLevel = turtle.getFuelLevel()
472+
        "To finish the next harvest "
473
        .."as well or better than this one, "
474-
          print("after harvest: "..(n)
474+
        .."%d more fuel units are "
475-
              .." of ".. MAX_REPEATS)
475+
        .."needed.  That's %d pieces "
476-
              
476+
        .."of coal at least.  "
477-
          print("fuelLevel ".. fuelLevel)
477+
        .."Slot #9 please", fuelNeeded,
478-
          local fuelPerTurn = (fuelStart-fuelLevel)
478+
        coals ) )
479-
          print( "fuelPerTurn ".. fuelPerTurn )
479+
480-
          if fuelLevel< fuelPerTurn and n < MAX_REPEATS then
480+
481-
            print("Next harvest will be partial,")
481+
482-
            print("unless enough more fuel is added.")
482+
483-
            print("Use slot 9 (first slot of 3rd row).")
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-
  local rowCntFromUsr = 0
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-
    rowCntFromUsr = tArgs[1]
516+
      local rowsDone = reapAndSow( widthFromUsr )
517-
    if tonumber(rowCntFromUsr)==nil then
517+
518
      if rowsDone > 0 then
519
        if okSoFar then
520
       
521-
      rowCntFromUsr = tonumber(rowCntFromUsr)
521+
          printFuelMsg(n, fuelStart, widthFromUsr )
522
          
523
          local endTime = os.clock()
524
          local duration = endTime - startTime
525
          local waitTime = ( GROW_WAIT*60)-duration
526-
    badArgMsg = "Supply how many rows"
526+
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-
    farm( rowCntFromUsr )
534+
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)