Krutoy242

TurtleAI

May 1st, 2014
456
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 102.97 KB | None | 0 0
  1. -- ********************************************************************************** --
  2. -- **                                                                              ** --
  3. -- **   Minecraft Artificial Intelligence Turtle                                   ** --
  4. -- **   ----------------------------------------------------                       ** --
  5. -- **                                                                              ** --
  6. -- **   pastebin run u5wHiXH1                                                      ** --
  7. -- **                                                                              ** --
  8. -- **   Big thanks AustinKK for OreQuarry Turtle                                   ** --
  9. -- ********************************************************************************** --
  10.  
  11.  
  12.  
  13. -- ********************************************************************************** --
  14. -- **                                                                              ** --
  15. -- **                                                                              ** --
  16. -- **                                                                              ** --
  17. -- **                                                                              ** --
  18. -- **                                                                              ** --
  19. -- **                                Variables                                     ** --
  20. -- **                                                                              ** --
  21. -- **                                                                              ** --
  22. -- **                                                                              ** --
  23. -- **                                                                              ** --
  24. -- **                                                                              ** --
  25. -- ********************************************************************************** --
  26.  
  27.  
  28. -- Enumeration to store names for the 6 directions
  29. beaconName = { THRASH=1, STORAGE=2, SMELTERY=3 }
  30.  
  31. -- Enumeration of filling tempelates
  32. fillState = { plain=1, pattern=2 }
  33.  
  34. local beacon = {}
  35.  
  36. local globalStates = { IDL=1, STAIRS=2 }
  37. local currGlobalState = globalStates.IDL
  38.  
  39. local doNotEnsureSpaceInInventory = false -- Sometime, when we carry something
  40.  
  41. local startState = 4
  42.  
  43. -- ID table
  44. idSlots = {
  45.   coal        = 1,
  46.   chest       = 2,
  47.   cobblestone = 3,
  48.   dirt        = 4,
  49.   gravel      = 5,
  50.   ironOre     = 6,
  51.   goldOre     = 7,
  52.   a           = 8,
  53.   b           = 9,
  54.   c           = 10,
  55.   d           = 11,
  56.   e           = 12,
  57.   f           = 13,
  58.   g           = 14,
  59.   h           = 15,
  60.   i           = 16,
  61.   furnace     = 17
  62. }
  63. idSlotsMinCount = { 32, 32, 64} -- On start
  64.  
  65. craftPattern = {
  66.   [idSlots.furnace] =
  67.   { 3, 3, 3, 0,
  68.     3, 0, 3, 0,
  69.     3, 3, 3, 0,
  70.     0, 0, 0, 0}
  71. }
  72.  
  73. worldSide = {
  74.   n=1, -- North
  75.   e=2, -- East
  76.   s=3, -- South
  77.   w=4, -- West
  78.   u=5, -- Up
  79.   d=6  -- Down
  80. }
  81.  
  82. fillPattern = {
  83.   ['Plain'] =
  84.   { {{1}} },
  85.   ['O_hole'] =
  86.   { {{1, 1, 1},
  87.      {1, 0, 1},
  88.      {1, 1, 1}}},
  89.   ['AntonsGrid'] =
  90.   { {{3, 2, 2, 2},
  91.      {2, 1, 1, 1},
  92.      {2, 1, 1, 1},
  93.      {2, 1, 1, 1}},
  94.     {{2, 1, 1, 1},
  95.      {1, 0, 0, 0},
  96.      {1, 0, 0, 0},
  97.      {1, 0, 0, 0}},
  98.     {{2, 1, 1, 1},
  99.      {1, 0, 0, 0},
  100.      {1, 0, 0, 0},
  101.      {1, 0, 0, 0}},
  102.     {{2, 1, 1, 1},
  103.      {1, 0, 0, 0},
  104.      {1, 0, 0, 0},
  105.      {1, 0, 0, 0}}},
  106.   ['Diagonal'] =
  107.   { {{1, 0, 0},
  108.      {0, 0, 0},
  109.      {0, 0, 0}},
  110.     {{0, 0, 0},
  111.      {0, 1, 0},
  112.      {0, 0, 0}},
  113.     {{0, 0, 0},
  114.      {0, 0, 0},
  115.      {0, 0, 1}}},
  116.   ['QuarterColumn'] =
  117.   { {{ 0, 0, 0, 0, 0},
  118.      { 0, 0, 0, 0, 0},
  119.      { 0, 0, 0, 0, 0},
  120.      { 0, 0, 0, 0, 1},
  121.      { 0, 0, 0, 1, 0}},
  122.     {{ 0, 0, 0, 0, 0},
  123.      { 0, 0, 0, 0, 0},
  124.      { 0, 0, 0, 0, 0},
  125.      { 0, 0, 0, 0, 2},
  126.      { 0, 0, 0, 2, 0}},
  127.     {{ 0, 0, 0, 0, 0},
  128.      { 0, 0, 0, 0, 0},
  129.      { 0, 0, 0, 0, 0},
  130.      { 0, 0, 0, 0, 0},
  131.      { 0, 0, 0, 0, 1}},
  132.     {{ 0, 0, 0, 0, 0},
  133.      { 0, 0, 0, 0, 0},
  134.      { 0, 0, 0, 0, 0},
  135.      { 0, 0, 0, 0, 0},
  136.      { 0, 0, 0, 0, 3}}},
  137.   ['AdvRoad_Diag'] =
  138.   { {{ 3, 2, 2, 2, 2, 2, 1},
  139.      { 3, 2, 2, 2, 2, 2, 3},
  140.      { 3, 2, 2, 2, 2, 2, 3},
  141.      { 1, 2, 2, 2, 2, 2, 3}},
  142.      
  143.     {{ 0, 0, 0, 0, 0, 0, 4},
  144.      { 0, 0, 0, 0, 0, 0, 0},
  145.      { 0, 0, 0, 0, 0, 0, 0},
  146.      { 4, 0, 0, 0, 0, 0, 0}},
  147.      
  148.     {{ 0, 0, 0, 0, 0, 0, 0},
  149.      { 0, 0, 0, 0, 0, 0, 0},
  150.      { 0, 0, 0, 0, 0, 0, 0},
  151.      { 0, 0, 0, 0, 0, 0, 0}}}
  152. }
  153.  
  154.  
  155. local SLOT_FUEL  = 1
  156. local SLOT_CHEST = 2
  157.  
  158.  
  159. -- ********************************************************************************** --
  160. -- Note: If you are in a world with flat bedrock, change the value below from 5 to 2.
  161. --       You don't need to change this, but the turtle is slightly faster if you do.
  162. -- ********************************************************************************** --
  163. local bottomLayer = 5 -- The y co-ords of the layer immediately above bedrock
  164.  
  165. -- Enumeration to store the the different types of message that can be written
  166. messageLevel = { DEBUG=0, INFO=1, WARNING=2, ERROR=3, FATAL=4 }
  167.  
  168. -- Enumeration to store names for the 6 directions
  169. way = { FORWARD=0, RIGHT=1, BACK=2, LEFT=3, UP=4, DOWN=5 }
  170.  
  171. -- Enumeration of mining states
  172. miningState = { START=0, LAYER=1, EMPTYCHESTDOWN=2, EMPTYINVENTORY=3 }
  173.  
  174.  
  175. local messageOutputLevel = messageLevel.INFO
  176. local messageOutputFileName
  177. local fuelLevelToRefuelAt = 5
  178. local refuelItemsToUseWhenRefuelling = 63
  179. local maximumGravelStackSupported = 25 -- The number of stacked gravel or sand blocks supported
  180. local noiseBlocksCount
  181. local returningToStart = false
  182. local lookForChests = false -- Determines if chests should be located as part of the quarrying
  183. local miningOffset -- The offset to the mining layer. This is set depending on whether chests are being looked for or not
  184. local lastEmptySlot = 1 -- The last inventory slot that was empty when the program started (is either 15 if not looking for chests or 14 if we are)
  185. local turtleId
  186. local isWirelessTurtle
  187. local currentlySelectedSlot = 0 -- The slot that the last noise block was found in
  188. local lastMoveNeededDig = true -- Determines whether the last move needed a dig first
  189. local haveBeenAtZeroZeroOnLayer -- Determines whether the turtle has been at (0, 0) in this mining layer
  190. local orientationAtZeroZero -- The turtle's orientation when it was at (0, 0)
  191. local levelToReturnTo -- The level that the turtle should return to in order to head back to the start to unload
  192.  
  193. -- Variables used to support a resume
  194. local startupParamsFile = "OreQuarryParams.txt"
  195. local oreQuarryLocation = "OreQuarryLocation.txt"
  196. local returnToStartFile = "OreQuarryReturn.txt"
  197. local startupBackup = "startup_bak"
  198. local supportResume = true -- Determines whether the turtle is being run in the mode that supports resume
  199. local resuming = false -- Determines whether the turtle is currently in the process of resuming
  200. local resumeX
  201. local resumeY
  202. local resumeZ
  203. local resumeOrient
  204. local resumeMiningState
  205.  
  206. -- Variables to store the current location and orientation of the turtle. x is right, left, y is up, down and
  207. -- z is forward, back with relation to the starting orientation. Y is the actual turtle level, x and z are
  208. -- in relation to the starting point (i.e. the starting point is (0, 0))
  209. local currX=0
  210. local currY=0
  211. local currZ=0
  212. local currOrient=way.FORWARD
  213. local currMiningState = miningState.START
  214.  
  215. -- Command line parameters
  216. local startHeight -- Represents the height (y co-ord) that the turtle started at
  217. local quarryWidth -- Represents the length of the mines that the turtle will dig
  218.  
  219.  
  220.  
  221. -- ********************************************************************************** --
  222. -- **                                                                              ** --
  223. -- **                                                                              ** --
  224. -- **                                                                              ** --
  225. -- **                                                                              ** --
  226. -- **                                                                              ** --
  227. -- **                                Utilities                                     ** --
  228. -- **                                                                              ** --
  229. -- **                                                                              ** --
  230. -- **                                                                              ** --
  231. -- **                                                                              ** --
  232. -- **                                                                              ** --
  233. -- ********************************************************************************** --
  234.  
  235.  
  236. --[[---------------
  237. LuaBit v0.4
  238. -------------------
  239. a bitwise operation lib for lua.
  240.  
  241. http://luaforge.net/projects/bit/
  242.  
  243. How to use:
  244. -------------------
  245.  bit.bnot(n) -- bitwise not (~n)
  246.  bit.band(m, n) -- bitwise and (m & n)
  247.  bit.bor(m, n) -- bitwise or (m | n)
  248.  bit.bxor(m, n) -- bitwise xor (m ^ n)
  249.  bit.brshift(n, bits) -- right shift (n >> bits)
  250.  bit.blshift(n, bits) -- left shift (n << bits)
  251.  bit.blogic_rshift(n, bits) -- logic right shift(zero fill >>>)
  252.  
  253. Please note that bit.brshift and bit.blshift only support number within
  254. 32 bits.
  255.  
  256. 2 utility functions are provided too:
  257.  bit.tobits(n) -- convert n into a bit table(which is a 1/0 sequence)
  258.                -- high bits first
  259.  bit.tonumb(bit_tbl) -- convert a bit table into a number
  260. -------------------
  261.  
  262. Under the MIT license.
  263.  
  264. copyright(c) 2006~2007 hanzhao (abrash_han@hotmail.com)
  265. --]]---------------
  266.  
  267. do
  268.  
  269. ------------------------
  270. -- bit lib implementions
  271.  
  272. local function check_int(n)
  273.  -- checking not float
  274.  if(n - math.floor(n) > 0) then
  275.   error("trying to use bitwise operation on non-integer!")
  276.  end
  277. end
  278.  
  279. local function to_bits(n)
  280.  check_int(n)
  281.  if(n < 0) then
  282.   -- negative
  283.   return to_bits(bit.bnot(math.abs(n)) + 1)
  284.  end
  285.  -- to bits table
  286.  local tbl = {}
  287.  local cnt = 1
  288.  while (n > 0) do
  289.   local last = math.mod(n,2)
  290.   if(last == 1) then
  291.    tbl[cnt] = 1
  292.   else
  293.    tbl[cnt] = 0
  294.   end
  295.   n = (n-last)/2
  296.   cnt = cnt + 1
  297.  end
  298.  
  299.  return tbl
  300. end
  301.  
  302. local function tbl_to_number(tbl)
  303.  local n = table.getn(tbl)
  304.  
  305.  local rslt = 0
  306.  local power = 1
  307.  for i = 1, n do
  308.   rslt = rslt + tbl[i]*power
  309.   power = power*2
  310.  end
  311.  
  312.  return rslt
  313. end
  314.  
  315. local function expand(tbl_m, tbl_n)
  316.  local big = {}
  317.  local small = {}
  318.  if(table.getn(tbl_m) > table.getn(tbl_n)) then
  319.   big = tbl_m
  320.   small = tbl_n
  321.  else
  322.   big = tbl_n
  323.   small = tbl_m
  324.  end
  325.  -- expand small
  326.  for i = table.getn(small) + 1, table.getn(big) do
  327.   small[i] = 0
  328.  end
  329.  
  330. end
  331.  
  332. local function bit_or(m, n)
  333.  local tbl_m = to_bits(m)
  334.  local tbl_n = to_bits(n)
  335.  expand(tbl_m, tbl_n)
  336.  
  337.  local tbl = {}
  338.  local rslt = math.max(table.getn(tbl_m), table.getn(tbl_n))
  339.  for i = 1, rslt do
  340.   if(tbl_m[i]== 0 and tbl_n[i] == 0) then
  341.    tbl[i] = 0
  342.   else
  343.    tbl[i] = 1
  344.   end
  345.  end
  346.  
  347.  return tbl_to_number(tbl)
  348. end
  349.  
  350. local function bit_and(m, n)
  351.  local tbl_m = to_bits(m)
  352.  local tbl_n = to_bits(n)
  353.  expand(tbl_m, tbl_n)
  354.  
  355.  local tbl = {}
  356.  local rslt = math.max(table.getn(tbl_m), table.getn(tbl_n))
  357.  for i = 1, rslt do
  358.   if(tbl_m[i]== 0 or tbl_n[i] == 0) then
  359.    tbl[i] = 0
  360.   else
  361.    tbl[i] = 1
  362.   end
  363.  end
  364.  
  365.  return tbl_to_number(tbl)
  366. end
  367.  
  368. local function bit_not(n)
  369.  
  370.  local tbl = to_bits(n)
  371.  local size = math.max(table.getn(tbl), 32)
  372.  for i = 1, size do
  373.   if(tbl[i] == 1) then
  374.    tbl[i] = 0
  375.   else
  376.    tbl[i] = 1
  377.   end
  378.  end
  379.  return tbl_to_number(tbl)
  380. end
  381.  
  382. local function bit_xor(m, n)
  383.  local tbl_m = to_bits(m)
  384.  local tbl_n = to_bits(n)
  385.  expand(tbl_m, tbl_n)
  386.  
  387.  local tbl = {}
  388.  local rslt = math.max(table.getn(tbl_m), table.getn(tbl_n))
  389.  for i = 1, rslt do
  390.   if(tbl_m[i] ~= tbl_n[i]) then
  391.    tbl[i] = 1
  392.   else
  393.    tbl[i] = 0
  394.   end
  395.  end
  396.  
  397.  --table.foreach(tbl, print)
  398.  
  399.  return tbl_to_number(tbl)
  400. end
  401.  
  402. local function bit_rshift(n, bits)
  403.  check_int(n)
  404.  
  405.  local high_bit = 0
  406.  if(n < 0) then
  407.   -- negative
  408.   n = bit_not(math.abs(n)) + 1
  409.   high_bit = 2147483648 -- 0x80000000
  410.  end
  411.  
  412.  for i=1, bits do
  413.   n = n/2
  414.   n = bit_or(math.floor(n), high_bit)
  415.  end
  416.  return math.floor(n)
  417. end
  418.  
  419. -- logic rightshift assures zero filling shift
  420. local function bit_logic_rshift(n, bits)
  421.  check_int(n)
  422.  if(n < 0) then
  423.   -- negative
  424.   n = bit_not(math.abs(n)) + 1
  425.  end
  426.  for i=1, bits do
  427.   n = n/2
  428.  end
  429.  return math.floor(n)
  430. end
  431.  
  432. local function bit_lshift(n, bits)
  433.  check_int(n)
  434.  
  435.  if(n < 0) then
  436.   -- negative
  437.   n = bit_not(math.abs(n)) + 1
  438.  end
  439.  
  440.  for i=1, bits do
  441.   n = n*2
  442.  end
  443.  return bit_and(n, 4294967295) -- 0xFFFFFFFF
  444. end
  445.  
  446. local function bit_xor2(m, n)
  447.  local rhs = bit_or(bit_not(m), bit_not(n))
  448.  local lhs = bit_or(m, n)
  449.  local rslt = bit_and(lhs, rhs)
  450.  return rslt
  451. end
  452.  
  453. --------------------
  454. -- bit lib interface
  455.  
  456. bit = {
  457.  -- bit operations
  458.  bnot = bit_not,
  459.  band = bit_and,
  460.  bor  = bit_or,
  461.  bxor = bit_xor,
  462.  brshift = bit_rshift,
  463.  blshift = bit_lshift,
  464.  bxor2 = bit_xor2,
  465.  blogic_rshift = bit_logic_rshift,
  466.  
  467.  -- utility func
  468.  tobits = to_bits,
  469.  tonumb = tbl_to_number,
  470. }
  471.  
  472. end
  473.  
  474. -- ********************************************************************************** --
  475. function makeSet (list)
  476.   local set = {}
  477.   for _, l in ipairs(list) do set[l] = true end
  478.   return set
  479. end
  480.  
  481.  
  482. -- ********************************************************************************** --
  483. -- Clear screen and set cursor to start
  484. function clear()
  485.    term.clear()
  486.    term.setCursorPos (1,1)
  487. end
  488.  
  489. -- ********************************************************************************** --
  490. function readNumberParametr(requestText, from, to)
  491.   while true do
  492.      clear()
  493.      print (requestText)
  494.      local event, param1 = os.pullEvent ("char") -- limit os.pullEvent to the char event
  495.      local result = tonumber(param1)
  496.      if result >= from and result <= to then
  497.          return result
  498.      else
  499.          print ('\nerror')
  500.          sleep (0.5) -- I don't like a whole 2 seconds but 1 second is too short
  501.      end
  502.   end
  503. end
  504.  
  505. function readTable(requestText, canBeSkipped, separator)
  506.   local resultStr = ''
  507.  
  508.   while true do
  509.     clear()
  510.     print(requestText)
  511.     resultStr = read()
  512.     if resultStr == '' and canBeSkipped == true then
  513.       return nil
  514.     elseif resultStr ~= '' then
  515.       local result = {}
  516.       local i=1
  517.       for v in string.gmatch(resultStr, separator) do
  518.         result[i] = v
  519.         i = i+1
  520.       end
  521.       return result
  522.     end
  523.   end
  524. end
  525.  
  526. function readTableOfNumbers(requestText, canBeSkipped, numbersCount, separator)
  527.   local resultStr = ''
  528.   local result = {}
  529.   for i=1,numbersCount do result[i]=0 end
  530.  
  531.  
  532.   while true do
  533.     local returnedResult = readTable(requestText, canBeSkipped, separator)
  534.    
  535.     if not returnedResult and canBeSkipped == true then
  536.       return result
  537.     elseif(returnedResult)then
  538.       local isAllNumbers = true
  539.       for i=1,numbersCount do
  540.         if(type(tonumber(returnedResult[i])) == "number") then
  541.           result[i] = tonumber(returnedResult[i])
  542.         else
  543.           print(returnedResult[i]..' is not number!')
  544.           sleep(1)
  545.           isAllNumbers=false
  546.         end
  547.       end
  548.      
  549.       if isAllNumbers == true then
  550.         return result
  551.       end
  552.     end
  553.   end
  554. end
  555.  
  556. -- ********************************************************************************** --
  557. function table.shallow_copy(t)
  558.   local t2 = {}
  559.   for k,v in pairs(t) do
  560.     t2[k] = v
  561.   end
  562.   return t2
  563. end
  564.  
  565.  
  566. -- ********************************************************************************** --
  567. -- Writes an output message
  568. -- ********************************************************************************** --
  569. function writeMessage(message, msgLevel)
  570.   if (msgLevel >= messageOutputLevel) then
  571.     print(message)
  572.  
  573.     -- If this turtle has a modem, then write the message to red net
  574.     if (isWirelessTurtle == true) then
  575.       if (turtleId == nil) then
  576.         rednet.broadcast(message)
  577.       else
  578.         -- Broadcast the message (prefixed with the turtle's id)
  579.         rednet.broadcast("[".. turtleId.."] "..message)
  580.       end
  581.     end
  582.  
  583.     if (messageOutputFileName ~= nil) then
  584.       -- Open file, write message and close file (flush doesn't seem to work!)
  585.       local outputFile
  586.       if (fs.exists(messageOutputFileName) == true) then
  587.         outputFile = io.open(messageOutputFileName, "a")
  588.       else
  589.         outputFile = io.open(messageOutputFileName, "w")
  590.       end
  591.  
  592.       outputFile:write(message)
  593.       outputFile:write("\n")
  594.       outputFile:close()
  595.     end
  596.   end
  597. end
  598.  
  599.  
  600. function p(message)
  601.   print('# '..message)
  602. end
  603.  
  604.  
  605.  function turtleDig(direction)
  606.   if (direction == nil) or (direction == way.FORWARD) then
  607.     return turtle.dig()
  608.   elseif(direction == way.DOWN) then
  609.     return turtle.digDown()
  610.   elseif(direction == way.UP) then
  611.     return turtle.digUp()
  612.   else
  613.     writeMessage('Wrong direction for turtleDig()', messageLevel.ERROR)
  614.     return false
  615.   end
  616.  end
  617.  
  618.  function getAnyKey()
  619.   local key
  620.   repeat
  621.     key=io.read()
  622.   until key==nil
  623.  end
  624.  
  625. -- ********************************************************************************** --
  626. -- **                                                                              ** --
  627. -- **                                                                              ** --
  628. -- **                                                                              ** --
  629. -- **                                                                              ** --
  630. -- **                                                                              ** --
  631. -- **                            Turtle wrappers                                   ** --
  632. -- **                                                                              ** --
  633. -- **                                                                              ** --
  634. -- **                                                                              ** --
  635. -- **                                                                              ** --
  636. -- **                                                                              ** --
  637. -- ********************************************************************************** --
  638.  
  639. -- ********************************************************************************** --
  640. -- Ensures that the turtle has fuel
  641. -- ********************************************************************************** --
  642. function ensureFuel()
  643.  
  644.   -- Determine whether a refuel is required
  645.   local fuelLevel = turtle.getFuelLevel()
  646.   if (fuelLevel ~= "unlimited") then
  647.     if (fuelLevel < fuelLevelToRefuelAt) then
  648.       -- Need to refuel
  649.       turtle.select(SLOT_FUEL)
  650.       currentlySelectedSlot = SLOT_FUEL
  651.       local coalItemsCount = turtle.getItemCount(SLOT_FUEL)
  652.  
  653.       -- Do we need to impact the emergency fuel to continue? (always  
  654.       -- keep one fuel item in slot SLOT_FUEL)
  655.       if (coalItemsCount == 0) then
  656.         writeMessage("Completely out of fuel!", messageLevel.FATAL)
  657.       elseif (coalItemsCount == 1) then
  658.         writeMessage("Out of Fuel!", messageLevel.ERROR)
  659.         turtle.refuel()
  660.       else
  661.         -- Refuel all coal and leave 1
  662.         turtle.refuel(coalItemsCount - 1)
  663.       end
  664.     end
  665.   end
  666. end        
  667.  
  668. -- ********************************************************************************** --
  669. -- Checks that the turtle has inventory space by checking for spare slots and returning
  670. -- to the starting point to empty out if it doesn't.
  671. --
  672. -- Takes the position required to move to in order to empty the turtle's inventory
  673. -- should it be full as arguments
  674. -- ********************************************************************************** --
  675. function ensureInventorySpace()
  676.   -- TODO: Enable ensuring
  677.   do return false end
  678.  
  679.   -- If already returning to start, then don't need to do anything
  680.   if ((returningToStart == false) and (doNotEnsureSpaceInInventory == false)) then
  681.  
  682.     -- If the last inventory slot is full, then need to return to the start and empty
  683.     if (turtle.getItemCount(lastEmptySlot) > 0) then
  684.  
  685.       -- Return to the starting point and empty the inventory, then go back to mining
  686.       returnToStartAndUnload(true)
  687.     end
  688.   end
  689. end
  690.  
  691. -- ********************************************************************************** --
  692. -- Function to move to the starting point, call a function that is passed in
  693. -- and return to the same location (if required)
  694. -- ********************************************************************************** --
  695. function returnToStartAndUnload(returnBackToMiningPoint)
  696.  
  697.   writeMessage("returnToStartAndUnload called", messageLevel.DEBUG)
  698.   returningToStart = true
  699.   local storedX, storedY, storedZ, storedOrient
  700.   local prevMiningState = currMiningState
  701.  
  702.   if (resuming == true) then
  703.     -- Get the stored parameters from the necessary file
  704.     local resumeFile = fs.open(returnToStartFile, "r")
  705.     if (resumeFile ~= nil) then
  706.       -- Restore the parameters from the file
  707.       local beenAtZero = resumeFile.readLine()
  708.       if (beenAtZero == "y") then
  709.         haveBeenAtZeroZeroOnLayer = true
  710.       else
  711.         haveBeenAtZeroZeroOnLayer = false
  712.       end
  713.  
  714.       local miningPointFlag = resumeFile.readLine()
  715.       if (miningPointFlag == "y") then
  716.         returnBackToMiningPoint = true
  717.       else
  718.         returnBackToMiningPoint = false
  719.       end
  720.  
  721.       currX = readNumber(resumeFile)
  722.       currY = readNumber(resumeFile)
  723.       currZ = readNumber(resumeFile)
  724.       currOrient = readNumber(resumeFile)
  725.       levelToReturnTo = readNumber(resumeFile)
  726.       prevMiningState = readNumber(resumeFile)
  727.       orientationAtZeroZero = readNumber(resumeFile)
  728.       resumeFile.close()
  729.  
  730.     else
  731.       writeMessage("Failed to read return to start file", messageLevel.ERROR)
  732.     end
  733.   elseif (supportResume == true) then
  734.  
  735.     local outputFile = io.open(returnToStartFile, "w")
  736.  
  737.     if (haveBeenAtZeroZeroOnLayer == true) then
  738.       outputFile:write("y\n")
  739.     else
  740.       outputFile:write("n\n")
  741.     end
  742.     if (returnBackToMiningPoint == true) then
  743.       outputFile:write("y\n")
  744.     else
  745.       outputFile:write("n\n")
  746.     end
  747.  
  748.     outputFile:write(currX)
  749.     outputFile:write("\n")
  750.     outputFile:write(currY)
  751.     outputFile:write("\n")
  752.     outputFile:write(currZ)
  753.     outputFile:write("\n")
  754.     outputFile:write(currOrient)
  755.     outputFile:write("\n")
  756.     outputFile:write(levelToReturnTo)
  757.     outputFile:write("\n")
  758.     outputFile:write(prevMiningState)
  759.     outputFile:write("\n")
  760.     outputFile:write(orientationAtZeroZero)
  761.     outputFile:write("\n")
  762.  
  763.     outputFile:close()
  764.   end
  765.    
  766.   storedX = currX
  767.   storedY = currY
  768.   storedZ = currZ
  769.   storedOrient = currOrient
  770.  
  771.   -- Store the current location and orientation so that it can be returned to
  772.   currMiningState = miningState.EMPTYINVENTORY
  773.   writeMessage("last item count = "..turtle.getItemCount(lastEmptySlot), messageLevel.DEBUG)
  774.  
  775.   if ((turtle.getItemCount(lastEmptySlot) > 0) or (returnBackToMiningPoint == false)) then
  776.  
  777.     writeMessage("Heading back to surface", messageLevel.DEBUG)
  778.  
  779.     -- Move down to the correct layer to return via
  780.     if (currY > levelToReturnTo) then
  781.       while (currY > levelToReturnTo) do
  782.         turtleDown()
  783.       end
  784.     elseif (currY < levelToReturnTo) then
  785.       while (currY < levelToReturnTo) do
  786.         turtleUp()
  787.       end
  788.     end
  789.  
  790.     if ((haveBeenAtZeroZeroOnLayer == false) or (orientationAtZeroZero == way.FORWARD)) then
  791.       -- Move back to the correct X position first
  792.       if (currX > 0) then
  793.         turtleSetOrientation(way.LEFT)
  794.         while (currX > 0) do
  795.           turtleForward()
  796.         end
  797.       elseif (currX < 0) then
  798.         -- This should never happen
  799.         writeMessage("Current x is less than 0 in returnToStartAndUnload", messageLevel.ERROR)
  800.       end
  801.  
  802.       -- Then move back to the correct Z position
  803.       if (currZ > 0) then
  804.         turtleSetOrientation(way.BACK)
  805.         while (currZ > 0) do
  806.           turtleForward()
  807.         end
  808.       elseif (currZ < 0) then
  809.         -- This should never happen
  810.         writeMessage("Current z is less than 0 in returnToStartAndUnload", messageLevel.ERROR)
  811.       end
  812.     else
  813.       -- Move back to the correct Z position first
  814.       if (currZ > 0) then
  815.         turtleSetOrientation(way.BACK)
  816.         while (currZ > 0) do
  817.           turtleForward()
  818.         end
  819.       elseif (currZ < 0) then
  820.         -- This should never happen
  821.         writeMessage("Current z is less than 0 in returnToStartAndUnload", messageLevel.ERROR)
  822.       end
  823.  
  824.       -- Then move back to the correct X position
  825.       if (currX > 0) then
  826.         turtleSetOrientation(way.LEFT)
  827.         while (currX > 0) do
  828.           turtleForward()
  829.         end
  830.       elseif (currX < 0) then
  831.         -- This should never happen
  832.         writeMessage("Current x is less than 0 in returnToStartAndUnload", messageLevel.ERROR)
  833.       end
  834.     end
  835.  
  836.     -- Return to the starting layer
  837.     if (currY < startHeight) then
  838.       while (currY < startHeight) do
  839.         turtleUp()
  840.       end
  841.     elseif (currY > startHeight) then
  842.       -- This should never happen
  843.       writeMessage("Current height is greater than start height in returnToStartAndUnload", messageLevel.ERROR)
  844.     end
  845.  
  846.     -- Empty the inventory
  847.     local slotLoop = 1
  848.  
  849.     -- Face the chest
  850.     turtleSetOrientation(way.BACK)
  851.  
  852.     -- Loop over each of the slots (except the 16th one which stores fuel)
  853.     while (slotLoop < 16) do
  854.       -- If this is one of the slots that contains a noise block, empty all blocks except
  855.       -- one
  856.       turtle.select(slotLoop) -- Don't bother updating selected slot variable as it will set later in this function
  857.       if ((slotLoop <= noiseBlocksCount) or ((slotLoop == 15) and (lastEmptySlot == 14))) then
  858.         writeMessage("Dropping (n-1) from slot "..slotLoop.." ["..turtle.getItemCount(slotLoop).."]", messageLevel.DEBUG)  
  859.         if (turtle.getItemCount(slotLoop) > 0) then
  860.           turtle.drop(turtle.getItemCount(slotLoop) - 1)
  861.         end
  862.       else
  863.         -- Not a noise block, drop all of the items in this slot
  864.         writeMessage("Dropping (all) from slot "..slotLoop.." ["..turtle.getItemCount(slotLoop).."]", messageLevel.DEBUG)  
  865.         if (turtle.getItemCount(slotLoop) > 0) then
  866.           turtle.drop()
  867.         end
  868.       end
  869.      
  870.       slotLoop = slotLoop + 1
  871.     end
  872.  
  873.     -- While we are here, refill the fuel items if there is capacity
  874.     if (turtle.getItemCount(16) < 64) then
  875.       turtleSetOrientation(way.LEFT)
  876.       turtle.select(16) -- Don't bother updating selected slot variable as it will set later in this function
  877.       local currFuelItems = turtle.getItemCount(16)
  878.       turtle.suck()
  879.       while ((currFuelItems ~= turtle.getItemCount(16)) and (turtle.getItemCount(16) < 64)) do
  880.         currFuelItems = turtle.getItemCount(16)
  881.         turtle.suck()
  882.       end
  883.  
  884.       slotLoop = noiseBlocksCount + 1
  885.       -- Have now picked up all the items that we can. If we have also picked up some
  886.       -- additional fuel in some of the other slots, then drop it again
  887.       while (slotLoop <= lastEmptySlot) do
  888.         -- Drop any items found in this slot
  889.         if (turtle.getItemCount(slotLoop) > 0) then
  890.           turtle.select(slotLoop) -- Don't bother updating selected slot variable as it will set later in this function
  891.           turtle.drop()
  892.         end
  893.         slotLoop = slotLoop + 1
  894.       end
  895.     end
  896.  
  897.     -- Select the 1st slot because sometimes when leaving the 15th or 16th slots selected it can result
  898.     -- in that slot being immediately filled (resulting in the turtle returning to base again too soon)
  899.     turtle.select(1)
  900.     currentlySelectedSlot = 1
  901.   end
  902.  
  903.   -- If required, move back to the point that we were mining at before returning to the start
  904.   if (returnBackToMiningPoint == true) then
  905.  
  906.     -- If resuming, refresh the starting point to be the top of the return shaft
  907.     if (resuming == true) then
  908.       currX = 0
  909.       currY = startHeight
  910.       currZ = 0
  911.       currOrient = resumeOrient
  912.     end
  913.  
  914.     -- Return back to the required layer
  915.     while (currY > levelToReturnTo) do
  916.       turtleDown()
  917.     end
  918.  
  919.     if ((haveBeenAtZeroZeroOnLayer == false) or (orientationAtZeroZero == way.FORWARD)) then
  920.       -- Move back to the correct Z position first
  921.       writeMessage("Stored Z: "..storedZ..", currZ: "..currZ, messageLevel.DEBUG)
  922.       if (storedZ > currZ) then
  923.         writeMessage("Orienting forward", messageLevel.DEBUG)
  924.         writeMessage("Moving in z way", messageLevel.DEBUG)
  925.         turtleSetOrientation(way.FORWARD)
  926.         while (storedZ > currZ) do
  927.           turtleForward()
  928.         end
  929.       elseif (storedZ < currZ) then
  930.         -- This should never happen
  931.         writeMessage("Stored z is less than current z in returnToStartAndUnload", messageLevel.ERROR)
  932.       end
  933.  
  934.       -- Then move back to the correct X position
  935.       if (storedX > currX) then
  936.         writeMessage("Stored X: "..storedX..", currX: "..currX, messageLevel.DEBUG)
  937.         writeMessage("Orienting right", messageLevel.DEBUG)
  938.         writeMessage("Moving in x way", messageLevel.DEBUG)
  939.         turtleSetOrientation(way.RIGHT)
  940.         while (storedX > currX) do
  941.           turtleForward()
  942.         end
  943.       elseif (storedX < currX) then
  944.         -- This should never happen
  945.         writeMessage("Stored x is less than current x in returnToStartAndUnload", messageLevel.ERROR)
  946.       end
  947.     else
  948.       -- Move back to the correct X position first
  949.       if (storedX > currX) then
  950.         writeMessage("Stored X: "..storedX..", currX: "..currX, messageLevel.DEBUG)
  951.         writeMessage("Orienting right", messageLevel.DEBUG)
  952.         writeMessage("Moving in x way", messageLevel.DEBUG)
  953.         turtleSetOrientation(way.RIGHT)
  954.         while (storedX > currX) do
  955.           turtleForward()
  956.         end
  957.       elseif (storedX < currX) then
  958.         -- This should never happen
  959.         writeMessage("Stored x is less than current x in returnToStartAndUnload", messageLevel.ERROR)
  960.       end
  961.  
  962.       -- Then move back to the correct Z position
  963.       writeMessage("Stored Z: "..storedZ..", currZ: "..currZ, messageLevel.DEBUG)
  964.       if (storedZ > currZ) then
  965.         writeMessage("Orienting forward", messageLevel.DEBUG)
  966.         writeMessage("Moving in z way", messageLevel.DEBUG)
  967.         turtleSetOrientation(way.FORWARD)
  968.         while (storedZ > currZ) do
  969.           turtleForward()
  970.         end
  971.       elseif (storedZ < currZ) then
  972.         -- This should never happen
  973.         writeMessage("Stored z is less than current z in returnToStartAndUnload", messageLevel.ERROR)
  974.       end
  975.     end
  976.  
  977.     -- Move back to the correct layer
  978.     if (storedY < currY) then
  979.       while (storedY < currY) do
  980.         turtleDown()
  981.       end
  982.     elseif (storedY > currY) then
  983.       while (storedY > currY) do
  984.         turtleUp()
  985.       end
  986.     end
  987.  
  988.     -- Finally, set the correct orientation
  989.     turtleSetOrientation(storedOrient)
  990.  
  991.     writeMessage("Have returned to the mining point", messageLevel.DEBUG)
  992.   end
  993.  
  994.   -- Store the current location and orientation so that it can be returned to
  995.   currMiningState = prevMiningState
  996.  
  997.   returningToStart = false
  998.  
  999. end
  1000.  
  1001. -- ********************************************************************************** --
  1002. -- Empties a chest's contents
  1003. -- ********************************************************************************** --
  1004. function emptyChest(suckFn)
  1005.  
  1006.   local prevInventoryCount = {}
  1007.   local inventoryLoop
  1008.   local chestEmptied = false
  1009.  
  1010.   -- Record the number of items in each of the inventory slots
  1011.   for inventoryLoop = 1, 16 do
  1012.     prevInventoryCount[inventoryLoop] = turtle.getItemCount(inventoryLoop)
  1013.   end
  1014.  
  1015.   while (chestEmptied == false) do
  1016.     -- Pick up the next item
  1017.     suckFn()
  1018.  
  1019.     -- Determine the number of items in each of the inventory slots now
  1020.     local newInventoryCount = {}
  1021.     for inventoryLoop = 1, 16 do
  1022.       newInventoryCount[inventoryLoop] = turtle.getItemCount(inventoryLoop)
  1023.     end
  1024.  
  1025.     -- Now, determine whether there have been any items taken from the chest
  1026.     local foundDifferentItemCount = false
  1027.     inventoryLoop = 1
  1028.     while ((foundDifferentItemCount == false) and (inventoryLoop <= 16)) do
  1029.       if (prevInventoryCount[inventoryLoop] ~= newInventoryCount[inventoryLoop]) then
  1030.         foundDifferentItemCount = true
  1031.       else
  1032.         inventoryLoop = inventoryLoop + 1
  1033.       end
  1034.     end
  1035.    
  1036.     -- If no items have been found with a different item count, then the chest has been emptied
  1037.     chestEmptied = not foundDifferentItemCount
  1038.  
  1039.     if (chestEmptied == false) then
  1040.       prevInventoryCount = newInventoryCount
  1041.       -- Check that there is sufficient inventory space as may have picked up a block
  1042.       ensureInventorySpace()
  1043.     end
  1044.   end
  1045.  
  1046.   writeMessage("Finished emptying chest", messageLevel.DEBUG)
  1047. end
  1048.  
  1049. -- ********************************************************************************** --
  1050. -- Write the current location to a file
  1051. -- ********************************************************************************** --
  1052. function saveLocation()
  1053.  
  1054.   -- Write the x, y, z and orientation to the file
  1055.   if ((supportResume == true) and (resuming == false)) then
  1056.     local outputFile = io.open(oreQuarryLocation, "w")
  1057.     outputFile:write(currMiningState)
  1058.     outputFile:write("\n")
  1059.     outputFile:write(currX)
  1060.     outputFile:write("\n")
  1061.     outputFile:write(currY)
  1062.     outputFile:write("\n")
  1063.     outputFile:write(currZ)
  1064.     outputFile:write("\n")
  1065.     outputFile:write(currOrient)
  1066.     outputFile:write("\n")
  1067.     outputFile:close()
  1068.   end
  1069.  
  1070. end
  1071.  
  1072. -- ********************************************************************************** --
  1073. -- If the turtle is resuming and the current co-ordinates, orientation and
  1074. -- mining state have been matched, then no longer resuming
  1075. -- ********************************************************************************** --
  1076. function updateResumingFlag()
  1077.  
  1078.   if (resuming == true) then
  1079.     if ((resumeMiningState == currMiningState) and (resumeX == currX) and (resumeY == currY) and (resumeZ == currZ) and (resumeOrient == currOrient)) then
  1080.       resuming = false
  1081.     end
  1082.   end
  1083.  
  1084. end
  1085.  
  1086. -- ********************************************************************************** --
  1087. -- Generic function to move the Turtle (pushing through any gravel or other
  1088. -- things such as mobs that might get in the way).
  1089. --
  1090. -- The only thing that should stop the turtle moving is bedrock. Where this is
  1091. -- found, the function will return after 15 seconds returning false
  1092. -- ********************************************************************************** --
  1093. function moveTurtle(moveFn, detectFn, digFn, attackFn, compareFn, suckFn, maxDigCount, newX, newY, newZ)
  1094.  
  1095.   local moveSuccess = false
  1096.  
  1097.   -- If we are resuming, then don't do anything in this function other than updating the
  1098.   -- co-ordinates as if the turtle had moved
  1099.   if (resuming == true) then
  1100.     -- Set the move success to true (but don't move) - unless this is below bedrock level
  1101.     -- in which case return false
  1102.     if (currY <= 0) then
  1103.       moveSuccess = false
  1104.     else
  1105.       moveSuccess = true
  1106.     end
  1107.  
  1108.     -- Update the co-ordinates to reflect the movement
  1109.     currX = newX
  1110.     currY = newY
  1111.     currZ = newZ
  1112.  
  1113.   else
  1114.     local prevX, prevY, prevZ
  1115.     prevX = currX
  1116.     prevY = currY
  1117.     prevZ = currZ
  1118.  
  1119.     -- TODO: Ensure fuel in another place
  1120.     --ensureFuel()
  1121.  
  1122.     -- Flag to determine whether digging has been tried yet. If it has
  1123.     -- then pause briefly before digging again to allow sand or gravel to
  1124.     -- drop
  1125.     local digCount = 0
  1126.  
  1127.     if (lastMoveNeededDig == false) then
  1128.       -- Didn't need to dig last time the turtle moved, so try moving first
  1129.  
  1130.       currX = newX
  1131.       currY = newY
  1132.       currZ = newZ
  1133.       saveLocation()
  1134.  
  1135.       moveSuccess = moveFn()
  1136.  
  1137.       -- If move failed, update the co-ords back to the previous co-ords
  1138.       if (moveSuccess == false) then
  1139.         currX = prevX
  1140.         currY = prevY
  1141.         currZ = prevZ
  1142.         saveLocation()
  1143.       end
  1144.  
  1145.       -- Don't need to set the last move needed dig. It is already false, if
  1146.       -- move success is now true, then it won't be changed
  1147.     else
  1148.       -- If we are looking for chests, then check that this isn't a chest before trying to dig it
  1149.       if (lookForChests == true) then
  1150.         if (isNoiseBlock(compareFn) == false) then
  1151.           if (detectFn() == true) then
  1152.             -- Determine if it is a chest before digging it
  1153.             if (isChestBlock(compareFn) == true) then
  1154.               -- Have found a chest, empty it before continuing
  1155.               emptyChest (suckFn)
  1156.             end
  1157.           end
  1158.         end
  1159.       end
  1160.  
  1161.       -- Try to dig (without doing a detect as it is quicker)
  1162.       local digSuccess = digFn()
  1163.       if (digSuccess == true) then
  1164.         digCount = 1
  1165.       end
  1166.  
  1167.       currX = newX
  1168.       currY = newY
  1169.       currZ = newZ
  1170.       saveLocation()
  1171.  
  1172.       moveSuccess = moveFn()
  1173.  
  1174.       if (moveSuccess == true) then
  1175.         lastMoveNeededDig = digSuccess
  1176.       else
  1177.         currX = prevX
  1178.         currY = prevY
  1179.         currZ = prevZ
  1180.         saveLocation()
  1181.       end
  1182.  
  1183.     end
  1184.  
  1185.     -- Loop until we've successfully moved
  1186.     if (moveSuccess == false) then
  1187.       while ((moveSuccess == false) and (digCount < maxDigCount)) do
  1188.  
  1189.         -- If there is a block in front, dig it
  1190.         if (detectFn() == true) then
  1191.        
  1192.             -- If we've already tried digging, then pause before digging again to let
  1193.             -- any sand or gravel drop, otherwise check for a chest before digging
  1194.             if(digCount == 0) then
  1195.               -- Am about to dig a block - check that it is not a chest if necessary
  1196.               -- If we are looking for chests, then check that this isn't a chest before moving
  1197.               if (lookForChests == true) then
  1198.                 if (isNoiseBlock(compareFn) == false) then
  1199.                   if (detectFn() == true) then
  1200.                     -- Determine if it is a chest before digging it
  1201.                     if (isChestBlock(compareFn) == true) then
  1202.                       -- Have found a chest, empty it before continuing
  1203.                       emptyChest (suckFn)
  1204.                     end
  1205.                   end
  1206.                 end
  1207.               end
  1208.             else
  1209.               sleep(0.1)
  1210.             end
  1211.  
  1212.             digFn()
  1213.             digCount = digCount + 1
  1214.         else
  1215.            -- Am being stopped from moving by a mob, attack it
  1216.            attackFn()
  1217.         end
  1218.  
  1219.         currX = newX
  1220.         currY = newY
  1221.         currZ = newZ
  1222.         saveLocation()
  1223.  
  1224.         -- Try the move again
  1225.         moveSuccess = moveFn()
  1226.  
  1227.         if (moveSuccess == false) then
  1228.           currX = prevX
  1229.           currY = prevY
  1230.           currZ = prevZ
  1231.           saveLocation()
  1232.         end
  1233.       end
  1234.  
  1235.       if (digCount == 0) then
  1236.         lastMoveNeededDig = false
  1237.       else
  1238.         lastMoveNeededDig = true
  1239.       end
  1240.     end
  1241.   end
  1242.  
  1243.   -- If we are resuming and the current co-ordinates and orientation are the resume point
  1244.   -- then are no longer resuming
  1245.   if (moveSuccess == true) then
  1246.     updateResumingFlag()
  1247.   end
  1248.  
  1249.   -- Return the move success
  1250.   return moveSuccess
  1251.  
  1252. end
  1253.  
  1254. -- ********************************************************************************** --
  1255. -- Move the turtle forward one block (updating the turtle's position)
  1256. -- ********************************************************************************** --
  1257. function turtleForward()
  1258.  
  1259.   -- Determine the new co-ordinate that the turtle will be moving to
  1260.   local newX, newZ
  1261.  
  1262.   -- Update the current co-ordinates
  1263.   if (currOrient == way.FORWARD) then
  1264.     newZ = currZ + 1
  1265.     newX = currX
  1266.   elseif (currOrient == way.LEFT) then
  1267.     newX = currX - 1
  1268.     newZ = currZ
  1269.   elseif (currOrient == way.BACK) then
  1270.     newZ = currZ - 1
  1271.     newX = currX
  1272.   elseif (currOrient == way.RIGHT) then
  1273.     newX = currX + 1
  1274.     newZ = currZ
  1275.   else
  1276.     writeMessage ("Invalid currOrient in turtleForward function", messageLevel.ERROR)
  1277.   end
  1278.  
  1279.   local returnVal = moveTurtle(turtle.forward, turtle.detect, turtle.dig, turtle.attack, turtle.compare, turtle.suck, maximumGravelStackSupported, newX, currY, newZ)
  1280.  
  1281.   if (returnVal == true) then
  1282.     -- Check that there is sufficient inventory space as may have picked up a block
  1283.     ensureInventorySpace()
  1284.   end
  1285.  
  1286.   return returnVal
  1287. end
  1288.  
  1289. -- ********************************************************************************** --
  1290. -- Move the turtle up one block (updating the turtle's position)
  1291. -- ********************************************************************************** --
  1292. function turtleUp()
  1293.  
  1294.   local returnVal = moveTurtle(turtle.up, turtle.detectUp, turtle.digUp, turtle.attackUp, turtle.compareUp, turtle.suckUp, maximumGravelStackSupported, currX, currY + 1, currZ)
  1295.  
  1296.   if (returnVal == true) then
  1297.     -- Check that there is sufficient inventory space as may have picked up a block
  1298.     ensureInventorySpace()
  1299.   end
  1300.  
  1301.   return returnVal
  1302. end
  1303.  
  1304. -- ********************************************************************************** --
  1305. -- Move the turtle down one block (updating the turtle's position)
  1306. -- ********************************************************************************** --
  1307. function turtleDown()
  1308.  
  1309.   local returnVal = moveTurtle(turtle.down, turtle.detectDown, turtle.digDown, turtle.attackDown, turtle.compareDown, turtle.suckDown, 1, currX, currY - 1, currZ)
  1310.  
  1311.   if (returnVal == true) then
  1312.     -- Check that there is sufficient inventory space as may have picked up a block
  1313.     ensureInventorySpace()
  1314.   end
  1315.  
  1316.   return returnVal
  1317.  
  1318. end
  1319.  
  1320. -- ********************************************************************************** --
  1321. -- Move the turtle back one block (updating the turtle's position)
  1322. -- ********************************************************************************** --
  1323. function turtleBack()
  1324.  
  1325.   -- Assume that the turtle will move, and switch the co-ords back if it doesn't
  1326.   -- (do this so that we can write the co-ords to a file before moving)
  1327.   local newX, newZ
  1328.   local prevX, prevZ
  1329.   prevX = currX
  1330.   prevZ = currZ
  1331.  
  1332.   -- Update the current co-ordinates
  1333.   if (currOrient == way.FORWARD) then
  1334.     newZ = currZ - 1
  1335.     newX = currX
  1336.   elseif (currOrient == way.LEFT) then
  1337.     newX = currX + 1
  1338.     newZ = currZ
  1339.   elseif (currOrient == way.BACK) then
  1340.     newZ = currZ + 1
  1341.     newX = currX
  1342.   elseif (currOrient == way.RIGHT) then
  1343.     newX = currX - 1
  1344.     newZ = currZ
  1345.   else
  1346.     writeMessage ("Invalid currOrient in turtleBack function", messageLevel.ERROR)
  1347.   end
  1348.  
  1349.   -- First try to move back using the standard function
  1350.  
  1351.   currX = newX
  1352.   currZ = newZ
  1353.   saveLocation()
  1354.   local returnVal = turtle.back()
  1355.  
  1356.   if (returnVal == false) then
  1357.     -- Didn't move. Reset the co-ordinates to the previous value
  1358.     currX = prevX
  1359.     currZ = prevZ
  1360.  
  1361.     -- Reset the location back to the previous location (because the turn takes 0.8 of a second
  1362.     -- so could be stopped before getting to the forward function)
  1363.     saveLocation()
  1364.  
  1365.     turtle.turnRight()
  1366.     turtle.turnRight()
  1367.  
  1368.     -- Try to move by using the forward function (note, the orientation will be set as
  1369.     -- the same way as this function started because if the function stops, that is the
  1370.     -- way that we want to consider the turtle to be pointing)
  1371.  
  1372.     returnVal = moveTurtle(turtle.forward, turtle.detect, turtle.dig, turtle.attack, turtle.compare, turtle.suck, maximumGravelStackSupported, newX, currY, newZ)
  1373.  
  1374.     turtle.turnRight()
  1375.     turtle.turnRight()
  1376.   end
  1377.  
  1378.   if (returnVal == true) then
  1379.     -- Check that there is sufficient inventory space as may have picked up a block
  1380.     ensureInventorySpace()
  1381.   end
  1382.    
  1383.   return returnVal
  1384. end
  1385.  
  1386. -- ********************************************************************************** --
  1387. -- Turns the turtle (updating the current orientation at the same time)
  1388. -- ********************************************************************************** --
  1389. function turtleTurn(turnDir)
  1390.  
  1391.   if (turnDir == way.LEFT) then
  1392.     if (currOrient == way.FORWARD) then
  1393.       currOrient = way.LEFT
  1394.     elseif (currOrient == way.LEFT) then
  1395.       currOrient = way.BACK
  1396.     elseif (currOrient == way.BACK) then
  1397.       currOrient = way.RIGHT
  1398.     elseif (currOrient == way.RIGHT) then
  1399.       currOrient = way.FORWARD
  1400.     else
  1401.       writeMessage ("Invalid currOrient in turtleTurn function", messageLevel.ERROR)
  1402.     end
  1403.  
  1404.     -- If we are resuming, just check to see whether have reached the resume point, otherwise
  1405.     -- turn
  1406.     if (resuming == true) then
  1407.       updateResumingFlag()
  1408.     else
  1409.       -- Write the new orientation and turn
  1410.       saveLocation()
  1411.       turtle.turnLeft()
  1412.     end
  1413.  
  1414.   elseif (turnDir == way.RIGHT) then
  1415.     if (currOrient == way.FORWARD) then
  1416.       currOrient = way.RIGHT
  1417.     elseif (currOrient == way.LEFT) then
  1418.       currOrient = way.FORWARD
  1419.     elseif (currOrient == way.BACK) then
  1420.       currOrient = way.LEFT
  1421.     elseif (currOrient == way.RIGHT) then
  1422.       currOrient = way.BACK
  1423.     else
  1424.       writeMessage ("Invalid currOrient in turtleTurn function", messageLevel.ERROR)
  1425.     end
  1426.  
  1427.     -- If we are resuming, just check to see whether have reached the resume point, otherwise
  1428.     -- turn
  1429.     if (resuming == true) then
  1430.       updateResumingFlag()
  1431.  
  1432.       writeMessage("["..currMiningState..", "..currX..", "..currY..", "..currZ..", "..currOrient.."]", messageLevel.DEBUG)
  1433.     else
  1434.       -- Write the new orientation and turn
  1435.       saveLocation()
  1436.       turtle.turnRight()
  1437.     end
  1438.   else
  1439.     writeMessage ("Invalid turnDir in turtleTurn function", messageLevel.ERROR)
  1440.   end
  1441. end
  1442.  
  1443. -- ********************************************************************************** --
  1444. -- Sets the turtle to a specific orientation, irrespective of its current orientation
  1445. -- ********************************************************************************** --
  1446. function turtleSetOrientation(newOrient)
  1447.  
  1448.   if (currOrient ~= newOrient) then
  1449.     if (currOrient == way.FORWARD) then
  1450.       if (newOrient == way.RIGHT) then
  1451.         currOrient = newOrient
  1452.  
  1453.         -- If resuming, check whether the resume point has been reached, otherwise turn
  1454.         if (resuming == true) then
  1455.           updateResumingFlag()
  1456.         else
  1457.           -- Write the new orientation and turn
  1458.           saveLocation()
  1459.           turtle.turnRight()
  1460.         end
  1461.       elseif (newOrient == way.BACK) then
  1462.         currOrient = newOrient
  1463.  
  1464.         -- If resuming, check whether the resume point has been reached, otherwise turn
  1465.         if (resuming == true) then
  1466.           updateResumingFlag()
  1467.         else
  1468.           -- Write the new orientation and turn
  1469.           saveLocation()
  1470.           turtle.turnRight()
  1471.           turtle.turnRight()
  1472.         end
  1473.       elseif (newOrient == way.LEFT) then
  1474.         currOrient = newOrient
  1475.  
  1476.         -- If resuming, check whether the resume point has been reached, otherwise turn
  1477.         if (resuming == true) then
  1478.           updateResumingFlag()
  1479.         else
  1480.           -- Write the new orientation and turn
  1481.           saveLocation()
  1482.           turtle.turnLeft()
  1483.         end
  1484.       else
  1485.         writeMessage ("Invalid newOrient in turtleSetOrientation function", messageLevel.ERROR)
  1486.       end
  1487.     elseif (currOrient == way.RIGHT) then
  1488.       if (newOrient == way.BACK) then
  1489.         currOrient = newOrient
  1490.  
  1491.         -- If resuming, check whether the resume point has been reached, otherwise turn
  1492.         if (resuming == true) then
  1493.           updateResumingFlag()
  1494.         else
  1495.           -- Write the new orientation and turn
  1496.           saveLocation()
  1497.           turtle.turnRight()
  1498.         end
  1499.       elseif (newOrient == way.LEFT) then
  1500.         currOrient = newOrient
  1501.  
  1502.         -- If resuming, check whether the resume point has been reached, otherwise turn
  1503.         if (resuming == true) then
  1504.           updateResumingFlag()
  1505.         else
  1506.           -- Write the new orientation and turn
  1507.           saveLocation()
  1508.           turtle.turnRight()
  1509.           turtle.turnRight()
  1510.         end
  1511.       elseif (newOrient == way.FORWARD) then
  1512.         currOrient = newOrient
  1513.  
  1514.         -- If resuming, check whether the resume point has been reached, otherwise turn
  1515.         if (resuming == true) then
  1516.           updateResumingFlag()
  1517.         else
  1518.           -- Write the new orientation and turn
  1519.           saveLocation()
  1520.           turtle.turnLeft()
  1521.         end
  1522.       else
  1523.         writeMessage ("Invalid newOrient in turtleSetOrientation function", messageLevel.ERROR)
  1524.       end
  1525.     elseif (currOrient == way.BACK) then
  1526.       if (newOrient == way.LEFT) then
  1527.         currOrient = newOrient
  1528.  
  1529.         -- If resuming, check whether the resume point has been reached, otherwise turn
  1530.         if (resuming == true) then
  1531.           updateResumingFlag()
  1532.         else
  1533.           -- Write the new orientation and turn
  1534.           saveLocation()
  1535.           turtle.turnRight()
  1536.         end
  1537.       elseif (newOrient == way.FORWARD) then
  1538.         currOrient = newOrient
  1539.  
  1540.         -- If resuming, check whether the resume point has been reached, otherwise turn
  1541.         if (resuming == true) then
  1542.           updateResumingFlag()
  1543.         else
  1544.           -- Write the new orientation and turn
  1545.           saveLocation()
  1546.           turtle.turnRight()
  1547.           turtle.turnRight()
  1548.         end
  1549.       elseif (newOrient == way.RIGHT) then
  1550.         currOrient = newOrient
  1551.  
  1552.         -- If resuming, check whether the resume point has been reached, otherwise turn
  1553.         if (resuming == true) then
  1554.           updateResumingFlag()
  1555.         else
  1556.           -- Write the new orientation and turn
  1557.           saveLocation()
  1558.           turtle.turnLeft()
  1559.         end
  1560.       else
  1561.         writeMessage ("Invalid newOrient in turtleSetOrientation function", messageLevel.ERROR)
  1562.       end
  1563.     elseif (currOrient == way.LEFT) then
  1564.       if (newOrient == way.FORWARD) then
  1565.         currOrient = newOrient
  1566.  
  1567.         -- If resuming, check whether the resume point has been reached, otherwise turn
  1568.         if (resuming == true) then
  1569.           updateResumingFlag()
  1570.         else
  1571.           -- Write the new orientation and turn
  1572.           saveLocation()
  1573.           turtle.turnRight()
  1574.         end
  1575.       elseif (newOrient == way.RIGHT) then
  1576.         currOrient = newOrient
  1577.  
  1578.         -- If resuming, check whether the resume point has been reached, otherwise turn
  1579.         if (resuming == true) then
  1580.           updateResumingFlag()
  1581.         else
  1582.           -- Write the new orientation and turn
  1583.           saveLocation()
  1584.           turtle.turnRight()
  1585.           turtle.turnRight()
  1586.         end
  1587.       elseif (newOrient == way.BACK) then
  1588.         currOrient = newOrient
  1589.  
  1590.         -- If resuming, check whether the resume point has been reached, otherwise turn
  1591.         if (resuming == true) then
  1592.           updateResumingFlag()
  1593.         else
  1594.           -- Write the new orientation and turn
  1595.           saveLocation()
  1596.           turtle.turnLeft()
  1597.         end
  1598.       else
  1599.         writeMessage ("Invalid newOrient in turtleSetOrientation function", messageLevel.ERROR)
  1600.       end
  1601.     else
  1602.       writeMessage ("Invalid currOrient in turtleTurn function", messageLevel.ERROR)
  1603.     end
  1604.   end
  1605. end
  1606.  
  1607. -- ********************************************************************************** --
  1608. -- Determines if a particular block is considered a noise block or not. A noise
  1609. -- block is one that is a standard block in the game (stone, dirt, gravel etc.) and
  1610. -- is one to ignore as not being an ore. Function works by comparing the block
  1611. -- in question against a set of blocks in the turtle's inventory which are known not to
  1612. -- be noise blocks. Param is the function to use to compare the block for a noise block
  1613. -- ********************************************************************************** --
  1614. function isNoiseBlock(compareFn)
  1615.  
  1616.   -- Consider air to be a noise block
  1617.   local returnVal = false
  1618.  
  1619.   if (resuming == true) then
  1620.     returnVal = true
  1621.   else
  1622.     local seamLoop = 1
  1623.     local prevSelectedSlot  
  1624.  
  1625.     -- If the currently selected slot is a noise block, then compare against this first
  1626.     -- so that the slot doesn't need to be selected again (there is a 0.05s cost to do
  1627.     -- this even if it is the currently selected slot)
  1628.     if (currentlySelectedSlot <= noiseBlocksCount) then
  1629.       returnVal = compareFn()
  1630.     end
  1631.  
  1632.     if (returnVal == false) then
  1633.       prevSelectedSlot = currentlySelectedSlot
  1634.       while((returnVal == false) and (seamLoop <= noiseBlocksCount)) do
  1635.         if (seamLoop ~= prevSelectedSlot) then
  1636.           turtle.select(seamLoop)
  1637.           currentlySelectedSlot = seamLoop
  1638.           returnVal = compareFn()
  1639.         end
  1640.         seamLoop = seamLoop + 1
  1641.       end
  1642.     end
  1643.   end
  1644.  
  1645.   -- Return the calculated value
  1646.   return returnVal
  1647.  
  1648. end
  1649.  
  1650. -- ********************************************************************************** --
  1651. -- Determines if a particular block is a chest. Returns false if it is not a chest
  1652. -- or chests are not being detected
  1653. -- ********************************************************************************** --
  1654. function isChestBlock(compareFn)
  1655.  
  1656.   -- Check the block in the appropriate way to see whether it is a chest. Only
  1657.   -- do this if we are looking for chests
  1658.   local returnVal = false
  1659.   if (lookForChests == true) then
  1660.     turtle.select(15)
  1661.     currentlySelectedSlot = 15
  1662.     returnVal = compareFn()
  1663.   end
  1664.  
  1665.   -- Return the calculated value
  1666.   return returnVal
  1667.  
  1668. end
  1669.  
  1670. -- ********************************************************************************** --
  1671. -- Function to calculate the number of non seam blocks in the turtle's inventory. This
  1672. -- is all of the blocks at the start of the inventory (before the first empty slot is
  1673. -- found
  1674. -- ********************************************************************************** --
  1675. function determineNoiseBlocksCountCount()
  1676.   -- Determine the location of the first empty inventory slot. All items before this represent
  1677.   -- noise items.
  1678.   local foundFirstBlankInventorySlot = false
  1679.   noiseBlocksCount = 1
  1680.   while ((noiseBlocksCount < 16) and (foundFirstBlankInventorySlot == false)) do
  1681.     if (turtle.getItemCount(noiseBlocksCount) > 0) then
  1682.       noiseBlocksCount = noiseBlocksCount + 1
  1683.     else
  1684.       foundFirstBlankInventorySlot = true
  1685.     end
  1686.   end
  1687.   noiseBlocksCount = noiseBlocksCount - 1
  1688.  
  1689.   -- Determine whether a chest was provided, and hence whether we should support
  1690.   -- looking for chests
  1691.   if (turtle.getItemCount(15) > 0) then
  1692.     lookForChests = true
  1693.     lastEmptySlot = 14
  1694.     miningOffset = 0
  1695.     writeMessage("Looking for chests...", messageLevel.DEBUG)
  1696.   else
  1697.     lastEmptySlot = 15
  1698.     miningOffset = 1
  1699.     writeMessage("Ignoring chests...", messageLevel.DEBUG)
  1700.   end
  1701. end
  1702.  
  1703. -- ********************************************************************************** --
  1704. -- Creates a quarry mining out only ores and leaving behind any noise blocks
  1705. -- ********************************************************************************** --
  1706. function createQuarry()
  1707.  
  1708.   -- Determine the top mining layer layer. The turtle mines in layers of 3, and the bottom layer
  1709.   -- is the layer directly above bedrock.
  1710.   --
  1711.   -- The actual layer that the turtle operates in is the middle of these three layers,
  1712.   -- so determine the top layer
  1713.   local topMiningLayer = startHeight + ((bottomLayer - startHeight - 2) % 3) - 1 + miningOffset
  1714.  
  1715.   -- If the top layer is up, then ignore it and move to the next layer
  1716.   if (topMiningLayer > currY) then
  1717.     topMiningLayer = topMiningLayer - 3
  1718.   end
  1719.  
  1720.   local startedLayerToRight = true -- Only used where the quarry is of an odd width
  1721.  
  1722.   -- Loop over each mining row
  1723.   local miningLevel
  1724.   for miningLevel = (bottomLayer + miningOffset), topMiningLayer, 3 do
  1725.     writeMessage("Mining Layer: "..miningLevel, messageLevel.INFO)
  1726.     haveBeenAtZeroZeroOnLayer = false
  1727.  
  1728.     -- While the initial shaft is being dug out, set the level to return to in order to unload
  1729.     -- to the just take the turtle straight back up
  1730.     if (miningLevel == (bottomLayer + miningOffset)) then
  1731.       levelToReturnTo = startHeight
  1732.     end
  1733.  
  1734.     -- Move to the correct level to start mining
  1735.     if (currY > miningLevel) then
  1736.       while (currY > miningLevel) do
  1737.         turtleDown()
  1738.       end
  1739.     elseif (currY < miningLevel) then
  1740.       while (currY < miningLevel) do
  1741.         turtleUp()
  1742.       end
  1743.     end
  1744.  
  1745.     -- Am now mining the levels (update the mining state to reflect that fact)
  1746.     currMiningState = miningState.LAYER
  1747.  
  1748.     -- Set the layer to return via when returning to the surface as the one below the currently
  1749.     -- mined one
  1750.     if (miningLevel == (bottomLayer + miningOffset)) then
  1751.       levelToReturnTo = (bottomLayer + miningOffset)
  1752.     else
  1753.       levelToReturnTo = miningLevel - 3
  1754.     end
  1755.  
  1756.     -- Move turtle into the correct orientation to start mining (if this is the
  1757.     -- first row to be mined, then don't need to turn, otherwise turn towards the next
  1758.     -- mining section)
  1759.  
  1760.     writeMessage("Mining Level: "..miningLevel..", Bottom Layer: "..bottomLayer..", Mining Offset: "..miningOffset, messageLevel.DEBUG)
  1761.  
  1762.     if (miningLevel > (bottomLayer + miningOffset)) then
  1763.       -- Turn towards the next mining layer
  1764.       if (quarryWidth % 2 == 0) then
  1765.         -- An even width quarry, always turn right
  1766.         turtleTurn(way.RIGHT)
  1767.       else
  1768.         -- Turn the opposite way to that which we turned before
  1769.         if (startedLayerToRight == true) then
  1770.           turtleTurn(way.LEFT)
  1771.           startedLayerToRight = false
  1772.         else
  1773.           turtleTurn(way.RIGHT)
  1774.           startedLayerToRight = true
  1775.         end
  1776.       end
  1777.     end
  1778.  
  1779.     local mineRows
  1780.     local onNearSideOfQuarry = true
  1781.     local diggingAway = true
  1782.     for mineRows = 1, quarryWidth do
  1783.  
  1784.       -- If this is not the first row, then get into position to mine the next row
  1785.       if ((mineRows == 1) and (lookForChests == false)) then
  1786.         -- Not looking for chests, check the block below for being an ore. Only do this
  1787.         -- if we're not looking for chests since the program doesn't support chests in
  1788.         -- bedrock
  1789.         if (isNoiseBlock(turtle.compareDown) == false) then
  1790.           turtle.digDown()
  1791.           ensureInventorySpace()
  1792.         end
  1793.       elseif (mineRows > 1) then
  1794.         -- Move into position for mining the next row
  1795.         if (onNearSideOfQuarry == diggingAway) then
  1796.           if (startedLayerToRight == true) then
  1797.             turtleTurn(way.LEFT)
  1798.           else
  1799.             turtleTurn(way.RIGHT)
  1800.           end
  1801.         else
  1802.           if (startedLayerToRight == true) then
  1803.             turtleTurn(way.RIGHT)
  1804.           else
  1805.             turtleTurn(way.LEFT)
  1806.           end
  1807.         end
  1808.  
  1809.         turtleForward()
  1810.  
  1811.         -- Before making the final turn, check the block below. Do this
  1812.         -- now because if it is a chest, then we want to back up and
  1813.         -- approach it from the side (so that we don't lose items if we
  1814.         -- have to return to the start through it).
  1815.         --
  1816.         -- This is the point at which it is safe to back up without moving
  1817.         -- out of the quarry area (unless at bedrock in which case don't bother
  1818.         -- as we'll be digging down anyway)
  1819.         if (miningLevel ~= bottomLayer) then
  1820.           if (isNoiseBlock(turtle.compareDown) == false) then
  1821.             -- If we are not looking for chests, then just dig it (it takes
  1822.             -- less time to try to dig and fail as it does to do detect and
  1823.             -- only dig if there is a block there)
  1824.             if (lookForChests == false) then
  1825.               turtle.digDown()
  1826.               ensureInventorySpace()
  1827.             elseif (turtle.detectDown() == true) then
  1828.               if (isChestBlock(turtle.compareDown) == true) then
  1829.                 -- There is a chest block below. Move back and approach
  1830.                 -- from the side to ensure that we don't need to return to
  1831.                 -- start through the chest itself (potentially losing items)
  1832.                 turtleBack()
  1833.                 turtleDown()
  1834.                 currMiningState = miningState.EMPTYCHESTDOWN
  1835.                 emptyChest(turtle.suck)
  1836.                 currMiningState = miningState.LAYER
  1837.                 turtleUp()
  1838.                 turtleForward()
  1839.                 turtle.digDown()
  1840.                 ensureInventorySpace()
  1841.               else
  1842.                 turtle.digDown()
  1843.                 ensureInventorySpace()
  1844.               end
  1845.             end
  1846.           end
  1847.         end
  1848.  
  1849.         -- Move into final position for mining the next row
  1850.         if (onNearSideOfQuarry == diggingAway) then
  1851.           if (startedLayerToRight == true) then
  1852.             turtleTurn(way.LEFT)
  1853.           else
  1854.             turtleTurn(way.RIGHT)
  1855.           end
  1856.         else
  1857.           if (startedLayerToRight == true) then
  1858.             turtleTurn(way.RIGHT)
  1859.           else
  1860.             turtleTurn(way.LEFT)
  1861.           end
  1862.         end
  1863.       end
  1864.  
  1865.       -- Dig to the other side of the quarry
  1866.       local blocksMined
  1867.       for blocksMined = 0, (quarryWidth - 1) do
  1868.         if (blocksMined > 0) then
  1869.           -- Only move forward if this is not the first space
  1870.           turtleForward()
  1871.         end
  1872.  
  1873.         -- If the current block is (0,0), then record the fact that the
  1874.         -- turtle has been through this block and what it's orientation was and update the layer
  1875.         -- that it should return via to get back to the surface (it no longer needs to go down
  1876.         -- a level to prevent losing ores).
  1877.         if ((currX == 0) and (currZ == 0)) then
  1878.           -- Am at (0, 0). Remember this, and what way I was facing so that the quickest route
  1879.           -- to the surface can be taken
  1880.           levelToReturnTo = miningLevel
  1881.           haveBeenAtZeroZeroOnLayer = true
  1882.           orientationAtZeroZero = currOrient
  1883.         end
  1884.  
  1885.         -- If currently at bedrock, just move down until the turtle can't go any
  1886.         -- further. This allows the blocks within the bedrock to be mined
  1887.         if (miningLevel == bottomLayer) then
  1888.           -- Temporarily turn off looking for chests to increase bedrock mining speed (this
  1889.           -- means that the program doesn't support chests below level 5 - but I think
  1890.           -- they they don't exist anyway)
  1891.           local lookForChestsPrev = lookForChests
  1892.           lookForChests = false
  1893.  
  1894.           -- Manually set the flag to determine whether the turtle should try to move first or
  1895.           -- dig first. At bedrock, is very rarely any space
  1896.  
  1897.           -- Just above bedrock layer, dig down until can't dig any lower, and then
  1898.           -- come back up. This replicates how the quarry functions
  1899.           lastMoveNeededDig = true
  1900.           local moveDownSuccess = turtleDown()
  1901.           while (moveDownSuccess == true) do
  1902.             moveDownSuccess = turtleDown()
  1903.           end
  1904.  
  1905.           -- Know that we are moving back up through air, therefore set the flag to force the
  1906.           -- turtle to try moving first
  1907.           lastMoveNeededDig = false
  1908.  
  1909.           -- Have now hit bedrock, move back to the mining layer
  1910.           while (currY < bottomLayer) do
  1911.             turtleUp()
  1912.           end
  1913.  
  1914.           -- Now back at the level above bedrock, again reset the flag to tell the turtle to
  1915.           -- try digging again (because it is rare to find air at bedrock level)
  1916.           lastMoveNeededDig = false
  1917.  
  1918.           -- Reset the look for chests value
  1919.           lookForChests = lookForChestsPrev
  1920.         elseif ((blocksMined > 0) and ((currX ~= 0) or (currZ ~= 0))) then
  1921.           -- This isn't the first block of the row, nor are we at (0, 0) so we need to check the
  1922.           -- block below
  1923.  
  1924.           -- Check the block down for being a noise block (don't need to check the first
  1925.           -- block as it has already been checked in the outer loop)
  1926.           if (isNoiseBlock(turtle.compareDown) == false) then
  1927.             -- If we are not looking for chests, then just dig it (it takes
  1928.             -- less time to try to dig and fail as it does to do detect and
  1929.             -- only dig if there is a block there)
  1930.             if (lookForChests == false) then
  1931.               turtle.digDown()
  1932.               ensureInventorySpace()
  1933.             elseif (turtle.detectDown() == true) then
  1934.               if (isChestBlock(turtle.compareDown) == true) then
  1935.                 -- There is a chest block below. Move back and approach
  1936.                 -- from the side to ensure that we don't need to return to
  1937.                 -- start through the chest itself (potentially losing items)
  1938.                 turtleBack()
  1939.                 currMiningState = miningState.EMPTYCHESTDOWN
  1940.                 turtleDown()
  1941.                 emptyChest(turtle.suck)
  1942.                 currMiningState = miningState.LAYER
  1943.                 turtleUp()
  1944.                 turtleForward()
  1945.                 turtle.digDown()
  1946.                 ensureInventorySpace()
  1947.               else
  1948.                 turtle.digDown()
  1949.                 ensureInventorySpace()
  1950.               end
  1951.             end
  1952.           end
  1953.         end
  1954.        
  1955.         -- Check the block above for ores (if we're not a (0, 0) in which case
  1956.         -- we know it's air)
  1957.         if ((currX ~= 0) or (currZ ~= 0)) then
  1958.           if (isNoiseBlock(turtle.compareUp) == false) then
  1959.             -- If we are not looking for chests, then just dig it (it takes
  1960.             -- less time to try to dig and fail as it does to do detect and
  1961.             -- only dig if there is a block there)
  1962.             if (lookForChests == false) then
  1963.               turtle.digUp()
  1964.               ensureInventorySpace()
  1965.             elseif (turtle.detectUp() == true) then
  1966.               -- Determine if it is a chest before digging it
  1967.               if (isChestBlock(turtle.compareUp) == true) then
  1968.                 -- There is a chest block above. Empty it before digging it
  1969.                 emptyChest(turtle.suckUp)
  1970.                 turtle.digUp()
  1971.                 ensureInventorySpace()
  1972.               else
  1973.                 turtle.digUp()
  1974.                 ensureInventorySpace()
  1975.               end
  1976.             end
  1977.           end
  1978.         end
  1979.       end
  1980.  
  1981.       -- Am now at the other side of the quarry
  1982.       onNearSideOfQuarry = not onNearSideOfQuarry
  1983.     end
  1984.  
  1985.     -- If we were digging away from the starting point, will be digging
  1986.     -- back towards it on the next layer
  1987.     diggingAway = not diggingAway
  1988.   end
  1989.  
  1990.   -- Return to the start
  1991.   returnToStartAndUnload(false)
  1992.  
  1993.   -- Face forward
  1994.   turtleSetOrientation(way.FORWARD)
  1995. end
  1996.  
  1997. -- ********************************************************************************** --
  1998. -- Reads the next number from a given file
  1999. -- ********************************************************************************** --
  2000. function readNumber(inputFile)
  2001.  
  2002.   local returnVal
  2003.   local nextLine = inputFile.readLine()
  2004.   if (nextLine ~= nil) then
  2005.     returnVal = tonumber(nextLine)
  2006.   end
  2007.  
  2008.   return returnVal
  2009. end
  2010.  
  2011. -- ********************************************************************************** --
  2012. -- Startup function to support resuming mining turtle
  2013. -- ********************************************************************************** --
  2014. function isResume()
  2015.  
  2016.   local returnVal = false
  2017.  
  2018.   -- Try to open the resume file
  2019.   local resumeFile = fs.open(startupParamsFile, "r")
  2020.   if (resumeFile == nil) then
  2021.     -- No resume file (presume that we are not supporting it)
  2022.     supportResume = false
  2023.   else
  2024.     writeMessage("Found startup params file", messageLevel.DEBUG)
  2025.  
  2026.     -- Read in the startup params
  2027.     quarryWidth = readNumber(resumeFile)
  2028.     startHeight = readNumber(resumeFile)
  2029.     noiseBlocksCount = readNumber(resumeFile)
  2030.     lastEmptySlot = readNumber(resumeFile)
  2031.     resumeFile.close()
  2032.  
  2033.     -- If the parameters were successfully read, then set the resuming flag to true
  2034.     if ((quarryWidth ~= nil) and (startHeight ~= nil) and (noiseBlocksCount ~= nil) and (lastEmptySlot ~= nil)) then
  2035.  
  2036.       resuming = true
  2037.       writeMessage("Read params", messageLevel.DEBUG)
  2038.  
  2039.       -- Determine the look for chest and mining offset
  2040.       if (lastEmptySlot == 14) then
  2041.         lookForChests = true
  2042.         miningOffset = 0
  2043.       else
  2044.         lookForChests = false
  2045.         miningOffset = 1
  2046.       end
  2047.  
  2048.       -- Get the turtle resume location
  2049.       resumeFile = fs.open(oreQuarryLocation, "r")
  2050.       if (resumeFile ~= nil) then
  2051.  
  2052.         resumeMiningState = readNumber(resumeFile)
  2053.         resumeX = readNumber(resumeFile)
  2054.         resumeY = readNumber(resumeFile)
  2055.         resumeZ = readNumber(resumeFile)
  2056.         resumeOrient = readNumber(resumeFile)
  2057.         resumeFile.close()
  2058.  
  2059.         -- Ensure that the resume location has been found
  2060.         if ((resumeMiningState ~= nil) and (resumeX ~= nil) and (resumeY ~= nil) and (resumeZ ~= nil) and (resumeOrient ~= nil)) then
  2061.           returnVal = true
  2062.           local emptiedInventory = false
  2063.  
  2064.           -- Perform any mining state specific startup
  2065.           if (resumeMiningState == miningState.EMPTYINVENTORY) then
  2066.             -- Am mid way through an empty inventory cycle. Complete it before
  2067.             -- starting the main Quarry function
  2068.             returnToStartAndUnload(true)
  2069.             resuming = true
  2070.  
  2071.             -- Continue from the current position
  2072.             resumeX = currX
  2073.             resumeY = currY
  2074.             levelToReturnTo = resumeY
  2075.             resumeZ = currZ
  2076.             resumeOrient = currOrient
  2077.  
  2078.             writeMessage("Resuming with state of "..currMiningState, messageLevel.DEBUG)
  2079.             resumeMiningState = currMiningState
  2080.             emptiedInventory = true
  2081.           end
  2082.  
  2083.           -- If was emptying a chest when the program stopped, then move back
  2084.           -- to a point which the Quarry
  2085.           if (resumeMiningState == miningState.EMPTYCHESTDOWN) then
  2086.  
  2087.             -- Set the current X, Y, Z and orientation to the true position that
  2088.             -- the turtle is at
  2089.             if (emptiedInventory == false) then
  2090.               currX = resumeX
  2091.               currY = resumeY
  2092.               currZ = resumeZ
  2093.               currOrient = resumeOrient
  2094.             end
  2095.  
  2096.             -- Set the mining state as layer, assume haven't been through zero
  2097.             -- zero and set the level to return to as the one below the current one
  2098.             currMiningState = miningState.LAYER
  2099.             levelToReturnTo = currY - 2
  2100.             haveBeenAtZeroZeroOnLayer = false
  2101.  
  2102.             -- Temporarily disable resuming (so that the new location is written to the file
  2103.             -- in case the program stops again)
  2104.             resuming = false
  2105.             turtleUp()
  2106.             resuming = true
  2107.  
  2108.             resumeY = currY
  2109.             resumeMiningState = miningState.LAYER
  2110.           end
  2111.         end
  2112.       end
  2113.     end
  2114.  
  2115.     if (returnVal == false) then
  2116.       writeMessage("Failed to resume", messageLevel.ERROR)
  2117.     end
  2118.   end
  2119.  
  2120.   return returnVal
  2121. end
  2122.  
  2123. -- ********************************************************************************** --
  2124. -- **                                                                              ** --
  2125. -- **                                                                              ** --
  2126. -- **                                                                              ** --
  2127. -- **                                                                              ** --
  2128. -- **                                                                              ** --
  2129. -- **                            Starting functions                                ** --
  2130. -- **                                                                              ** --
  2131. -- **                                                                              ** --
  2132. -- **                                                                              ** --
  2133. -- **                                                                              ** --
  2134. -- **                                                                              ** --
  2135. -- ********************************************************************************** --
  2136.  
  2137.  
  2138. -- Process the input arguments - storing them to global variables
  2139. local paramsOK = true
  2140.  
  2141. function startOreQuarry()
  2142.   -- Detect whether this is a wireless turtle, and if so, open the modem
  2143.   local peripheralConnected = peripheral.getType("right")
  2144.   if (peripheralConnected == "modem") then
  2145.     isWirelessTurtle = true
  2146.   end
  2147.    
  2148.   -- If a wireless turtle, open the modem
  2149.   if (isWirelessTurtle == true) then
  2150.     turtleId = os.getComputerLabel()
  2151.     rednet.open("right")
  2152.   end
  2153.    
  2154.   if (#args == 0) then
  2155.     -- Is this a resume?
  2156.     if (isResume() == false) then
  2157.       paramsOK = false
  2158.     end
  2159.   elseif (#args == 1) then
  2160.     quarryWidth = tonumber(args[1])
  2161.     local x, y, z = gps.locate(5)
  2162.     startHeight = y
  2163.     if (startHeight == nil) then
  2164.       writeMessage("Can't locate GPS", messageLevel.FATAL)
  2165.       paramsOK = false
  2166.     end
  2167.   elseif (#args == 2) then
  2168.     if (args[2] == "/r") then
  2169.       quarryWidth = tonumber(args[1])
  2170.       supportResume = false
  2171.     else
  2172.       quarryWidth = tonumber(args[1])
  2173.       startHeight = tonumber(args[2])
  2174.     end
  2175.   elseif (#args == 3) then
  2176.     quarryWidth = tonumber(args[1])
  2177.     startHeight = tonumber(args[2])
  2178.     if (args[3] == "/r") then
  2179.       supportResume = false
  2180.     else
  2181.       paramsOK = false
  2182.     end
  2183.   end
  2184.    
  2185.   if ((paramsOK == false) and (resuming == false)) then
  2186.     writeMessage("Usage: "..shell.getRunningProgram().." <diameter> [turtleY] [/r]", messageLevel.FATAL)
  2187.     paramsOK = false
  2188.   end
  2189.    
  2190.   if (paramsOK == true) then
  2191.     if ((startHeight < 6) or (startHeight > 128)) then
  2192.       writeMessage("turtleY must be between 6 and 128", messageLevel.FATAL)
  2193.       paramsOK = false
  2194.     end
  2195.    
  2196.     if ((quarryWidth < 2) or (quarryWidth > 64)) then
  2197.       writeMessage("diameter must be between 2 and 64", messageLevel.FATAL)
  2198.       paramsOK = false
  2199.     end
  2200.   end
  2201.    
  2202.   if (paramsOK == true) then
  2203.     if (resuming == true) then
  2204.       writeMessage("Resuming Ore Quarry...", messageLevel.INFO)
  2205.     else
  2206.       writeMessage("----------------------------------", messageLevel.INFO)
  2207.       writeMessage("** Ore Quarry v0.71 by AustinKK **", messageLevel.INFO)
  2208.       writeMessage("----------------------------------", messageLevel.INFO)
  2209.     end
  2210.    
  2211.     -- Set the turtle's starting position
  2212.     currX = 0
  2213.     currY = startHeight
  2214.     currZ = 0
  2215.     currOrient = way.FORWARD
  2216.    
  2217.     -- Calculate which blocks in the inventory signify noise blocks
  2218.     if (resuming == false) then
  2219.       determineNoiseBlocksCountCount()
  2220.     end
  2221.    
  2222.     if ((noiseBlocksCount == 0) or (noiseBlocksCount > 13)) then
  2223.       writeMessage("No noise blocks have been been added. Please place blocks that the turtle should not mine (e.g. Stone, Dirt, Gravel etc.) in the first few slots of the turtle\'s inventory. The first empty slot signifies the end of the noise blocks.", messageLevel.FATAL)
  2224.     else
  2225.       -- If we are supporting resume (and are not currently in the process of resuming)
  2226.       -- then store startup parameters in appropriate files
  2227.       if ((supportResume == true) and (resuming == false)) then
  2228.         -- Write the startup parameters to  file
  2229.         local outputFile = io.open(startupParamsFile, "w")
  2230.         outputFile:write(quarryWidth)
  2231.         outputFile:write("\n")
  2232.         outputFile:write(startHeight)
  2233.         outputFile:write("\n")
  2234.         outputFile:write(noiseBlocksCount)
  2235.         outputFile:write("\n")
  2236.         outputFile:write(lastEmptySlot)
  2237.         outputFile:write("\n")
  2238.         outputFile:close()
  2239.    
  2240.         -- Setup the startup file
  2241.    
  2242.         -- Take a backup of the current startup file
  2243.         if (fs.exists("startup") == true) then
  2244.           fs.copy("startup", startupBackup)
  2245.           outputFile = io.open("startup", "a")
  2246.         else
  2247.           outputFile = io.open("startup", "w")
  2248.         end
  2249.        
  2250.         -- Write an info message so that people know how to get out of auto-resume
  2251.         outputFile:write("\nprint(\"Running auto-restart...\")\n")
  2252.         outputFile:write("print(\"If you want to stop auto-resume and restore original state:\")\n")
  2253.         outputFile:write("print(\"1) Hold Ctrl-T until the program terminates\")\n")
  2254.         outputFile:write("print(\"2) Type \\\"rm startup\\\" (without quotes) and hit Enter\")\n")
  2255.         outputFile:write("print(\"\")\n\n")
  2256.    
  2257.         -- Write the code required to restart the turtle
  2258.         outputFile:write("shell.run(\"")
  2259.         outputFile:write(shell.getRunningProgram())
  2260.         outputFile:write("\")\n")
  2261.         outputFile:close()
  2262.    
  2263.       end
  2264.    
  2265.       -- Create a Quarry
  2266.       turtle.select(1)
  2267.       currentlySelectedSlot = 1
  2268.       createQuarry()
  2269.    
  2270.       -- Restore the file system to its original configuration
  2271.       if (supportResume == true) then
  2272.         fs.delete("startup")
  2273.         if (fs.exists(startupBackup) == true) then
  2274.           fs.move(startupBackup, "startup")
  2275.         end
  2276.    
  2277.         if (fs.exists(startupParamsFile) == true) then
  2278.           fs.delete(startupParamsFile)
  2279.         end
  2280.    
  2281.         if (fs.exists(oreQuarryLocation) == true) then
  2282.           fs.delete(oreQuarryLocation)
  2283.         end
  2284.    
  2285.         if (fs.exists(returnToStartFile) == true) then
  2286.           fs.delete(returnToStartFile)
  2287.         end
  2288.       end
  2289.     end
  2290.   end
  2291. end
  2292.  
  2293.  
  2294. -- ********************************************************************************** --
  2295. -- **                                                                              ** --
  2296. -- **                                                                              ** --
  2297. -- **                                                                              ** --
  2298. -- **                                                                              ** --
  2299. -- **                                                                              ** --
  2300. -- **                                PROGRAMS                                      ** --
  2301. -- **                                                                              ** --
  2302. -- **                                                                              ** --
  2303. -- **                                                                              ** --
  2304. -- **                                                                              ** --
  2305. -- **                                                                              ** --
  2306. -- ********************************************************************************** --
  2307.  
  2308.    
  2309. -- ********************************************************************************** --
  2310. -- PROGRAM: STAIRS BUILDER
  2311. -- Slots map:
  2312. -- F B S S
  2313. -- S S S S
  2314. -- S S S S
  2315. -- S S S S
  2316. -- F - Fuel, B - Corner Blocks, S - stairs
  2317. -- ********************************************************************************** --
  2318. local strsW = 7
  2319. local strsH = 7
  2320.  
  2321. local strsDirect = true;
  2322.  
  2323. local steps=2
  2324. local isRunning = true
  2325.  
  2326. -- Start loop for building
  2327. function startStairsBuilder()
  2328.   currGlobalState = globalStates.STAIRS
  2329.  
  2330.   -- Set stairs size
  2331.   if (#args == 2) then
  2332.     strsW = tonumber(args[1])
  2333.     strsH = tonumber(args[1])
  2334.   elseif (#args == 3) then
  2335.     strsW = tonumber(args[1])
  2336.     strsH = tonumber(args[2])
  2337.   end
  2338.  
  2339.   -- Starting movements
  2340.   turtle.select(1)
  2341.   turtle.refuel()
  2342.   turtle.select(3)
  2343.   turtle.place()
  2344.   turtle.up()
  2345.   turtle.forward()
  2346.   turtle.forward()
  2347.   turtle.down()
  2348.  
  2349.   -- main loop
  2350.   while (isHaveStairs() and isRunning) do
  2351.     if (((steps < strsW) and strsDirect) or ((steps < strsH) and (strsDirect==false)) ) then
  2352.       turtle.placeUp()
  2353.       turtle.forward()
  2354.       if (((steps ~= (strsW-1)) and strsDirect) or ((steps ~= (strsH-1)) and (strsDirect==false)) ) then
  2355.         turtle.up()
  2356.     end
  2357.       steps = steps + 1
  2358.     else
  2359.       if(strsDirect)then
  2360.       strsDirect = false
  2361.     else
  2362.       strsDirect = true
  2363.     end
  2364.    
  2365.     steps = 2
  2366.     turtle.turnRight()
  2367.     turtle.select(2)
  2368.     turtle.placeUp()
  2369.     turtle.forward()
  2370.     turtle.up()
  2371.     turtle.select(currSelectedSlot)
  2372.     end
  2373.   end
  2374.  
  2375.   return true
  2376. end
  2377.  
  2378. -- Check inventory
  2379. function isHaveStairsAndCorners()
  2380.   if(turtle.getItemCount(2) == 0) then
  2381.     return false
  2382.   end
  2383.  
  2384.   while ((turtle.getItemCount(currSelectedSlot) == 0) and (currSelectedSlot < 16)) do
  2385.       currSelectedSlot = currSelectedSlot + 1
  2386.       turtle.select(currSelectedSlot)
  2387.   end
  2388.  
  2389.   if (turtle.getItemCount(currSelectedSlot)==0) then
  2390.       return false
  2391.   else
  2392.       return true
  2393.   end
  2394. end
  2395.  
  2396. -- ********************************************************************************** --
  2397. -- PROGRAM: DOCK BUILDER
  2398. -- Slots map:
  2399. -- F C B _
  2400. -- _ _ _ _
  2401. -- _ _ _ _
  2402. -- _ _ _ _
  2403. -- F - Fuel, C - Chest, B - Cobblestone, _ - Thrash
  2404. --
  2405. -- Additional: Must have chest from back at start
  2406. -- ********************************************************************************** --
  2407.  
  2408. function startBuildFirstStorage()
  2409.   p('startBuildFirstStorage()')
  2410.  
  2411.   -- Check is enough chests
  2412.   while (turtle.getItemCount(idSlots.chest) < idSlotsMinCount[idSlots.chest]) do
  2413.     writeMessage('Put at least 32 chests in slot'..idSlots.chest..'and press any key', messageLevel.ERROR)
  2414.     getAnyKey()
  2415.   end
  2416.  
  2417.   -- Build Thrash collector
  2418.   -- TMP
  2419.   currX = 0
  2420.   currY = 0
  2421.   currZ = 0
  2422.  
  2423.   -- Place 3 chests
  2424.   turtleTurn(way.LEFT)
  2425.   placeBlock(idSlots.chest)
  2426.   turtleTurn(way.RIGHT)
  2427.   placeBlock(idSlots.chest)
  2428.   turtleTurn(way.RIGHT)
  2429.   placeBlock(idSlots.chest)
  2430.  
  2431.   -- Move to storage
  2432.   turtleUp()
  2433.   turtleGoTo(beacon[beaconName.STORAGE].x, beacon[beaconName.STORAGE].y + 1, beacon[beaconName.STORAGE].z)
  2434.   turtleDown()
  2435.  
  2436.   -- Place bunch of chests
  2437.   local chestPlaced = 0
  2438.   while (chestPlaced < 16) do
  2439.     orientToChestInStorage()
  2440.     placeBlock(idSlots.chest)
  2441.  
  2442.     turtleSetOrientation(way.RIGHT)
  2443.     turtleForward()
  2444.    
  2445.     chestPlaced = chestPlaced+1
  2446.   end
  2447.  
  2448.   return true
  2449. end
  2450.  
  2451. -- ********************************************************************************** --
  2452. -- PROGRAM: SortUnload
  2453. -- Slots map:
  2454. -- _ _ _ _
  2455. -- _ _ _ _
  2456. -- _ _ _ _
  2457. -- _ _ _ _
  2458. -- Emptyes all to different chests by type
  2459. --
  2460. --
  2461. -- ********************************************************************************** --
  2462. function program_unloadBySorting()
  2463.   p('program_unloadBySorting()')
  2464.  
  2465.   -- Go back to first
  2466.   turtleGoToBeacon(beaconName.STORAGE)
  2467.  
  2468.   -- Unload each slot in different chest
  2469.   -- TODO: Working with more then 16 items
  2470.   local slotLoop = 1
  2471.   while (slotLoop < 16) and (turtle.getItemCount(slotLoop) > 0) do
  2472.  
  2473.     orientToChestInStorage()
  2474.  
  2475.     turtle.select(slotLoop)
  2476.     if( turtle.drop() ) then
  2477.       turtleSetOrientation(way.RIGHT)
  2478.       turtleForward()
  2479.     else
  2480.       writeMessage('Cant drop items!', messageLevel.FATAL)
  2481.       -- TODO: Action if inventory is full or cant drop items
  2482.       return false
  2483.     end
  2484.     slotLoop = slotLoop+1
  2485.   end  
  2486.  
  2487.   return true
  2488. end
  2489.  
  2490. -- ********************************************************************************** --
  2491. -- PROGRAM: Fill
  2492. -- Slots map:
  2493. -- _ _ _ _
  2494. -- _ _ _ _
  2495. -- _ _ _ _
  2496. -- _ _ _ _
  2497. -- Build!!
  2498. --
  2499. --
  2500. -- ********************************************************************************** --
  2501. fillingFlags = {
  2502.   'whole',          -- All blocks will filling up
  2503.   'sides',          -- Making boxes
  2504.   'mirror',         -- Pattern texture will mirrored
  2505.   'mirror -1',      -- Each mirrored pattern indexes will shif by one block
  2506.   'mirror -1x',
  2507.   'mirror -1y',
  2508.   'mirror -1z',
  2509.   'y->', 'x->',     -- Build first x-z blocks, then go to next y layer
  2510.   'x++', 'x--',     -- Shift next coord. Userful for stairs
  2511.   'y++', 'y--',
  2512.   'z++', 'z--',
  2513.   'clear',          -- Replaces all pattern indexes to -1
  2514.   'clearAllSkipped',-- Replaces all 0 to -1
  2515.   'skipClearing',   -- Replaces all -1 to 0
  2516. }
  2517.  
  2518. function fill(_sizeX, _sizeY, _sizeZ, patternId, x, y, z, direction, isGoBackAfterFill, fillFlags)
  2519.  
  2520.   -- Default direction: DOWN
  2521.   if(direction==nil) then direction=way.DOWN end
  2522.  
  2523.   local correction = {x=0,y=0,z=0}
  2524.   if(direction==way.DOWN) then correction.y =  1 end
  2525.   if(direction==way.UP)   then correction.y = -1 end
  2526.   -- TODO: Make support for all directions
  2527.  
  2528.   -- Default position: zero
  2529.   if(x==nil) then x=0 end
  2530.   if(y==nil) then y=0 end
  2531.   if(z==nil) then z=0 end
  2532.    
  2533.   -- Default pattern index - plain fill
  2534.   if(patternId == nil) then patternId = 'plain' end
  2535.  
  2536.   -- Default go home - yes, go back
  2537.   if(isGoBackAfterFill == nil) then isGoBackAfterFill = true end
  2538.  
  2539.   -- Compute slots pattern.
  2540.   -- Pattern shows what block index in what slot
  2541.   local slotsPattern = getSlotsPattern()
  2542.  
  2543.   -- =====================================================================
  2544.   -- =====================================================================
  2545.  
  2546.   local startPos = {x=currX, y=currY, z=currZ}
  2547.  
  2548.   -- Pattern sizes per align
  2549.   local ptSzY = #fillPattern[patternId]
  2550.   local ptSzZ = #fillPattern[patternId][1]
  2551.   local ptSzX = #fillPattern[patternId][1][1]
  2552.  
  2553.   -- There we will storage what slots was deplited, out of building blocks
  2554.   -- 0: slot in use, have blocks.
  2555.   -- 1: slot deplited, haven't blocks or have thrash
  2556.   local blacklistPattern = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
  2557.  
  2558.   -- Real sizes of dimensions
  2559.   local sizeX, sizeY, sizeZ
  2560.   local fabled_ptSzX,fabled_ptSzY,fabled_ptSzZ
  2561.  
  2562.   if    (fillFlags['y->']) then
  2563.     sizeX, sizeY, sizeZ = _sizeX, _sizeZ, _sizeY
  2564.     fabled_ptSzX,fabled_ptSzY,fabled_ptSzZ = ptSzX,ptSzZ,ptSzY
  2565.   elseif(fillFlags['x->']) then
  2566.     sizeX, sizeY, sizeZ = _sizeZ, _sizeX, _sizeY
  2567.     fabled_ptSzX,fabled_ptSzY,fabled_ptSzZ = ptSzZ,ptSzX,ptSzY
  2568.   else
  2569.     sizeX, sizeY, sizeZ = _sizeX, _sizeY, _sizeZ
  2570.     fabled_ptSzX,fabled_ptSzY,fabled_ptSzZ = ptSzX,ptSzY,ptSzZ
  2571.   end
  2572.  
  2573.  
  2574.   local totalVolume = sizeX*sizeY*sizeZ
  2575.  
  2576.   for O=0, totalVolume-1 do
  2577.    
  2578.     local _u, _v, _w -- Imaginationed positions on 3d grid
  2579.     local u, v, w    -- Real position on 3d grid
  2580.    
  2581.  
  2582.     _u = math.floor(O/(sizeX*sizeZ))
  2583.     _v = math.floor(O/sizeX) % sizeZ
  2584.     _w = math.floor(O%sizeX)
  2585.    
  2586.    
  2587.      -- Ping-pong
  2588.     if (not fillFlags['y->']) and (not fillFlags['x->']) then
  2589.       if(_u%2==1) then _v = sizeZ - _v - 1 end
  2590.     else
  2591.     end
  2592.     if(_v%2==1) then _w = sizeX - _w - 1 end
  2593.    
  2594.     -- Change filling directions
  2595.     if    (fillFlags['y->']) then
  2596.       u,v,w = _v, _u, _w
  2597.     elseif(fillFlags['x->']) then
  2598.       u,v,w = _w, _u, _v
  2599.     else
  2600.       u,v,w = _u, _v, _w
  2601.     end
  2602.    
  2603.        
  2604.     -- Pattern piker must think we are on this positions
  2605.     local fabled_u, fabled_v, fabled_w = u,v,w
  2606.    
  2607.    
  2608.     if(fillFlags['mirror -1'] or fillFlags['mirror -1z']) then
  2609.       fabled_u = u + math.floor( (u+fabled_ptSzY-1) / (fabled_ptSzY*2-1) )
  2610.     end
  2611.     if(fillFlags['mirror -1'] or fillFlags['mirror -1y']) then
  2612.       fabled_v = v + math.floor( (v+fabled_ptSzZ-1) / (fabled_ptSzZ*2-1) )
  2613.     end
  2614.     if(fillFlags['mirror -1'] or fillFlags['mirror -1x']) then
  2615.       fabled_w = w + math.floor( (w+fabled_ptSzX-1) / (fabled_ptSzX*2-1) )
  2616.     end
  2617.  
  2618.  
  2619.       -- Compute pattern array indexes. Place on pattern that we want to take
  2620.     local ptX, ptY, ptZ = (fabled_w)%ptSzX+1, (fabled_u)%ptSzY+1, (fabled_v)%ptSzZ+1
  2621.    
  2622.     -- Flag "mirror" must mirrored all coordinates on even step
  2623.     -- Don't forget add here all mirrors flags!
  2624.     if(fillFlags['mirror'] or fillFlags['mirror -1'] or fillFlags['mirror -1x'] or
  2625.        fillFlags['mirror -1y'] or fillFlags['mirror -1z']) then
  2626.       if (math.floor(fabled_w/ptSzX) % 2) == 1 then ptX = 1+ptSzX-ptX end
  2627.       if (math.floor(fabled_u/ptSzY) % 2) == 1 then ptY = 1+ptSzY-ptY end
  2628.       if (math.floor(fabled_v/ptSzZ) % 2) == 1 then ptZ = 1+ptSzZ-ptZ end
  2629.     end
  2630.  
  2631.     -- Shift next coord
  2632.     local shift = {}
  2633.     shift.x = v*(fillFlags['x++'] and 1 or (fillFlags['x--'] and -1 or 0))
  2634.     shift.y = w*(fillFlags['y++'] and 1 or (fillFlags['y--'] and -1 or 0))
  2635.     shift.z = v*(fillFlags['z++'] and 1 or (fillFlags['z--'] and -1 or 0))
  2636.    
  2637.     -- Standart type of fill rule, take all pattern indexes
  2638.     -- Get block index from pattern, demands on position of turtle  
  2639.     local blockIndexToPlace = fillPattern[patternId][ptY][ptZ][ptX]
  2640.    
  2641.    
  2642.     if fillFlags['sides'] then
  2643.       if(u>0 and u<sizeY-1) and (v>0 and v<sizeZ-1) and (w>0 and w<sizeX-1) then
  2644.         blockIndexToPlace = 0
  2645.       end
  2646.     end
  2647.     if fillFlags['clear']           then blockIndexToPlace = -1 end
  2648.     if fillFlags['clearAllSkipped'] then if blockIndexToPlace== 0 then blockIndexToPlace = -1 end end
  2649.     if fillFlags['skipClearing']    then if blockIndexToPlace==-1 then blockIndexToPlace =  0 end end
  2650.      
  2651.     if( blockIndexToPlace ~= 0) then
  2652.       turtleGoTo(x+w + correction.x +shift.x,
  2653.                  y+u + correction.y +shift.z,
  2654.                  z+v + correction.z +shift.y + 1) -- Z-Shift means that turtle 0 0 0 point is forward
  2655.                  
  2656.       if blockIndexToPlace > 0 then
  2657.         local slotWithNeededItem = findInSlotsArrayByPattern(slotsPattern, blockIndexToPlace, blacklistPattern)
  2658.         if(slotWithNeededItem ~= 0) then
  2659.           -- We have block and can put it on place
  2660.           placeBlock(slotWithNeededItem, direction)
  2661.          
  2662.           -- If slot was emptyed, we must note, that now there will be thrash
  2663.           -- Each next time when turtle dig, empty slot will filling
  2664.           if(turtle.getItemCount(slotWithNeededItem) == 0) then
  2665.             blacklistPattern[slotWithNeededItem] = 1
  2666.            
  2667.             -- Check again if we have another slot with item
  2668.             if( findInSlotsArrayByPattern(slotsPattern, blockIndexToPlace, blacklistPattern) == 0)then
  2669.               -- No avaliable blocks to build!
  2670.               -- Save coords, take more blocks and return
  2671.               local buildProgressStopPos = {x=currX, y=currY, z=currZ}
  2672.               turtleGoTo(currX, _sizeY+1, currZ)
  2673.               turtleGoTo(currX, _sizeY+1, 0)
  2674.               local reloadedPattern = reloadForFilling(slotsPattern, blacklistPattern)
  2675.              
  2676.               -- If some slots was not reloaded, leave them in blacklist
  2677.               for i=1, 16 do
  2678.                 if(reloadedPattern[i] > 0) then blacklistPattern[i] = 0 end
  2679.               end
  2680.              
  2681.               -- TODO: Path finding for faster go back
  2682.               turtleGoTo(currX, _sizeY+1, currZ)
  2683.               turtleGoTo(buildProgressStopPos.x, buildProgressStopPos.y, buildProgressStopPos.z)
  2684.             end
  2685.           end
  2686.         else
  2687.           -- No blocks to place
  2688.           p('No blocks to plate here')
  2689.           return false
  2690.         end
  2691.       else
  2692.         -- Pattern says here is index < 0. Remove block here and do nothing
  2693.         turtleDig(direction)
  2694.       end
  2695.     else
  2696.       -- blockIndexToPlace == 0
  2697.     end
  2698.    
  2699.   end
  2700.  
  2701.   -- Now we finished filling territory. Just go home
  2702.   turtleGoTo(startPos.x, startPos.y, startPos.z)
  2703.   return true
  2704. end
  2705.  
  2706. -- ********************************************************************************** --
  2707. -- PROGRAM: BuildSmeltery
  2708. -- Slots map:
  2709. -- _ _ _ _
  2710. -- _ _ _ _
  2711. -- _ _ _ _
  2712. -- _ _ _ _
  2713. -- Build small bunch of furnaces
  2714. --
  2715. --
  2716. -- ********************************************************************************** --
  2717. function program_buildSmeltery()
  2718.   p('program_buildSmeltery()')
  2719.  
  2720.   local furnaceCount = 7 -- TODO: Correct value after tests
  2721.   craft(idSlots.furnace, furnaceCount)
  2722.  
  2723.   -- Go to smeltery
  2724.   fill(3, 1, 3, 'O_hole', beacon[beaconName.SMELTERY].x, beacon[beaconName.SMELTERY].y, beacon[beaconName.SMELTERY].z)
  2725.  
  2726.  
  2727.   return true
  2728. end
  2729.  
  2730. -- ********************************************************************************** --
  2731. -- Place item in front of turtle. Check if item already placed.
  2732. -- We must take +1 block: chest must have at least 1 block to store
  2733. -- for ID compares
  2734. -- ********************************************************************************** --
  2735. function takeBlocksFromStorage(itemSlotId, count)
  2736.  
  2737.   -- All slots must be empty
  2738.   for i=1,#idSlots do
  2739.     if( turtle.getItemCount(i) > 0 ) then
  2740.       -- TODO: Action when inventory has items
  2741.       writeMessage('Inventory have items, must clear all', messageLevel.ERROR)
  2742.       return false
  2743.     end
  2744.   end
  2745.  
  2746.   local x,y,z = getStoragePosByItemSlotID(itemSlotId)
  2747.   turtleGoTo(x,y,z)
  2748.  
  2749.   orientToChestInStorage()
  2750.  
  2751.   local itemsSucked = 0
  2752.   local slotLoop = 1
  2753.  
  2754.   while (itemsSucked < (count + 1)) do
  2755.     turtle.select(slotLoop)
  2756.    
  2757.     if( turtle.suck() ) then
  2758.       itemsSucked = itemsSucked + turtle.getItemCount(slotLoop)
  2759.     else
  2760.       p('Not enought items')
  2761.      
  2762.       -- Drop taken items back
  2763.       for i=slotLoop, 1, -1 do
  2764.         turtle.select(i)
  2765.         turtle.drop()
  2766.       end
  2767.      
  2768.       return false
  2769.     end
  2770.    
  2771.     slotLoop = slotLoop + 1
  2772.   end
  2773.  
  2774.   -- Place excess items back
  2775.   -- Including one additional item for filter
  2776.   if( itemsSucked > count ) then
  2777.     local excessCount = itemsSucked - count
  2778.     turtle.drop(excessCount)
  2779.   end
  2780.  
  2781.   return true
  2782. end
  2783.  
  2784.  
  2785. -- ********************************************************************************** --
  2786. -- Go to the storage and suck needed blocks. Storage must be defined
  2787. -- ********************************************************************************** --
  2788. function reloadForFilling(slotsPattern, blacklistPattern)
  2789.  
  2790.   local reloadedPattern = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
  2791.  
  2792.   -- Default blacklist. No thrash to drop
  2793.   if(blacklistPattern==nil) then blacklistPattern = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} end
  2794.  
  2795.   -- First, unload blacklisted slotls
  2796.   -- This is blocks that we dont using for building
  2797.   turtleGoTo(0,0,0)
  2798.   turtleSetOrientation(way.LEFT)
  2799.   for i=1, 16 do
  2800.     if( blacklistPattern[i] > 0) then
  2801.       turtle.select(i)
  2802.       turtle.drop()
  2803.     end
  2804.   end
  2805.  
  2806.   -- Then move to storages and take blocks
  2807.   for i=1, 16 do
  2808.     local itemSpace = turtle.getItemSpace(i)
  2809.     if( itemSpace > 0  and (slotsPattern[i] > 0)) then
  2810.       -- TODO: Working with different kind of storages, not only chest array
  2811.       turtleGoTo(0+(slotsPattern[i]-1)*2,0,0)
  2812.       turtleSetOrientation(way.BACK)
  2813.       turtle.select(i)
  2814.       if( turtle.suck(itemSpace) ) then
  2815.         -- Yes, we sucked something. Lets write it in pattern
  2816.         reloadedPattern[i] = 1
  2817.       end
  2818.     end
  2819.   end
  2820.  
  2821.   return reloadedPattern
  2822. end
  2823.  
  2824. -- ********************************************************************************** --
  2825. -- Place item in front of turtle. Check if item already placed.
  2826. -- ********************************************************************************** --
  2827. function placeBlock(itemSlot, direction)
  2828.  
  2829.   local detectFnc, compareFnc, placeFnc, attackFnc =
  2830.         turtle.detect, turtle.compare, turtle.place,turtle.attack
  2831.  
  2832.   if( direction == way.UP ) then
  2833.     detectFnc, compareFnc, placeFnc, attackFnc =
  2834.     turtle.detectUp, turtle.compareUp, turtle.placeUp, turtle.attackUp
  2835.   elseif( direction == way.DOWN )then
  2836.     detectFnc, compareFnc, placeFnc, attackFnc =
  2837.     turtle.detectDown, turtle.compareDown, turtle.placeDown, turtle.attackDown
  2838.   end
  2839.  
  2840.   -- slotsPattern is array of 16 nubbers that represent
  2841.   -- what kind of blocks lying in what kind of
  2842.   if(itemSlot == nil) then
  2843.     selectNonEmptySlot()
  2844.   else
  2845.     turtle.select(itemSlot)
  2846.   end
  2847.  
  2848.   local placeSucces = false
  2849.   local digCount = 0
  2850.   local maxDigCount = 20
  2851.  
  2852.  
  2853.   -- Check if there is already item  then try to place
  2854.   placeSucces = placeFnc()
  2855.  
  2856.   if((not placeSucces) and detectFnc()) then
  2857.     if(compareFnc()) then
  2858.       -- Item that we must set already here
  2859.       return true
  2860.     else
  2861.       -- There is something else. Dig/Attack and place item
  2862.       turtleDig(direction)
  2863.       digCount = digCount + 1
  2864.     end
  2865.   end
  2866.  
  2867.   -- Now try to place item until item will placed
  2868.   while ((placeSucces == false) and (digCount < maxDigCount)) do
  2869.     if (detectFnc()) then
  2870.       if(digCount > 0) then
  2871.         sleep(0.1)
  2872.       end
  2873.       turtleDig(direction)
  2874.       digCount = digCount + 1
  2875.     else
  2876.        -- Am being stopped from moving by a mob, attack it
  2877.        attackFnc()
  2878.     end
  2879.     -- Try the place again
  2880.     placeSucces = placeFnc()
  2881.   end
  2882.  
  2883.   return placeSucces
  2884. end
  2885.  
  2886. -- ********************************************************************************** --
  2887. -- Select non-empty slot
  2888. -- ********************************************************************************** --
  2889. function selectNonEmptySlot()
  2890.   for i=1, 16 do
  2891.     if( turtle.getItemCount(i) > 0) then
  2892.       turtle.select(i)
  2893.       return true
  2894.     end
  2895.   end
  2896.   return false
  2897. end
  2898.  
  2899. -- ********************************************************************************** --
  2900. -- Get slot pattern.
  2901. -- Returning array(16) that represent indexes in slots
  2902. -- ********************************************************************************** --
  2903. function getSlotsPattern()
  2904.   local ptattern = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} -- Standart pattern. All slots empty
  2905.   local lastUnemptySlot = 0
  2906.   local lastEnum = 1
  2907.  
  2908.   for i=1, 16 do
  2909.     turtle.select(i)
  2910.     if( turtle.getItemCount(i) > 0) then
  2911.       if (lastUnemptySlot == 0) then
  2912.         lastUnemptySlot = i
  2913.       elseif (i>1) and (turtle.compareTo(lastUnemptySlot) == false) then
  2914.         lastEnum = lastEnum + 1
  2915.         lastUnemptySlot = i
  2916.       end
  2917.      
  2918.       ptattern[i] = lastEnum
  2919.     end
  2920.   end
  2921.   return ptattern
  2922. end
  2923.  
  2924.  
  2925. -- ********************************************************************************** --
  2926. -- Craft things.
  2927. -- ********************************************************************************** --
  2928. function craft(itemSlotId, count)
  2929.   print('craft('..itemSlotId..','..count..')')
  2930.  
  2931.   local itemsForPattern = 0
  2932.  
  2933.   -- Count how much we need
  2934.   for i=1, 16 do
  2935.     if( craftPattern[itemSlotId][i] > 0 ) then
  2936.       itemsForPattern = itemsForPattern + 1
  2937.     end
  2938.   end
  2939.  
  2940.   -- TODO: Change code to work with different kind of crafting blocs
  2941.   takeBlocksFromStorage(craftPattern[itemSlotId][1], count * itemsForPattern)
  2942.  
  2943.   -- Move items like in craftPattern
  2944.   -- TODO: Working with large numbers of items
  2945.  
  2946.   turtle.select(1)
  2947.   local lastSelectedSlot = 1
  2948.   for i=2, 16 do
  2949.     if( craftPattern[itemSlotId][i] > 0 ) then
  2950.       turtle.transferTo(i, turtle.getItemCount( lastSelectedSlot ) - count)
  2951.       turtle.select(i)
  2952.       lastSelectedSlot = i
  2953.     end
  2954.   end
  2955.  
  2956.   turtle.select(1)
  2957.   turtle.craft()
  2958.  
  2959.   return true
  2960. end
  2961.  
  2962.  
  2963. -- ********************************************************************************** --
  2964. -- ********************************************************************************** --
  2965. -- ********************************************************************************** --
  2966.  
  2967. function addBeaconCoords(x,y,z,beaconId)
  2968.   p("addBeaconCoords:"..x.." "..y.." "..z..' '..beaconId)
  2969.   beacon[beaconId] = {x=0, y=0, z=0}
  2970.   beacon[beaconId].x = x
  2971.   beacon[beaconId].y = y
  2972.   beacon[beaconId].z = z
  2973. end
  2974.  
  2975. function saveBeacon(b)
  2976.   addBeaconCoords(currX,currY,currZ,b)
  2977. end
  2978.  
  2979. function turtleGoToBeacon(b)
  2980.   turtleGoTo(beacon[b].x,beacon[b].y,beacon[b].z)
  2981. end
  2982.  
  2983. function getStoragePosByItemSlotID(itemSlotId)
  2984.  
  2985.   return  beacon[beaconName.STORAGE].x + itemSlotId-1,
  2986.           beacon[beaconName.STORAGE].y,
  2987.           beacon[beaconName.STORAGE].z
  2988. end
  2989.  
  2990. function turtleGoTo(x,y,z)  
  2991.   -- TODO: Check highway and path finding
  2992.  
  2993.   while (x<currX) do
  2994.     turtleSetOrientation(way.LEFT)
  2995.     turtleForward()
  2996.   end
  2997.   while (x>currX) do
  2998.     turtleSetOrientation(way.RIGHT)
  2999.     turtleForward()
  3000.   end
  3001.   while (z<currZ) do
  3002.     turtleSetOrientation(way.BACK)
  3003.     turtleForward()
  3004.   end
  3005.   while (z>currZ) do
  3006.     turtleSetOrientation(way.FORWARD)
  3007.     turtleForward()
  3008.   end
  3009.   while (y<currY) do
  3010.     turtleDown()
  3011.   end
  3012.   while (y>currY) do
  3013.     turtleUp()
  3014.   end
  3015. end
  3016.  
  3017. function orientToChestInStorage()
  3018.   if( ((beacon[beaconName.STORAGE].x - currX) % 2) == 0 ) then
  3019.     turtleSetOrientation(way.FORWARD)
  3020.   else
  3021.     turtleSetOrientation(way.BACK)
  3022.   end
  3023. end
  3024.  
  3025. function selectPatternByBlacklist(pattern, blacklist)
  3026.   local resultPattern = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
  3027.   for i=1, 16 do
  3028.       if(blacklist[i] == 0) then resultPattern[i] = pattern[i] end
  3029.   end
  3030.   return resultPattern
  3031. end
  3032.  
  3033. function findInSlotsArrayByPattern(arr, n, blacklist)
  3034.   blacklist = blacklist or {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
  3035.  
  3036.   -- Set indexes to 0 if blacklist here is 1
  3037.   local filteredArr = selectPatternByBlacklist(arr, blacklist)
  3038.  
  3039.   for i=1, 16 do
  3040.     if(filteredArr[i] == n) and (turtle.getItemCount(i) > 0) then
  3041.       return i
  3042.     end
  3043.   end
  3044.   return 0
  3045. end
  3046.  
  3047. -- ********************************************************************************** --
  3048. -- Main Function                                          
  3049. -- ********************************************************************************** --
  3050. local args = { ... }
  3051.  
  3052. startupMode = {
  3053.   'Refuel all slots','Fill'
  3054. }
  3055.  
  3056. -- Load wrappers, if we lunch from other place
  3057. if(turtle == nil) then
  3058.   dofile('src/ComputerCraft.lua')
  3059. end
  3060.  
  3061.  
  3062. function startup()
  3063.   term.clear()
  3064.   term.setCursorPos(1,1)
  3065.  
  3066.   local welcomingText = [[
  3067. =======================================
  3068. == Krutoy Turtle - universal builder ==
  3069. =======================================
  3070. ]]
  3071.   sleep(1)
  3072.   while true do
  3073.    
  3074.    
  3075.     local paramsLine = welcomingText
  3076.     local separator = '----------------------\n'
  3077.     local result = 0
  3078.     local currLine = 'Select mode:\n 1 - Refuel all slots\n 2 - Fill'
  3079.     result = readNumberParametr(paramsLine..currLine, 1, #startupMode)
  3080.     local mode = startupMode[result]
  3081.    
  3082.    
  3083.    
  3084.     if(mode == 'Refuel all slots') then
  3085.       clear()
  3086.       for i=1, 16 do
  3087.         turtle.select(i)
  3088.         turtle.refuel()
  3089.       end
  3090.     end
  3091.    
  3092.    
  3093.    
  3094.    
  3095.     if(mode == 'Fill') then
  3096.       paramsLine = paramsLine..'MODE:    Fill\n'
  3097.  
  3098.       currLine = 'Select fill pattern:\n'
  3099.       local pattern = nil
  3100.       local n = 1
  3101.       for k,v in pairs(fillPattern) do
  3102.         currLine = currLine..' '..n..' - '..k..'\n'
  3103.         n = n+1
  3104.       end
  3105.       result = readNumberParametr(paramsLine..separator..currLine, 1, n)
  3106.       n = 1
  3107.       for k,v in pairs(fillPattern) do
  3108.         if(n == result) then
  3109.           pattern = k
  3110.           paramsLine = paramsLine..'PATTERN: '..pattern..'\n'
  3111.           break
  3112.         end
  3113.         n = n+1
  3114.       end
  3115.      
  3116.      
  3117.       currLine = 'Specify size by x y z, separate with spaces, and press ENTER:\n'
  3118.       result = readTableOfNumbers(paramsLine..separator..currLine, false, 3, "%S+")
  3119.       local sizeX,sizeY,sizeZ = result[1],result[2],result[3]
  3120.       paramsLine = paramsLine..'SIZE:    {'..sizeX..', '..sizeY..', '..sizeZ..'}\n'
  3121.      
  3122.      
  3123.       currLine = 'Set position by x y z, separate with spaces, and press ENTER\n(or press ENTER to skip)\n'
  3124.       result = readTableOfNumbers(paramsLine..separator..currLine, true, 3, "%S+")
  3125.       local x,y,z = result[1],result[2],result[3]
  3126.       paramsLine = paramsLine..'POS:     {'..x..', '..y..', '..z..'}\n'
  3127.      
  3128.      
  3129.       currLine = 'Add flags if need, separate with commas, and press ENTER\n'
  3130.       result = readTable(paramsLine..separator..currLine, true, "%s*([^,]+)")
  3131.       local fillFlags = {}
  3132.       if(result) then fillFlags = makeSet(result) end
  3133.      
  3134.       clear()
  3135.       print(separator..paramsLine..separator)
  3136.       sleep(1)
  3137.      
  3138.        
  3139.       ---------------------------------------
  3140.       fill(sizeX,sizeZ,sizeY, pattern, x,y,z, way.DOWN, true, fillFlags)
  3141.     end
  3142.   end
  3143. end
  3144.  
  3145. --[[
  3146.  
  3147. -- Code to connect other file to project
  3148. local response=http.get("http://pastebin...")
  3149. local filetext=response.readAll()
  3150. local func,err=loadstring(filetext,"имя чанка")
  3151.  
  3152. if not err then
  3153. setfenv(func,getfenv(1))
  3154. func()
  3155. else
  3156. error(err)
  3157. end
  3158.  
  3159. ]]--
  3160.  
  3161. startup()
Add Comment
Please, Sign In to add comment